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": "#|$ACL2s-Preamble$;\n; Julien Schmaltz\n;; Generic Scheduling Module of GeNoC\n;; Feb 16th", "end": 37, "score": 0.999883234500885, "start": 22, "tag": "NAME", "value": "Julien Schmaltz" }, { "context": ";; Feb 16th 2005\n;; File: GeNoC-scheduling.lisp\n;; Amr HELMY Revised and modified January 24th 2008\n;;edited b", "end": 136, "score": 0.9449099898338318, "start": 127, "tag": "NAME", "value": "Amr HELMY" }, { "context": "Revised and modified January 24th 2008\n;;edited by Amr HELMY, Laurence Pierre august 22nd of august 2007\n\n;;Am", "end": 197, "score": 0.9992311596870422, "start": 188, "tag": "NAME", "value": "Amr HELMY" }, { "context": " modified January 24th 2008\n;;edited by Amr HELMY, Laurence Pierre august 22nd of august 2007\n\n;;Amr helmy\n;;31st oc", "end": 214, "score": 0.9998920559883118, "start": 199, "tag": "NAME", "value": "Laurence Pierre" }, { "context": "MY, Laurence Pierre august 22nd of august 2007\n\n;;Amr helmy\n;;31st october 2007\n\n(begin-book);$ACL2s-Preamble", "end": 254, "score": 0.8781155347824097, "start": 245, "tag": "NAME", "value": "Amr helmy" } ]
books/workshops/2009/verbeek-schmaltz/verbeek/generic-modules/GeNoC-scheduling.lisp
mayankmanj/acl2
305
#|$ACL2s-Preamble$; ; Julien Schmaltz ;; Generic Scheduling Module of GeNoC ;; Feb 16th 2005 ;; File: GeNoC-scheduling.lisp ;; Amr HELMY Revised and modified January 24th 2008 ;;edited by Amr HELMY, Laurence Pierre august 22nd of august 2007 ;;Amr helmy ;;31st october 2007 (begin-book);$ACL2s-Preamble$|# (in-package "ACL2") (include-book "GeNoC-nodeset") (include-book "GeNoC-misc") ;; imports also GeNoC-types (include-book "GeNoC-ntkstate")#|ACL2s-ToDo-Line|# ; ;; Inputs: TrLst = ( ... (Id org frm route) ...), measure, NodeSet, and ;; the current network state ;; outputs: TrLst updated, arrived missives, new state of the network, ;; measure updated (defspec GenericScheduling ;; Function Scheduling represents the scheduling policy of the ;; network. ;; arguments: TrLst measure P ;; outputs: newTrLst Arrived newP newMeasure (((scheduling * * * *) => (mv * * * *)) ((get_next_priority *)=> *) ((scheduling-assumptions * * * *) => *) ((legal-measure * * * * *) => *) ((initial-measure * * * *) => *)) (local (defun get_next_priority (port) port)) (local (defun scheduling-assumptions (TrLst NodeSet ntkstate order) (declare (ignore TrLst NodeSet ntkstate order)) nil)) (local (defun legal-measure (measure trlst nodeset ntkstate order) (declare (ignore measure trlst nodeset ntkstate order)) nil)) (local (defun initial-measure (trlst nodeset ntkstate order) (declare (ignore trlst nodeset ntkstate order)) nil)) (local (defun scheduling (TrLst NodeSet ntkstate order) ;; local witness (mv ;; TrLst updated (if (not (scheduling-assumptions TrLst NodeSet ntkstate order)) (totmissives TrLst) nil) ;; arrived messages ;(if (is-base-measure measure) nil ; TrLst) ;; measure is nil nil ;; ntkstate preserved ntkstate) )) ;; Proof obligations (also named constraints) ;; ----------------------------------------- (defthm scheduled-nil-nil ;; the result of the scheduling function in the case of empty ;; input list is equal to nil (equal (car (scheduling nil nodeset ntkstate order)) nil)) ;; 1/ Types of newTrLst, Arrived and P (state) ;; --------------------------------- ;; The type of newTrLst is a valid traveling missives list (defthm tmissivesp-newTrlst (implies (trlstp TrLst nodeset) (tmissivesp (mv-nth 0 (scheduling TrLst NodeSet ntkstate order)) NodeSet))) ;; so is the list of Arrived (defthm trlstp-Arrived ;; OK (implies (trlstp TrLst nodeset) (trlstp (mv-nth 1 (scheduling TrLst NodeSet ntkstate order)) nodeset))) ;; the state list P is a ValidState (defthm Valid-state-ntkstate (implies (validstate ntkstate) (validstate (mv-nth 3 (scheduling TrLst NodeSet ntkstate order))))) ;; 2/ the measure provided to GeNoC must be decreasing. ;; ------------------------------------------------------ ;; scheduling-assumptions must be a boolean (defthm booleanp-assumptions (booleanp (scheduling-assumptions TrLst NodeSet ntkstate order)) :rule-classes :type-prescription) ;; legal-measure nust be a boolean (defthm booleanp-legal-measure (booleanp (legal-measure measure trlst nodeset ntkstate order)) :rule-classes :type-prescription) ;; the measure must decrease on each call of scheduling (defthm measure-decreases (implies (and (legal-measure measure trlst nodeset ntkstate order) (scheduling-assumptions trlst NodeSet ntkstate order)) (O< (acl2-count (mv-nth 2 (scheduling TrLst NodeSet ntkstate order))) (acl2-count measure)))) ;; 3/ Correctness of the arrived missives ;; ------------------------------------------------------------------ ;; For any arrived missive arr, there exists a unique travel ;; tr in the initial TrLst, such that IdV(arr) = IdV(tr) ;; and FrmV(arr) = FrmV(tr) and RoutesV(arr) is a ;; sublist of RoutesV(tr). ;; In ACL2, the uniqueness of the ids is given by the predicate ;; TrLstp. ;; ------------------------------------------------------------------- ;; First, let us define this correctness (defun s/d-travel-correctness (arr-TrLst TrLst/arr-ids) (if (endp arr-TrLst) (if (endp TrLst/arr-ids) t nil) (let* ((arr-tr (car arr-TrLst)) (tr (car TrLst/arr-ids))) (and (equal (FrmV arr-tr) (FrmV tr)) (equal (IdV arr-tr) (IdV tr)) (equal (OrgV arr-tr) (OrgV tr)) (equal (FlitV arr-tr) (FlitV tr)) (equal (timeV arr-tr) (TimeV tr)) (subsetp (RoutesV arr-tr) (RoutesV tr)) (s/d-travel-correctness (cdr arr-TrLst) (cdr TrLst/arr-ids)))))) (defthm s/d-travel-correctness-unitary (implies (trlstp x nodeset) (s/d-travel-correctness x x))) (defthm arrived-travels-correctness (mv-let (newTrLst Arrived newMeasure newstate ) (scheduling TrLst NodeSet ntkstate order) (declare (ignore newTrLst newMeasure newstate )) (implies (TrLstp TrLst nodeset) (s/d-travel-correctness Arrived (extract-sublst TrLst (V-ids Arrived))))) :hints (("Goal" :in-theory (disable trlstp)))) (defthm subsetp-arrived-newTrLst-ids ;; this should be provable from the two lemmas above ;; but it will always be trivial to prove, and it is ;; useful in subsequent proofs. (mv-let (newTrLst Arrived newMeasure newstate ) (scheduling TrLst NodeSet ntkstate order) (declare (ignore newMeasure newstate )) (implies (TrLstp TrLst nodeset) (and (subsetp (v-ids Arrived) (v-ids Trlst)) (subsetp (Tm-ids newTrLst) (v-ids TrLst)))))) ;; 4. Correctness of the newTrLst travels ;; ------------------------------------- ;; the correctness of the newTrLst travels differs from ;; the correctness of the Arrived travels because, ;; for the Arrived travels we will generally keep only ;; one route, but for the newTrLst travels we will not modify ;; the travels and keep all the routes. In fact, by ;; converting a travel back to a missive we will remove the ;; routes. ;; --------------------------------------------------------- ;; the list newTrLst is equal to filtering the initial ;; TrLst according to the Ids of newTrLst (defthm newTrLst-travel-correctness ;; OK ;; the correctness of newtrlst is the equivalence of the transformation ;;of the newtrlst into missives, and the transformation of the ;;initial trlst (input to the scheduling function) ;;into tmissives and then to missives ;; this rule will cause an infinite number of rewrites that's why ;; it's in rule-classes nil, we have to create an instance to use ;; it (mv-let (newTrLst Arrived newMeasure newstate ) (scheduling TrLst NodeSet ntkstate order) (declare (ignore Arrived newMeasure newstate)) (implies (TrLstp TrLst nodeset) (equal (tomissives newTrLst) (extract-sublst (tomissives(totmissives TrLst)) (Tm-ids newTrLst))))) :rule-classes nil) ;; 6/ if scheduling assumptions are not met, measure is nil (defthm mv-nth-2-scheduling-on-zero-measure ;; OK ;; if the scheduling measure is 0 ;; the new measure is equal to the initial one (implies (and (not (scheduling-assumptions TrLst NodeSet ntkstate order)) (TrLstp trlst nodeset)) (equal (mv-nth 2 (scheduling TrLst NodeSet ntkstate order)) ;; new measure nil))) (defthm mv-nth-0-scheduling-on-zero-measure ;; OK ;; if the scheduling measure is 0 ;; the set of newTrLst s is equal to the initial TrLst (implies (not (scheduling-assumptions TrLst NodeSet ntkstate order)) (equal (mv-nth 0 (scheduling TrLst NodeSet ntkstate order)) (totmissives TrLst)))) ;; 7/ The intersection of the ids of the Arrived travels and those ;; of the newTrLst travels is empty ;; ----------------------------------------------------------------- (defthm not-in-newTrLst-Arrived ;; OK (mv-let (newTrLst Arrived newmeasure newstate ) (scheduling TrLst NodeSet ntkstate order) (declare (ignore newmeasure newstate )) (implies (TrLstp TrLst nodeset) (not-in (Tm-ids newTrLst) (v-ids Arrived))))) ;; some constraints required because we do not have a definition ;; for scheduling (defthm consp-scheduling ;; OK ;; for the mv-nth (consp (scheduling TrLst NodeSet ntkstate order)) :rule-classes :type-prescription) (defthm true-listp-car-scheduling ;; OK (implies (true-listp TrLst) (true-listp (mv-nth 0 (scheduling TrLst NodeSet ntkstate order )))) :rule-classes :type-prescription) (defthm true-listp-mv-nth-1-sched-1 ;; OK (implies (true-listp TrLst) (true-listp (mv-nth 1 (scheduling TrLst NodeSet ntkstate order)))) :rule-classes :type-prescription) (defthm true-listp-mv-nth-1-sched-2 ;; OK (implies (TrLstp TrLst nodeset) (true-listp (mv-nth 1 (scheduling TrLst NodeSet ntkstate order)))) :rule-classes :type-prescription) ) ;; end of scheduling (defthm correctroutesp-s/d-travel-correctness ;; OK ;; correctroutesp between trlst/ids and it's transformation into ;; tmissves, and the s/d-travel-correctness, between trlst/ids and ;; trlst1 ;; implies the correctroutesp between trlst1 and trlst/ids (implies (and (CorrectRoutesp TrLst/ids (ToTMissives TrLst/ids) NodeSet) (s/d-travel-correctness TrLst1 TrLst/ids)) (CorrectRoutesp TrLst1 (ToTMissives TrLst/ids) NodeSet))) (defthm scheduling-preserves-route-correctness ;; OK ;; we prove that sheduling preserve the correctness of the routes ;; after the transformation (mv-let (newTrLst Arrived newmeasure newstate ) (scheduling TrLst NodeSet ntkstate order) (declare (ignore newTrLst newstate newmeasure )) (implies (and (CorrectRoutesp TrLst (ToTMissives TrLst) NodeSet) (TrLstp TrLst nodeset)) (CorrectRoutesp Arrived (ToTMissives (extract-sublst TrLst (V-ids Arrived))) NodeSet))) :otf-flg t :hints (("GOAL" :do-not '(eliminate-destructors generalize) :do-not-induct t :in-theory (disable mv-nth ;; to have my rules used ToTMissives-extract-sublst TrLstp)))) (defthm TMissivesp-mv-nth-0-scheduling ;; OK (let ((NodeSet (NodeSetGenerator Params))) (implies (and (CorrectRoutesp TrLst (ToTMissives TrLst) NodeSet) (ValidParamsp Params) (TrLstp TrLst nodeset)) (TMissivesp (mv-nth 0 (scheduling TrLst NodeSet ntkstate order)) NodeSet))) :hints (("Goal" :use (:instance tmissivesp-newTrlst (nodeset (NodeSetGenerator Params))))))
68194
#|$ACL2s-Preamble$; ; <NAME> ;; Generic Scheduling Module of GeNoC ;; Feb 16th 2005 ;; File: GeNoC-scheduling.lisp ;; <NAME> Revised and modified January 24th 2008 ;;edited by <NAME>, <NAME> august 22nd of august 2007 ;;<NAME> ;;31st october 2007 (begin-book);$ACL2s-Preamble$|# (in-package "ACL2") (include-book "GeNoC-nodeset") (include-book "GeNoC-misc") ;; imports also GeNoC-types (include-book "GeNoC-ntkstate")#|ACL2s-ToDo-Line|# ; ;; Inputs: TrLst = ( ... (Id org frm route) ...), measure, NodeSet, and ;; the current network state ;; outputs: TrLst updated, arrived missives, new state of the network, ;; measure updated (defspec GenericScheduling ;; Function Scheduling represents the scheduling policy of the ;; network. ;; arguments: TrLst measure P ;; outputs: newTrLst Arrived newP newMeasure (((scheduling * * * *) => (mv * * * *)) ((get_next_priority *)=> *) ((scheduling-assumptions * * * *) => *) ((legal-measure * * * * *) => *) ((initial-measure * * * *) => *)) (local (defun get_next_priority (port) port)) (local (defun scheduling-assumptions (TrLst NodeSet ntkstate order) (declare (ignore TrLst NodeSet ntkstate order)) nil)) (local (defun legal-measure (measure trlst nodeset ntkstate order) (declare (ignore measure trlst nodeset ntkstate order)) nil)) (local (defun initial-measure (trlst nodeset ntkstate order) (declare (ignore trlst nodeset ntkstate order)) nil)) (local (defun scheduling (TrLst NodeSet ntkstate order) ;; local witness (mv ;; TrLst updated (if (not (scheduling-assumptions TrLst NodeSet ntkstate order)) (totmissives TrLst) nil) ;; arrived messages ;(if (is-base-measure measure) nil ; TrLst) ;; measure is nil nil ;; ntkstate preserved ntkstate) )) ;; Proof obligations (also named constraints) ;; ----------------------------------------- (defthm scheduled-nil-nil ;; the result of the scheduling function in the case of empty ;; input list is equal to nil (equal (car (scheduling nil nodeset ntkstate order)) nil)) ;; 1/ Types of newTrLst, Arrived and P (state) ;; --------------------------------- ;; The type of newTrLst is a valid traveling missives list (defthm tmissivesp-newTrlst (implies (trlstp TrLst nodeset) (tmissivesp (mv-nth 0 (scheduling TrLst NodeSet ntkstate order)) NodeSet))) ;; so is the list of Arrived (defthm trlstp-Arrived ;; OK (implies (trlstp TrLst nodeset) (trlstp (mv-nth 1 (scheduling TrLst NodeSet ntkstate order)) nodeset))) ;; the state list P is a ValidState (defthm Valid-state-ntkstate (implies (validstate ntkstate) (validstate (mv-nth 3 (scheduling TrLst NodeSet ntkstate order))))) ;; 2/ the measure provided to GeNoC must be decreasing. ;; ------------------------------------------------------ ;; scheduling-assumptions must be a boolean (defthm booleanp-assumptions (booleanp (scheduling-assumptions TrLst NodeSet ntkstate order)) :rule-classes :type-prescription) ;; legal-measure nust be a boolean (defthm booleanp-legal-measure (booleanp (legal-measure measure trlst nodeset ntkstate order)) :rule-classes :type-prescription) ;; the measure must decrease on each call of scheduling (defthm measure-decreases (implies (and (legal-measure measure trlst nodeset ntkstate order) (scheduling-assumptions trlst NodeSet ntkstate order)) (O< (acl2-count (mv-nth 2 (scheduling TrLst NodeSet ntkstate order))) (acl2-count measure)))) ;; 3/ Correctness of the arrived missives ;; ------------------------------------------------------------------ ;; For any arrived missive arr, there exists a unique travel ;; tr in the initial TrLst, such that IdV(arr) = IdV(tr) ;; and FrmV(arr) = FrmV(tr) and RoutesV(arr) is a ;; sublist of RoutesV(tr). ;; In ACL2, the uniqueness of the ids is given by the predicate ;; TrLstp. ;; ------------------------------------------------------------------- ;; First, let us define this correctness (defun s/d-travel-correctness (arr-TrLst TrLst/arr-ids) (if (endp arr-TrLst) (if (endp TrLst/arr-ids) t nil) (let* ((arr-tr (car arr-TrLst)) (tr (car TrLst/arr-ids))) (and (equal (FrmV arr-tr) (FrmV tr)) (equal (IdV arr-tr) (IdV tr)) (equal (OrgV arr-tr) (OrgV tr)) (equal (FlitV arr-tr) (FlitV tr)) (equal (timeV arr-tr) (TimeV tr)) (subsetp (RoutesV arr-tr) (RoutesV tr)) (s/d-travel-correctness (cdr arr-TrLst) (cdr TrLst/arr-ids)))))) (defthm s/d-travel-correctness-unitary (implies (trlstp x nodeset) (s/d-travel-correctness x x))) (defthm arrived-travels-correctness (mv-let (newTrLst Arrived newMeasure newstate ) (scheduling TrLst NodeSet ntkstate order) (declare (ignore newTrLst newMeasure newstate )) (implies (TrLstp TrLst nodeset) (s/d-travel-correctness Arrived (extract-sublst TrLst (V-ids Arrived))))) :hints (("Goal" :in-theory (disable trlstp)))) (defthm subsetp-arrived-newTrLst-ids ;; this should be provable from the two lemmas above ;; but it will always be trivial to prove, and it is ;; useful in subsequent proofs. (mv-let (newTrLst Arrived newMeasure newstate ) (scheduling TrLst NodeSet ntkstate order) (declare (ignore newMeasure newstate )) (implies (TrLstp TrLst nodeset) (and (subsetp (v-ids Arrived) (v-ids Trlst)) (subsetp (Tm-ids newTrLst) (v-ids TrLst)))))) ;; 4. Correctness of the newTrLst travels ;; ------------------------------------- ;; the correctness of the newTrLst travels differs from ;; the correctness of the Arrived travels because, ;; for the Arrived travels we will generally keep only ;; one route, but for the newTrLst travels we will not modify ;; the travels and keep all the routes. In fact, by ;; converting a travel back to a missive we will remove the ;; routes. ;; --------------------------------------------------------- ;; the list newTrLst is equal to filtering the initial ;; TrLst according to the Ids of newTrLst (defthm newTrLst-travel-correctness ;; OK ;; the correctness of newtrlst is the equivalence of the transformation ;;of the newtrlst into missives, and the transformation of the ;;initial trlst (input to the scheduling function) ;;into tmissives and then to missives ;; this rule will cause an infinite number of rewrites that's why ;; it's in rule-classes nil, we have to create an instance to use ;; it (mv-let (newTrLst Arrived newMeasure newstate ) (scheduling TrLst NodeSet ntkstate order) (declare (ignore Arrived newMeasure newstate)) (implies (TrLstp TrLst nodeset) (equal (tomissives newTrLst) (extract-sublst (tomissives(totmissives TrLst)) (Tm-ids newTrLst))))) :rule-classes nil) ;; 6/ if scheduling assumptions are not met, measure is nil (defthm mv-nth-2-scheduling-on-zero-measure ;; OK ;; if the scheduling measure is 0 ;; the new measure is equal to the initial one (implies (and (not (scheduling-assumptions TrLst NodeSet ntkstate order)) (TrLstp trlst nodeset)) (equal (mv-nth 2 (scheduling TrLst NodeSet ntkstate order)) ;; new measure nil))) (defthm mv-nth-0-scheduling-on-zero-measure ;; OK ;; if the scheduling measure is 0 ;; the set of newTrLst s is equal to the initial TrLst (implies (not (scheduling-assumptions TrLst NodeSet ntkstate order)) (equal (mv-nth 0 (scheduling TrLst NodeSet ntkstate order)) (totmissives TrLst)))) ;; 7/ The intersection of the ids of the Arrived travels and those ;; of the newTrLst travels is empty ;; ----------------------------------------------------------------- (defthm not-in-newTrLst-Arrived ;; OK (mv-let (newTrLst Arrived newmeasure newstate ) (scheduling TrLst NodeSet ntkstate order) (declare (ignore newmeasure newstate )) (implies (TrLstp TrLst nodeset) (not-in (Tm-ids newTrLst) (v-ids Arrived))))) ;; some constraints required because we do not have a definition ;; for scheduling (defthm consp-scheduling ;; OK ;; for the mv-nth (consp (scheduling TrLst NodeSet ntkstate order)) :rule-classes :type-prescription) (defthm true-listp-car-scheduling ;; OK (implies (true-listp TrLst) (true-listp (mv-nth 0 (scheduling TrLst NodeSet ntkstate order )))) :rule-classes :type-prescription) (defthm true-listp-mv-nth-1-sched-1 ;; OK (implies (true-listp TrLst) (true-listp (mv-nth 1 (scheduling TrLst NodeSet ntkstate order)))) :rule-classes :type-prescription) (defthm true-listp-mv-nth-1-sched-2 ;; OK (implies (TrLstp TrLst nodeset) (true-listp (mv-nth 1 (scheduling TrLst NodeSet ntkstate order)))) :rule-classes :type-prescription) ) ;; end of scheduling (defthm correctroutesp-s/d-travel-correctness ;; OK ;; correctroutesp between trlst/ids and it's transformation into ;; tmissves, and the s/d-travel-correctness, between trlst/ids and ;; trlst1 ;; implies the correctroutesp between trlst1 and trlst/ids (implies (and (CorrectRoutesp TrLst/ids (ToTMissives TrLst/ids) NodeSet) (s/d-travel-correctness TrLst1 TrLst/ids)) (CorrectRoutesp TrLst1 (ToTMissives TrLst/ids) NodeSet))) (defthm scheduling-preserves-route-correctness ;; OK ;; we prove that sheduling preserve the correctness of the routes ;; after the transformation (mv-let (newTrLst Arrived newmeasure newstate ) (scheduling TrLst NodeSet ntkstate order) (declare (ignore newTrLst newstate newmeasure )) (implies (and (CorrectRoutesp TrLst (ToTMissives TrLst) NodeSet) (TrLstp TrLst nodeset)) (CorrectRoutesp Arrived (ToTMissives (extract-sublst TrLst (V-ids Arrived))) NodeSet))) :otf-flg t :hints (("GOAL" :do-not '(eliminate-destructors generalize) :do-not-induct t :in-theory (disable mv-nth ;; to have my rules used ToTMissives-extract-sublst TrLstp)))) (defthm TMissivesp-mv-nth-0-scheduling ;; OK (let ((NodeSet (NodeSetGenerator Params))) (implies (and (CorrectRoutesp TrLst (ToTMissives TrLst) NodeSet) (ValidParamsp Params) (TrLstp TrLst nodeset)) (TMissivesp (mv-nth 0 (scheduling TrLst NodeSet ntkstate order)) NodeSet))) :hints (("Goal" :use (:instance tmissivesp-newTrlst (nodeset (NodeSetGenerator Params))))))
true
#|$ACL2s-Preamble$; ; PI:NAME:<NAME>END_PI ;; Generic Scheduling Module of GeNoC ;; Feb 16th 2005 ;; File: GeNoC-scheduling.lisp ;; PI:NAME:<NAME>END_PI Revised and modified January 24th 2008 ;;edited by PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI august 22nd of august 2007 ;;PI:NAME:<NAME>END_PI ;;31st october 2007 (begin-book);$ACL2s-Preamble$|# (in-package "ACL2") (include-book "GeNoC-nodeset") (include-book "GeNoC-misc") ;; imports also GeNoC-types (include-book "GeNoC-ntkstate")#|ACL2s-ToDo-Line|# ; ;; Inputs: TrLst = ( ... (Id org frm route) ...), measure, NodeSet, and ;; the current network state ;; outputs: TrLst updated, arrived missives, new state of the network, ;; measure updated (defspec GenericScheduling ;; Function Scheduling represents the scheduling policy of the ;; network. ;; arguments: TrLst measure P ;; outputs: newTrLst Arrived newP newMeasure (((scheduling * * * *) => (mv * * * *)) ((get_next_priority *)=> *) ((scheduling-assumptions * * * *) => *) ((legal-measure * * * * *) => *) ((initial-measure * * * *) => *)) (local (defun get_next_priority (port) port)) (local (defun scheduling-assumptions (TrLst NodeSet ntkstate order) (declare (ignore TrLst NodeSet ntkstate order)) nil)) (local (defun legal-measure (measure trlst nodeset ntkstate order) (declare (ignore measure trlst nodeset ntkstate order)) nil)) (local (defun initial-measure (trlst nodeset ntkstate order) (declare (ignore trlst nodeset ntkstate order)) nil)) (local (defun scheduling (TrLst NodeSet ntkstate order) ;; local witness (mv ;; TrLst updated (if (not (scheduling-assumptions TrLst NodeSet ntkstate order)) (totmissives TrLst) nil) ;; arrived messages ;(if (is-base-measure measure) nil ; TrLst) ;; measure is nil nil ;; ntkstate preserved ntkstate) )) ;; Proof obligations (also named constraints) ;; ----------------------------------------- (defthm scheduled-nil-nil ;; the result of the scheduling function in the case of empty ;; input list is equal to nil (equal (car (scheduling nil nodeset ntkstate order)) nil)) ;; 1/ Types of newTrLst, Arrived and P (state) ;; --------------------------------- ;; The type of newTrLst is a valid traveling missives list (defthm tmissivesp-newTrlst (implies (trlstp TrLst nodeset) (tmissivesp (mv-nth 0 (scheduling TrLst NodeSet ntkstate order)) NodeSet))) ;; so is the list of Arrived (defthm trlstp-Arrived ;; OK (implies (trlstp TrLst nodeset) (trlstp (mv-nth 1 (scheduling TrLst NodeSet ntkstate order)) nodeset))) ;; the state list P is a ValidState (defthm Valid-state-ntkstate (implies (validstate ntkstate) (validstate (mv-nth 3 (scheduling TrLst NodeSet ntkstate order))))) ;; 2/ the measure provided to GeNoC must be decreasing. ;; ------------------------------------------------------ ;; scheduling-assumptions must be a boolean (defthm booleanp-assumptions (booleanp (scheduling-assumptions TrLst NodeSet ntkstate order)) :rule-classes :type-prescription) ;; legal-measure nust be a boolean (defthm booleanp-legal-measure (booleanp (legal-measure measure trlst nodeset ntkstate order)) :rule-classes :type-prescription) ;; the measure must decrease on each call of scheduling (defthm measure-decreases (implies (and (legal-measure measure trlst nodeset ntkstate order) (scheduling-assumptions trlst NodeSet ntkstate order)) (O< (acl2-count (mv-nth 2 (scheduling TrLst NodeSet ntkstate order))) (acl2-count measure)))) ;; 3/ Correctness of the arrived missives ;; ------------------------------------------------------------------ ;; For any arrived missive arr, there exists a unique travel ;; tr in the initial TrLst, such that IdV(arr) = IdV(tr) ;; and FrmV(arr) = FrmV(tr) and RoutesV(arr) is a ;; sublist of RoutesV(tr). ;; In ACL2, the uniqueness of the ids is given by the predicate ;; TrLstp. ;; ------------------------------------------------------------------- ;; First, let us define this correctness (defun s/d-travel-correctness (arr-TrLst TrLst/arr-ids) (if (endp arr-TrLst) (if (endp TrLst/arr-ids) t nil) (let* ((arr-tr (car arr-TrLst)) (tr (car TrLst/arr-ids))) (and (equal (FrmV arr-tr) (FrmV tr)) (equal (IdV arr-tr) (IdV tr)) (equal (OrgV arr-tr) (OrgV tr)) (equal (FlitV arr-tr) (FlitV tr)) (equal (timeV arr-tr) (TimeV tr)) (subsetp (RoutesV arr-tr) (RoutesV tr)) (s/d-travel-correctness (cdr arr-TrLst) (cdr TrLst/arr-ids)))))) (defthm s/d-travel-correctness-unitary (implies (trlstp x nodeset) (s/d-travel-correctness x x))) (defthm arrived-travels-correctness (mv-let (newTrLst Arrived newMeasure newstate ) (scheduling TrLst NodeSet ntkstate order) (declare (ignore newTrLst newMeasure newstate )) (implies (TrLstp TrLst nodeset) (s/d-travel-correctness Arrived (extract-sublst TrLst (V-ids Arrived))))) :hints (("Goal" :in-theory (disable trlstp)))) (defthm subsetp-arrived-newTrLst-ids ;; this should be provable from the two lemmas above ;; but it will always be trivial to prove, and it is ;; useful in subsequent proofs. (mv-let (newTrLst Arrived newMeasure newstate ) (scheduling TrLst NodeSet ntkstate order) (declare (ignore newMeasure newstate )) (implies (TrLstp TrLst nodeset) (and (subsetp (v-ids Arrived) (v-ids Trlst)) (subsetp (Tm-ids newTrLst) (v-ids TrLst)))))) ;; 4. Correctness of the newTrLst travels ;; ------------------------------------- ;; the correctness of the newTrLst travels differs from ;; the correctness of the Arrived travels because, ;; for the Arrived travels we will generally keep only ;; one route, but for the newTrLst travels we will not modify ;; the travels and keep all the routes. In fact, by ;; converting a travel back to a missive we will remove the ;; routes. ;; --------------------------------------------------------- ;; the list newTrLst is equal to filtering the initial ;; TrLst according to the Ids of newTrLst (defthm newTrLst-travel-correctness ;; OK ;; the correctness of newtrlst is the equivalence of the transformation ;;of the newtrlst into missives, and the transformation of the ;;initial trlst (input to the scheduling function) ;;into tmissives and then to missives ;; this rule will cause an infinite number of rewrites that's why ;; it's in rule-classes nil, we have to create an instance to use ;; it (mv-let (newTrLst Arrived newMeasure newstate ) (scheduling TrLst NodeSet ntkstate order) (declare (ignore Arrived newMeasure newstate)) (implies (TrLstp TrLst nodeset) (equal (tomissives newTrLst) (extract-sublst (tomissives(totmissives TrLst)) (Tm-ids newTrLst))))) :rule-classes nil) ;; 6/ if scheduling assumptions are not met, measure is nil (defthm mv-nth-2-scheduling-on-zero-measure ;; OK ;; if the scheduling measure is 0 ;; the new measure is equal to the initial one (implies (and (not (scheduling-assumptions TrLst NodeSet ntkstate order)) (TrLstp trlst nodeset)) (equal (mv-nth 2 (scheduling TrLst NodeSet ntkstate order)) ;; new measure nil))) (defthm mv-nth-0-scheduling-on-zero-measure ;; OK ;; if the scheduling measure is 0 ;; the set of newTrLst s is equal to the initial TrLst (implies (not (scheduling-assumptions TrLst NodeSet ntkstate order)) (equal (mv-nth 0 (scheduling TrLst NodeSet ntkstate order)) (totmissives TrLst)))) ;; 7/ The intersection of the ids of the Arrived travels and those ;; of the newTrLst travels is empty ;; ----------------------------------------------------------------- (defthm not-in-newTrLst-Arrived ;; OK (mv-let (newTrLst Arrived newmeasure newstate ) (scheduling TrLst NodeSet ntkstate order) (declare (ignore newmeasure newstate )) (implies (TrLstp TrLst nodeset) (not-in (Tm-ids newTrLst) (v-ids Arrived))))) ;; some constraints required because we do not have a definition ;; for scheduling (defthm consp-scheduling ;; OK ;; for the mv-nth (consp (scheduling TrLst NodeSet ntkstate order)) :rule-classes :type-prescription) (defthm true-listp-car-scheduling ;; OK (implies (true-listp TrLst) (true-listp (mv-nth 0 (scheduling TrLst NodeSet ntkstate order )))) :rule-classes :type-prescription) (defthm true-listp-mv-nth-1-sched-1 ;; OK (implies (true-listp TrLst) (true-listp (mv-nth 1 (scheduling TrLst NodeSet ntkstate order)))) :rule-classes :type-prescription) (defthm true-listp-mv-nth-1-sched-2 ;; OK (implies (TrLstp TrLst nodeset) (true-listp (mv-nth 1 (scheduling TrLst NodeSet ntkstate order)))) :rule-classes :type-prescription) ) ;; end of scheduling (defthm correctroutesp-s/d-travel-correctness ;; OK ;; correctroutesp between trlst/ids and it's transformation into ;; tmissves, and the s/d-travel-correctness, between trlst/ids and ;; trlst1 ;; implies the correctroutesp between trlst1 and trlst/ids (implies (and (CorrectRoutesp TrLst/ids (ToTMissives TrLst/ids) NodeSet) (s/d-travel-correctness TrLst1 TrLst/ids)) (CorrectRoutesp TrLst1 (ToTMissives TrLst/ids) NodeSet))) (defthm scheduling-preserves-route-correctness ;; OK ;; we prove that sheduling preserve the correctness of the routes ;; after the transformation (mv-let (newTrLst Arrived newmeasure newstate ) (scheduling TrLst NodeSet ntkstate order) (declare (ignore newTrLst newstate newmeasure )) (implies (and (CorrectRoutesp TrLst (ToTMissives TrLst) NodeSet) (TrLstp TrLst nodeset)) (CorrectRoutesp Arrived (ToTMissives (extract-sublst TrLst (V-ids Arrived))) NodeSet))) :otf-flg t :hints (("GOAL" :do-not '(eliminate-destructors generalize) :do-not-induct t :in-theory (disable mv-nth ;; to have my rules used ToTMissives-extract-sublst TrLstp)))) (defthm TMissivesp-mv-nth-0-scheduling ;; OK (let ((NodeSet (NodeSetGenerator Params))) (implies (and (CorrectRoutesp TrLst (ToTMissives TrLst) NodeSet) (ValidParamsp Params) (TrLstp TrLst nodeset)) (TMissivesp (mv-nth 0 (scheduling TrLst NodeSet ntkstate order)) NodeSet))) :hints (("Goal" :use (:instance tmissivesp-newTrlst (nodeset (NodeSetGenerator Params))))))
[ { "context": ";;;; Copyright (c) 2014\n;;;;\n;;;; Robert Strandh ([email protected])\n;;;;\n;;;; all rights r", "end": 52, "score": 0.9998533725738525, "start": 38, "tag": "NAME", "value": "Robert Strandh" }, { "context": " Copyright (c) 2014\n;;;;\n;;;; Robert Strandh ([email protected])\n;;;;\n;;;; all rights reserved.\n;;;;\n;;;; Permiss", "end": 78, "score": 0.9999295473098755, "start": 54, "tag": "EMAIL", "value": "[email protected]" } ]
Code/String/trim.lisp
ebrasca/SICL
1
;;;; Copyright (c) 2014 ;;;; ;;;; Robert Strandh ([email protected]) ;;;; ;;;; all rights reserved. ;;;; ;;;; Permission is hereby granted to use this software for any ;;;; purpose, including using, modifying, and redistributing it. ;;;; ;;;; The software is provided "as-is" with no warranty. The user of ;;;; this software assumes any responsibility of the consequences. ;;;; This file is part of the string module of the SICL project. ;;;; See the file SICL.text for a description of the project. ;;;; See the file string.text for a description of the module. (cl:in-package #:sicl-string) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; ;;; Utilities. ;;; Check that a list is a proper list of characters. It has already been ;;; checked that the bag is a list. (defun verify-list-bag (bag) (unless (null bag) (loop with slow = bag with fast = bag while (consp fast) unless (characterp (car fast)) do (error 'bag-contains-non-character :datum (car fast) :expected-type 'character) do (setf fast (cdr fast)) while (consp fast) until (eq slow fast) unless (characterp (car fast)) do (error 'bag-contains-non-character :datum (car fast) :expected-type 'character) do (setf fast (cdr fast)) (setf slow (cdr slow)) finally (cond ((eq slow fast) (error 'bag-is-circular-list :datum bag :expected-type 'proper-list)) ((and (atom fast) (not (null fast))) (error 'bag-is-dotted-list :datum bag :expected-type 'proper-list)) (t nil))))) ;;; Check that a vector contains only characters. (defun verify-vector-bag (bag) (loop for element across bag unless (characterp element) do (error 'bag-contains-non-character :datum element :expected-type 'character))) ;;; We assume that the bag has been checked so that it is known to ;;; be a proper list of characters. (defun character-in-list-bag-p (character bag) (declare (type character character) (optimize (speed 3) (safety 0) (debug 0))) (loop for c in bag when (char= character c) return t)) (declaim (inline character-in-list-bag-p)) (defun character-in-simple-string-bag-p (character bag) (declare (type character character) (type simple-string bag) (optimize (speed 3) (safety 0) (debug 0))) (loop for i from 0 below (length bag) when (char= character (schar bag i)) return t)) (declaim (inline character-in-simple-string-bag-p)) (defun character-in-simple-vector-bag-p (character bag) (declare (type character character) (type simple-vector bag) (optimize (speed 3) (safety 0) (debug 0))) (loop for i from 0 below (length bag) when (char= character (svref bag i)) return t)) (declaim (inline character-in-simple-vector-bag-p)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; ;;; Function STRING-LEFT-TRIM. ;;; A version of STRING-LEFT-TRIM for a character bag represented as a ;;; list, and a string represented as a simple string. (defun string-left-trim-list-simple-string (character-bag string) (declare (type simple-string string)) (let ((length (length string))) (declare (type fixnum length)) (if (or (zerop length) (not (character-in-list-bag-p (schar string 0) character-bag))) string (locally (declare (optimize (speed 3) (debug 0) (safety 0))) (loop for i of-type fixnum from 0 below length unless (character-in-list-bag-p (schar string i) character-bag) return (extract-interval-simple string i length) finally (return "")))))) ;;; A version of STRING-LEFT-TRIM for a character bag represented as a ;;; simple-string, and a string represented as a simple string. (defun string-left-trim-simple-string-simple-string (character-bag string) (declare (type simple-string string)) (let ((length (length string))) (declare (type fixnum length)) (if (or (zerop length) (not (character-in-simple-string-bag-p (schar string 0) character-bag))) string (locally (declare (optimize (speed 3) (debug 0) (safety 0))) (loop for i of-type fixnum from 0 below length unless (character-in-simple-string-bag-p (schar string i) character-bag) return (extract-interval-simple string i length) finally (return "")))))) ;;; A version of STRING-LEFT-TRIM for a character bag represented as a ;;; simple vector, and a string represented as a simple string. (defun string-left-trim-simple-vector-simple-string (character-bag string) (declare (type simple-string string)) (let ((length (length string))) (declare (type fixnum length)) (if (or (zerop length) (not (character-in-simple-vector-bag-p (schar string 0) character-bag))) string (locally (declare (optimize (speed 3) (debug 0) (safety 0))) (loop for i of-type fixnum from 0 below length unless (character-in-simple-vector-bag-p (schar string i) character-bag) return (extract-interval-simple string i length) finally (return "")))))) (defun string-left-trim (character-bag string-designator) (let ((string (string string-designator)) (bag character-bag)) (etypecase bag (list (verify-list-bag bag) (string-left-trim-list-simple-string bag string)) (simple-string (string-left-trim-simple-string-simple-string bag string)) (simple-vector (verify-vector-bag bag) (string-left-trim-simple-vector-simple-string bag string))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; ;;; Function STRING-RIGHT-TRIM. ;;; A version of STRING-RIGHT-TRIM for a character bag represented as a ;;; list, and a string represented as a simple string. (defun string-right-trim-list-simple-string (character-bag string) (declare (type simple-string string)) (let ((length (length string))) (declare (type fixnum length)) (if (or (zerop length) (not (character-in-list-bag-p (schar string (1- length)) character-bag))) string (locally (declare (optimize (speed 3) (debug 0) (safety 0))) (loop for i of-type fixnum downfrom (1- length) to 0 unless (character-in-list-bag-p (schar string i) character-bag) return (extract-interval-simple string 0 (1+ i)) finally (return "")))))) ;;; A version of STRING-RIGHT-TRIM for a character bag represented as a ;;; simple-string, and a string represented as a simple string. (defun string-right-trim-simple-string-simple-string (character-bag string) (declare (type simple-string string)) (let ((length (length string))) (declare (type fixnum length)) (if (or (zerop length) (not (character-in-simple-string-bag-p (schar string (1- length)) character-bag))) string (locally (declare (optimize (speed 3) (debug 0) (safety 0))) (loop for i of-type fixnum downfrom (1- length) to 0 unless (character-in-simple-string-bag-p (schar string i) character-bag) return (extract-interval-simple string 0 (1+ i)) finally (return "")))))) ;;; A version of STRING-RIGHT-TRIM for a character bag represented as a ;;; simple vector, and a string represented as a simple string. (defun string-right-trim-simple-vector-simple-string (character-bag string) (declare (type simple-string string)) (let ((length (length string))) (declare (type fixnum length)) (if (or (zerop length) (not (character-in-simple-vector-bag-p (schar string (1- length)) character-bag))) string (locally (declare (optimize (speed 3) (debug 0) (safety 0))) (loop for i of-type fixnum downfrom (1- length) to 0 unless (character-in-simple-vector-bag-p (schar string i) character-bag) return (extract-interval-simple string 0 (1+ i)) finally (return "")))))) (defun string-right-trim (character-bag string-designator) (let ((string (string string-designator)) (bag character-bag)) (etypecase bag (list (verify-list-bag bag) (string-right-trim-list-simple-string bag string)) (simple-string (string-right-trim-simple-string-simple-string bag string)) (simple-vector (verify-vector-bag bag) (string-right-trim-simple-vector-simple-string bag string))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; ;;; Function STRING-TRIM. ;;; A version of STRING-TRIM for a character bag represented as a ;;; list, and a string represented as a simple string. (defun string-trim-list-simple-string (character-bag string) (declare (type simple-string string)) (let ((length (length string))) (declare (type fixnum length)) (if (or (zerop length) (and (not (character-in-list-bag-p (schar string 0) character-bag)) (not (character-in-list-bag-p (schar string (1- length)) character-bag)))) string (locally (declare (optimize (speed 3) (debug 0) (safety 0))) (loop for i of-type fixnum downfrom (1- length) to 0 unless (character-in-list-bag-p (schar string i) character-bag) return (loop for j from 0 to i unless (character-in-list-bag-p (schar string j) character-bag) return (extract-interval-simple string j (1+ i))) finally (return "")))))) ;;; A version of STRING-TRIM for a character bag represented as a ;;; simple-string, and a string represented as a simple string. (defun string-trim-simple-string-simple-string (character-bag string) (declare (type simple-string string)) (let ((length (length string))) (declare (type fixnum length)) (if (or (zerop length) (and (not (character-in-simple-string-bag-p (schar string 0) character-bag)) (not (character-in-simple-string-bag-p (schar string (1- length)) character-bag)))) string (locally (declare (optimize (speed 3) (debug 0) (safety 0))) (loop for i of-type fixnum downfrom (1- length) to 0 unless (character-in-simple-string-bag-p (schar string i) character-bag) return (loop for j from 0 to i unless (character-in-simple-string-bag-p (schar string j) character-bag) return (extract-interval-simple string j (1+ i))) finally (return "")))))) ;;; A version of STRING-TRIM for a character bag represented as a ;;; simple vector, and a string represented as a simple string. (defun string-trim-simple-vector-simple-string (character-bag string) (declare (type simple-string string)) (let ((length (length string))) (declare (type fixnum length)) (if (or (zerop length) (and (not (character-in-simple-vector-bag-p (schar string 0) character-bag)) (not (character-in-simple-vector-bag-p (schar string (1- length)) character-bag)))) string (locally (declare (optimize (speed 3) (debug 0) (safety 0))) (loop for i of-type fixnum downfrom (1- length) to 0 unless (character-in-simple-vector-bag-p (schar string i) character-bag) return (loop for j from 0 to i unless (character-in-simple-vector-bag-p (schar string j) character-bag) return (extract-interval-simple string j (1+ i))) finally (return "")))))) (defun string-trim (character-bag string-designator) (let ((string (string string-designator)) (bag character-bag)) (etypecase bag (list (verify-list-bag bag) (string-trim-list-simple-string bag string)) (simple-string (string-trim-simple-string-simple-string bag string)) (simple-vector (verify-vector-bag bag) (string-trim-simple-vector-simple-string bag string)))))
20973
;;;; Copyright (c) 2014 ;;;; ;;;; <NAME> (<EMAIL>) ;;;; ;;;; all rights reserved. ;;;; ;;;; Permission is hereby granted to use this software for any ;;;; purpose, including using, modifying, and redistributing it. ;;;; ;;;; The software is provided "as-is" with no warranty. The user of ;;;; this software assumes any responsibility of the consequences. ;;;; This file is part of the string module of the SICL project. ;;;; See the file SICL.text for a description of the project. ;;;; See the file string.text for a description of the module. (cl:in-package #:sicl-string) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; ;;; Utilities. ;;; Check that a list is a proper list of characters. It has already been ;;; checked that the bag is a list. (defun verify-list-bag (bag) (unless (null bag) (loop with slow = bag with fast = bag while (consp fast) unless (characterp (car fast)) do (error 'bag-contains-non-character :datum (car fast) :expected-type 'character) do (setf fast (cdr fast)) while (consp fast) until (eq slow fast) unless (characterp (car fast)) do (error 'bag-contains-non-character :datum (car fast) :expected-type 'character) do (setf fast (cdr fast)) (setf slow (cdr slow)) finally (cond ((eq slow fast) (error 'bag-is-circular-list :datum bag :expected-type 'proper-list)) ((and (atom fast) (not (null fast))) (error 'bag-is-dotted-list :datum bag :expected-type 'proper-list)) (t nil))))) ;;; Check that a vector contains only characters. (defun verify-vector-bag (bag) (loop for element across bag unless (characterp element) do (error 'bag-contains-non-character :datum element :expected-type 'character))) ;;; We assume that the bag has been checked so that it is known to ;;; be a proper list of characters. (defun character-in-list-bag-p (character bag) (declare (type character character) (optimize (speed 3) (safety 0) (debug 0))) (loop for c in bag when (char= character c) return t)) (declaim (inline character-in-list-bag-p)) (defun character-in-simple-string-bag-p (character bag) (declare (type character character) (type simple-string bag) (optimize (speed 3) (safety 0) (debug 0))) (loop for i from 0 below (length bag) when (char= character (schar bag i)) return t)) (declaim (inline character-in-simple-string-bag-p)) (defun character-in-simple-vector-bag-p (character bag) (declare (type character character) (type simple-vector bag) (optimize (speed 3) (safety 0) (debug 0))) (loop for i from 0 below (length bag) when (char= character (svref bag i)) return t)) (declaim (inline character-in-simple-vector-bag-p)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; ;;; Function STRING-LEFT-TRIM. ;;; A version of STRING-LEFT-TRIM for a character bag represented as a ;;; list, and a string represented as a simple string. (defun string-left-trim-list-simple-string (character-bag string) (declare (type simple-string string)) (let ((length (length string))) (declare (type fixnum length)) (if (or (zerop length) (not (character-in-list-bag-p (schar string 0) character-bag))) string (locally (declare (optimize (speed 3) (debug 0) (safety 0))) (loop for i of-type fixnum from 0 below length unless (character-in-list-bag-p (schar string i) character-bag) return (extract-interval-simple string i length) finally (return "")))))) ;;; A version of STRING-LEFT-TRIM for a character bag represented as a ;;; simple-string, and a string represented as a simple string. (defun string-left-trim-simple-string-simple-string (character-bag string) (declare (type simple-string string)) (let ((length (length string))) (declare (type fixnum length)) (if (or (zerop length) (not (character-in-simple-string-bag-p (schar string 0) character-bag))) string (locally (declare (optimize (speed 3) (debug 0) (safety 0))) (loop for i of-type fixnum from 0 below length unless (character-in-simple-string-bag-p (schar string i) character-bag) return (extract-interval-simple string i length) finally (return "")))))) ;;; A version of STRING-LEFT-TRIM for a character bag represented as a ;;; simple vector, and a string represented as a simple string. (defun string-left-trim-simple-vector-simple-string (character-bag string) (declare (type simple-string string)) (let ((length (length string))) (declare (type fixnum length)) (if (or (zerop length) (not (character-in-simple-vector-bag-p (schar string 0) character-bag))) string (locally (declare (optimize (speed 3) (debug 0) (safety 0))) (loop for i of-type fixnum from 0 below length unless (character-in-simple-vector-bag-p (schar string i) character-bag) return (extract-interval-simple string i length) finally (return "")))))) (defun string-left-trim (character-bag string-designator) (let ((string (string string-designator)) (bag character-bag)) (etypecase bag (list (verify-list-bag bag) (string-left-trim-list-simple-string bag string)) (simple-string (string-left-trim-simple-string-simple-string bag string)) (simple-vector (verify-vector-bag bag) (string-left-trim-simple-vector-simple-string bag string))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; ;;; Function STRING-RIGHT-TRIM. ;;; A version of STRING-RIGHT-TRIM for a character bag represented as a ;;; list, and a string represented as a simple string. (defun string-right-trim-list-simple-string (character-bag string) (declare (type simple-string string)) (let ((length (length string))) (declare (type fixnum length)) (if (or (zerop length) (not (character-in-list-bag-p (schar string (1- length)) character-bag))) string (locally (declare (optimize (speed 3) (debug 0) (safety 0))) (loop for i of-type fixnum downfrom (1- length) to 0 unless (character-in-list-bag-p (schar string i) character-bag) return (extract-interval-simple string 0 (1+ i)) finally (return "")))))) ;;; A version of STRING-RIGHT-TRIM for a character bag represented as a ;;; simple-string, and a string represented as a simple string. (defun string-right-trim-simple-string-simple-string (character-bag string) (declare (type simple-string string)) (let ((length (length string))) (declare (type fixnum length)) (if (or (zerop length) (not (character-in-simple-string-bag-p (schar string (1- length)) character-bag))) string (locally (declare (optimize (speed 3) (debug 0) (safety 0))) (loop for i of-type fixnum downfrom (1- length) to 0 unless (character-in-simple-string-bag-p (schar string i) character-bag) return (extract-interval-simple string 0 (1+ i)) finally (return "")))))) ;;; A version of STRING-RIGHT-TRIM for a character bag represented as a ;;; simple vector, and a string represented as a simple string. (defun string-right-trim-simple-vector-simple-string (character-bag string) (declare (type simple-string string)) (let ((length (length string))) (declare (type fixnum length)) (if (or (zerop length) (not (character-in-simple-vector-bag-p (schar string (1- length)) character-bag))) string (locally (declare (optimize (speed 3) (debug 0) (safety 0))) (loop for i of-type fixnum downfrom (1- length) to 0 unless (character-in-simple-vector-bag-p (schar string i) character-bag) return (extract-interval-simple string 0 (1+ i)) finally (return "")))))) (defun string-right-trim (character-bag string-designator) (let ((string (string string-designator)) (bag character-bag)) (etypecase bag (list (verify-list-bag bag) (string-right-trim-list-simple-string bag string)) (simple-string (string-right-trim-simple-string-simple-string bag string)) (simple-vector (verify-vector-bag bag) (string-right-trim-simple-vector-simple-string bag string))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; ;;; Function STRING-TRIM. ;;; A version of STRING-TRIM for a character bag represented as a ;;; list, and a string represented as a simple string. (defun string-trim-list-simple-string (character-bag string) (declare (type simple-string string)) (let ((length (length string))) (declare (type fixnum length)) (if (or (zerop length) (and (not (character-in-list-bag-p (schar string 0) character-bag)) (not (character-in-list-bag-p (schar string (1- length)) character-bag)))) string (locally (declare (optimize (speed 3) (debug 0) (safety 0))) (loop for i of-type fixnum downfrom (1- length) to 0 unless (character-in-list-bag-p (schar string i) character-bag) return (loop for j from 0 to i unless (character-in-list-bag-p (schar string j) character-bag) return (extract-interval-simple string j (1+ i))) finally (return "")))))) ;;; A version of STRING-TRIM for a character bag represented as a ;;; simple-string, and a string represented as a simple string. (defun string-trim-simple-string-simple-string (character-bag string) (declare (type simple-string string)) (let ((length (length string))) (declare (type fixnum length)) (if (or (zerop length) (and (not (character-in-simple-string-bag-p (schar string 0) character-bag)) (not (character-in-simple-string-bag-p (schar string (1- length)) character-bag)))) string (locally (declare (optimize (speed 3) (debug 0) (safety 0))) (loop for i of-type fixnum downfrom (1- length) to 0 unless (character-in-simple-string-bag-p (schar string i) character-bag) return (loop for j from 0 to i unless (character-in-simple-string-bag-p (schar string j) character-bag) return (extract-interval-simple string j (1+ i))) finally (return "")))))) ;;; A version of STRING-TRIM for a character bag represented as a ;;; simple vector, and a string represented as a simple string. (defun string-trim-simple-vector-simple-string (character-bag string) (declare (type simple-string string)) (let ((length (length string))) (declare (type fixnum length)) (if (or (zerop length) (and (not (character-in-simple-vector-bag-p (schar string 0) character-bag)) (not (character-in-simple-vector-bag-p (schar string (1- length)) character-bag)))) string (locally (declare (optimize (speed 3) (debug 0) (safety 0))) (loop for i of-type fixnum downfrom (1- length) to 0 unless (character-in-simple-vector-bag-p (schar string i) character-bag) return (loop for j from 0 to i unless (character-in-simple-vector-bag-p (schar string j) character-bag) return (extract-interval-simple string j (1+ i))) finally (return "")))))) (defun string-trim (character-bag string-designator) (let ((string (string string-designator)) (bag character-bag)) (etypecase bag (list (verify-list-bag bag) (string-trim-list-simple-string bag string)) (simple-string (string-trim-simple-string-simple-string bag string)) (simple-vector (verify-vector-bag bag) (string-trim-simple-vector-simple-string bag string)))))
true
;;;; Copyright (c) 2014 ;;;; ;;;; PI:NAME:<NAME>END_PI (PI:EMAIL:<EMAIL>END_PI) ;;;; ;;;; all rights reserved. ;;;; ;;;; Permission is hereby granted to use this software for any ;;;; purpose, including using, modifying, and redistributing it. ;;;; ;;;; The software is provided "as-is" with no warranty. The user of ;;;; this software assumes any responsibility of the consequences. ;;;; This file is part of the string module of the SICL project. ;;;; See the file SICL.text for a description of the project. ;;;; See the file string.text for a description of the module. (cl:in-package #:sicl-string) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; ;;; Utilities. ;;; Check that a list is a proper list of characters. It has already been ;;; checked that the bag is a list. (defun verify-list-bag (bag) (unless (null bag) (loop with slow = bag with fast = bag while (consp fast) unless (characterp (car fast)) do (error 'bag-contains-non-character :datum (car fast) :expected-type 'character) do (setf fast (cdr fast)) while (consp fast) until (eq slow fast) unless (characterp (car fast)) do (error 'bag-contains-non-character :datum (car fast) :expected-type 'character) do (setf fast (cdr fast)) (setf slow (cdr slow)) finally (cond ((eq slow fast) (error 'bag-is-circular-list :datum bag :expected-type 'proper-list)) ((and (atom fast) (not (null fast))) (error 'bag-is-dotted-list :datum bag :expected-type 'proper-list)) (t nil))))) ;;; Check that a vector contains only characters. (defun verify-vector-bag (bag) (loop for element across bag unless (characterp element) do (error 'bag-contains-non-character :datum element :expected-type 'character))) ;;; We assume that the bag has been checked so that it is known to ;;; be a proper list of characters. (defun character-in-list-bag-p (character bag) (declare (type character character) (optimize (speed 3) (safety 0) (debug 0))) (loop for c in bag when (char= character c) return t)) (declaim (inline character-in-list-bag-p)) (defun character-in-simple-string-bag-p (character bag) (declare (type character character) (type simple-string bag) (optimize (speed 3) (safety 0) (debug 0))) (loop for i from 0 below (length bag) when (char= character (schar bag i)) return t)) (declaim (inline character-in-simple-string-bag-p)) (defun character-in-simple-vector-bag-p (character bag) (declare (type character character) (type simple-vector bag) (optimize (speed 3) (safety 0) (debug 0))) (loop for i from 0 below (length bag) when (char= character (svref bag i)) return t)) (declaim (inline character-in-simple-vector-bag-p)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; ;;; Function STRING-LEFT-TRIM. ;;; A version of STRING-LEFT-TRIM for a character bag represented as a ;;; list, and a string represented as a simple string. (defun string-left-trim-list-simple-string (character-bag string) (declare (type simple-string string)) (let ((length (length string))) (declare (type fixnum length)) (if (or (zerop length) (not (character-in-list-bag-p (schar string 0) character-bag))) string (locally (declare (optimize (speed 3) (debug 0) (safety 0))) (loop for i of-type fixnum from 0 below length unless (character-in-list-bag-p (schar string i) character-bag) return (extract-interval-simple string i length) finally (return "")))))) ;;; A version of STRING-LEFT-TRIM for a character bag represented as a ;;; simple-string, and a string represented as a simple string. (defun string-left-trim-simple-string-simple-string (character-bag string) (declare (type simple-string string)) (let ((length (length string))) (declare (type fixnum length)) (if (or (zerop length) (not (character-in-simple-string-bag-p (schar string 0) character-bag))) string (locally (declare (optimize (speed 3) (debug 0) (safety 0))) (loop for i of-type fixnum from 0 below length unless (character-in-simple-string-bag-p (schar string i) character-bag) return (extract-interval-simple string i length) finally (return "")))))) ;;; A version of STRING-LEFT-TRIM for a character bag represented as a ;;; simple vector, and a string represented as a simple string. (defun string-left-trim-simple-vector-simple-string (character-bag string) (declare (type simple-string string)) (let ((length (length string))) (declare (type fixnum length)) (if (or (zerop length) (not (character-in-simple-vector-bag-p (schar string 0) character-bag))) string (locally (declare (optimize (speed 3) (debug 0) (safety 0))) (loop for i of-type fixnum from 0 below length unless (character-in-simple-vector-bag-p (schar string i) character-bag) return (extract-interval-simple string i length) finally (return "")))))) (defun string-left-trim (character-bag string-designator) (let ((string (string string-designator)) (bag character-bag)) (etypecase bag (list (verify-list-bag bag) (string-left-trim-list-simple-string bag string)) (simple-string (string-left-trim-simple-string-simple-string bag string)) (simple-vector (verify-vector-bag bag) (string-left-trim-simple-vector-simple-string bag string))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; ;;; Function STRING-RIGHT-TRIM. ;;; A version of STRING-RIGHT-TRIM for a character bag represented as a ;;; list, and a string represented as a simple string. (defun string-right-trim-list-simple-string (character-bag string) (declare (type simple-string string)) (let ((length (length string))) (declare (type fixnum length)) (if (or (zerop length) (not (character-in-list-bag-p (schar string (1- length)) character-bag))) string (locally (declare (optimize (speed 3) (debug 0) (safety 0))) (loop for i of-type fixnum downfrom (1- length) to 0 unless (character-in-list-bag-p (schar string i) character-bag) return (extract-interval-simple string 0 (1+ i)) finally (return "")))))) ;;; A version of STRING-RIGHT-TRIM for a character bag represented as a ;;; simple-string, and a string represented as a simple string. (defun string-right-trim-simple-string-simple-string (character-bag string) (declare (type simple-string string)) (let ((length (length string))) (declare (type fixnum length)) (if (or (zerop length) (not (character-in-simple-string-bag-p (schar string (1- length)) character-bag))) string (locally (declare (optimize (speed 3) (debug 0) (safety 0))) (loop for i of-type fixnum downfrom (1- length) to 0 unless (character-in-simple-string-bag-p (schar string i) character-bag) return (extract-interval-simple string 0 (1+ i)) finally (return "")))))) ;;; A version of STRING-RIGHT-TRIM for a character bag represented as a ;;; simple vector, and a string represented as a simple string. (defun string-right-trim-simple-vector-simple-string (character-bag string) (declare (type simple-string string)) (let ((length (length string))) (declare (type fixnum length)) (if (or (zerop length) (not (character-in-simple-vector-bag-p (schar string (1- length)) character-bag))) string (locally (declare (optimize (speed 3) (debug 0) (safety 0))) (loop for i of-type fixnum downfrom (1- length) to 0 unless (character-in-simple-vector-bag-p (schar string i) character-bag) return (extract-interval-simple string 0 (1+ i)) finally (return "")))))) (defun string-right-trim (character-bag string-designator) (let ((string (string string-designator)) (bag character-bag)) (etypecase bag (list (verify-list-bag bag) (string-right-trim-list-simple-string bag string)) (simple-string (string-right-trim-simple-string-simple-string bag string)) (simple-vector (verify-vector-bag bag) (string-right-trim-simple-vector-simple-string bag string))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; ;;; Function STRING-TRIM. ;;; A version of STRING-TRIM for a character bag represented as a ;;; list, and a string represented as a simple string. (defun string-trim-list-simple-string (character-bag string) (declare (type simple-string string)) (let ((length (length string))) (declare (type fixnum length)) (if (or (zerop length) (and (not (character-in-list-bag-p (schar string 0) character-bag)) (not (character-in-list-bag-p (schar string (1- length)) character-bag)))) string (locally (declare (optimize (speed 3) (debug 0) (safety 0))) (loop for i of-type fixnum downfrom (1- length) to 0 unless (character-in-list-bag-p (schar string i) character-bag) return (loop for j from 0 to i unless (character-in-list-bag-p (schar string j) character-bag) return (extract-interval-simple string j (1+ i))) finally (return "")))))) ;;; A version of STRING-TRIM for a character bag represented as a ;;; simple-string, and a string represented as a simple string. (defun string-trim-simple-string-simple-string (character-bag string) (declare (type simple-string string)) (let ((length (length string))) (declare (type fixnum length)) (if (or (zerop length) (and (not (character-in-simple-string-bag-p (schar string 0) character-bag)) (not (character-in-simple-string-bag-p (schar string (1- length)) character-bag)))) string (locally (declare (optimize (speed 3) (debug 0) (safety 0))) (loop for i of-type fixnum downfrom (1- length) to 0 unless (character-in-simple-string-bag-p (schar string i) character-bag) return (loop for j from 0 to i unless (character-in-simple-string-bag-p (schar string j) character-bag) return (extract-interval-simple string j (1+ i))) finally (return "")))))) ;;; A version of STRING-TRIM for a character bag represented as a ;;; simple vector, and a string represented as a simple string. (defun string-trim-simple-vector-simple-string (character-bag string) (declare (type simple-string string)) (let ((length (length string))) (declare (type fixnum length)) (if (or (zerop length) (and (not (character-in-simple-vector-bag-p (schar string 0) character-bag)) (not (character-in-simple-vector-bag-p (schar string (1- length)) character-bag)))) string (locally (declare (optimize (speed 3) (debug 0) (safety 0))) (loop for i of-type fixnum downfrom (1- length) to 0 unless (character-in-simple-vector-bag-p (schar string i) character-bag) return (loop for j from 0 to i unless (character-in-simple-vector-bag-p (schar string j) character-bag) return (extract-interval-simple string j (1+ i))) finally (return "")))))) (defun string-trim (character-bag string-designator) (let ((string (string string-designator)) (bag character-bag)) (etypecase bag (list (verify-list-bag bag) (string-trim-list-simple-string bag string)) (simple-string (string-trim-simple-string-simple-string bag string)) (simple-vector (verify-vector-bag bag) (string-trim-simple-vector-simple-string bag string)))))
[ { "context": "lize.lisp\n\n#|\nThe MIT license.\n\nCopyright (c) 2013 Paul L. Krueger\n\nPermission is hereby granted, free of charge, to", "end": 80, "score": 0.9998819231987, "start": 65, "tag": "NAME", "value": "Paul L. Krueger" } ]
Utilities/objc-initialize.lisp
plkrueger/CocoaInterface
34
;; objc-initialize.lisp #| The MIT license. Copyright (c) 2013 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. |# #| WARNING: This will replace CCL-defined initialize-instance :after methods for ns:ns-window and ns:ns-view which are defined in cocoa-window.lisp. While I made every effort to ensure compatibility with those methods and have experienced no difficulty when running with my replacements, if you have other code that depends on specific keywords defined in those routines, you may have to either modify your code or not load this file. This file provides initialize-instance :after methods for many standard Objective-C classes, especially ns:ns-view subclasses, but it is not a comprehensive list. The norm in Lisp is to call make-instance and provide all necessary initialization values as keywords. In Objective-C the norm is to provide a few initWith... methods that supply only a limited number of initialization parameters. The developer is then expected to customize those objects by using any number of set... methods. We could certainly do the same in Lisp, but to make life more natural I have created these initialize-instance :after methods. The idea is that you can do something like the following: (make-instance '<ns-object-class-name> {:key val}*) Most common sorts of argument types needed for the Objective-C methods are automatically converted from corresponding Lisp types provided in the make-instance call. Many sorts of constants are automatically converted from keyword equivalents (see the convert... methods for those values). If their superclass also defines the initialize-instance :after method then of course it will be called as well. Each method defines keywords corresponding to set... methods that are specific to that class. So in an initialize-instance :after method for any object you can use keywords for that class or any of its superclasses. Many supporting functions named convert-... will convert keyword arguments. If the meaning of them is not clear, you should consult Apple documentation for additional information. The function initialize-keys is provided to give you a list of valid keywords for any object that you might want to initialize. Note that these methods will NOT be called if you create instances using normal Objective-C forms such as (#/init (#/alloc <class>)) They will only be invoked if you specifically call make-instance ... Final suggestions. If you execute any make-instance forms from the Lisp listener for these classes (especially classes associated withwindows or views) you should wrap the call with a (on-main-thread ... ) form (defined in ns-object-utils.lisp). This assures that the objects are created on the main thread, which is increasingly necessary for Objective-C objects created at runtime. Objects returned by these methods will typically be owned by the caller and you must explicitly (#/release <object) when you are done with it to avoid a memory leak. Note that a memory leak is much better than trying to reference a ptr to an object that was released prematurely. Such a reference is likely to cause a runtime exception. |# (assert (>= #$NSAppKitVersionNumber #$NSAppKitVersionNumber10_7)) (eval-when (:compile-toplevel :load-toplevel :execute) (require :interface-packages) (require :coerce-obj) (require :selector-utils) (require :list-utils) (require :file-directory-utils)) (in-package :iu) ;; convert- ... functions (defun convert-animation-behavior (ab-key) (if (numberp ab-key) ab-key (ecase ab-key (:default #$NSWindowAnimationBehaviorDefault) (:none #$NSWindowAnimationBehaviorNone) (:document-window #$NSWindowAnimationBehaviorDocumentWindow) (:utility-window #$NSWindowAnimationBehaviorUtilityWindow) (:alert-panel #$NSWindowAnimationBehaviorAlertPanel)))) (defun convert-bezel-style (style-key) (if (numberp style-key) style-key (ecase style-key (:rounded #$NSRoundedBezelStyle) (:regular-square #$NSRegularSquareBezelStyle) (:thick-square #$NSThickSquareBezelStyle) (:thicker-square #$NSThickerSquareBezelStyle) (:disclosure #$NSDisclosureBezelStyle) (:shadowless-square #$NSShadowlessSquareBezelStyle) (:circular #$NSCircularBezelStyle) (:textured-square #$NSTexturedSquareBezelStyle) (:help-button #$NSHelpButtonBezelStyle) (:small-square #$NSSmallSquareBezelStyle) (:textured-rounded #$NSTexturedRoundedBezelStyle) (:round-rect #$NSRoundRectBezelStyle) (:recessed #$NSRecessedBezelStyle) (:rounded-disclosure #$NSRoundedDisclosureBezelStyle) (:inline #$NSInlineBezelStyle) (:small-icon-button #$NSSmallIconButtonBezelStyle)))) (defun convert-border (border-key) (if (numberp border-key) border-key (ecase border-key (:line #$NSLineBorder) (:bezel #$NSBezelBorder) (:groove #$NSGrooveBorder) (:none #$NSNoBorder)))) (defun convert-box-type (bt-key) (if (numberp bt-key) bt-key (ecase bt-key (:primary #$NSBoxPrimary) (:secondary #$NSBoxSecondary) (:separator #$NSBoxSeparator) (:old-style #$NSBoxOldStyle) (:custom #$NSBoxCustom)))) (defun convert-button-type (type-key) (if (numberp type-key) type-key (ecase type-key (:momentary-light #$NSMomentaryLightButton) (:push-on-push-off #$NSPushOnPushOffButton) (:toggle #$NSToggleButton) (:switch #$NSSwitchButton) (:radio #$NSRadioButton) (:momentary-change #$NSMomentaryChangeButton) (:on-off #$NSOnOffButton) (:momentary-push-in #$NSMomentaryPushInButton) (:momentary-push #$NSMomentaryPushButton)))) (defun convert-collection-behavior (c-key) (cond ((listp c-key) (apply #'logior (mapcar #'convert-collection-behavior c-key))) ((numberp c-key) c-key) (t (ecase c-key (:default #$NSWindowCollectionBehaviorDefault) (:can-join-all-spaces #$NSWindowCollectionBehaviorCanJoinAllSpaces) (:move-to-active-space #$NSWindowCollectionBehaviorMoveToActiveSpace) (:managed #$NSWindowCollectionBehaviorManaged) (:transient #$NSWindowCollectionBehaviorTransient) (:stationary #$NSWindowCollectionBehaviorStationary) (:participates-in-cycle #$NSWindowCollectionBehaviorParticipatesInCycle) (:ignores-cycle #$NSWindowCollectionBehaviorIgnoresCycle) (:full-screen-primary #$NSWindowCollectionBehaviorFullScreenPrimary) (:full-screen-auxiliary #$NSWindowCollectionBehaviorFullScreenAuxiliary))))) (defun convert-column-resizing (cr-key) (if (numberp cr-key) cr-key (ecase cr-key (:no-resizing #$NSTableColumnNoResizing) (:auto-resizing #$NSTableColumnAutoresizingMask) (:user-resizing #$NSTableColumnUserResizingMask)))) (defun convert-cursor (cursor-key) ;; not all applicable to scroll-views, but included for completeness and use elsewhere (if (numberp cursor-key) cursor-key (ecase cursor-key (:arrow (#/arrowCursor ns:ns-cursor)) (:closed-hand (#/closedHandCursor ns:ns-cursor)) (:contextual-menu (#/contextualMenuCursor ns:ns-cursor)) (:crosshair (#/crosshairCursor ns:ns-cursor)) (:current (#/currentCursor ns:ns-cursor)) (:current-system (#/currentSystemCursor ns:ns-cursor)) (:disappearing-item (#/disappearingItemCursor ns:ns-cursor)) (:drag-copy (#/dragCopyCursor ns:ns-cursor)) (:drag-link (#/dragLinkCursor ns:ns-cursor)) (:ibeam (#/IBeamCursor ns:ns-cursor)) (:ibeam-for-vertical (#/IBeamCursorForVerticalLayout ns:ns-cursor)) (:open-hand (#/openHandCursor ns:ns-cursor)) (:op-not-allowed (#/operationNotAllowedCursor ns:ns-cursor)) (:pointing-hand (#/pointingHandCursor ns:ns-cursor)) (:resize-down (#/resizeDownCursor ns:ns-cursor)) (:resize-left (#/resizeLeftCursor ns:ns-cursor)) (:resize-left-right (#/resizeLeftRightCursor ns:ns-cursor)) (:resize-right (#/resizeRightCursor ns:ns-cursor)) (:resize-up (#/resizeUpCursor ns:ns-cursor)) (:resize-up-down (#/resizeUpDownCursor ns:ns-cursor))))) (defun convert-date-style (ds-key) (if (numberp ds-key) ds-key (ecase ds-key (:none #$NSDateFormatterNoStyle) (:short #$NSDateFormatterShortStyle) (:medium #$NSDateFormatterMediumStyle) (:long #$NSDateFormatterLongStyle) (:full #$NSDateFormatterFullStyle)))) (defun convert-elasticity (e-key) (if (numberp e-key) e-key (ecase e-key (:automatic #$NSScrollElasticityAutomatic) (:none #$NSScrollElasticityNone) (:allowed #$NSScrollElasticityAllowed)))) (defun convert-find-bar-position (find-key) (if (numberp find-key) find-key (ecase find-key (:above-ruler #$NSScrollViewFindBarPositionAboveHorizontalRuler) (:above-content #$NSScrollViewFindBarPositionAboveContent) (:below-content #$NSScrollViewFindBarPositionBelowContent)))) (defun convert-focus-ring-type (fr-key) (if (numberp fr-key) fr-key (ecase fr-key (:default #$NSFocusRingTypeDefault) (:none #$NSFocusRingTypeNone) (:exterior #$NSFocusRingTypeExterior)))) (defun convert-grid-style (s-key) (if (numberp s-key) s-key (ecase s-key (:none #$NSTableViewGridNone) (:solid-vertical #$NSTableViewSolidVerticalGridLineMask) (:solid-horizontal #$NSTableViewSolidHorizontalGridLineMask) (:dashed-horizontal #$NSTableViewDashedHorizontalGridLineMask)))) (defun convert-grid-styles (style) (if (listp style) (apply #'logior (mapcar #'convert-grid-style style)) (convert-grid-style style))) (defun convert-image-position (i-key) #| Together, NSCellHasImageOnLeftOrBottom, NSCellHasImageHorizontal, and NSCellHasOverlappingImage control the position of the cell’s image and text. To place the image above, set none of them. To place the image below, set NSCellHasImageOnLeftOrBottom. To place the image to the right, set NSCellHasImageHorizontal. To place the image to the left, set NSCellHasImageHorizontal and NSCellHasImageOnLeftOrBottom. To place the image directly over, set NSCellHasOverlappingImage. |# (if (numberp i-key) i-key (ecase i-key (:no-image #$NSNoImage) (:image-only #$NSImageOnly) (:image-left #$NSImageLeft) (:image-right #$NSImageRight) (:image-below #$NSImageBelow) (:image-above #$NSImageAbove) (:image-overlaps #$NSImageOverlaps)))) (defun convert-key-modifier-mask (mod-key) (cond ((listp mod-key) (apply #'logior (mapcar #'convert-key-modifier-mask mod-key))) ((numberp mod-key) mod-key) (t (ecase mod-key (:shift #$NSShiftKeyMask) (:control #$NSControlKeyMask) (:alternate #$NSAlternateKeyMask) (:option #$NSAlternateKeyMask) ;; same as alt key (:command #$NSCommandKeyMask))))) (defun convert-knob-style (k-key) (if (numberp k-key) k-key (ecase k-key (:default #$NSScrollerKnobStyleDefault) (:dark #$NSScrollerKnobStyleDark) (:light #$NSScrollerKnobStyleLight)))) (defun convert-number-style (ns-key) (if (numberp ns-key) ns-key (ecase ns-key (:none #$NSNumberFormatterNoStyle) (:decimal #$NSNumberFormatterDecimalStyle) (:currency #$NSNumberFormatterCurrencyStyle) (:percent #$NSNumberFormatterPercentStyle) (:scientific #$NSNumberFormatterScientificStyle) (:spell-out #$NSNumberFormatterSpellOutStyle)))) (defun convert-padding-position (pp-key) (if (numberp pp-key) pp-key (ecase pp-key (:before-prefix #$NSNumberFormatterPadBeforePrefix) (:after-prefix #$NSNumberFormatterPadAfterPrefix) (:before-suffix #$NSNumberFormatterPadBeforeSuffix) (:after-suffix #$NSNumberFormatterPadAfterSuffix)))) (defun convert-resizing-mask (rs-key) (cond ((listp rs-key) (apply #'logior (mapcar #'convert-resizing-mask rs-key))) ((numberp rs-key) rs-key) (t (ecase rs-key (:not-sizable #$NSViewNotSizable) (:min-x-margin #$NSViewMinXMargin) (:width-sizable #$NSViewWidthSizable) (:max-x-margin #$NSViewMaxXMargin) (:min-y-margin #$NSViewMinYMargin) (:height-sizable #$NSViewHeightSizable) (:max-y-margin #$NSViewMaxYMargin))))) (defun convert-row-size-style (rss-key) (if (numberp rss-key) rss-key (ecase rss-key (:default #$NSTableViewRowSizeStyleDefault) (:custom #$NSTableViewRowSizeStyleCustom) (:small #$NSTableViewRowSizeStyleSmall) (:medium #$NSTableViewRowSizeStyleMedium) (:large #$NSTableViewRowSizeStyleLarge)))) (defun convert-rounding-mode (rm-key) (if (numberp rm-key) rm-key (ecase rm-key (:ceiling #$NSNumberFormatterRoundCeiling) (:floor #$NSNumberFormatterRoundFloor) (:down #$NSNumberFormatterRoundDown) (:up #$NSNumberFormatterRoundUp) (:half-even #$NSNumberFormatterRoundHalfEven) (:half-down #$NSNumberFormatterRoundHalfDown) (:half-up #$NSNumberFormatterRoundHalfUp)))) (defun convert-scroller-style (style-key) (if (numberp style-key) style-key (ecase style-key (:legacy #$NSScrollerStyleLegacy) (:overlay #$NSScrollerStyleOverlay)))) (defun convert-selection-highlight-style (shs-key) (if (numberp shs-key) shs-key (ecase shs-key (:none #$NSTableViewSelectionHighlightStyleNone) (:regular #$NSTableViewSelectionHighlightStyleRegular) (:source-list #$NSTableViewSelectionHighlightStyleSourceList)))) (defun convert-sharing-type (st-key) (if (numberp st-key) st-key (ecase st-key (:none #$NSWindowSharingNone) (:read-only #$NSWindowSharingReadOnly) (:read-write #$NSWindowSharingReadWrite)))) (defun convert-state (st-key) (if (numberp st-key) st-key (ecase st-key (:on #$NSOnState) (:off #$NSOffState) (:mixed #$NSMixedState)))) (defun convert-table-col-resizing (tcr-key) (if (numberp tcr-key) tcr-key (ecase tcr-key (:none #$NSTableViewNoColumnAutoresizing) (:uniform #$NSTableViewUniformColumnAutoresizingStyle) (:sequential-column #$NSTableViewSequentialColumnAutoresizingStyle) (:reverse-sequential-column #$NSTableViewReverseSequentialColumnAutoresizingStyle) (:last-column-only #$NSTableViewLastColumnOnlyAutoresizingStyle) (:first-column-only #$NSTableViewFirstColumnOnlyAutoresizingStyle)))) (defun convert-table-drag-feedback-style (td-key) (if (numberp td-key) td-key (ecase td-key (:none #$NSTableViewDraggingDestinationFeedbackStyleNone) (:regular #$NSTableViewDraggingDestinationFeedbackStyleRegular) (:source-list #$NSTableViewDraggingDestinationFeedbackStyleSourceList)))) (defun convert-table-drag-src-op (td-key) (if (numberp td-key) td-key (ecase td-key (:none #$NSDragOperationNone) (:copy #$NSDragOperationCopy) (:link #$NSDragOperationLink) (:generic #$NSDragOperationGeneric) (:private #$NSDragOperationPrivate) (:move #$NSDragOperationMove) (:delete #$NSDragOperationDelete) (:every #$NSDragOperationEvery)))) (defun convert-text-alignment (al-key) (if (numberp al-key) al-key (ecase al-key (:left #$NSLeftTextAlignment) (:right #$NSRightTextAlignment) (:center #$NSCenterTextAlignment) (:justified #$NSJustifiedTextAlignment) (:natural #$NSNaturalTextAlignment)))) (defun convert-text-bezel-style (b-key) (if (numberp b-key) b-key (ecase b-key (:square #$NSTextFieldSquareBezel) (:rounded #$NSTextFieldRoundedBezel)))) (defun convert-text-checking-type (type) (ecase type (:all-system #$NSTextCheckingAllSystemTypes) (:all-custom #$NSTextCheckingAllCustomTypes) (:all #$NSTextCheckingAllTypes))) (defun convert-text-checking-types (types) (typecase types (number types) (keyword (convert-text-checking-type types)) (list (apply #'logior (mapcar #'convert-text-checking-type types))) (t types))) ;; let it error (defun convert-text-orientation (o-key) ;; should be one of :horizontal, :h, :vertical, or :v (if (numberp o-key) o-key (ecase o-key ((:vertical :v) #$NSTextLayoutOrientationVertical) ((:horizontal :h) #$NSTextLayoutOrientationHorizontal)))) (defun convert-title-position (tp-key) (if (numberp tp-key) tp-key (ecase tp-key (:none #$NSNoTitle) (:above-top #$NSAboveTop) (:at-top #$NSAtTop) (:below-top #$NSBelowTop) (:above-bottom #$NSAboveBottom) (:at-bottom #$NSAtBottom) (:below-bottom #$NSBelowBottom)))) (defun convert-window-backing-loc (wb-key) (if (numberp wb-key) wb-key (ecase wb-key (:default #$NSWindowBackingLocationDefault) (:video-memory #$NSWindowBackingLocationVideoMemory) (:main-memory #$NSWindowBackingLocationMainMemory)))) (defun convert-window-depth (wd-key) (if (numberp wd-key) wd-key (ecase wd-key (:rgb-24 #$NSWindowDepthTwentyfourBitRGB) (:rgb-64 #$NSWindowDepthSixtyfourBitRGB) (:rgb-128 #$NSWindowDepthOnehundredtwentyeightBitRGB)))) (defun convert-window-level (wl-key) ;; For some reason the defined constants are not in the CCL interface database, but I found ;; http://dev.dartmouth.edu/svn/softdev/email/blitz/clients/BlitzMail/tags/start/projDev%20Mac%20CIncludes/CGWindowLevel.h ;; which provided the mechanism to derive the values. (if (numberp wl-key) wl-key (ecase wl-key (:normal (#_CGWindowLevelForKey #$kCGNormalWindowLevelKey)) ;; #$NSNormalWindowLevel (:floating (#_CGWindowLevelForKey #$kCGFloatingWindowLevelKey)) ;; #$NSFloatingWindowLevel (:submenu (#_CGWindowLevelForKey #$kCGTornOffMenuWindowLevelKey)) ;; #$NSSubmenuWindowLevel (same as torn-off) (:torn-off-menu (#_CGWindowLevelForKey #$kCGTornOffMenuWindowLevelKey)) ;; #$NSTornOffMenuWindowLevel (:main-menu (#_CGWindowLevelForKey #$kCGMainMenuWindowLevelKey)) ;; #$NSMainMenuWindowLevel (:status (#_CGWindowLevelForKey #$kCGStatusWindowLevelKey)) ;; #$NSStatusWindowLevel (:modal-panel (#_CGWindowLevelForKey #$kCGModalPanelWindowLevelKey)) ;; #$NSModalPanelWindowLevel (:pop-up-menu (#_CGWindowLevelForKey #$kCGPopUpMenuWindowLevelKey)) ;; #$NSPopUpMenuWindowLevel (:screen-saver (#_CGWindowLevelForKey #$kCGScreenSaverWindowLevelKey)) ;; #$NSScreenSaverWindowLevel (:dock-window (#_CGWindowLevelForKey #$kCGDockWindowLevelKey))))) ;; #$NSDockWindowLevel (defun convert-writing-direction (wd-key) (if (numberp wd-key) wd-key (ecase wd-key (:natural #$NSWritingDirectionNatural) (:left-to-right #$NSWritingDirectionLeftToRight) (:right-to-left #$NSWritingDirectionRightToLeft)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; ns-object subclasses (defmethod initialize-instance :after ((self ns:ns-document) &key (display-name nil display-name-p) ;; string or ns:ns-string (draft nil draft-p) (has-undo-manager nil has-undo-manager-p) (print-info nil print-info-p) ;; ns:ns-print-info object (undo-manager nil undo-manager-p) ;; ns:ns-undo-manager object &allow-other-keys) (when display-name-p (#/setDisplayName: self (coerce-obj display-name 'ns:ns-string))) (when draft-p (#/setDraft: self draft)) (when has-undo-manager-p (#/setHasUndoManager: self has-undo-manager)) (when print-info-p (#/setPrintInfo: self print-info)) (when undo-manager-p (#/setUndoManager: self undo-manager))) (defmethod initialize-instance :after ((self ns:ns-menu) &key (allows-context-menu-plug-ins nil allows-context-menu-plug-ins-p) (autoenables-items nil autoenables-items-p) (delegate nil delegate-p) ;; an object that follows the NSMenuDelegate protocol (font nil font-p) ;; ns:ns-font (minimum-width nil minimum-width-p) ;; number coerceable to a double float (shows-state-column nil shows-state-column-p) (title nil title-p) ;; string, attributed-string, ns:ns-string (menu-items nil menu-items-p) ;; list of ns:ns-menu-item &allow-other-keys) (when allows-context-menu-plug-ins-p (#/setAllowsContextMenuPlugIns: self allows-context-menu-plug-ins)) (when autoenables-items-p (#/setAutoenablesItems: self autoenables-items)) (when delegate-p (#/setDelegate: self delegate)) (when font-p (#/setFont: self font)) (when minimum-width-p (#/setMinimumWidth: self (cgfloat minimum-width))) (when shows-state-column-p (#/setShowsStateColumn: self shows-state-column)) (when title-p (#/setTitle: self (coerce-obj title 'ns:ns-string))) (when menu-items-p (dolist (mi menu-items) (#/addItem: self mi)))) (defmethod initialize-instance :after ((self ns:ns-menu-item) &key (action nil action-p) ;; string or objective-c selector (alternate nil alternate-p) (attributed-title nil attributed-title-p) (enabled nil enabled-p) (hidden nil hidden-p) (image nil image-p) ;; ns:ns-image (indentation-level nil indentation-level-p) ;; integer (key-equivalent nil key-equivalent-p) ;; string, attributed-string, ns:ns-string (key-equivalent-modifier-mask nil key-equivalent-modifier-mask-p) (mixed-state-image nil mixed-state-image-p) ;; ns:ns-image (off-state-image nil off-state-image-p) ;; ns:ns-image (on-state-image nil on-state-image-p) ;; ns:ns-image (represented-object nil represented-object-p) ;; ns-ns-object (state nil state-p) ;; one of :on :off :mixed (submenu nil submenu-p) ;; ns:ns-menu (tag nil tag-p) ;; integer (target nil target-p) ;; ns-ns-object (title nil title-p) ;; string, attributed-string, ns:ns-string (tool-tip nil tool-tip-p) ;; string, attributed-string, ns:ns-string (view nil view-p) ;; ns:ns-view &allow-other-keys) (when action-p (#/setAction: self (get-selector action))) (when alternate-p (#/setAlternate: self alternate)) (when attributed-title-p (#/setAttributedTitle: self (coerce-obj attributed-title 'ns:ns-attributed-string))) (when enabled-p (#/setEnabled: self enabled)) (when hidden-p (#/setHidden: self hidden)) (when image-p (#/setImage: self image)) (when indentation-level-p (#/setIndentationLevel: self indentation-level)) (when key-equivalent-p (#/setKeyEquivalent: self (coerce-obj key-equivalent 'ns:ns-string))) (when key-equivalent-modifier-mask-p (#/setKeyEquivalentModifierMask: self (convert-key-modifier-mask key-equivalent-modifier-mask))) (when mixed-state-image-p (#/setMixedStateImage: self mixed-state-image)) (when off-state-image-p (#/setOffStateImage: self off-state-image)) (when on-state-image-p (#/setOnStateImage: self on-state-image)) (when represented-object-p (#/setRepresentedObject: self represented-object)) (when state-p (#/setState: self (convert-state state))) (when submenu-p (#/setSubmenu: self submenu)) (when tag-p (#/setTag: self tag)) (when target-p (#/setTarget: self target)) (when title-p (#/setTitle: self (coerce-obj title 'ns:ns-string))) (when tool-tip-p (#/setToolTip: self (coerce-obj tool-tip 'ns:ns-string))) (when view-p (#/setView: self view))) (defmethod initialize-instance :after ((self ns:ns-table-column) &key (column-title nil column-title-p) ;; string or ns:ns-string (data-cell nil data-cell-p) ;; ns:ns-cell (editable nil editable-p) (formatter nil formatter-p) ;; ns:ns-formatter (header-cell nil header-cell-p) ;; ns:ns-cell (header-tool-tip nil header-tool-tip-p) ;; string or ns:ns-string (hidden nil hidden-p) (identifier nil identifier-p) ;; string or ns:ns-string (max-width nil max-width-p) ;; number (min-width nil min-width-p) ;; number (resizing-mask nil resizing-mask-p) ;; number or keyword: :no-resizing :auto-resizing :user-resizing (sort-descriptor-prototype nil sort-descriptor-prototype-p) ;; ns:ns-sort-descriptor (width nil width-p) ;; number (wraps nil wraps-p) &allow-other-keys) (when column-title-p (#/setStringValue: (#/headerCell self) (coerce-obj column-title 'ns:ns-string))) (when data-cell-p (#/setDataCell: self data-cell)) (when editable-p (#/setEditable: self editable)) (when formatter-p (#/setFormatter: (#/dataCell self) formatter)) (when header-cell-p (#/setHeaderCell: self header-cell)) (when header-tool-tip-p (#/setHeaderToolTip: self (coerce-obj header-tool-tip 'ns:ns-string))) (when hidden-p (#/setHidden: self hidden)) (when identifier-p (#/setIdentifier: self (coerce-obj identifier 'ns:ns-string))) (when max-width-p (#/setMaxWidth: self (cgfloat max-width))) (when min-width-p (#/setMinWidth: self (cgfloat min-width))) (when resizing-mask-p (#/setResizingMask: self (convert-column-resizing resizing-mask))) (when sort-descriptor-prototype-p (#/setSortDescriptorPrototype: self sort-descriptor-prototype)) (when width-p (#/setWidth: self (cgfloat width))) (when wraps-p (#/setWraps: (#/dataCell self) wraps))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; ns-formatter subclasses (defmethod initialize-instance :after ((self ns:ns-date-formatter) &key (calendar nil calendar-p) ;; ns:ns-calendar (date-format nil date-format-p) ;; string or ns:ns-string (date-style nil date-style-p) ;; number or keyword: :none :short :medium :long :full (default-date nil default-date-p) ;; lisp date or ns:ns-date (does-relative-date-formatting nil does-relative-date-formatting-p) (era-symbols nil era-symbols-p) ;; list of strings or ns:ns-string objects (gregorian-start-date nil gregorian-start-date-p) ;; lisp date or ns:ns-date (lenient nil lenient-p) (locale nil locale-p) ;; ns:ns-locale (long-era-symbols nil long-era-symbols-p) ;; list of strings or ns:ns-string objects (month-symbols nil month-symbols-p) ;; list of strings or ns:ns-string objects (pm-symbol nil pm-symbol-p) ;; string or ns:ns-string (quarter-symbols nil quarter-symbols-p) ;; list of strings or ns:ns-string objects (short-month-symbols nil short-month-symbols-p) ;; list of strings or ns:ns-string objects (short-quarter-symbols nil short-quarter-symbols-p) ;; list of strings or ns:ns-string objects (short-standalone-month-symbols nil short-standalone-month-symbols-p) ;; list of strings or ns:ns-string objects (short-standalone-quarter-symbols nil short-standalone-quarter-symbols-p) ;; list of strings or ns:ns-string objects (short-standalone-weekday-symbols nil short-standalone-weekday-symbols-p) ;; list of strings or ns:ns-string objects (short-weekday-symbols nil short-weekday-symbols-p) ;; list of strings or ns:ns-string objects (standalone-month-symbols nil standalone-month-symbols-p) ;; list of strings or ns:ns-string objects (standalone-quarter-symbols nil standalone-quarter-symbols-p) ;; list of strings or ns:ns-string objects (standalone-weekday-symbols nil standalone-weekday-symbols-p) ;; list of strings or ns:ns-string objects (time-style nil time-style-p) ;; number or keyword: :none :short :medium :long :full (time-zone nil time-zone-p) ;; ns:ns-time-zone (two-digit-start-date nil two-digit-start-date-p) ;; lisp date or ns:ns-date (very-short-month-symbols nil very-short-month-symbols-p) ;; list of strings or ns:ns-string objects (very-short-standalone-month-symbols nil very-short-standalone-month-symbols-p) ;; list of strings or ns:ns-string objects (very-short-standalone-weekday-symbols nil very-short-standalone-weekday-symbols-p) ;; list of strings or ns:ns-string objects (very-short-weekday-symbols nil very-short-weekday-symbols-p) ;; list of strings or ns:ns-string objects (weekday-symbols nil weekday-symbols-p) ;; list of strings or ns:ns-string objects &allow-other-keys) (when calendar-p (#/setCalendar: self calendar)) (when date-format-p (#/setDateFormat: self (coerce-obj date-format 'ns:ns-string))) (when date-style-p (#/setDateStyle: self (convert-date-style date-style))) (when default-date-p (#/setDefaultDate: self (coerce-obj default-date 'ns:ns-date))) (when does-relative-date-formatting-p (#/setDoesRelativeDateFormatting: self does-relative-date-formatting)) (when era-symbols-p (#/setEraSymbols: self (coerce-obj era-symbols 'ns:ns-array))) (when gregorian-start-date-p (#/setGregorianStartDate: self (coerce-obj gregorian-start-date 'ns:ns-date))) (when lenient-p (#/setLenient: self lenient)) (when locale-p (#/setLocale: self locale)) (when long-era-symbols-p (#/setLongEraSymbols: self (coerce-obj long-era-symbols 'ns:ns-array))) (when month-symbols-p (#/setMonthSymbols: self (coerce-obj month-symbols 'ns:ns-array))) (when pm-symbol-p (#/setPMSymbol: self (coerce-obj pm-symbol 'ns:ns-string))) (when quarter-symbols-p (#/setQuarterSymbols: self (coerce-obj quarter-symbols 'ns:ns-array))) (when short-month-symbols-p (#/setShortMonthSymbols: self (coerce-obj short-month-symbols 'ns:ns-array))) (when short-quarter-symbols-p (#/setShortQuarterSymbols: self (coerce-obj short-quarter-symbols 'ns:ns-array))) (when short-standalone-month-symbols-p (#/setShortStandaloneMonthSymbols: self (coerce-obj short-standalone-month-symbols 'ns:ns-array))) (when short-standalone-quarter-symbols-p (#/setShortStandaloneQuarterSymbols: self (coerce-obj short-standalone-quarter-symbols 'ns:ns-array))) (when short-standalone-weekday-symbols-p (#/setShortStandaloneWeekdaySymbols: self (coerce-obj short-standalone-weekday-symbols 'ns:ns-array))) (when short-weekday-symbols-p (#/setShortWeekdaySymbols: self (coerce-obj short-weekday-symbols 'ns:ns-array))) (when standalone-month-symbols-p (#/setStandaloneMonthSymbols: self (coerce-obj standalone-month-symbols 'ns:ns-array))) (when standalone-quarter-symbols-p (#/setStandaloneQuarterSymbols: self (coerce-obj standalone-quarter-symbols 'ns:ns-array))) (when standalone-weekday-symbols-p (#/setStandaloneWeekdaySymbols: self (coerce-obj standalone-weekday-symbols 'ns:ns-array))) (when time-style-p (#/setTimeStyle: self (convert-date-style time-style))) ;; date and time use same constants (when time-zone-p (#/setTimeZone: self time-zone)) (when two-digit-start-date-p (#/setTwoDigitStartDate: self (coerce-obj two-digit-start-date 'ns:ns-date))) (when very-short-month-symbols-p (#/setVeryShortMonthSymbols: self (coerce-obj very-short-month-symbols 'ns:ns-array))) (when very-short-standalone-month-symbols-p (#/setVeryShortStandaloneMonthSymbols: self (coerce-obj very-short-standalone-month-symbols 'ns:ns-array))) (when very-short-standalone-weekday-symbols-p (#/setVeryShortStandaloneWeekdaySymbols: self (coerce-obj very-short-standalone-weekday-symbols 'ns:ns-array))) (when very-short-weekday-symbols-p (#/setVeryShortWeekdaySymbols: self (coerce-obj very-short-weekday-symbols 'ns:ns-array))) (when weekday-symbols-p (#/setWeekdaySymbols: self (coerce-obj weekday-symbols 'ns:ns-array)))) (defmethod initialize-instance :after ((self ns:ns-number-formatter) &key (allows-floats nil allows-floats-p) (always-shows-decimal-separator nil always-shows-decimal-separator-p) (attributed-string-for-nil nil attributed-string-for-nil-p) ;; string attributed-string ns:ns-string or ns:ns-attributed-string (attributed-string-for-not-a-number nil attributed-string-for-not-a-number-p) ;; string attributed-string ns:ns-string or ns:ns-attributed-string (attributed-string-for-zero nil attributed-string-for-zero-p) ;; string attributed-string ns:ns-string or ns:ns-attributed-string (currency-decimal-separator nil currency-decimal-separator-p) ;; string or ns:ns-string (currency-grouping-separator nil currency-grouping-separator-p) ;; string or ns:ns-string (currency-symbol nil currency-symbol-p) ;; string or ns:ns-string (decimal-separator nil decimal-separator-p) ;; string or ns:ns-string (exponent-symbol nil exponent-symbol-p) ;; string or ns:ns-string (format nil format-p) ;; string or ns:ns-string (format-width nil format-width-p) ;; integer (generates-decimal-numbers nil generates-decimal-numbers-p) (grouping-separator nil grouping-separator-p) ;; string or ns:ns-string (grouping-size nil grouping-size-p) ;; integer (has-thousand-separators nil has-thousand-separators-p) (international-currency-symbol nil international-currency-symbol-p) ;; string or ns:ns-string (lenient nil lenient-p) (locale nil locale-p) ;; ns:ns-locale (localizes-format nil localizes-format-p) (maximum nil maximum-p) ;; number (maximum-fraction-digits nil maximum-fraction-digits-p) ;; integer (maximum-integer-digits nil maximum-integer-digits-p) ;; integer (maximum-significant-digits nil maximum-significant-digits-p) ;; integer (minimum nil minimum-p) ;; number (minimum-fraction-digits nil minimum-fraction-digits-p) ;; integer (minimum-integer-digits nil minimum-integer-digits-p) ;; integer (minimum-significant-digits nil minimum-significant-digits-p) ;; integer (minus-sign nil minus-sign-p) ;; string or ns:ns-string (multiplier nil multiplier-p) ;; number (negative-format nil negative-format-p) ;; string or ns:ns-string (negative-infinity-symbol nil negative-infinity-symbol-p) ;; string or ns:ns-string (negative-prefix nil negative-prefix-p) ;; string or ns:ns-string (negative-suffix nil negative-suffix-p) ;; string or ns:ns-string (nil-symbol nil nil-symbol-p) ;; string or ns:ns-string (not-a-number-symbol nil not-a-number-symbol-p) ;; string or ns:ns-string (number-style nil number-style-p) ;; number or keyword: :none :decimal :currency :percent :scientific :spell-out (padding-character nil padding-character-p) ;; string or ns:ns-string (padding-position nil padding-position-p) ;; number or keyword: :before-prefix :after-prefix :before-suffix :after-suffix (partial-string-validation-enabled nil partial-string-validation-enabled-p) (percent-symbol nil percent-symbol-p) ;; string or ns:ns-string (per-mill-symbol nil per-mill-symbol-p) ;; string or ns:ns-string (plus-sign nil plus-sign-p) ;; string or ns:ns-string (positive-format nil positive-format-p) ;; string or ns:ns-string (positive-infinity-symbol nil positive-infinity-symbol-p) ;; string or ns:ns-string (positive-prefix nil positive-prefix-p) ;; string or ns:ns-string (positive-suffix nil positive-suffix-p) ;; string or ns:ns-string (rounding-behavior nil rounding-behavior-p) ;; ns:ns-decimal-number-handler (rounding-increment nil rounding-increment-p) ;; number (rounding-mode nil rounding-mode-p) ;; number or keyword: :ceiling :floor :down :up :half-even :half-down :half-up (secondary-grouping-size nil secondary-grouping-size-p) ;; integer (text-attributes-for-negative-infinity nil text-attributes-for-negative-infinity-p) ;; assoc-list, hash-table, or ns:ns-dictionary of attribute-value pairs (text-attributes-for-negative-values nil text-attributes-for-negative-values-p) ;; assoc-list, hash-table, or ns:ns-dictionary of attribute-value pairs (text-attributes-for-nil nil text-attributes-for-nil-p) ;; assoc-list, hash-table, or ns:ns-dictionary of attribute-value pairs (text-attributes-for-not-a-number nil text-attributes-for-not-a-number-p) ;; assoc-list, hash-table, or ns:ns-dictionary of attribute-value pairs (text-attributes-for-positive-infinity nil text-attributes-for-positive-infinity-p) ;; assoc-list, hash-table, or ns:ns-dictionary of attribute-value pairs (text-attributes-for-positive-values nil text-attributes-for-positive-values-p) ;; assoc-list, hash-table, or ns:ns-dictionary of attribute-value pairs (text-attributes-for-zero nil text-attributes-for-zero-p) ;; assoc-list, hash-table, or ns:ns-dictionary of attribute-value pairs (thousand-separator nil thousand-separator-p) ;; string or ns:ns-string (uses-grouping-separator nil uses-grouping-separator-p) (uses-significant-digits nil uses-significant-digits-p) (zero-symbol nil zero-symbol-p) ;; string or ns:ns-string &allow-other-keys) ;; set basic style first, permitting modifications with other keywords (when number-style-p (#/setNumberStyle: self (convert-number-style number-style))) (when allows-floats-p (#/setAllowsFloats: self allows-floats)) (when always-shows-decimal-separator-p (#/setAlwaysShowsDecimalSeparator: self always-shows-decimal-separator)) (when attributed-string-for-nil-p (#/setAttributedStringForNil: self (coerce-obj attributed-string-for-nil 'ns:ns-attributed-string))) (when attributed-string-for-not-a-number-p (#/setAttributedStringForNotANumber: self (coerce-obj attributed-string-for-not-a-number 'ns:ns-attributed-string))) (when attributed-string-for-zero-p (#/setAttributedStringForZero: self (coerce-obj attributed-string-for-zero 'ns:ns-attributed-string))) (when currency-decimal-separator-p (#/setCurrencyDecimalSeparator: self (coerce-obj currency-decimal-separator 'ns:ns-string))) (when currency-grouping-separator-p (#/setCurrencyGroupingSeparator: self (coerce-obj currency-grouping-separator 'ns:ns-string))) (when currency-symbol-p (#/setCurrencySymbol: self (coerce-obj currency-symbol 'ns:ns-string))) (when decimal-separator-p (#/setDecimalSeparator: self (coerce-obj decimal-separator 'ns:ns-string))) (when exponent-symbol-p (#/setExponentSymbol: self (coerce-obj exponent-symbol 'ns:ns-string))) (when format-p (#/setFormat: self (coerce-obj format 'ns:ns-string))) (when format-width-p (#/setFormatWidth: self (coerce format-width 'integer))) (when generates-decimal-numbers-p (#/setGeneratesDecimalNumbers: self generates-decimal-numbers)) (when grouping-separator-p (#/setGroupingSeparator: self (coerce-obj grouping-separator 'ns:ns-string))) (when grouping-size-p (#/setGroupingSize: self (coerce grouping-size 'integer))) (when has-thousand-separators-p (#/setHasThousandSeparators: self has-thousand-separators)) (when international-currency-symbol-p (#/setInternationalCurrencySymbol: self (coerce-obj international-currency-symbol 'ns:ns-string))) (when lenient-p (#/setLenient: self lenient)) (when locale-p (#/setLocale: self locale)) (when localizes-format-p (#/setLocalizesFormat: self localizes-format)) (when maximum-p (#/setMaximum: self (coerce-obj maximum 'ns:ns-number))) (when maximum-fraction-digits-p (#/setMaximumFractionDigits: self (coerce maximum-fraction-digits 'integer))) (when maximum-integer-digits-p (#/setMaximumIntegerDigits: self (coerce maximum-integer-digits 'integer))) (when maximum-significant-digits-p (#/setMaximumSignificantDigits: self (coerce maximum-significant-digits 'integer))) (when minimum-p (#/setMinimum: self (coerce-obj minimum 'ns:ns-number))) (when minimum-fraction-digits-p (#/setMinimumFractionDigits: self (coerce minimum-fraction-digits 'integer))) (when minimum-integer-digits-p (#/setMinimumIntegerDigits: self (coerce minimum-integer-digits 'integer))) (when minimum-significant-digits-p (#/setMinimumSignificantDigits: self (coerce minimum-significant-digits 'integer))) (when minus-sign-p (#/setMinusSign: self (coerce-obj minus-sign 'ns:ns-string))) (when multiplier-p (#/setMultiplier: self (coerce-obj multiplier 'ns:ns-number))) (when negative-format-p (#/setNegativeFormat: self (coerce-obj negative-format 'ns:ns-string))) (when negative-infinity-symbol-p (#/setNegativeInfinitySymbol: self (coerce-obj negative-infinity-symbol 'ns:ns-string))) (when negative-prefix-p (#/setNegativePrefix: self (coerce-obj negative-prefix 'ns:ns-string))) (when negative-suffix-p (#/setNegativeSuffix: self (coerce-obj negative-suffix 'ns:ns-string))) (when nil-symbol-p (#/setNilSymbol: self (coerce-obj nil-symbol 'ns:ns-string))) (when not-a-number-symbol-p (#/setNotANumberSymbol: self (coerce-obj not-a-number-symbol 'ns:ns-string))) (when padding-character-p (#/setPaddingCharacter: self (coerce-obj padding-character 'ns:ns-string))) (when padding-position-p (#/setPaddingPosition: self (convert-padding-position padding-position))) (when partial-string-validation-enabled-p (#/setPartialStringValidationEnabled: self partial-string-validation-enabled)) (when percent-symbol-p (#/setPercentSymbol: self (coerce-obj percent-symbol 'ns:ns-string))) (when per-mill-symbol-p (#/setPerMillSymbol: self (coerce-obj per-mill-symbol 'ns:ns-string))) (when plus-sign-p (#/setPlusSign: self (coerce-obj plus-sign 'ns:ns-string))) (when positive-format-p (#/setPositiveFormat: self (coerce-obj positive-format 'ns:ns-string))) (when positive-infinity-symbol-p (#/setPositiveInfinitySymbol: self (coerce-obj positive-infinity-symbol 'ns:ns-string))) (when positive-prefix-p (#/setPositivePrefix: self (coerce-obj positive-prefix 'ns:ns-string))) (when positive-suffix-p (#/setPositiveSuffix: self (coerce-obj positive-suffix 'ns:ns-string))) (when rounding-behavior-p (#/setRoundingBehavior: self rounding-behavior)) (when rounding-increment-p (#/setRoundingIncrement: self (coerce-obj rounding-increment 'ns:ns-number))) (when rounding-mode-p (#/setRoundingMode: self (convert-rounding-mode rounding-mode))) (when secondary-grouping-size-p (#/setSecondaryGroupingSize: self (coerce secondary-grouping-size 'integer))) (when text-attributes-for-negative-infinity-p (#/setTextAttributesForNegativeInfinity: self (coerce-obj text-attributes-for-negative-infinity 'ns:ns-dictionary))) (when text-attributes-for-negative-values-p (#/setTextAttributesForNegativeValues: self (coerce-obj text-attributes-for-negative-values 'ns:ns-dictionary))) (when text-attributes-for-nil-p (#/setTextAttributesForNil: self (coerce-obj text-attributes-for-nil 'ns:ns-dictionary))) (when text-attributes-for-not-a-number-p (#/setTextAttributesForNotANumber: self (coerce-obj text-attributes-for-not-a-number 'ns:ns-dictionary))) (when text-attributes-for-positive-infinity-p (#/setTextAttributesForPositiveInfinity: self (coerce-obj text-attributes-for-positive-infinity 'ns:ns-dictionary))) (when text-attributes-for-positive-values-p (#/setTextAttributesForPositiveValues: self (coerce-obj text-attributes-for-positive-values 'ns:ns-dictionary))) (when text-attributes-for-zero-p (#/setTextAttributesForZero: self (coerce-obj text-attributes-for-zero 'ns:ns-dictionary))) (when thousand-separator-p (#/setThousandSeparator: self (coerce-obj thousand-separator 'ns:ns-string))) (when uses-grouping-separator-p (#/setUsesGroupingSeparator: self uses-grouping-separator)) (when uses-significant-digits-p (#/setUsesSignificantDigits: self uses-significant-digits)) (when zero-symbol-p (#/setZeroSymbol: self (coerce-obj zero-symbol 'ns:ns-string)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; ns-responder subclasses (defmethod initialize-instance :after ((self ns:ns-view) &key (accepts-touch-events nil accepts-touch-events-p) (alpha-value 0 alpha-value-p) (animations nil animations-p) (autoresizes-subviews nil autoresizes-subviews-p) (autoresizing-mask 0 autoresizing-mask-p) ;; number or list of resizing keys: see convert-resizing-mask (bounds 0 bounds-p) ;; ns:ns-rectangle or list: (x y width height) (bounds-origin 0 bounds-origin-p) ;; ns:ns-point or list: (x y) (bounds-rotation 0 bounds-rotation-p) ;; angle in degrees (bounds-size 0 bounds-size-p) ;; ns:ns-size or list: (width height) (can-draw-concurrently nil can-draw-concurrently-p) (focus-ring-type nil focus-ring-type-p) ;; number or keyword: see convert-focus-ring-type (frame nil frame-p) ;; ns:ns-rect (frame-center-rotation nil frame-center-rotation-p) ;; angle in degrees (frame-origin nil frame-origin-p) ;; ns:ns-point or list: (x y) (frame-rotation nil frame-rotation-p) ;; angle in degrees (frame-size nil frame-size-p) ;; ns:ns-size or list: (width height) (hidden nil hidden-p) (layer nil layer-p) ;; CALayer (posts-bounds-changed-notifications nil posts-bounds-changed-notifications-p) (posts-frame-changed-notifications nil posts-frame-changed-notifications-p) (shadow nil shadow-p) ;; ns:ns-shadow (subviews nil subviews-p) ;; list of subviews (tool-tip "" tool-tip-p) ;; string (wants-resting-touches nil wants-resting-touches-p) &allow-other-keys) (when accepts-touch-events-p (#/setAcceptsTouchEvents: self accepts-touch-events)) (when alpha-value-p (#/setAlphaValue: self (cgfloat alpha-value))) (when animations-p (#/setAnimations: self (coerce-obj animations 'ns:ns-dictionary))) (when autoresizes-subviews-p (#/setAutoresizesSubviews: self autoresizes-subviews)) (when autoresizing-mask-p (#/setAutoresizingMask: self (convert-resizing-mask autoresizing-mask))) (when bounds-p (#/setBounds: self (coerce-obj bounds 'ns:ns-rect))) (when bounds-origin-p (#/setBoundsOrigin: self (coerce-obj bounds-origin 'ns:ns-point))) (when bounds-rotation-p (#/setBoundsRotation: self (cgfloat bounds-rotation))) (when bounds-size-p (#/setBoundsSize: self (coerce-obj bounds-size 'ns:ns-size))) (when can-draw-concurrently-p (#/setCanDrawConcurrently: self can-draw-concurrently)) (when focus-ring-type-p (#/setFocusRingType: self (convert-focus-ring-type focus-ring-type))) (when frame-p (#/setFrame: self (coerce-obj frame 'ns:ns-rect))) (when frame-center-rotation-p (#/setFrameCenterRotation: self (cgfloat frame-center-rotation))) (when frame-origin-p (#/setFrameOrigin: self (coerce-obj frame-origin 'ns:ns-point))) (when frame-rotation-p (#/setFrameRotation: self (cgfloat frame-rotation))) (when frame-size-p (#/setFrameSize: self (coerce-obj frame-size 'ns:ns-size))) (when hidden-p (#/setHidden: self hidden)) (when layer-p (#/setLayer: self layer)) (when posts-bounds-changed-notifications-p (#/setPostsBoundsChangedNotifications: self posts-bounds-changed-notifications)) (when posts-frame-changed-notifications-p (#/setPostsFrameChangedNotifications: self posts-frame-changed-notifications)) (when shadow-p (#/setShadow: self shadow)) (when subviews-p (#/setSubviews: self (coerce-obj subviews 'ns:ns-array))) (when tool-tip-p (#/setToolTip: self (coerce-obj tool-tip 'ns:ns-string))) (when wants-resting-touches-p (#/setWantsRestingTouches: self wants-resting-touches))) (defmethod initialize-instance :after ((self ns:ns-window) &key (accepts-mouse-moved-events nil accepts-mouse-moved-events-p) (allows-concurrent-view-drawing nil allows-concurrent-view-drawing-p) (allows-tool-tips-when-application-is-inactive nil allows-tool-tips-when-application-is-inactive-p) (alpha-value 0 alpha-value-p) (animation-behavior nil animation-behavior-p) ;; number or keyword: see convert-animation-behavior (aspect-ratio nil aspect-ratio-p) ;; ns:ns-size or list: (width height) (autodisplay nil autodisplay-p) (background-color nil background-color-p) ;; ns:ns-color or keyword acceptable to (coerce-obj <keyword> 'ns:ns-color) (can-become-visible-without-login nil can-become-visible-without-login-p) (can-hide nil can-hide-p) (collection-behavior nil collection-behavior-p) ;; number, keyword, or list of keywords: see convert-collection-bahavior (color-space nil color-space-p) ;; ns:ns-color-space (content-aspect-ratio nil content-aspect-ratio-p) ;; ns:ns-size or list: (width height) (content-max-size nil content-max-size-p) ;; ns:ns-size or list: (width height) (content-min-size nil content-min-size-p) (content-resize-increments nil content-resize-increments-p) ;; ns:ns-size or list: (width height) (content-size nil content-size-p) ;; ns:ns-size or list: (width height) (content-view nil content-view-p) ;; ns:ns-view (content-subviews nil content-subviews-p) ;; a list of subviews to add to the window's content view (default-button-cell nil default-button-cell-p) ;; ns:ns-button-cell (delegate nil delegate-p) ;; ns:ns-object (depth-limit nil depth-limit-p) ;; number or keyword: :rgb-24, :rgb-64 or :rgb-128 (displays-when-screen-profile-changes nil displays-when-screen-profile-changes-p) (dynamic-depth-limit nil dynamic-depth-limit-p) ;; t or nil (excluded-from-windows-menu nil excluded-from-windows-menu-p) (frame nil frame-p) ;; ns:ns-rect or (frame-autosave-name nil frame-autosave-name-p) ;; string or ns:ns-string (frame-from-string nil frame-from-string-p) ;; string or ns:ns-string (frame-origin nil frame-origin-p) ;; ns-point or list: (x y) (frame-top-left-point nil frame-top-left-point-p) ;; ns-point or list: (x y) (frame-using-name nil frame-using-name-p) ;; string or ns:ns-string (has-shadow nil has-shadow-p) (hides-on-deactivate nil hides-on-deactivate-p) (ignores-mouse-events nil ignores-mouse-events-p) (initial-first-responder nil initial-first-responder-p) ;; ns:ns-view (level nil level-p) ;; number or keyword: see convert-window-level (max-size nil max-size-p) ;; ns:ns-size or list: (width height) (miniwindow-image nil miniwindow-image-p) ;; ns:ns-image (miniwindow-title nil miniwindow-title-p) ;; string or ns:ns-string (min-size nil min-size-p) ;; ns:ns-size or list: (width height) (movable nil movable-p) (movable-by-window-background nil movable-by-window-background-p) (one-shot nil one-shot-p) (opaque nil opaque-p) (preferred-backing-location nil preferred-backing-location-p) ;; number or keyword: :default :video-memory :main-memory (preserves-content-during-live-resize nil preserves-content-during-live-resize-p) (prevents-application-termination-when-modal nil prevents-application-termination-when-modal-p) (released-when-closed nil released-when-closed-p) (represented-filename nil represented-filename-p) ;; string or ns:ns-string (represented-url nil represented-url-p) ;; ns:ns-url (resize-increments nil resize-increments-p) ;; ns-size or list: (width height) (restorable nil restorable-p) (restoration-class nil restoration-class-p) ;; class that conforms to the NSWindowRestoration protocol (sharing-type nil sharing-type-p) ;; number or keyword: see convert-sharing-type (shows-resize-indicator nil shows-resize-indicator-p) (shows-toolbar-button nil shows-toolbar-button-p) (titled t titled-p) (closable t closable-p) (resizable t resizable-p) (miniaturizable t miniaturizable-p) (title nil title-p) ;; string or ns:ns-string (title-with-represented-filename nil title-with-represented-filename-p) ;; string or ns:ns-string (toolbar nil toolbar-p) ;; ns:ns-toolbar (window-controller nil window-controller-p) ;; ns:ns-window-controller &allow-other-keys) (when accepts-mouse-moved-events-p (#/setAcceptsMouseMovedEvents: self accepts-mouse-moved-events)) (when allows-concurrent-view-drawing-p (#/setAllowsConcurrentViewDrawing: self allows-concurrent-view-drawing)) (when allows-tool-tips-when-application-is-inactive-p (#/setAllowsToolTipsWhenApplicationIsInactive: self allows-tool-tips-when-application-is-inactive)) (when alpha-value-p (#/setAlphaValue: self (cgfloat alpha-value))) (when animation-behavior-p (#/setAnimationBehavior: self (convert-animation-behavior animation-behavior))) (when aspect-ratio-p (#/setAspectRatio: self (coerce-obj aspect-ratio 'ns:ns-size))) (when autodisplay-p (#/setAutodisplay: self autodisplay)) (when background-color-p (#/setBackgroundColor: self (coerce-obj background-color 'ns:ns-color))) (when can-become-visible-without-login-p (#/setCanBecomeVisibleWithoutLogin: self can-become-visible-without-login)) (when can-hide-p (#/setCanHide: self can-hide)) (when collection-behavior-p (#/setCollectionBehavior: self (convert-collection-behavior collection-behavior))) (when color-space-p (#/setColorSpace: self color-space)) (when content-aspect-ratio-p (#/setContentAspectRatio: self (coerce-obj content-aspect-ratio 'ns:ns-size))) (when content-max-size-p (#/setContentMaxSize: self (coerce-obj content-max-size 'ns:ns-size))) (when content-min-size-p (#/setContentMinSize: self (coerce-obj content-min-size 'ns:ns-size))) (when content-resize-increments-p (#/setContentResizeIncrements: self (coerce-obj content-resize-increments 'ns:ns-size))) (when content-size-p (#/setContentSize: self (coerce-obj content-size 'ns:ns-size))) (when content-view-p (#/setContentView: self content-view)) (when content-subviews-p (let ((cv (#/contentView self))) (dolist (sv content-subviews) (#/addSubview: cv sv)))) (when default-button-cell-p (#/setDefaultButtonCell: self default-button-cell)) (when delegate-p (#/setDelegate: self delegate)) (when depth-limit-p (#/setDepthLimit: self (convert-window-depth depth-limit))) (when displays-when-screen-profile-changes-p (#/setDisplaysWhenScreenProfileChanges: self displays-when-screen-profile-changes)) (when dynamic-depth-limit-p (#/setDynamicDepthLimit: self dynamic-depth-limit)) (when excluded-from-windows-menu-p (#/setExcludedFromWindowsMenu: self excluded-from-windows-menu)) (when frame-p (#/setFrame:display: self (coerce-obj frame 'ns:ns-rect) #$NO)) (when frame-autosave-name-p (#/setFrameAutosaveName: self (coerce-obj frame-autosave-name 'ns:ns-string))) (when frame-from-string-p (#/setFrameFromString: self (coerce-obj frame-from-string 'ns:ns-string))) (when frame-origin-p (#/setFrameOrigin: self (coerce-obj frame-origin 'ns:ns-point))) (when frame-top-left-point-p (#/setFrameTopLeftPoint: self (coerce-obj frame-top-left-point 'ns:ns-point))) (when frame-using-name-p (#/setFrameUsingName: self (coerce-obj frame-using-name 'ns:ns-string))) (when has-shadow-p (#/setHasShadow: self has-shadow)) (when hides-on-deactivate-p (#/setHidesOnDeactivate: self hides-on-deactivate)) (when ignores-mouse-events-p (#/setIgnoresMouseEvents: self ignores-mouse-events)) (when initial-first-responder-p (#/setInitialFirstResponder: self initial-first-responder)) (when level-p (#/setLevel: self (convert-window-level level))) (when max-size-p (#/setMaxSize: self (coerce-obj max-size 'ns:ns-size))) (when miniwindow-image-p (#/setMiniwindowImage: self miniwindow-image)) (when miniwindow-title-p (#/setMiniwindowTitle: self (coerce-obj miniwindow-title 'ns:ns-string))) (when min-size-p (#/setMinSize: self (coerce-obj min-size 'ns:ns-size))) (when movable-p (#/setMovable: self movable)) (when movable-by-window-background-p (#/setMovableByWindowBackground: self movable-by-window-background)) (when one-shot-p (#/setOneShot: self one-shot)) (when opaque-p (#/setOpaque: self opaque)) (when preferred-backing-location-p (#/setPreferredBackingLocation: self (convert-window-backing-loc preferred-backing-location))) (when preserves-content-during-live-resize-p (#/setPreservesContentDuringLiveResize: self preserves-content-during-live-resize)) (when prevents-application-termination-when-modal-p (#/setPreventsApplicationTerminationWhenModal: self prevents-application-termination-when-modal)) (when released-when-closed-p (#/setReleasedWhenClosed: self released-when-closed)) (when represented-filename-p (#/setRepresentedFilename: self (coerce-obj represented-filename 'ns:ns-string))) (when represented-url-p (#/setRepresentedURL: self represented-url)) (when resize-increments-p (#/setResizeIncrements: self (coerce-obj resize-increments 'ns:ns-size))) (when restorable-p (#/setRestorable: self restorable)) (when restoration-class-p (#/setRestorationClass: self restoration-class)) (when sharing-type-p (#/setSharingType: self (convert-sharing-type sharing-type))) (when shows-resize-indicator-p (#/setShowsResizeIndicator: self shows-resize-indicator)) (when (or titled-p closable-p resizable-p miniaturizable-p) (#/setStyleMask: self (+ (if titled #$NSTitledWindowMask 0) (if closable #$NSClosableWindowMask 0) (if resizable #$NSResizableWindowMask 0) (if miniaturizable #$NSMiniaturizableWindowMask 0)))) (when (and title-p title) ;; need the title check for back compatibility with initialize-instance :after method ;; defined in cocoa-window.lisp which this will replace (#/setTitle: self (coerce-obj title 'ns:ns-string))) (when title-with-represented-filename-p (#/setTitleWithRepresentedFilename: self (coerce-obj title-with-represented-filename 'ns:ns-string))) (when toolbar-p (#/setToolbar: self toolbar)) (when shows-toolbar-button-p (#/setShowsToolbarButton: self shows-toolbar-button)) (when window-controller-p (#/setWindowController: self window-controller))) (defmethod initialize-instance :after ((self ns:ns-window-controller) &key (window nil window-p) &allow-other-keys) (when window-p (#/initWithWindow: self window))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; ns-view subclasses (defmethod initialize-instance :after ((self ns:ns-box) &key (border-color nil border-color-p) ;; ns:ns-color or keyword (border-type nil border-type-p) ;; number or keyword (border-width nil border-width-p) ;; number (box-type nil box-type-p) ;; number or keyword (content-view nil content-view-p) ;; ns:ns-view (content-view-margins nil content-view-margins-p) ;; ns:ns-size or list of the form (width height) (corner-radius nil corner-radius-p) ;; number (fill-color nil fill-color-p) ;; ns:ns-color or keyword (title nil title-p) ;; string, ns:ns-string (title-font nil title-font-p) ;; ns:ns-font (title-position nil title-position-p) ;; title-position keyword (transparent nil transparent-p) &allow-other-keys) (when border-color-p (#/setBorderColor: self (coerce-obj border-color 'ns:ns-color))) (when border-type-p (#/setBorderType: self (convert-border border-type))) (when border-width-p (#/setBorderWidth: self (cgfloat border-width))) (when box-type-p (#/setBoxType: self (convert-box-type box-type))) (when content-view-p (#/setContentView: self content-view)) (when content-view-margins-p (#/setContentViewMargins: self (coerce-obj content-view-margins 'ns:ns-size)) (#/sizeToFit self)) (when corner-radius-p (#/setCornerRadius: self (cgfloat corner-radius))) (when fill-color-p (#/setFillColor: self (coerce-obj fill-color 'ns:ns-color))) (when title-p (#/setTitle: self (coerce-obj title 'ns:ns-string))) (when title-font-p (#/setTitleFont: self title-font)) (when title-position-p (#/setTitlePosition: self (convert-title-position title-position))) (when transparent-p (#/setTransparent: self transparent))) (defmethod initialize-instance :after ((self ns:ns-combo-box) &key (button-bordered nil button-bordered-p) (completes nil completes-p) (data-source nil data-source-p) ;; object that conforms to the NSComboBoxDataSource protocol (delegate nil delegate-p) ;; object that conforms to the NSComboBoxDelegate protocol (has-vertical-scroller nil has-vertical-scroller-p) (intercell-spacing nil intercell-spacing-p) ;; ns:ns-size or list of the form (width height) (item-height nil item-height-p) ;; number coercable to a double-float (items-with-object-values nil items-with-object-values-p) ;; list of strings or numbers (number-of-visible-items nil number-of-visible-items-p) ;; integer number (uses-data-source nil uses-data-source-p) &allow-other-keys) (when button-bordered-p (#/setButtonBordered: self button-bordered)) (when completes-p (#/setCompletes: self completes)) (when uses-data-source-p ;; must come before data-source (#/setUsesDataSource: self uses-data-source)) (when data-source-p (#/setDataSource: self data-source)) (when delegate-p (#/setDelegate: self delegate)) (when has-vertical-scroller-p (#/setHasVerticalScroller: self has-vertical-scroller)) (when intercell-spacing-p (#/setIntercellSpacing: self (coerce-obj intercell-spacing 'ns:ns-size))) (when item-height-p (#/setItemHeight: self (cgfloat item-height))) (when items-with-object-values-p (#/addItemsWithObjectValues: self (coerce-obj items-with-object-values 'ns:ns-array))) (when number-of-visible-items-p (#/setNumberOfVisibleItems: self (coerce number-of-visible-items 'integer)))) (defmethod initialize-instance :after ((self ns:ns-control) &key (action nil action-p) ;; string (alignment :natural alignment-p) ;; number or keyword defined in convert-text-alignment (allows-undo nil allows-undo-p) (attributed-string-value "" attributed-string-value-p) ;; string or attributed-string (base-writing-direction :natural base-writing-direction-p) ;; number or keyword from convert-writing-direction (continuous nil continuous-p) (initial-value nil initial-value-p) ;; numeric value (enabled t enabled-p) (font nil font-p) ;; ns:ns-font (formatter nil formatter-p) ;; ns:ns-formatter, see formatters.lisp (ignores-multi-click t ignores-multi-click-p) (refuses-first-responder nil refuses-first-responder-p) (tag 0 tag-p) ;; integer (target nil target-p) ;; ns:ns-object &allow-other-keys) ;; see view.lisp for other allowed keywords (when action-p (#/setAction: self (get-selector action))) (when alignment-p (#/setAlignment: self (convert-text-alignment alignment))) (when allows-undo-p (#/setAllowsUndo: (#/cell self) allows-undo)) (when attributed-string-value-p (#/setAttributedStringValue: self (coerce-obj attributed-string-value 'ns:ns-attributed-string))) (when base-writing-direction-p (#/setBaseWritingDirection: self (convert-writing-direction base-writing-direction))) (when continuous-p (#/setContinuous: self continuous)) (when initial-value-p (cond ((floatp initial-value) (#/setFloatValue: self initial-value)) ((integerp initial-value) (#/setIntegerValue: self initial-value)) ((typep initial-value 'double-float) (#/setDoubleValue: self initial-value)) ((numberp initial-value) (#/setFloatValue: self (float initial-value))) ((stringp initial-value) (#/setStringValue: self (coerce-obj initial-value 'ns:ns-string))) ((typep initial-value 'ns:ns-object) (#/setObjectValue: self initial-value)))) (when enabled-p (#/setEnabled: self enabled)) (when (and font-p (typep font 'ns:ns-font)) (#/setFont: self font)) (when (and formatter-p (typep formatter 'ns:ns-formatter)) (#/setFormatter: self formatter)) (when ignores-multi-click-p (#/setIgnoresMultiClick: self ignores-multi-click)) (when refuses-first-responder-p (#/setRefusesFirstResponder: self refuses-first-responder)) (when (and tag-p (numberp tag)) (#/setTag: self (truncate tag))) (when (and target-p (typep target 'ns:ns-object)) (#/setTarget: self target))) (defmethod initialize-instance :after ((self ns:ns-scroll-view) &key (autohides-scrollers t autohides-scrollers-p) ;; t or nil (background-color nil background-color-p) ;; ns:ns-color or keyword acceptable to (coerce-obj <keyword> 'ns:ns-color) (border-type nil border-type-p) ;; number or keyword: see convert-border (content-view nil content-view-p) (document-cursor nil document-cursor-p) ;; number or keyword: see convert-cursor (document-view nil document-view-p) ;; the view that will be scrolled (draws-background nil draws-background-p) (find-bar-position nil find-bar-position-p) ;; number or keyword: see convert-find-bar-position (has-horizontal-ruler nil has-horizontal-ruler-p) ;; t or nil (has-horizontal-scroller nil has-horizontal-scroller-p) ;; t or nil (has-vertical-ruler nil has-vertical-ruler-p) ;; t or nil (has-vertical-scroller nil has-vertical-scroller-p) ;; t or nil (horizontal-line-scroll nil horizontal-line-scroll-p) ;; points to scroll (horizontal-page-scroll nil horizontal-page-scroll-p) ;; points to scroll (horizontal-ruler-view nil horizontal-ruler-view-p) ;; ns:ns-ruler-view (horizontal-scroll-elasticity nil horizontal-scroll-elasticity-p) ;; number or keyword: see convert-elasticity (horizontal-scroller nil horizontal-scroller-p) ;; ns:ns-scroller (line-scroll nil line-scroll-p) ;; points to scroll in both h and v (page-scroll nil page-scroll-p) ;; points to scroll in both h and v (rulers-visible nil rulers-visible-p) (scroller-knob-style nil scroller-knob-style-p) ;; number or keyword: see convert-knob-style (scroller-style nil scroller-style-p) ;; number or keyword: see convert-scroller-style (scrolls-dynamically t scrolls-dynamically-p) ;; t or nil whether to redraw while scrolling (uses-predominant-axis-scrolling t uses-predominant-axis-scrolling-p) ;; t or nil (vertical-line-scroll nil vertical-line-scroll-p) ;; points to scroll (vertical-page-scroll nil vertical-page-scroll-p) ;; points to scroll (vertical-ruler-view nil vertical-ruler-view-p) ;; ns:ns-ruler-view (vertical-scroll-elasticity nil vertical-scroll-elasticity-p) ;; number or keyword: see convert-elasticity (vertical-scroller nil vertical-scroller-p) ;; ns:ns-scroller &allow-other-keys) (when autohides-scrollers-p (#/setAutohidesScrollers: self autohides-scrollers)) (when background-color-p (#/setBackgroundColor: self (coerce-obj background-color 'ns:ns-color))) (when border-type-p (#/setBorderType: self (convert-border border-type))) (when content-view-p (#/setContentView: self content-view)) (when document-cursor-p (#/setDocumentCursor: self (convert-cursor document-cursor))) (when document-view-p (#/setDocumentView: self document-view)) (when draws-background-p (#/setDrawsBackground: self draws-background)) (when find-bar-position-p (#/setFindBarPosition: self (convert-find-bar-position find-bar-position))) (when has-horizontal-ruler-p (#/setHasHorizontalRuler: self has-horizontal-ruler)) (when has-horizontal-scroller-p (#/setHasHorizontalScroller: self has-horizontal-scroller)) (when has-vertical-ruler-p (#/setHasVerticalRuler: self has-vertical-ruler)) (when has-vertical-scroller-p (#/setHasVerticalScroller: self has-vertical-scroller)) (when horizontal-line-scroll-p (#/setHorizontalLineScroll: self (cgfloat horizontal-line-scroll))) (when horizontal-page-scroll-p (#/setHorizontalPageScroll: self (cgfloat horizontal-page-scroll))) (when horizontal-ruler-view-p (#/setHorizontalRulerView: self horizontal-ruler-view)) (when horizontal-scroll-elasticity-p (#/setHorizontalScrollElasticity: self (convert-elasticity horizontal-scroll-elasticity))) (when horizontal-scroller-p (#/setHorizontalScroller: self horizontal-scroller)) (when line-scroll-p (#/setLineScroll: self (cgfloat line-scroll))) (when page-scroll-p (#/setPageScroll: self (cgfloat page-scroll))) (when rulers-visible-p (#/setRulersVisible: self rulers-visible)) (when scroller-knob-style-p (#/setScrollerKnobStyle: self (convert-knob-style scroller-knob-style))) (when scroller-style-p (#/setScrollerStyle: self (convert-scroller-style scroller-style))) (when scrolls-dynamically-p (#/setScrollsDynamically: self scrolls-dynamically)) (when uses-predominant-axis-scrolling-p (#/setUsesPredominantAxisScrolling: self uses-predominant-axis-scrolling)) (when vertical-line-scroll-p (#/setVerticalLineScroll: self (cgfloat vertical-line-scroll))) (when vertical-page-scroll-p (#/setVerticalPageScroll: self (cgfloat vertical-page-scroll))) (when vertical-ruler-view-p (#/setVerticalRulerView: self vertical-ruler-view)) (when vertical-scroll-elasticity-p (#/setVerticalScrollElasticity: self (convert-elasticity vertical-scroll-elasticity))) (when vertical-scroller-p (#/setVerticalScroller: self vertical-scroller)) self) (defmethod initialize-instance :after ((self ns:ns-text) &key (alignment nil alignment-p) (background-color nil background-color-p) ;; ns:ns-color or keyword convertible by coerce-obj (base-writing-direction nil base-writing-direction-p) ;; number or keyword from convert-writing-direction (delegate nil delegate-p) ;; any ns:ns-object (draws-background nil draws-background-p) (editable nil editable-p) (field-editor nil field-editor-p) (font nil font-p) ;; ns:ns-font (horizontally-resizable nil horizontally-resizable-p) (imports-graphics nil imports-graphics-p) (max-size nil max-size-p) ;; ns:ns-size or list of the form (<width> <height>) (min-size nil min-size-p) ;; ns:ns-size or list of the form (<width> <height>) (rich-text nil rich-text-p) (selectable nil selectable-p) (string nil string-p) ;; string, attributed-string, or ns:ns-string (text-color nil text-color-p) ;; ns:ns-color or keyword convertible by coerce-obj (uses-font-panel nil uses-font-panel-p) (vertically-resizable nil vertically-resizable-p) &allow-other-keys) ;; see control.lisp and view.lisp for other allowed keywords (when alignment-p (#/setAlignment: self (convert-text-alignment alignment))) (when background-color-p (#/setBackgroundColor: self (coerce-obj background-color 'ns:ns-color))) (when base-writing-direction-p (#/setBaseWritingDirection: self (convert-writing-direction base-writing-direction))) (when delegate-p (#/setDelegate: self delegate)) (when draws-background-p (#/setDrawsBackground: self draws-background)) (when editable-p (#/setEditable: self editable)) (when field-editor-p (#/setFieldEditor: self field-editor)) (when font-p (#/setFont: self font)) (when horizontally-resizable-p (#/setHorizontallyResizable: self horizontally-resizable)) (when imports-graphics-p (#/setImportsGraphics: self imports-graphics)) (when max-size-p (#/setMaxSize: self (coerce-obj max-size 'ns:ns-size))) (when min-size-p (#/setMinSize: self (coerce-obj min-size 'ns:ns-size))) (when rich-text-p (#/setRichText: self rich-text)) (when selectable-p (#/setSelectable: self selectable)) (when string-p (if rich-text-p (#/setAttributedString: (#/textStorage self) (coerce-obj string 'ns:ns-attributed-string)) (#/setString: self (coerce-obj string 'ns:ns-string)))) (when text-color-p (#/setTextColor: self (coerce-obj text-color 'ns:ns-color))) (when uses-font-panel-p (#/setUsesFontPanel: self uses-font-panel)) (when vertically-resizable-p (#/setVerticallyResizable: self vertically-resizable))) (defmethod initialize-instance :after ((self ns:ns-text-view) &key (delegate nil delegate-p) ;; ns:ns-object (displayes-link-tool-tips nil displayes-link-tool-tips-p) (draws-background nil draws-background-p) (editable nil editable-p) (enabled-text-checking-types nil enabled-text-checking-types-p) ;; keyword or list of keywords or number (field-editor nil field-editor-p) (grammar-checking-enabled nil grammar-checking-enabled-p) (imports-graphics nil imports-graphics-p) (incremental-searching-enabled nil incremental-searching-enabled-p) (insertion-point-color nil insertion-point-color-p) ;; ns:ns-color or keyword acceptable to (coerce-obj <keyword> 'ns:ns-color) (layout-orientation nil layout-orientation-p) ;; number or keyword: :h :horizontal :v :vertical (link-text-attributes nil link-text-attributes-p) ;; assoc-list, hash-table, or ns:ns-dictionary of attribute-value pairs (marked-text-attributes nil marked-text-attributes-p) ;; assoc-list, hash-table, or ns:ns-dictionary of attribute-value pairs (rich-text nil rich-text-p) (ruler-visible nil ruler-visible-p) (selectable nil selectable-p) (selected-text-attributes nil selected-text-attributes-p) ;; assoc-list, hash-table, or ns:ns-dictionary of attribute-value pairs (smart-insert-delete-enabled nil smart-insert-delete-enabled-p) (text-container nil text-container-p) ;; ns:ns-text-container (text-container-inset nil text-container-inset-p) ;; ns:ns-size or list: (width height) (uses-find-bar nil uses-find-bar-p) (uses-find-panel nil uses-find-panel-p) (uses-font-panel nil uses-font-panel-p) (uses-inspector-bar nil uses-inspector-bar-p) (uses-ruler nil uses-ruler-p) &allow-other-keys) ;; see control.lisp and view.lisp for other allowed keywords (when delegate-p (#/setDelegate: self delegate)) (when displayes-link-tool-tips-p (#/setDisplaysLinkToolTips: self displayes-link-tool-tips)) (when draws-background-p (#/setDrawsBackground: self draws-background)) (when editable-p (#/setEditable: self editable)) (when enabled-text-checking-types-p (#/setEnabledTextCheckingTypes: self (convert-text-checking-types enabled-text-checking-types))) (when field-editor-p (#/setFieldEditor: self field-editor)) (when grammar-checking-enabled-p (#/setGrammarCheckingEnabled: self grammar-checking-enabled)) (when imports-graphics-p (#/setImportsGraphics: self imports-graphics)) (when incremental-searching-enabled-p (#/setIncrementalSearchingEnabled: self incremental-searching-enabled)) (when insertion-point-color-p (#/setInsertionPointColor: self (coerce-obj insertion-point-color 'ns:ns-color))) (when layout-orientation-p (#/setLayoutOrientation: self (convert-text-orientation layout-orientation))) (when link-text-attributes-p (#/setLinkTextAttributes: self (coerce-obj link-text-attributes 'ns:ns-dictionary))) (when marked-text-attributes-p (#/setMarkedTextAttributes: self (coerce-obj marked-text-attributes 'ns:ns-dictionary))) (when rich-text-p (#/setRichText: self rich-text)) (when ruler-visible-p (#/setRulerVisible: self ruler-visible)) (when selectable-p (#/setSelectable: self selectable)) (when selected-text-attributes-p (#/setSelectedTextAttributes: self (coerce-obj selected-text-attributes 'ns:ns-dictionary))) (when smart-insert-delete-enabled-p (#/setSmartInsertDeleteEnabled: self smart-insert-delete-enabled)) (when text-container-p (#/setTextContainer: self text-container)) (when text-container-inset-p (#/setTextContainerInset: self (coerce-obj text-container-inset 'ns:ns-size))) (when uses-find-bar-p (#/setUsesFindBar: self uses-find-bar)) (when uses-find-panel-p (#/setUsesFindPanel: self uses-find-panel)) (when uses-font-panel-p (#/setUsesFontPanel: self uses-font-panel)) (when uses-inspector-bar-p (#/setUsesInspectorBar: self uses-inspector-bar)) (when uses-ruler-p (#/setUsesRuler: self uses-ruler))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; ns-control subclasses (defmethod initialize-instance :after ((self ns:ns-button) &key (allows-mixed-state nil allows-mixed-state-p) (alternate-image nil alternate-image-p) ;; ns:ns-image (alternate-title nil alternate-title-p) ;; string, attributed-string, ns:ns-string (attributed-alternate-title nil attributed-alternate-title-p) ;; string, attributed-string or Obj-C equivalents (attributed-title nil attributed-title-p) ;; string, attributed-string or Obj-C equivalents (bezel-style nil bezel-style-p) ;; number or keyword: see convert-bezel-style (bordered nil bordered-p) (button-type nil button-type-p) ;; number or keyword: see convert-button-type (image nil image-p) ;; ns:ns-image (image-position nil image-position-p) ;; single value or list, values are numbers or keyword: see convert-image-position (key-equivalent nil key-equivalent-p) (key-equivalent-modifier-mask 0 key-equivalent-modifier-mask-p) ;; number or list of keywords or keyword: :control, :alternate, or :command (shows-border-only-while-mouse-inside nil shows-border-only-while-mouse-inside-p) (sound nil sound-p) (state nil state-p) ;; number or keyword: :on, :off, or :mixed (title nil title-p) ;; string, attributed-string or Obj-C equivalents (transparent nil transparent-p) &allow-other-keys) ;; see control.lisp and view.lisp for other allowed keywords (when allows-mixed-state-p (#/setAllowsMixedState: self allows-mixed-state)) (when alternate-image-p (#/setAlternateImage: self alternate-image)) (when alternate-title-p (#/setAlternateTitle: self (coerce-obj alternate-title 'ns:ns-string))) (when attributed-alternate-title-p (#/setAttributedAlternateTitle: self (coerce-obj attributed-alternate-title 'ns:ns-attributed-string))) (when attributed-title-p (#/setAttributedTitle: self (coerce-obj attributed-title 'ns:ns-attributed-string))) (when bezel-style-p (#/setBezelStyle: self (convert-bezel-style bezel-style))) (when bordered-p (#/setBordered: self bordered)) (when button-type-p (#/setButtonType: self (convert-button-type button-type))) (when image-p (#/setImage: self image)) (when image-position-p (if (listp image-position) (dolist (ip image-position) (#/setImagePosition: self (convert-image-position ip))) (#/setImagePosition: self (convert-image-position image-position)))) (when key-equivalent-p (#/setKeyEquivalent: self (coerce-obj key-equivalent 'ns:ns-string))) (when key-equivalent-modifier-mask-p (#/setKeyEquivalentModifierMask: self (convert-key-modifier-mask key-equivalent-modifier-mask))) (when shows-border-only-while-mouse-inside-p (#/setShowsBorderOnlyWhileMouseInside: self shows-border-only-while-mouse-inside)) (when (and sound-p (typep sound 'ns:ns-sound)) (#/setSound: self sound)) (when state-p (#/setState: self (convert-state state))) (when title-p (#/setTitle: self (coerce-obj title 'ns:ns-string))) (when transparent-p (#/setTransparent: self transparent)) self) (defmethod initialize-instance :after ((self ns:ns-color-well) &key (bordered nil bordered-p) (color nil color-p) ;; ns:ns-color or keyword acceptable to (coerce-obj <keyword> 'ns:ns-color) &allow-other-keys) (when bordered-p (#/setBordered: self bordered)) (when color-p (#/setColor: self (coerce-obj color 'ns:ns-color)))) (defmethod initialize-instance :after ((self ns:ns-outline-view) &key (autoresizes-outline-column nil autoresizes-outline-column-p) (autosave-expanded-items nil autosave-expanded-items-p) (indentation-marker-follows-cell nil indentation-marker-follows-cell-p) (indentation-per-level nil indentation-per-level-p) (outline-table-column nil outline-table-column-p) ;; ns:ns-table-column &allow-other-keys) (when autoresizes-outline-column-p (#/setAutoresizesOutlineColumn: self autoresizes-outline-column)) (when autosave-expanded-items-p (#/setAutosaveExpandedItems: self autosave-expanded-items)) (when indentation-marker-follows-cell-p (#/setIndentationMarkerFollowsCell: self indentation-marker-follows-cell)) (when indentation-per-level-p (#/setIndentationPerLevel: self (cgfloat indentation-per-level))) (when outline-table-column-p (#/setOutlineTableColumn: self outline-table-column))) (defmethod initialize-instance :after ((self ns:ns-slider) &key (allows-tick-mark-values-only nil allows-tick-mark-values-only-p) (alt-increment-value 1 alt-increment-value-p) (image nil image-p) ;; ns:ns-image (max-value nil max-value-p) (min-value nil min-value-p) (number-of-tick-marks 0 number-of-tick-marks-p) ;; integer &allow-other-keys) ;; see control.lisp and view.lisp for other allowed keywords (when allows-tick-mark-values-only-p (#/setAllowsTickMarkValuesOnly: self allows-tick-mark-values-only)) (when (and alt-increment-value-p (numberp alt-increment-value)) (#/setAltIncrementValue: self (cgfloat alt-increment-value))) (when image-p (#/setImage: self image)) (when (and max-value-p (numberp max-value)) (#/setMaxValue: self (cgfloat max-value))) (when (and min-value-p (numberp min-value)) (#/setMinValue: self (cgfloat min-value))) (when (and number-of-tick-marks-p (numberp number-of-tick-marks)) (#/setNumberOfTickMarks: self (truncate number-of-tick-marks))) self) (defmethod initialize-instance :after ((self ns:ns-table-view) &key (columns nil columns-p) ;; list of ns:ns-table-columns (allows-column-reordering nil allows-column-reordering-p) (allows-column-resizing nil allows-column-resizing-p) (allows-column-selection nil allows-column-selection-p) (allows-empty-selection nil allows-empty-selection-p) (allows-multiple-selection nil allows-multiple-selection-p) (allows-type-select nil allows-type-select-p) (autosave-name nil autosave-name-p) ;; string or ns:ns-string (autosave-table-columns nil autosave-table-columns-p) (background-color nil background-color-p) ;; ns:ns-color or keyword acceptable to (coerce-obj <keyword> 'ns:ns-color) (column-autoresizing-style nil column-autoresizing-style-p) ;; number or keyword: see convert-table-col-resizing (corner-view nil corner-view-p) ;; ns:ns-view (data-source nil data-source-p) ;; ns:ns-object which conforms to NSTableViewDataSource protocol (delegate nil delegate-p) ;; ns:ns-object which conforms to NSTableViewDelegate protocol (double-action nil double-action-p) ;; string (dragging-destination-feedback-style nil dragging-destination-feedback-style-p) ;; number or :none :regular :source-list (dragging-source-operation-mask nil dragging-source-operation-mask-p) ;; number or keyword: see convert-table-drag-src-op (floats-group-rows nil floats-group-rows-p) (grid-color nil grid-color-p) ;; ns:ns-color or keyword acceptable to (coerce-obj <keyword> 'ns:ns-color) (grid-style-mask nil grid-style-mask-p) ;; number or keyword or list of keywords: see convert-grid-style (header-view nil header-view-p) ;; ns:ns-table-header-view (intercell-spacing nil intercell-spacing-p) ;; ns:ns-size or list: (width height) (row-height nil row-height-p) ;; number (row-size-style nil row-size-style-p) ;; number or keyword: see convert-row-size-style (selection-highlight-style nil selection-highlight-style-p) ;; number or keyword: see convert-selection-highlight-style (sort-descriptors nil sort-descriptors-p) ;; list, 1D array, or ns:ns-array of ns:ns-sort-descriptor objects (uses-alternating-row-background-colors nil uses-alternating-row-background-colors-p) (vertical-motion-can-begin-drag nil vertical-motion-can-begin-drag-p) &allow-other-keys) (when columns-p ;; must do this first because other parameters only affect columns that already exist (dolist (col columns) (#/addTableColumn: self col))) (when allows-column-reordering-p (#/setAllowsColumnReordering: self allows-column-reordering)) (when allows-column-resizing-p (#/setAllowsColumnResizing: self allows-column-resizing)) (when allows-column-selection-p (#/setAllowsColumnSelection: self allows-column-selection)) (when allows-empty-selection-p (#/setAllowsEmptySelection: self allows-empty-selection)) (when allows-multiple-selection-p (#/setAllowsMultipleSelection: self allows-multiple-selection)) (when allows-type-select-p (#/setAllowsTypeSelect: self allows-type-select)) (when autosave-name-p (#/setAutosaveName: self (coerce-obj autosave-name 'ns:ns-string))) (when autosave-table-columns-p (#/setAutosaveTableColumns: self autosave-table-columns)) (when background-color-p (#/setBackgroundColor: self (coerce-obj background-color 'ns:ns-color))) (when column-autoresizing-style-p (#/setColumnAutoresizingStyle: self (convert-table-col-resizing column-autoresizing-style))) (when corner-view-p (#/setCornerView: self corner-view)) (when data-source-p (#/setDataSource: self data-source)) (when delegate-p (#/setDelegate: self delegate)) (when double-action-p (#/setDoubleAction: self (get-selector double-action))) (when dragging-destination-feedback-style-p (#/setDraggingDestinationFeedbackStyle: self (convert-table-drag-feedback-style dragging-destination-feedback-style))) (when dragging-source-operation-mask-p (#/setDraggingSourceOperationMask:forLocal: self (convert-table-drag-src-op dragging-source-operation-mask) t)) (when floats-group-rows-p (#/setFloatsGroupRows: self floats-group-rows)) (when grid-color-p (#/setGridColor: self (coerce-obj grid-color 'ns:ns-color))) (when grid-style-mask-p (#/setGridStyleMask: self (convert-grid-styles grid-style-mask))) (when header-view-p (#/setHeaderView: self header-view)) (when intercell-spacing-p (#/setIntercellSpacing: self (coerce-obj intercell-spacing 'ns:ns-size))) (when row-height-p (#/setRowHeight: self (cgfloat row-height))) (when row-size-style-p (#/setRowSizeStyle: self (convert-row-size-style row-size-style))) (when selection-highlight-style-p (#/setSelectionHighlightStyle: self (convert-selection-highlight-style selection-highlight-style))) (when sort-descriptors-p (#/setSortDescriptors: self (coerce-obj sort-descriptors 'ns:ns-array))) (when uses-alternating-row-background-colors-p (#/setUsesAlternatingRowBackgroundColors: self uses-alternating-row-background-colors)) (when vertical-motion-can-begin-drag-p (#/setVerticalMotionCanBeginDrag: self vertical-motion-can-begin-drag))) (defmethod initialize-instance :after ((self ns:ns-text-field) &key (bezeled nil bezeled-p) (bezel-style nil bezel-style-p) ;; number or keyword: see values in convert-text-bezel-style above (bordered nil bordered-p) (delegate nil delegate-p) ;; ns:ns-object (draws-background nil draws-background-p) (editable nil editable-p) (imports-graphics nil imports-graphics-p) (preferred-max-layout-width nil preferred-max-layout-width-p) (selectable nil selectable-p) (text-color nil text-color-p) ;; ns:ns-color or keyword acceptable to (coerce-obj <keyword> 'ns:ns-color) &allow-other-keys) ;; see control.lisp and view.lisp for other allowed keywords (when bezeled-p (#/setBezeled: self bezeled)) (when bezel-style-p (#/setBezelStyle: self (convert-text-bezel-style bezel-style))) (when bordered-p (#/setBordered: self bordered)) (when delegate-p (#/setDelegate: self delegate)) (when draws-background-p (#/setDrawsBackground: self draws-background)) (when editable-p (#/setEditable: self editable)) (when imports-graphics-p (#/setImportsGraphics: self imports-graphics)) (when preferred-max-layout-width-p (#/setPreferredMaxLayoutWidth: self preferred-max-layout-width)) (when selectable-p (#/setSelectable: self selectable)) (when text-color-p (#/setTextColor: self (coerce-obj text-color 'ns:ns-color)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; ns-window subclasses (defmethod initialize-instance :after ((self ns:ns-panel) &key (floating-panel nil floating-panel-p) (works-when-modal nil works-when-modal-p) &allow-other-keys) ;; see window.lisp for other allowed keywords (when floating-panel-p (#/setFloatingPanel: self floating-panel)) (when works-when-modal-p (#/setWorksWhenModal: self works-when-modal))) (defmethod initialize-instance :after ((self ns:ns-save-panel) &key (accessory-view nil accessory-view-p) ;; ns-view object (allowed-file-types (%null-ptr)) ;; list of strings of allowed file types (allows-other-file-types nil allows-other-file-types-p) (can-create-directories nil can-create-directories-p) (can-select-hidden-extension nil can-select-hidden-extension-p) (delegate nil delegate-p) ;; NSOpenSavePanelDelegate object (directory-url nil directory-url-p) ;; ns:ns-url (extension-hidden nil extension-hidden-p) (message nil message-p) (name-field-label nil name-field-label-p) (name-field-string-value nil name-field-string-value-p) (prompt nil prompt-p) (shows-hidden-files nil shows-hidden-files-p) ;;(shows-tag-field nil shows-tag-field-p) ;;(tag-names nil tag-names-p) ;; list of strings (title nil title-p) ;; string (treats-file-packages-as-directories nil treats-file-packages-as-directories-p) &allow-other-keys) ;; see window.lisp for other allowed keywords (when accessory-view-p (#/setAccessoryView: self accessory-view)) (#/setAllowedFileTypes: self (if allowed-file-types (coerce-obj allowed-file-types 'ns:ns-array) (%null-ptr))) (when allows-other-file-types-p (#/setAllowsOtherFileTypes: self allows-other-file-types)) (when can-create-directories-p (#/setCanCreateDirectories: self can-create-directories)) (when can-select-hidden-extension-p (#/setCanSelectHiddenExtension: self can-select-hidden-extension)) (when delegate-p (#/setDelegate: self delegate)) (when directory-url-p (#/setDirectoryURL: self directory-url)) (when extension-hidden-p (#/setExtensionHidden: self extension-hidden)) (when message-p (#/setMessage: self (coerce-obj message 'ns:ns-string))) (when name-field-label-p (#/setNameFieldLabel: self (coerce-obj name-field-label 'ns:ns-string))) (when name-field-string-value-p (#/setNameFieldStringValue: self (coerce-obj name-field-string-value 'ns:ns-string))) (when prompt-p (#/setPrompt: self (coerce-obj prompt 'ns:ns-string))) (when shows-hidden-files-p (#/setShowsHiddenFiles: self shows-hidden-files)) ;;(when shows-tag-field-p ;; (#/setShowsTagField: self shows-tag-field)) ;;(when tag-names-p ;; (#/setTagNames: self (coerce-obj tag-names 'ns:ns-array))) (when title-p (#/setTitle: self (coerce-obj title 'ns:ns-string))) (when treats-file-packages-as-directories-p (#/setTreatsFilePackagesAsDirectories: self treats-file-packages-as-directories))) ;;; NOTE: you should not create an ns-open-panel using make-instance. Instead use make-open-panel ;;; loaded from open-panel.lisp. That will avoid getting a rash of CG trace messages logged to the ;;; system log (I found this the hard way). Retaining an ns-open-panel in any fashion will cause ;;; the log messages. (defmethod initialize-instance :after ((self ns:ns-open-panel) &key (allows-multiple-selection nil allows-multiple-selection-p) (can-choose-directories nil can-choose-directories-p) (can-choose-files nil can-choose-files-p) (resolves-aliases nil resolves-aliases-p) &allow-other-keys) (when allows-multiple-selection-p (#/setAllowsMultipleSelection: self allows-multiple-selection)) (when can-choose-directories-p (#/setCanChooseDirectories: self can-choose-directories)) (when can-choose-files-p (#/setCanChooseFiles: self can-choose-files)) (when resolves-aliases-p (#/setResolvesAliases: self resolves-aliases))) (provide :objc-initialize)
59242
;; objc-initialize.lisp #| The MIT license. Copyright (c) 2013 <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. |# #| WARNING: This will replace CCL-defined initialize-instance :after methods for ns:ns-window and ns:ns-view which are defined in cocoa-window.lisp. While I made every effort to ensure compatibility with those methods and have experienced no difficulty when running with my replacements, if you have other code that depends on specific keywords defined in those routines, you may have to either modify your code or not load this file. This file provides initialize-instance :after methods for many standard Objective-C classes, especially ns:ns-view subclasses, but it is not a comprehensive list. The norm in Lisp is to call make-instance and provide all necessary initialization values as keywords. In Objective-C the norm is to provide a few initWith... methods that supply only a limited number of initialization parameters. The developer is then expected to customize those objects by using any number of set... methods. We could certainly do the same in Lisp, but to make life more natural I have created these initialize-instance :after methods. The idea is that you can do something like the following: (make-instance '<ns-object-class-name> {:key val}*) Most common sorts of argument types needed for the Objective-C methods are automatically converted from corresponding Lisp types provided in the make-instance call. Many sorts of constants are automatically converted from keyword equivalents (see the convert... methods for those values). If their superclass also defines the initialize-instance :after method then of course it will be called as well. Each method defines keywords corresponding to set... methods that are specific to that class. So in an initialize-instance :after method for any object you can use keywords for that class or any of its superclasses. Many supporting functions named convert-... will convert keyword arguments. If the meaning of them is not clear, you should consult Apple documentation for additional information. The function initialize-keys is provided to give you a list of valid keywords for any object that you might want to initialize. Note that these methods will NOT be called if you create instances using normal Objective-C forms such as (#/init (#/alloc <class>)) They will only be invoked if you specifically call make-instance ... Final suggestions. If you execute any make-instance forms from the Lisp listener for these classes (especially classes associated withwindows or views) you should wrap the call with a (on-main-thread ... ) form (defined in ns-object-utils.lisp). This assures that the objects are created on the main thread, which is increasingly necessary for Objective-C objects created at runtime. Objects returned by these methods will typically be owned by the caller and you must explicitly (#/release <object) when you are done with it to avoid a memory leak. Note that a memory leak is much better than trying to reference a ptr to an object that was released prematurely. Such a reference is likely to cause a runtime exception. |# (assert (>= #$NSAppKitVersionNumber #$NSAppKitVersionNumber10_7)) (eval-when (:compile-toplevel :load-toplevel :execute) (require :interface-packages) (require :coerce-obj) (require :selector-utils) (require :list-utils) (require :file-directory-utils)) (in-package :iu) ;; convert- ... functions (defun convert-animation-behavior (ab-key) (if (numberp ab-key) ab-key (ecase ab-key (:default #$NSWindowAnimationBehaviorDefault) (:none #$NSWindowAnimationBehaviorNone) (:document-window #$NSWindowAnimationBehaviorDocumentWindow) (:utility-window #$NSWindowAnimationBehaviorUtilityWindow) (:alert-panel #$NSWindowAnimationBehaviorAlertPanel)))) (defun convert-bezel-style (style-key) (if (numberp style-key) style-key (ecase style-key (:rounded #$NSRoundedBezelStyle) (:regular-square #$NSRegularSquareBezelStyle) (:thick-square #$NSThickSquareBezelStyle) (:thicker-square #$NSThickerSquareBezelStyle) (:disclosure #$NSDisclosureBezelStyle) (:shadowless-square #$NSShadowlessSquareBezelStyle) (:circular #$NSCircularBezelStyle) (:textured-square #$NSTexturedSquareBezelStyle) (:help-button #$NSHelpButtonBezelStyle) (:small-square #$NSSmallSquareBezelStyle) (:textured-rounded #$NSTexturedRoundedBezelStyle) (:round-rect #$NSRoundRectBezelStyle) (:recessed #$NSRecessedBezelStyle) (:rounded-disclosure #$NSRoundedDisclosureBezelStyle) (:inline #$NSInlineBezelStyle) (:small-icon-button #$NSSmallIconButtonBezelStyle)))) (defun convert-border (border-key) (if (numberp border-key) border-key (ecase border-key (:line #$NSLineBorder) (:bezel #$NSBezelBorder) (:groove #$NSGrooveBorder) (:none #$NSNoBorder)))) (defun convert-box-type (bt-key) (if (numberp bt-key) bt-key (ecase bt-key (:primary #$NSBoxPrimary) (:secondary #$NSBoxSecondary) (:separator #$NSBoxSeparator) (:old-style #$NSBoxOldStyle) (:custom #$NSBoxCustom)))) (defun convert-button-type (type-key) (if (numberp type-key) type-key (ecase type-key (:momentary-light #$NSMomentaryLightButton) (:push-on-push-off #$NSPushOnPushOffButton) (:toggle #$NSToggleButton) (:switch #$NSSwitchButton) (:radio #$NSRadioButton) (:momentary-change #$NSMomentaryChangeButton) (:on-off #$NSOnOffButton) (:momentary-push-in #$NSMomentaryPushInButton) (:momentary-push #$NSMomentaryPushButton)))) (defun convert-collection-behavior (c-key) (cond ((listp c-key) (apply #'logior (mapcar #'convert-collection-behavior c-key))) ((numberp c-key) c-key) (t (ecase c-key (:default #$NSWindowCollectionBehaviorDefault) (:can-join-all-spaces #$NSWindowCollectionBehaviorCanJoinAllSpaces) (:move-to-active-space #$NSWindowCollectionBehaviorMoveToActiveSpace) (:managed #$NSWindowCollectionBehaviorManaged) (:transient #$NSWindowCollectionBehaviorTransient) (:stationary #$NSWindowCollectionBehaviorStationary) (:participates-in-cycle #$NSWindowCollectionBehaviorParticipatesInCycle) (:ignores-cycle #$NSWindowCollectionBehaviorIgnoresCycle) (:full-screen-primary #$NSWindowCollectionBehaviorFullScreenPrimary) (:full-screen-auxiliary #$NSWindowCollectionBehaviorFullScreenAuxiliary))))) (defun convert-column-resizing (cr-key) (if (numberp cr-key) cr-key (ecase cr-key (:no-resizing #$NSTableColumnNoResizing) (:auto-resizing #$NSTableColumnAutoresizingMask) (:user-resizing #$NSTableColumnUserResizingMask)))) (defun convert-cursor (cursor-key) ;; not all applicable to scroll-views, but included for completeness and use elsewhere (if (numberp cursor-key) cursor-key (ecase cursor-key (:arrow (#/arrowCursor ns:ns-cursor)) (:closed-hand (#/closedHandCursor ns:ns-cursor)) (:contextual-menu (#/contextualMenuCursor ns:ns-cursor)) (:crosshair (#/crosshairCursor ns:ns-cursor)) (:current (#/currentCursor ns:ns-cursor)) (:current-system (#/currentSystemCursor ns:ns-cursor)) (:disappearing-item (#/disappearingItemCursor ns:ns-cursor)) (:drag-copy (#/dragCopyCursor ns:ns-cursor)) (:drag-link (#/dragLinkCursor ns:ns-cursor)) (:ibeam (#/IBeamCursor ns:ns-cursor)) (:ibeam-for-vertical (#/IBeamCursorForVerticalLayout ns:ns-cursor)) (:open-hand (#/openHandCursor ns:ns-cursor)) (:op-not-allowed (#/operationNotAllowedCursor ns:ns-cursor)) (:pointing-hand (#/pointingHandCursor ns:ns-cursor)) (:resize-down (#/resizeDownCursor ns:ns-cursor)) (:resize-left (#/resizeLeftCursor ns:ns-cursor)) (:resize-left-right (#/resizeLeftRightCursor ns:ns-cursor)) (:resize-right (#/resizeRightCursor ns:ns-cursor)) (:resize-up (#/resizeUpCursor ns:ns-cursor)) (:resize-up-down (#/resizeUpDownCursor ns:ns-cursor))))) (defun convert-date-style (ds-key) (if (numberp ds-key) ds-key (ecase ds-key (:none #$NSDateFormatterNoStyle) (:short #$NSDateFormatterShortStyle) (:medium #$NSDateFormatterMediumStyle) (:long #$NSDateFormatterLongStyle) (:full #$NSDateFormatterFullStyle)))) (defun convert-elasticity (e-key) (if (numberp e-key) e-key (ecase e-key (:automatic #$NSScrollElasticityAutomatic) (:none #$NSScrollElasticityNone) (:allowed #$NSScrollElasticityAllowed)))) (defun convert-find-bar-position (find-key) (if (numberp find-key) find-key (ecase find-key (:above-ruler #$NSScrollViewFindBarPositionAboveHorizontalRuler) (:above-content #$NSScrollViewFindBarPositionAboveContent) (:below-content #$NSScrollViewFindBarPositionBelowContent)))) (defun convert-focus-ring-type (fr-key) (if (numberp fr-key) fr-key (ecase fr-key (:default #$NSFocusRingTypeDefault) (:none #$NSFocusRingTypeNone) (:exterior #$NSFocusRingTypeExterior)))) (defun convert-grid-style (s-key) (if (numberp s-key) s-key (ecase s-key (:none #$NSTableViewGridNone) (:solid-vertical #$NSTableViewSolidVerticalGridLineMask) (:solid-horizontal #$NSTableViewSolidHorizontalGridLineMask) (:dashed-horizontal #$NSTableViewDashedHorizontalGridLineMask)))) (defun convert-grid-styles (style) (if (listp style) (apply #'logior (mapcar #'convert-grid-style style)) (convert-grid-style style))) (defun convert-image-position (i-key) #| Together, NSCellHasImageOnLeftOrBottom, NSCellHasImageHorizontal, and NSCellHasOverlappingImage control the position of the cell’s image and text. To place the image above, set none of them. To place the image below, set NSCellHasImageOnLeftOrBottom. To place the image to the right, set NSCellHasImageHorizontal. To place the image to the left, set NSCellHasImageHorizontal and NSCellHasImageOnLeftOrBottom. To place the image directly over, set NSCellHasOverlappingImage. |# (if (numberp i-key) i-key (ecase i-key (:no-image #$NSNoImage) (:image-only #$NSImageOnly) (:image-left #$NSImageLeft) (:image-right #$NSImageRight) (:image-below #$NSImageBelow) (:image-above #$NSImageAbove) (:image-overlaps #$NSImageOverlaps)))) (defun convert-key-modifier-mask (mod-key) (cond ((listp mod-key) (apply #'logior (mapcar #'convert-key-modifier-mask mod-key))) ((numberp mod-key) mod-key) (t (ecase mod-key (:shift #$NSShiftKeyMask) (:control #$NSControlKeyMask) (:alternate #$NSAlternateKeyMask) (:option #$NSAlternateKeyMask) ;; same as alt key (:command #$NSCommandKeyMask))))) (defun convert-knob-style (k-key) (if (numberp k-key) k-key (ecase k-key (:default #$NSScrollerKnobStyleDefault) (:dark #$NSScrollerKnobStyleDark) (:light #$NSScrollerKnobStyleLight)))) (defun convert-number-style (ns-key) (if (numberp ns-key) ns-key (ecase ns-key (:none #$NSNumberFormatterNoStyle) (:decimal #$NSNumberFormatterDecimalStyle) (:currency #$NSNumberFormatterCurrencyStyle) (:percent #$NSNumberFormatterPercentStyle) (:scientific #$NSNumberFormatterScientificStyle) (:spell-out #$NSNumberFormatterSpellOutStyle)))) (defun convert-padding-position (pp-key) (if (numberp pp-key) pp-key (ecase pp-key (:before-prefix #$NSNumberFormatterPadBeforePrefix) (:after-prefix #$NSNumberFormatterPadAfterPrefix) (:before-suffix #$NSNumberFormatterPadBeforeSuffix) (:after-suffix #$NSNumberFormatterPadAfterSuffix)))) (defun convert-resizing-mask (rs-key) (cond ((listp rs-key) (apply #'logior (mapcar #'convert-resizing-mask rs-key))) ((numberp rs-key) rs-key) (t (ecase rs-key (:not-sizable #$NSViewNotSizable) (:min-x-margin #$NSViewMinXMargin) (:width-sizable #$NSViewWidthSizable) (:max-x-margin #$NSViewMaxXMargin) (:min-y-margin #$NSViewMinYMargin) (:height-sizable #$NSViewHeightSizable) (:max-y-margin #$NSViewMaxYMargin))))) (defun convert-row-size-style (rss-key) (if (numberp rss-key) rss-key (ecase rss-key (:default #$NSTableViewRowSizeStyleDefault) (:custom #$NSTableViewRowSizeStyleCustom) (:small #$NSTableViewRowSizeStyleSmall) (:medium #$NSTableViewRowSizeStyleMedium) (:large #$NSTableViewRowSizeStyleLarge)))) (defun convert-rounding-mode (rm-key) (if (numberp rm-key) rm-key (ecase rm-key (:ceiling #$NSNumberFormatterRoundCeiling) (:floor #$NSNumberFormatterRoundFloor) (:down #$NSNumberFormatterRoundDown) (:up #$NSNumberFormatterRoundUp) (:half-even #$NSNumberFormatterRoundHalfEven) (:half-down #$NSNumberFormatterRoundHalfDown) (:half-up #$NSNumberFormatterRoundHalfUp)))) (defun convert-scroller-style (style-key) (if (numberp style-key) style-key (ecase style-key (:legacy #$NSScrollerStyleLegacy) (:overlay #$NSScrollerStyleOverlay)))) (defun convert-selection-highlight-style (shs-key) (if (numberp shs-key) shs-key (ecase shs-key (:none #$NSTableViewSelectionHighlightStyleNone) (:regular #$NSTableViewSelectionHighlightStyleRegular) (:source-list #$NSTableViewSelectionHighlightStyleSourceList)))) (defun convert-sharing-type (st-key) (if (numberp st-key) st-key (ecase st-key (:none #$NSWindowSharingNone) (:read-only #$NSWindowSharingReadOnly) (:read-write #$NSWindowSharingReadWrite)))) (defun convert-state (st-key) (if (numberp st-key) st-key (ecase st-key (:on #$NSOnState) (:off #$NSOffState) (:mixed #$NSMixedState)))) (defun convert-table-col-resizing (tcr-key) (if (numberp tcr-key) tcr-key (ecase tcr-key (:none #$NSTableViewNoColumnAutoresizing) (:uniform #$NSTableViewUniformColumnAutoresizingStyle) (:sequential-column #$NSTableViewSequentialColumnAutoresizingStyle) (:reverse-sequential-column #$NSTableViewReverseSequentialColumnAutoresizingStyle) (:last-column-only #$NSTableViewLastColumnOnlyAutoresizingStyle) (:first-column-only #$NSTableViewFirstColumnOnlyAutoresizingStyle)))) (defun convert-table-drag-feedback-style (td-key) (if (numberp td-key) td-key (ecase td-key (:none #$NSTableViewDraggingDestinationFeedbackStyleNone) (:regular #$NSTableViewDraggingDestinationFeedbackStyleRegular) (:source-list #$NSTableViewDraggingDestinationFeedbackStyleSourceList)))) (defun convert-table-drag-src-op (td-key) (if (numberp td-key) td-key (ecase td-key (:none #$NSDragOperationNone) (:copy #$NSDragOperationCopy) (:link #$NSDragOperationLink) (:generic #$NSDragOperationGeneric) (:private #$NSDragOperationPrivate) (:move #$NSDragOperationMove) (:delete #$NSDragOperationDelete) (:every #$NSDragOperationEvery)))) (defun convert-text-alignment (al-key) (if (numberp al-key) al-key (ecase al-key (:left #$NSLeftTextAlignment) (:right #$NSRightTextAlignment) (:center #$NSCenterTextAlignment) (:justified #$NSJustifiedTextAlignment) (:natural #$NSNaturalTextAlignment)))) (defun convert-text-bezel-style (b-key) (if (numberp b-key) b-key (ecase b-key (:square #$NSTextFieldSquareBezel) (:rounded #$NSTextFieldRoundedBezel)))) (defun convert-text-checking-type (type) (ecase type (:all-system #$NSTextCheckingAllSystemTypes) (:all-custom #$NSTextCheckingAllCustomTypes) (:all #$NSTextCheckingAllTypes))) (defun convert-text-checking-types (types) (typecase types (number types) (keyword (convert-text-checking-type types)) (list (apply #'logior (mapcar #'convert-text-checking-type types))) (t types))) ;; let it error (defun convert-text-orientation (o-key) ;; should be one of :horizontal, :h, :vertical, or :v (if (numberp o-key) o-key (ecase o-key ((:vertical :v) #$NSTextLayoutOrientationVertical) ((:horizontal :h) #$NSTextLayoutOrientationHorizontal)))) (defun convert-title-position (tp-key) (if (numberp tp-key) tp-key (ecase tp-key (:none #$NSNoTitle) (:above-top #$NSAboveTop) (:at-top #$NSAtTop) (:below-top #$NSBelowTop) (:above-bottom #$NSAboveBottom) (:at-bottom #$NSAtBottom) (:below-bottom #$NSBelowBottom)))) (defun convert-window-backing-loc (wb-key) (if (numberp wb-key) wb-key (ecase wb-key (:default #$NSWindowBackingLocationDefault) (:video-memory #$NSWindowBackingLocationVideoMemory) (:main-memory #$NSWindowBackingLocationMainMemory)))) (defun convert-window-depth (wd-key) (if (numberp wd-key) wd-key (ecase wd-key (:rgb-24 #$NSWindowDepthTwentyfourBitRGB) (:rgb-64 #$NSWindowDepthSixtyfourBitRGB) (:rgb-128 #$NSWindowDepthOnehundredtwentyeightBitRGB)))) (defun convert-window-level (wl-key) ;; For some reason the defined constants are not in the CCL interface database, but I found ;; http://dev.dartmouth.edu/svn/softdev/email/blitz/clients/BlitzMail/tags/start/projDev%20Mac%20CIncludes/CGWindowLevel.h ;; which provided the mechanism to derive the values. (if (numberp wl-key) wl-key (ecase wl-key (:normal (#_CGWindowLevelForKey #$kCGNormalWindowLevelKey)) ;; #$NSNormalWindowLevel (:floating (#_CGWindowLevelForKey #$kCGFloatingWindowLevelKey)) ;; #$NSFloatingWindowLevel (:submenu (#_CGWindowLevelForKey #$kCGTornOffMenuWindowLevelKey)) ;; #$NSSubmenuWindowLevel (same as torn-off) (:torn-off-menu (#_CGWindowLevelForKey #$kCGTornOffMenuWindowLevelKey)) ;; #$NSTornOffMenuWindowLevel (:main-menu (#_CGWindowLevelForKey #$kCGMainMenuWindowLevelKey)) ;; #$NSMainMenuWindowLevel (:status (#_CGWindowLevelForKey #$kCGStatusWindowLevelKey)) ;; #$NSStatusWindowLevel (:modal-panel (#_CGWindowLevelForKey #$kCGModalPanelWindowLevelKey)) ;; #$NSModalPanelWindowLevel (:pop-up-menu (#_CGWindowLevelForKey #$kCGPopUpMenuWindowLevelKey)) ;; #$NSPopUpMenuWindowLevel (:screen-saver (#_CGWindowLevelForKey #$kCGScreenSaverWindowLevelKey)) ;; #$NSScreenSaverWindowLevel (:dock-window (#_CGWindowLevelForKey #$kCGDockWindowLevelKey))))) ;; #$NSDockWindowLevel (defun convert-writing-direction (wd-key) (if (numberp wd-key) wd-key (ecase wd-key (:natural #$NSWritingDirectionNatural) (:left-to-right #$NSWritingDirectionLeftToRight) (:right-to-left #$NSWritingDirectionRightToLeft)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; ns-object subclasses (defmethod initialize-instance :after ((self ns:ns-document) &key (display-name nil display-name-p) ;; string or ns:ns-string (draft nil draft-p) (has-undo-manager nil has-undo-manager-p) (print-info nil print-info-p) ;; ns:ns-print-info object (undo-manager nil undo-manager-p) ;; ns:ns-undo-manager object &allow-other-keys) (when display-name-p (#/setDisplayName: self (coerce-obj display-name 'ns:ns-string))) (when draft-p (#/setDraft: self draft)) (when has-undo-manager-p (#/setHasUndoManager: self has-undo-manager)) (when print-info-p (#/setPrintInfo: self print-info)) (when undo-manager-p (#/setUndoManager: self undo-manager))) (defmethod initialize-instance :after ((self ns:ns-menu) &key (allows-context-menu-plug-ins nil allows-context-menu-plug-ins-p) (autoenables-items nil autoenables-items-p) (delegate nil delegate-p) ;; an object that follows the NSMenuDelegate protocol (font nil font-p) ;; ns:ns-font (minimum-width nil minimum-width-p) ;; number coerceable to a double float (shows-state-column nil shows-state-column-p) (title nil title-p) ;; string, attributed-string, ns:ns-string (menu-items nil menu-items-p) ;; list of ns:ns-menu-item &allow-other-keys) (when allows-context-menu-plug-ins-p (#/setAllowsContextMenuPlugIns: self allows-context-menu-plug-ins)) (when autoenables-items-p (#/setAutoenablesItems: self autoenables-items)) (when delegate-p (#/setDelegate: self delegate)) (when font-p (#/setFont: self font)) (when minimum-width-p (#/setMinimumWidth: self (cgfloat minimum-width))) (when shows-state-column-p (#/setShowsStateColumn: self shows-state-column)) (when title-p (#/setTitle: self (coerce-obj title 'ns:ns-string))) (when menu-items-p (dolist (mi menu-items) (#/addItem: self mi)))) (defmethod initialize-instance :after ((self ns:ns-menu-item) &key (action nil action-p) ;; string or objective-c selector (alternate nil alternate-p) (attributed-title nil attributed-title-p) (enabled nil enabled-p) (hidden nil hidden-p) (image nil image-p) ;; ns:ns-image (indentation-level nil indentation-level-p) ;; integer (key-equivalent nil key-equivalent-p) ;; string, attributed-string, ns:ns-string (key-equivalent-modifier-mask nil key-equivalent-modifier-mask-p) (mixed-state-image nil mixed-state-image-p) ;; ns:ns-image (off-state-image nil off-state-image-p) ;; ns:ns-image (on-state-image nil on-state-image-p) ;; ns:ns-image (represented-object nil represented-object-p) ;; ns-ns-object (state nil state-p) ;; one of :on :off :mixed (submenu nil submenu-p) ;; ns:ns-menu (tag nil tag-p) ;; integer (target nil target-p) ;; ns-ns-object (title nil title-p) ;; string, attributed-string, ns:ns-string (tool-tip nil tool-tip-p) ;; string, attributed-string, ns:ns-string (view nil view-p) ;; ns:ns-view &allow-other-keys) (when action-p (#/setAction: self (get-selector action))) (when alternate-p (#/setAlternate: self alternate)) (when attributed-title-p (#/setAttributedTitle: self (coerce-obj attributed-title 'ns:ns-attributed-string))) (when enabled-p (#/setEnabled: self enabled)) (when hidden-p (#/setHidden: self hidden)) (when image-p (#/setImage: self image)) (when indentation-level-p (#/setIndentationLevel: self indentation-level)) (when key-equivalent-p (#/setKeyEquivalent: self (coerce-obj key-equivalent 'ns:ns-string))) (when key-equivalent-modifier-mask-p (#/setKeyEquivalentModifierMask: self (convert-key-modifier-mask key-equivalent-modifier-mask))) (when mixed-state-image-p (#/setMixedStateImage: self mixed-state-image)) (when off-state-image-p (#/setOffStateImage: self off-state-image)) (when on-state-image-p (#/setOnStateImage: self on-state-image)) (when represented-object-p (#/setRepresentedObject: self represented-object)) (when state-p (#/setState: self (convert-state state))) (when submenu-p (#/setSubmenu: self submenu)) (when tag-p (#/setTag: self tag)) (when target-p (#/setTarget: self target)) (when title-p (#/setTitle: self (coerce-obj title 'ns:ns-string))) (when tool-tip-p (#/setToolTip: self (coerce-obj tool-tip 'ns:ns-string))) (when view-p (#/setView: self view))) (defmethod initialize-instance :after ((self ns:ns-table-column) &key (column-title nil column-title-p) ;; string or ns:ns-string (data-cell nil data-cell-p) ;; ns:ns-cell (editable nil editable-p) (formatter nil formatter-p) ;; ns:ns-formatter (header-cell nil header-cell-p) ;; ns:ns-cell (header-tool-tip nil header-tool-tip-p) ;; string or ns:ns-string (hidden nil hidden-p) (identifier nil identifier-p) ;; string or ns:ns-string (max-width nil max-width-p) ;; number (min-width nil min-width-p) ;; number (resizing-mask nil resizing-mask-p) ;; number or keyword: :no-resizing :auto-resizing :user-resizing (sort-descriptor-prototype nil sort-descriptor-prototype-p) ;; ns:ns-sort-descriptor (width nil width-p) ;; number (wraps nil wraps-p) &allow-other-keys) (when column-title-p (#/setStringValue: (#/headerCell self) (coerce-obj column-title 'ns:ns-string))) (when data-cell-p (#/setDataCell: self data-cell)) (when editable-p (#/setEditable: self editable)) (when formatter-p (#/setFormatter: (#/dataCell self) formatter)) (when header-cell-p (#/setHeaderCell: self header-cell)) (when header-tool-tip-p (#/setHeaderToolTip: self (coerce-obj header-tool-tip 'ns:ns-string))) (when hidden-p (#/setHidden: self hidden)) (when identifier-p (#/setIdentifier: self (coerce-obj identifier 'ns:ns-string))) (when max-width-p (#/setMaxWidth: self (cgfloat max-width))) (when min-width-p (#/setMinWidth: self (cgfloat min-width))) (when resizing-mask-p (#/setResizingMask: self (convert-column-resizing resizing-mask))) (when sort-descriptor-prototype-p (#/setSortDescriptorPrototype: self sort-descriptor-prototype)) (when width-p (#/setWidth: self (cgfloat width))) (when wraps-p (#/setWraps: (#/dataCell self) wraps))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; ns-formatter subclasses (defmethod initialize-instance :after ((self ns:ns-date-formatter) &key (calendar nil calendar-p) ;; ns:ns-calendar (date-format nil date-format-p) ;; string or ns:ns-string (date-style nil date-style-p) ;; number or keyword: :none :short :medium :long :full (default-date nil default-date-p) ;; lisp date or ns:ns-date (does-relative-date-formatting nil does-relative-date-formatting-p) (era-symbols nil era-symbols-p) ;; list of strings or ns:ns-string objects (gregorian-start-date nil gregorian-start-date-p) ;; lisp date or ns:ns-date (lenient nil lenient-p) (locale nil locale-p) ;; ns:ns-locale (long-era-symbols nil long-era-symbols-p) ;; list of strings or ns:ns-string objects (month-symbols nil month-symbols-p) ;; list of strings or ns:ns-string objects (pm-symbol nil pm-symbol-p) ;; string or ns:ns-string (quarter-symbols nil quarter-symbols-p) ;; list of strings or ns:ns-string objects (short-month-symbols nil short-month-symbols-p) ;; list of strings or ns:ns-string objects (short-quarter-symbols nil short-quarter-symbols-p) ;; list of strings or ns:ns-string objects (short-standalone-month-symbols nil short-standalone-month-symbols-p) ;; list of strings or ns:ns-string objects (short-standalone-quarter-symbols nil short-standalone-quarter-symbols-p) ;; list of strings or ns:ns-string objects (short-standalone-weekday-symbols nil short-standalone-weekday-symbols-p) ;; list of strings or ns:ns-string objects (short-weekday-symbols nil short-weekday-symbols-p) ;; list of strings or ns:ns-string objects (standalone-month-symbols nil standalone-month-symbols-p) ;; list of strings or ns:ns-string objects (standalone-quarter-symbols nil standalone-quarter-symbols-p) ;; list of strings or ns:ns-string objects (standalone-weekday-symbols nil standalone-weekday-symbols-p) ;; list of strings or ns:ns-string objects (time-style nil time-style-p) ;; number or keyword: :none :short :medium :long :full (time-zone nil time-zone-p) ;; ns:ns-time-zone (two-digit-start-date nil two-digit-start-date-p) ;; lisp date or ns:ns-date (very-short-month-symbols nil very-short-month-symbols-p) ;; list of strings or ns:ns-string objects (very-short-standalone-month-symbols nil very-short-standalone-month-symbols-p) ;; list of strings or ns:ns-string objects (very-short-standalone-weekday-symbols nil very-short-standalone-weekday-symbols-p) ;; list of strings or ns:ns-string objects (very-short-weekday-symbols nil very-short-weekday-symbols-p) ;; list of strings or ns:ns-string objects (weekday-symbols nil weekday-symbols-p) ;; list of strings or ns:ns-string objects &allow-other-keys) (when calendar-p (#/setCalendar: self calendar)) (when date-format-p (#/setDateFormat: self (coerce-obj date-format 'ns:ns-string))) (when date-style-p (#/setDateStyle: self (convert-date-style date-style))) (when default-date-p (#/setDefaultDate: self (coerce-obj default-date 'ns:ns-date))) (when does-relative-date-formatting-p (#/setDoesRelativeDateFormatting: self does-relative-date-formatting)) (when era-symbols-p (#/setEraSymbols: self (coerce-obj era-symbols 'ns:ns-array))) (when gregorian-start-date-p (#/setGregorianStartDate: self (coerce-obj gregorian-start-date 'ns:ns-date))) (when lenient-p (#/setLenient: self lenient)) (when locale-p (#/setLocale: self locale)) (when long-era-symbols-p (#/setLongEraSymbols: self (coerce-obj long-era-symbols 'ns:ns-array))) (when month-symbols-p (#/setMonthSymbols: self (coerce-obj month-symbols 'ns:ns-array))) (when pm-symbol-p (#/setPMSymbol: self (coerce-obj pm-symbol 'ns:ns-string))) (when quarter-symbols-p (#/setQuarterSymbols: self (coerce-obj quarter-symbols 'ns:ns-array))) (when short-month-symbols-p (#/setShortMonthSymbols: self (coerce-obj short-month-symbols 'ns:ns-array))) (when short-quarter-symbols-p (#/setShortQuarterSymbols: self (coerce-obj short-quarter-symbols 'ns:ns-array))) (when short-standalone-month-symbols-p (#/setShortStandaloneMonthSymbols: self (coerce-obj short-standalone-month-symbols 'ns:ns-array))) (when short-standalone-quarter-symbols-p (#/setShortStandaloneQuarterSymbols: self (coerce-obj short-standalone-quarter-symbols 'ns:ns-array))) (when short-standalone-weekday-symbols-p (#/setShortStandaloneWeekdaySymbols: self (coerce-obj short-standalone-weekday-symbols 'ns:ns-array))) (when short-weekday-symbols-p (#/setShortWeekdaySymbols: self (coerce-obj short-weekday-symbols 'ns:ns-array))) (when standalone-month-symbols-p (#/setStandaloneMonthSymbols: self (coerce-obj standalone-month-symbols 'ns:ns-array))) (when standalone-quarter-symbols-p (#/setStandaloneQuarterSymbols: self (coerce-obj standalone-quarter-symbols 'ns:ns-array))) (when standalone-weekday-symbols-p (#/setStandaloneWeekdaySymbols: self (coerce-obj standalone-weekday-symbols 'ns:ns-array))) (when time-style-p (#/setTimeStyle: self (convert-date-style time-style))) ;; date and time use same constants (when time-zone-p (#/setTimeZone: self time-zone)) (when two-digit-start-date-p (#/setTwoDigitStartDate: self (coerce-obj two-digit-start-date 'ns:ns-date))) (when very-short-month-symbols-p (#/setVeryShortMonthSymbols: self (coerce-obj very-short-month-symbols 'ns:ns-array))) (when very-short-standalone-month-symbols-p (#/setVeryShortStandaloneMonthSymbols: self (coerce-obj very-short-standalone-month-symbols 'ns:ns-array))) (when very-short-standalone-weekday-symbols-p (#/setVeryShortStandaloneWeekdaySymbols: self (coerce-obj very-short-standalone-weekday-symbols 'ns:ns-array))) (when very-short-weekday-symbols-p (#/setVeryShortWeekdaySymbols: self (coerce-obj very-short-weekday-symbols 'ns:ns-array))) (when weekday-symbols-p (#/setWeekdaySymbols: self (coerce-obj weekday-symbols 'ns:ns-array)))) (defmethod initialize-instance :after ((self ns:ns-number-formatter) &key (allows-floats nil allows-floats-p) (always-shows-decimal-separator nil always-shows-decimal-separator-p) (attributed-string-for-nil nil attributed-string-for-nil-p) ;; string attributed-string ns:ns-string or ns:ns-attributed-string (attributed-string-for-not-a-number nil attributed-string-for-not-a-number-p) ;; string attributed-string ns:ns-string or ns:ns-attributed-string (attributed-string-for-zero nil attributed-string-for-zero-p) ;; string attributed-string ns:ns-string or ns:ns-attributed-string (currency-decimal-separator nil currency-decimal-separator-p) ;; string or ns:ns-string (currency-grouping-separator nil currency-grouping-separator-p) ;; string or ns:ns-string (currency-symbol nil currency-symbol-p) ;; string or ns:ns-string (decimal-separator nil decimal-separator-p) ;; string or ns:ns-string (exponent-symbol nil exponent-symbol-p) ;; string or ns:ns-string (format nil format-p) ;; string or ns:ns-string (format-width nil format-width-p) ;; integer (generates-decimal-numbers nil generates-decimal-numbers-p) (grouping-separator nil grouping-separator-p) ;; string or ns:ns-string (grouping-size nil grouping-size-p) ;; integer (has-thousand-separators nil has-thousand-separators-p) (international-currency-symbol nil international-currency-symbol-p) ;; string or ns:ns-string (lenient nil lenient-p) (locale nil locale-p) ;; ns:ns-locale (localizes-format nil localizes-format-p) (maximum nil maximum-p) ;; number (maximum-fraction-digits nil maximum-fraction-digits-p) ;; integer (maximum-integer-digits nil maximum-integer-digits-p) ;; integer (maximum-significant-digits nil maximum-significant-digits-p) ;; integer (minimum nil minimum-p) ;; number (minimum-fraction-digits nil minimum-fraction-digits-p) ;; integer (minimum-integer-digits nil minimum-integer-digits-p) ;; integer (minimum-significant-digits nil minimum-significant-digits-p) ;; integer (minus-sign nil minus-sign-p) ;; string or ns:ns-string (multiplier nil multiplier-p) ;; number (negative-format nil negative-format-p) ;; string or ns:ns-string (negative-infinity-symbol nil negative-infinity-symbol-p) ;; string or ns:ns-string (negative-prefix nil negative-prefix-p) ;; string or ns:ns-string (negative-suffix nil negative-suffix-p) ;; string or ns:ns-string (nil-symbol nil nil-symbol-p) ;; string or ns:ns-string (not-a-number-symbol nil not-a-number-symbol-p) ;; string or ns:ns-string (number-style nil number-style-p) ;; number or keyword: :none :decimal :currency :percent :scientific :spell-out (padding-character nil padding-character-p) ;; string or ns:ns-string (padding-position nil padding-position-p) ;; number or keyword: :before-prefix :after-prefix :before-suffix :after-suffix (partial-string-validation-enabled nil partial-string-validation-enabled-p) (percent-symbol nil percent-symbol-p) ;; string or ns:ns-string (per-mill-symbol nil per-mill-symbol-p) ;; string or ns:ns-string (plus-sign nil plus-sign-p) ;; string or ns:ns-string (positive-format nil positive-format-p) ;; string or ns:ns-string (positive-infinity-symbol nil positive-infinity-symbol-p) ;; string or ns:ns-string (positive-prefix nil positive-prefix-p) ;; string or ns:ns-string (positive-suffix nil positive-suffix-p) ;; string or ns:ns-string (rounding-behavior nil rounding-behavior-p) ;; ns:ns-decimal-number-handler (rounding-increment nil rounding-increment-p) ;; number (rounding-mode nil rounding-mode-p) ;; number or keyword: :ceiling :floor :down :up :half-even :half-down :half-up (secondary-grouping-size nil secondary-grouping-size-p) ;; integer (text-attributes-for-negative-infinity nil text-attributes-for-negative-infinity-p) ;; assoc-list, hash-table, or ns:ns-dictionary of attribute-value pairs (text-attributes-for-negative-values nil text-attributes-for-negative-values-p) ;; assoc-list, hash-table, or ns:ns-dictionary of attribute-value pairs (text-attributes-for-nil nil text-attributes-for-nil-p) ;; assoc-list, hash-table, or ns:ns-dictionary of attribute-value pairs (text-attributes-for-not-a-number nil text-attributes-for-not-a-number-p) ;; assoc-list, hash-table, or ns:ns-dictionary of attribute-value pairs (text-attributes-for-positive-infinity nil text-attributes-for-positive-infinity-p) ;; assoc-list, hash-table, or ns:ns-dictionary of attribute-value pairs (text-attributes-for-positive-values nil text-attributes-for-positive-values-p) ;; assoc-list, hash-table, or ns:ns-dictionary of attribute-value pairs (text-attributes-for-zero nil text-attributes-for-zero-p) ;; assoc-list, hash-table, or ns:ns-dictionary of attribute-value pairs (thousand-separator nil thousand-separator-p) ;; string or ns:ns-string (uses-grouping-separator nil uses-grouping-separator-p) (uses-significant-digits nil uses-significant-digits-p) (zero-symbol nil zero-symbol-p) ;; string or ns:ns-string &allow-other-keys) ;; set basic style first, permitting modifications with other keywords (when number-style-p (#/setNumberStyle: self (convert-number-style number-style))) (when allows-floats-p (#/setAllowsFloats: self allows-floats)) (when always-shows-decimal-separator-p (#/setAlwaysShowsDecimalSeparator: self always-shows-decimal-separator)) (when attributed-string-for-nil-p (#/setAttributedStringForNil: self (coerce-obj attributed-string-for-nil 'ns:ns-attributed-string))) (when attributed-string-for-not-a-number-p (#/setAttributedStringForNotANumber: self (coerce-obj attributed-string-for-not-a-number 'ns:ns-attributed-string))) (when attributed-string-for-zero-p (#/setAttributedStringForZero: self (coerce-obj attributed-string-for-zero 'ns:ns-attributed-string))) (when currency-decimal-separator-p (#/setCurrencyDecimalSeparator: self (coerce-obj currency-decimal-separator 'ns:ns-string))) (when currency-grouping-separator-p (#/setCurrencyGroupingSeparator: self (coerce-obj currency-grouping-separator 'ns:ns-string))) (when currency-symbol-p (#/setCurrencySymbol: self (coerce-obj currency-symbol 'ns:ns-string))) (when decimal-separator-p (#/setDecimalSeparator: self (coerce-obj decimal-separator 'ns:ns-string))) (when exponent-symbol-p (#/setExponentSymbol: self (coerce-obj exponent-symbol 'ns:ns-string))) (when format-p (#/setFormat: self (coerce-obj format 'ns:ns-string))) (when format-width-p (#/setFormatWidth: self (coerce format-width 'integer))) (when generates-decimal-numbers-p (#/setGeneratesDecimalNumbers: self generates-decimal-numbers)) (when grouping-separator-p (#/setGroupingSeparator: self (coerce-obj grouping-separator 'ns:ns-string))) (when grouping-size-p (#/setGroupingSize: self (coerce grouping-size 'integer))) (when has-thousand-separators-p (#/setHasThousandSeparators: self has-thousand-separators)) (when international-currency-symbol-p (#/setInternationalCurrencySymbol: self (coerce-obj international-currency-symbol 'ns:ns-string))) (when lenient-p (#/setLenient: self lenient)) (when locale-p (#/setLocale: self locale)) (when localizes-format-p (#/setLocalizesFormat: self localizes-format)) (when maximum-p (#/setMaximum: self (coerce-obj maximum 'ns:ns-number))) (when maximum-fraction-digits-p (#/setMaximumFractionDigits: self (coerce maximum-fraction-digits 'integer))) (when maximum-integer-digits-p (#/setMaximumIntegerDigits: self (coerce maximum-integer-digits 'integer))) (when maximum-significant-digits-p (#/setMaximumSignificantDigits: self (coerce maximum-significant-digits 'integer))) (when minimum-p (#/setMinimum: self (coerce-obj minimum 'ns:ns-number))) (when minimum-fraction-digits-p (#/setMinimumFractionDigits: self (coerce minimum-fraction-digits 'integer))) (when minimum-integer-digits-p (#/setMinimumIntegerDigits: self (coerce minimum-integer-digits 'integer))) (when minimum-significant-digits-p (#/setMinimumSignificantDigits: self (coerce minimum-significant-digits 'integer))) (when minus-sign-p (#/setMinusSign: self (coerce-obj minus-sign 'ns:ns-string))) (when multiplier-p (#/setMultiplier: self (coerce-obj multiplier 'ns:ns-number))) (when negative-format-p (#/setNegativeFormat: self (coerce-obj negative-format 'ns:ns-string))) (when negative-infinity-symbol-p (#/setNegativeInfinitySymbol: self (coerce-obj negative-infinity-symbol 'ns:ns-string))) (when negative-prefix-p (#/setNegativePrefix: self (coerce-obj negative-prefix 'ns:ns-string))) (when negative-suffix-p (#/setNegativeSuffix: self (coerce-obj negative-suffix 'ns:ns-string))) (when nil-symbol-p (#/setNilSymbol: self (coerce-obj nil-symbol 'ns:ns-string))) (when not-a-number-symbol-p (#/setNotANumberSymbol: self (coerce-obj not-a-number-symbol 'ns:ns-string))) (when padding-character-p (#/setPaddingCharacter: self (coerce-obj padding-character 'ns:ns-string))) (when padding-position-p (#/setPaddingPosition: self (convert-padding-position padding-position))) (when partial-string-validation-enabled-p (#/setPartialStringValidationEnabled: self partial-string-validation-enabled)) (when percent-symbol-p (#/setPercentSymbol: self (coerce-obj percent-symbol 'ns:ns-string))) (when per-mill-symbol-p (#/setPerMillSymbol: self (coerce-obj per-mill-symbol 'ns:ns-string))) (when plus-sign-p (#/setPlusSign: self (coerce-obj plus-sign 'ns:ns-string))) (when positive-format-p (#/setPositiveFormat: self (coerce-obj positive-format 'ns:ns-string))) (when positive-infinity-symbol-p (#/setPositiveInfinitySymbol: self (coerce-obj positive-infinity-symbol 'ns:ns-string))) (when positive-prefix-p (#/setPositivePrefix: self (coerce-obj positive-prefix 'ns:ns-string))) (when positive-suffix-p (#/setPositiveSuffix: self (coerce-obj positive-suffix 'ns:ns-string))) (when rounding-behavior-p (#/setRoundingBehavior: self rounding-behavior)) (when rounding-increment-p (#/setRoundingIncrement: self (coerce-obj rounding-increment 'ns:ns-number))) (when rounding-mode-p (#/setRoundingMode: self (convert-rounding-mode rounding-mode))) (when secondary-grouping-size-p (#/setSecondaryGroupingSize: self (coerce secondary-grouping-size 'integer))) (when text-attributes-for-negative-infinity-p (#/setTextAttributesForNegativeInfinity: self (coerce-obj text-attributes-for-negative-infinity 'ns:ns-dictionary))) (when text-attributes-for-negative-values-p (#/setTextAttributesForNegativeValues: self (coerce-obj text-attributes-for-negative-values 'ns:ns-dictionary))) (when text-attributes-for-nil-p (#/setTextAttributesForNil: self (coerce-obj text-attributes-for-nil 'ns:ns-dictionary))) (when text-attributes-for-not-a-number-p (#/setTextAttributesForNotANumber: self (coerce-obj text-attributes-for-not-a-number 'ns:ns-dictionary))) (when text-attributes-for-positive-infinity-p (#/setTextAttributesForPositiveInfinity: self (coerce-obj text-attributes-for-positive-infinity 'ns:ns-dictionary))) (when text-attributes-for-positive-values-p (#/setTextAttributesForPositiveValues: self (coerce-obj text-attributes-for-positive-values 'ns:ns-dictionary))) (when text-attributes-for-zero-p (#/setTextAttributesForZero: self (coerce-obj text-attributes-for-zero 'ns:ns-dictionary))) (when thousand-separator-p (#/setThousandSeparator: self (coerce-obj thousand-separator 'ns:ns-string))) (when uses-grouping-separator-p (#/setUsesGroupingSeparator: self uses-grouping-separator)) (when uses-significant-digits-p (#/setUsesSignificantDigits: self uses-significant-digits)) (when zero-symbol-p (#/setZeroSymbol: self (coerce-obj zero-symbol 'ns:ns-string)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; ns-responder subclasses (defmethod initialize-instance :after ((self ns:ns-view) &key (accepts-touch-events nil accepts-touch-events-p) (alpha-value 0 alpha-value-p) (animations nil animations-p) (autoresizes-subviews nil autoresizes-subviews-p) (autoresizing-mask 0 autoresizing-mask-p) ;; number or list of resizing keys: see convert-resizing-mask (bounds 0 bounds-p) ;; ns:ns-rectangle or list: (x y width height) (bounds-origin 0 bounds-origin-p) ;; ns:ns-point or list: (x y) (bounds-rotation 0 bounds-rotation-p) ;; angle in degrees (bounds-size 0 bounds-size-p) ;; ns:ns-size or list: (width height) (can-draw-concurrently nil can-draw-concurrently-p) (focus-ring-type nil focus-ring-type-p) ;; number or keyword: see convert-focus-ring-type (frame nil frame-p) ;; ns:ns-rect (frame-center-rotation nil frame-center-rotation-p) ;; angle in degrees (frame-origin nil frame-origin-p) ;; ns:ns-point or list: (x y) (frame-rotation nil frame-rotation-p) ;; angle in degrees (frame-size nil frame-size-p) ;; ns:ns-size or list: (width height) (hidden nil hidden-p) (layer nil layer-p) ;; CALayer (posts-bounds-changed-notifications nil posts-bounds-changed-notifications-p) (posts-frame-changed-notifications nil posts-frame-changed-notifications-p) (shadow nil shadow-p) ;; ns:ns-shadow (subviews nil subviews-p) ;; list of subviews (tool-tip "" tool-tip-p) ;; string (wants-resting-touches nil wants-resting-touches-p) &allow-other-keys) (when accepts-touch-events-p (#/setAcceptsTouchEvents: self accepts-touch-events)) (when alpha-value-p (#/setAlphaValue: self (cgfloat alpha-value))) (when animations-p (#/setAnimations: self (coerce-obj animations 'ns:ns-dictionary))) (when autoresizes-subviews-p (#/setAutoresizesSubviews: self autoresizes-subviews)) (when autoresizing-mask-p (#/setAutoresizingMask: self (convert-resizing-mask autoresizing-mask))) (when bounds-p (#/setBounds: self (coerce-obj bounds 'ns:ns-rect))) (when bounds-origin-p (#/setBoundsOrigin: self (coerce-obj bounds-origin 'ns:ns-point))) (when bounds-rotation-p (#/setBoundsRotation: self (cgfloat bounds-rotation))) (when bounds-size-p (#/setBoundsSize: self (coerce-obj bounds-size 'ns:ns-size))) (when can-draw-concurrently-p (#/setCanDrawConcurrently: self can-draw-concurrently)) (when focus-ring-type-p (#/setFocusRingType: self (convert-focus-ring-type focus-ring-type))) (when frame-p (#/setFrame: self (coerce-obj frame 'ns:ns-rect))) (when frame-center-rotation-p (#/setFrameCenterRotation: self (cgfloat frame-center-rotation))) (when frame-origin-p (#/setFrameOrigin: self (coerce-obj frame-origin 'ns:ns-point))) (when frame-rotation-p (#/setFrameRotation: self (cgfloat frame-rotation))) (when frame-size-p (#/setFrameSize: self (coerce-obj frame-size 'ns:ns-size))) (when hidden-p (#/setHidden: self hidden)) (when layer-p (#/setLayer: self layer)) (when posts-bounds-changed-notifications-p (#/setPostsBoundsChangedNotifications: self posts-bounds-changed-notifications)) (when posts-frame-changed-notifications-p (#/setPostsFrameChangedNotifications: self posts-frame-changed-notifications)) (when shadow-p (#/setShadow: self shadow)) (when subviews-p (#/setSubviews: self (coerce-obj subviews 'ns:ns-array))) (when tool-tip-p (#/setToolTip: self (coerce-obj tool-tip 'ns:ns-string))) (when wants-resting-touches-p (#/setWantsRestingTouches: self wants-resting-touches))) (defmethod initialize-instance :after ((self ns:ns-window) &key (accepts-mouse-moved-events nil accepts-mouse-moved-events-p) (allows-concurrent-view-drawing nil allows-concurrent-view-drawing-p) (allows-tool-tips-when-application-is-inactive nil allows-tool-tips-when-application-is-inactive-p) (alpha-value 0 alpha-value-p) (animation-behavior nil animation-behavior-p) ;; number or keyword: see convert-animation-behavior (aspect-ratio nil aspect-ratio-p) ;; ns:ns-size or list: (width height) (autodisplay nil autodisplay-p) (background-color nil background-color-p) ;; ns:ns-color or keyword acceptable to (coerce-obj <keyword> 'ns:ns-color) (can-become-visible-without-login nil can-become-visible-without-login-p) (can-hide nil can-hide-p) (collection-behavior nil collection-behavior-p) ;; number, keyword, or list of keywords: see convert-collection-bahavior (color-space nil color-space-p) ;; ns:ns-color-space (content-aspect-ratio nil content-aspect-ratio-p) ;; ns:ns-size or list: (width height) (content-max-size nil content-max-size-p) ;; ns:ns-size or list: (width height) (content-min-size nil content-min-size-p) (content-resize-increments nil content-resize-increments-p) ;; ns:ns-size or list: (width height) (content-size nil content-size-p) ;; ns:ns-size or list: (width height) (content-view nil content-view-p) ;; ns:ns-view (content-subviews nil content-subviews-p) ;; a list of subviews to add to the window's content view (default-button-cell nil default-button-cell-p) ;; ns:ns-button-cell (delegate nil delegate-p) ;; ns:ns-object (depth-limit nil depth-limit-p) ;; number or keyword: :rgb-24, :rgb-64 or :rgb-128 (displays-when-screen-profile-changes nil displays-when-screen-profile-changes-p) (dynamic-depth-limit nil dynamic-depth-limit-p) ;; t or nil (excluded-from-windows-menu nil excluded-from-windows-menu-p) (frame nil frame-p) ;; ns:ns-rect or (frame-autosave-name nil frame-autosave-name-p) ;; string or ns:ns-string (frame-from-string nil frame-from-string-p) ;; string or ns:ns-string (frame-origin nil frame-origin-p) ;; ns-point or list: (x y) (frame-top-left-point nil frame-top-left-point-p) ;; ns-point or list: (x y) (frame-using-name nil frame-using-name-p) ;; string or ns:ns-string (has-shadow nil has-shadow-p) (hides-on-deactivate nil hides-on-deactivate-p) (ignores-mouse-events nil ignores-mouse-events-p) (initial-first-responder nil initial-first-responder-p) ;; ns:ns-view (level nil level-p) ;; number or keyword: see convert-window-level (max-size nil max-size-p) ;; ns:ns-size or list: (width height) (miniwindow-image nil miniwindow-image-p) ;; ns:ns-image (miniwindow-title nil miniwindow-title-p) ;; string or ns:ns-string (min-size nil min-size-p) ;; ns:ns-size or list: (width height) (movable nil movable-p) (movable-by-window-background nil movable-by-window-background-p) (one-shot nil one-shot-p) (opaque nil opaque-p) (preferred-backing-location nil preferred-backing-location-p) ;; number or keyword: :default :video-memory :main-memory (preserves-content-during-live-resize nil preserves-content-during-live-resize-p) (prevents-application-termination-when-modal nil prevents-application-termination-when-modal-p) (released-when-closed nil released-when-closed-p) (represented-filename nil represented-filename-p) ;; string or ns:ns-string (represented-url nil represented-url-p) ;; ns:ns-url (resize-increments nil resize-increments-p) ;; ns-size or list: (width height) (restorable nil restorable-p) (restoration-class nil restoration-class-p) ;; class that conforms to the NSWindowRestoration protocol (sharing-type nil sharing-type-p) ;; number or keyword: see convert-sharing-type (shows-resize-indicator nil shows-resize-indicator-p) (shows-toolbar-button nil shows-toolbar-button-p) (titled t titled-p) (closable t closable-p) (resizable t resizable-p) (miniaturizable t miniaturizable-p) (title nil title-p) ;; string or ns:ns-string (title-with-represented-filename nil title-with-represented-filename-p) ;; string or ns:ns-string (toolbar nil toolbar-p) ;; ns:ns-toolbar (window-controller nil window-controller-p) ;; ns:ns-window-controller &allow-other-keys) (when accepts-mouse-moved-events-p (#/setAcceptsMouseMovedEvents: self accepts-mouse-moved-events)) (when allows-concurrent-view-drawing-p (#/setAllowsConcurrentViewDrawing: self allows-concurrent-view-drawing)) (when allows-tool-tips-when-application-is-inactive-p (#/setAllowsToolTipsWhenApplicationIsInactive: self allows-tool-tips-when-application-is-inactive)) (when alpha-value-p (#/setAlphaValue: self (cgfloat alpha-value))) (when animation-behavior-p (#/setAnimationBehavior: self (convert-animation-behavior animation-behavior))) (when aspect-ratio-p (#/setAspectRatio: self (coerce-obj aspect-ratio 'ns:ns-size))) (when autodisplay-p (#/setAutodisplay: self autodisplay)) (when background-color-p (#/setBackgroundColor: self (coerce-obj background-color 'ns:ns-color))) (when can-become-visible-without-login-p (#/setCanBecomeVisibleWithoutLogin: self can-become-visible-without-login)) (when can-hide-p (#/setCanHide: self can-hide)) (when collection-behavior-p (#/setCollectionBehavior: self (convert-collection-behavior collection-behavior))) (when color-space-p (#/setColorSpace: self color-space)) (when content-aspect-ratio-p (#/setContentAspectRatio: self (coerce-obj content-aspect-ratio 'ns:ns-size))) (when content-max-size-p (#/setContentMaxSize: self (coerce-obj content-max-size 'ns:ns-size))) (when content-min-size-p (#/setContentMinSize: self (coerce-obj content-min-size 'ns:ns-size))) (when content-resize-increments-p (#/setContentResizeIncrements: self (coerce-obj content-resize-increments 'ns:ns-size))) (when content-size-p (#/setContentSize: self (coerce-obj content-size 'ns:ns-size))) (when content-view-p (#/setContentView: self content-view)) (when content-subviews-p (let ((cv (#/contentView self))) (dolist (sv content-subviews) (#/addSubview: cv sv)))) (when default-button-cell-p (#/setDefaultButtonCell: self default-button-cell)) (when delegate-p (#/setDelegate: self delegate)) (when depth-limit-p (#/setDepthLimit: self (convert-window-depth depth-limit))) (when displays-when-screen-profile-changes-p (#/setDisplaysWhenScreenProfileChanges: self displays-when-screen-profile-changes)) (when dynamic-depth-limit-p (#/setDynamicDepthLimit: self dynamic-depth-limit)) (when excluded-from-windows-menu-p (#/setExcludedFromWindowsMenu: self excluded-from-windows-menu)) (when frame-p (#/setFrame:display: self (coerce-obj frame 'ns:ns-rect) #$NO)) (when frame-autosave-name-p (#/setFrameAutosaveName: self (coerce-obj frame-autosave-name 'ns:ns-string))) (when frame-from-string-p (#/setFrameFromString: self (coerce-obj frame-from-string 'ns:ns-string))) (when frame-origin-p (#/setFrameOrigin: self (coerce-obj frame-origin 'ns:ns-point))) (when frame-top-left-point-p (#/setFrameTopLeftPoint: self (coerce-obj frame-top-left-point 'ns:ns-point))) (when frame-using-name-p (#/setFrameUsingName: self (coerce-obj frame-using-name 'ns:ns-string))) (when has-shadow-p (#/setHasShadow: self has-shadow)) (when hides-on-deactivate-p (#/setHidesOnDeactivate: self hides-on-deactivate)) (when ignores-mouse-events-p (#/setIgnoresMouseEvents: self ignores-mouse-events)) (when initial-first-responder-p (#/setInitialFirstResponder: self initial-first-responder)) (when level-p (#/setLevel: self (convert-window-level level))) (when max-size-p (#/setMaxSize: self (coerce-obj max-size 'ns:ns-size))) (when miniwindow-image-p (#/setMiniwindowImage: self miniwindow-image)) (when miniwindow-title-p (#/setMiniwindowTitle: self (coerce-obj miniwindow-title 'ns:ns-string))) (when min-size-p (#/setMinSize: self (coerce-obj min-size 'ns:ns-size))) (when movable-p (#/setMovable: self movable)) (when movable-by-window-background-p (#/setMovableByWindowBackground: self movable-by-window-background)) (when one-shot-p (#/setOneShot: self one-shot)) (when opaque-p (#/setOpaque: self opaque)) (when preferred-backing-location-p (#/setPreferredBackingLocation: self (convert-window-backing-loc preferred-backing-location))) (when preserves-content-during-live-resize-p (#/setPreservesContentDuringLiveResize: self preserves-content-during-live-resize)) (when prevents-application-termination-when-modal-p (#/setPreventsApplicationTerminationWhenModal: self prevents-application-termination-when-modal)) (when released-when-closed-p (#/setReleasedWhenClosed: self released-when-closed)) (when represented-filename-p (#/setRepresentedFilename: self (coerce-obj represented-filename 'ns:ns-string))) (when represented-url-p (#/setRepresentedURL: self represented-url)) (when resize-increments-p (#/setResizeIncrements: self (coerce-obj resize-increments 'ns:ns-size))) (when restorable-p (#/setRestorable: self restorable)) (when restoration-class-p (#/setRestorationClass: self restoration-class)) (when sharing-type-p (#/setSharingType: self (convert-sharing-type sharing-type))) (when shows-resize-indicator-p (#/setShowsResizeIndicator: self shows-resize-indicator)) (when (or titled-p closable-p resizable-p miniaturizable-p) (#/setStyleMask: self (+ (if titled #$NSTitledWindowMask 0) (if closable #$NSClosableWindowMask 0) (if resizable #$NSResizableWindowMask 0) (if miniaturizable #$NSMiniaturizableWindowMask 0)))) (when (and title-p title) ;; need the title check for back compatibility with initialize-instance :after method ;; defined in cocoa-window.lisp which this will replace (#/setTitle: self (coerce-obj title 'ns:ns-string))) (when title-with-represented-filename-p (#/setTitleWithRepresentedFilename: self (coerce-obj title-with-represented-filename 'ns:ns-string))) (when toolbar-p (#/setToolbar: self toolbar)) (when shows-toolbar-button-p (#/setShowsToolbarButton: self shows-toolbar-button)) (when window-controller-p (#/setWindowController: self window-controller))) (defmethod initialize-instance :after ((self ns:ns-window-controller) &key (window nil window-p) &allow-other-keys) (when window-p (#/initWithWindow: self window))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; ns-view subclasses (defmethod initialize-instance :after ((self ns:ns-box) &key (border-color nil border-color-p) ;; ns:ns-color or keyword (border-type nil border-type-p) ;; number or keyword (border-width nil border-width-p) ;; number (box-type nil box-type-p) ;; number or keyword (content-view nil content-view-p) ;; ns:ns-view (content-view-margins nil content-view-margins-p) ;; ns:ns-size or list of the form (width height) (corner-radius nil corner-radius-p) ;; number (fill-color nil fill-color-p) ;; ns:ns-color or keyword (title nil title-p) ;; string, ns:ns-string (title-font nil title-font-p) ;; ns:ns-font (title-position nil title-position-p) ;; title-position keyword (transparent nil transparent-p) &allow-other-keys) (when border-color-p (#/setBorderColor: self (coerce-obj border-color 'ns:ns-color))) (when border-type-p (#/setBorderType: self (convert-border border-type))) (when border-width-p (#/setBorderWidth: self (cgfloat border-width))) (when box-type-p (#/setBoxType: self (convert-box-type box-type))) (when content-view-p (#/setContentView: self content-view)) (when content-view-margins-p (#/setContentViewMargins: self (coerce-obj content-view-margins 'ns:ns-size)) (#/sizeToFit self)) (when corner-radius-p (#/setCornerRadius: self (cgfloat corner-radius))) (when fill-color-p (#/setFillColor: self (coerce-obj fill-color 'ns:ns-color))) (when title-p (#/setTitle: self (coerce-obj title 'ns:ns-string))) (when title-font-p (#/setTitleFont: self title-font)) (when title-position-p (#/setTitlePosition: self (convert-title-position title-position))) (when transparent-p (#/setTransparent: self transparent))) (defmethod initialize-instance :after ((self ns:ns-combo-box) &key (button-bordered nil button-bordered-p) (completes nil completes-p) (data-source nil data-source-p) ;; object that conforms to the NSComboBoxDataSource protocol (delegate nil delegate-p) ;; object that conforms to the NSComboBoxDelegate protocol (has-vertical-scroller nil has-vertical-scroller-p) (intercell-spacing nil intercell-spacing-p) ;; ns:ns-size or list of the form (width height) (item-height nil item-height-p) ;; number coercable to a double-float (items-with-object-values nil items-with-object-values-p) ;; list of strings or numbers (number-of-visible-items nil number-of-visible-items-p) ;; integer number (uses-data-source nil uses-data-source-p) &allow-other-keys) (when button-bordered-p (#/setButtonBordered: self button-bordered)) (when completes-p (#/setCompletes: self completes)) (when uses-data-source-p ;; must come before data-source (#/setUsesDataSource: self uses-data-source)) (when data-source-p (#/setDataSource: self data-source)) (when delegate-p (#/setDelegate: self delegate)) (when has-vertical-scroller-p (#/setHasVerticalScroller: self has-vertical-scroller)) (when intercell-spacing-p (#/setIntercellSpacing: self (coerce-obj intercell-spacing 'ns:ns-size))) (when item-height-p (#/setItemHeight: self (cgfloat item-height))) (when items-with-object-values-p (#/addItemsWithObjectValues: self (coerce-obj items-with-object-values 'ns:ns-array))) (when number-of-visible-items-p (#/setNumberOfVisibleItems: self (coerce number-of-visible-items 'integer)))) (defmethod initialize-instance :after ((self ns:ns-control) &key (action nil action-p) ;; string (alignment :natural alignment-p) ;; number or keyword defined in convert-text-alignment (allows-undo nil allows-undo-p) (attributed-string-value "" attributed-string-value-p) ;; string or attributed-string (base-writing-direction :natural base-writing-direction-p) ;; number or keyword from convert-writing-direction (continuous nil continuous-p) (initial-value nil initial-value-p) ;; numeric value (enabled t enabled-p) (font nil font-p) ;; ns:ns-font (formatter nil formatter-p) ;; ns:ns-formatter, see formatters.lisp (ignores-multi-click t ignores-multi-click-p) (refuses-first-responder nil refuses-first-responder-p) (tag 0 tag-p) ;; integer (target nil target-p) ;; ns:ns-object &allow-other-keys) ;; see view.lisp for other allowed keywords (when action-p (#/setAction: self (get-selector action))) (when alignment-p (#/setAlignment: self (convert-text-alignment alignment))) (when allows-undo-p (#/setAllowsUndo: (#/cell self) allows-undo)) (when attributed-string-value-p (#/setAttributedStringValue: self (coerce-obj attributed-string-value 'ns:ns-attributed-string))) (when base-writing-direction-p (#/setBaseWritingDirection: self (convert-writing-direction base-writing-direction))) (when continuous-p (#/setContinuous: self continuous)) (when initial-value-p (cond ((floatp initial-value) (#/setFloatValue: self initial-value)) ((integerp initial-value) (#/setIntegerValue: self initial-value)) ((typep initial-value 'double-float) (#/setDoubleValue: self initial-value)) ((numberp initial-value) (#/setFloatValue: self (float initial-value))) ((stringp initial-value) (#/setStringValue: self (coerce-obj initial-value 'ns:ns-string))) ((typep initial-value 'ns:ns-object) (#/setObjectValue: self initial-value)))) (when enabled-p (#/setEnabled: self enabled)) (when (and font-p (typep font 'ns:ns-font)) (#/setFont: self font)) (when (and formatter-p (typep formatter 'ns:ns-formatter)) (#/setFormatter: self formatter)) (when ignores-multi-click-p (#/setIgnoresMultiClick: self ignores-multi-click)) (when refuses-first-responder-p (#/setRefusesFirstResponder: self refuses-first-responder)) (when (and tag-p (numberp tag)) (#/setTag: self (truncate tag))) (when (and target-p (typep target 'ns:ns-object)) (#/setTarget: self target))) (defmethod initialize-instance :after ((self ns:ns-scroll-view) &key (autohides-scrollers t autohides-scrollers-p) ;; t or nil (background-color nil background-color-p) ;; ns:ns-color or keyword acceptable to (coerce-obj <keyword> 'ns:ns-color) (border-type nil border-type-p) ;; number or keyword: see convert-border (content-view nil content-view-p) (document-cursor nil document-cursor-p) ;; number or keyword: see convert-cursor (document-view nil document-view-p) ;; the view that will be scrolled (draws-background nil draws-background-p) (find-bar-position nil find-bar-position-p) ;; number or keyword: see convert-find-bar-position (has-horizontal-ruler nil has-horizontal-ruler-p) ;; t or nil (has-horizontal-scroller nil has-horizontal-scroller-p) ;; t or nil (has-vertical-ruler nil has-vertical-ruler-p) ;; t or nil (has-vertical-scroller nil has-vertical-scroller-p) ;; t or nil (horizontal-line-scroll nil horizontal-line-scroll-p) ;; points to scroll (horizontal-page-scroll nil horizontal-page-scroll-p) ;; points to scroll (horizontal-ruler-view nil horizontal-ruler-view-p) ;; ns:ns-ruler-view (horizontal-scroll-elasticity nil horizontal-scroll-elasticity-p) ;; number or keyword: see convert-elasticity (horizontal-scroller nil horizontal-scroller-p) ;; ns:ns-scroller (line-scroll nil line-scroll-p) ;; points to scroll in both h and v (page-scroll nil page-scroll-p) ;; points to scroll in both h and v (rulers-visible nil rulers-visible-p) (scroller-knob-style nil scroller-knob-style-p) ;; number or keyword: see convert-knob-style (scroller-style nil scroller-style-p) ;; number or keyword: see convert-scroller-style (scrolls-dynamically t scrolls-dynamically-p) ;; t or nil whether to redraw while scrolling (uses-predominant-axis-scrolling t uses-predominant-axis-scrolling-p) ;; t or nil (vertical-line-scroll nil vertical-line-scroll-p) ;; points to scroll (vertical-page-scroll nil vertical-page-scroll-p) ;; points to scroll (vertical-ruler-view nil vertical-ruler-view-p) ;; ns:ns-ruler-view (vertical-scroll-elasticity nil vertical-scroll-elasticity-p) ;; number or keyword: see convert-elasticity (vertical-scroller nil vertical-scroller-p) ;; ns:ns-scroller &allow-other-keys) (when autohides-scrollers-p (#/setAutohidesScrollers: self autohides-scrollers)) (when background-color-p (#/setBackgroundColor: self (coerce-obj background-color 'ns:ns-color))) (when border-type-p (#/setBorderType: self (convert-border border-type))) (when content-view-p (#/setContentView: self content-view)) (when document-cursor-p (#/setDocumentCursor: self (convert-cursor document-cursor))) (when document-view-p (#/setDocumentView: self document-view)) (when draws-background-p (#/setDrawsBackground: self draws-background)) (when find-bar-position-p (#/setFindBarPosition: self (convert-find-bar-position find-bar-position))) (when has-horizontal-ruler-p (#/setHasHorizontalRuler: self has-horizontal-ruler)) (when has-horizontal-scroller-p (#/setHasHorizontalScroller: self has-horizontal-scroller)) (when has-vertical-ruler-p (#/setHasVerticalRuler: self has-vertical-ruler)) (when has-vertical-scroller-p (#/setHasVerticalScroller: self has-vertical-scroller)) (when horizontal-line-scroll-p (#/setHorizontalLineScroll: self (cgfloat horizontal-line-scroll))) (when horizontal-page-scroll-p (#/setHorizontalPageScroll: self (cgfloat horizontal-page-scroll))) (when horizontal-ruler-view-p (#/setHorizontalRulerView: self horizontal-ruler-view)) (when horizontal-scroll-elasticity-p (#/setHorizontalScrollElasticity: self (convert-elasticity horizontal-scroll-elasticity))) (when horizontal-scroller-p (#/setHorizontalScroller: self horizontal-scroller)) (when line-scroll-p (#/setLineScroll: self (cgfloat line-scroll))) (when page-scroll-p (#/setPageScroll: self (cgfloat page-scroll))) (when rulers-visible-p (#/setRulersVisible: self rulers-visible)) (when scroller-knob-style-p (#/setScrollerKnobStyle: self (convert-knob-style scroller-knob-style))) (when scroller-style-p (#/setScrollerStyle: self (convert-scroller-style scroller-style))) (when scrolls-dynamically-p (#/setScrollsDynamically: self scrolls-dynamically)) (when uses-predominant-axis-scrolling-p (#/setUsesPredominantAxisScrolling: self uses-predominant-axis-scrolling)) (when vertical-line-scroll-p (#/setVerticalLineScroll: self (cgfloat vertical-line-scroll))) (when vertical-page-scroll-p (#/setVerticalPageScroll: self (cgfloat vertical-page-scroll))) (when vertical-ruler-view-p (#/setVerticalRulerView: self vertical-ruler-view)) (when vertical-scroll-elasticity-p (#/setVerticalScrollElasticity: self (convert-elasticity vertical-scroll-elasticity))) (when vertical-scroller-p (#/setVerticalScroller: self vertical-scroller)) self) (defmethod initialize-instance :after ((self ns:ns-text) &key (alignment nil alignment-p) (background-color nil background-color-p) ;; ns:ns-color or keyword convertible by coerce-obj (base-writing-direction nil base-writing-direction-p) ;; number or keyword from convert-writing-direction (delegate nil delegate-p) ;; any ns:ns-object (draws-background nil draws-background-p) (editable nil editable-p) (field-editor nil field-editor-p) (font nil font-p) ;; ns:ns-font (horizontally-resizable nil horizontally-resizable-p) (imports-graphics nil imports-graphics-p) (max-size nil max-size-p) ;; ns:ns-size or list of the form (<width> <height>) (min-size nil min-size-p) ;; ns:ns-size or list of the form (<width> <height>) (rich-text nil rich-text-p) (selectable nil selectable-p) (string nil string-p) ;; string, attributed-string, or ns:ns-string (text-color nil text-color-p) ;; ns:ns-color or keyword convertible by coerce-obj (uses-font-panel nil uses-font-panel-p) (vertically-resizable nil vertically-resizable-p) &allow-other-keys) ;; see control.lisp and view.lisp for other allowed keywords (when alignment-p (#/setAlignment: self (convert-text-alignment alignment))) (when background-color-p (#/setBackgroundColor: self (coerce-obj background-color 'ns:ns-color))) (when base-writing-direction-p (#/setBaseWritingDirection: self (convert-writing-direction base-writing-direction))) (when delegate-p (#/setDelegate: self delegate)) (when draws-background-p (#/setDrawsBackground: self draws-background)) (when editable-p (#/setEditable: self editable)) (when field-editor-p (#/setFieldEditor: self field-editor)) (when font-p (#/setFont: self font)) (when horizontally-resizable-p (#/setHorizontallyResizable: self horizontally-resizable)) (when imports-graphics-p (#/setImportsGraphics: self imports-graphics)) (when max-size-p (#/setMaxSize: self (coerce-obj max-size 'ns:ns-size))) (when min-size-p (#/setMinSize: self (coerce-obj min-size 'ns:ns-size))) (when rich-text-p (#/setRichText: self rich-text)) (when selectable-p (#/setSelectable: self selectable)) (when string-p (if rich-text-p (#/setAttributedString: (#/textStorage self) (coerce-obj string 'ns:ns-attributed-string)) (#/setString: self (coerce-obj string 'ns:ns-string)))) (when text-color-p (#/setTextColor: self (coerce-obj text-color 'ns:ns-color))) (when uses-font-panel-p (#/setUsesFontPanel: self uses-font-panel)) (when vertically-resizable-p (#/setVerticallyResizable: self vertically-resizable))) (defmethod initialize-instance :after ((self ns:ns-text-view) &key (delegate nil delegate-p) ;; ns:ns-object (displayes-link-tool-tips nil displayes-link-tool-tips-p) (draws-background nil draws-background-p) (editable nil editable-p) (enabled-text-checking-types nil enabled-text-checking-types-p) ;; keyword or list of keywords or number (field-editor nil field-editor-p) (grammar-checking-enabled nil grammar-checking-enabled-p) (imports-graphics nil imports-graphics-p) (incremental-searching-enabled nil incremental-searching-enabled-p) (insertion-point-color nil insertion-point-color-p) ;; ns:ns-color or keyword acceptable to (coerce-obj <keyword> 'ns:ns-color) (layout-orientation nil layout-orientation-p) ;; number or keyword: :h :horizontal :v :vertical (link-text-attributes nil link-text-attributes-p) ;; assoc-list, hash-table, or ns:ns-dictionary of attribute-value pairs (marked-text-attributes nil marked-text-attributes-p) ;; assoc-list, hash-table, or ns:ns-dictionary of attribute-value pairs (rich-text nil rich-text-p) (ruler-visible nil ruler-visible-p) (selectable nil selectable-p) (selected-text-attributes nil selected-text-attributes-p) ;; assoc-list, hash-table, or ns:ns-dictionary of attribute-value pairs (smart-insert-delete-enabled nil smart-insert-delete-enabled-p) (text-container nil text-container-p) ;; ns:ns-text-container (text-container-inset nil text-container-inset-p) ;; ns:ns-size or list: (width height) (uses-find-bar nil uses-find-bar-p) (uses-find-panel nil uses-find-panel-p) (uses-font-panel nil uses-font-panel-p) (uses-inspector-bar nil uses-inspector-bar-p) (uses-ruler nil uses-ruler-p) &allow-other-keys) ;; see control.lisp and view.lisp for other allowed keywords (when delegate-p (#/setDelegate: self delegate)) (when displayes-link-tool-tips-p (#/setDisplaysLinkToolTips: self displayes-link-tool-tips)) (when draws-background-p (#/setDrawsBackground: self draws-background)) (when editable-p (#/setEditable: self editable)) (when enabled-text-checking-types-p (#/setEnabledTextCheckingTypes: self (convert-text-checking-types enabled-text-checking-types))) (when field-editor-p (#/setFieldEditor: self field-editor)) (when grammar-checking-enabled-p (#/setGrammarCheckingEnabled: self grammar-checking-enabled)) (when imports-graphics-p (#/setImportsGraphics: self imports-graphics)) (when incremental-searching-enabled-p (#/setIncrementalSearchingEnabled: self incremental-searching-enabled)) (when insertion-point-color-p (#/setInsertionPointColor: self (coerce-obj insertion-point-color 'ns:ns-color))) (when layout-orientation-p (#/setLayoutOrientation: self (convert-text-orientation layout-orientation))) (when link-text-attributes-p (#/setLinkTextAttributes: self (coerce-obj link-text-attributes 'ns:ns-dictionary))) (when marked-text-attributes-p (#/setMarkedTextAttributes: self (coerce-obj marked-text-attributes 'ns:ns-dictionary))) (when rich-text-p (#/setRichText: self rich-text)) (when ruler-visible-p (#/setRulerVisible: self ruler-visible)) (when selectable-p (#/setSelectable: self selectable)) (when selected-text-attributes-p (#/setSelectedTextAttributes: self (coerce-obj selected-text-attributes 'ns:ns-dictionary))) (when smart-insert-delete-enabled-p (#/setSmartInsertDeleteEnabled: self smart-insert-delete-enabled)) (when text-container-p (#/setTextContainer: self text-container)) (when text-container-inset-p (#/setTextContainerInset: self (coerce-obj text-container-inset 'ns:ns-size))) (when uses-find-bar-p (#/setUsesFindBar: self uses-find-bar)) (when uses-find-panel-p (#/setUsesFindPanel: self uses-find-panel)) (when uses-font-panel-p (#/setUsesFontPanel: self uses-font-panel)) (when uses-inspector-bar-p (#/setUsesInspectorBar: self uses-inspector-bar)) (when uses-ruler-p (#/setUsesRuler: self uses-ruler))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; ns-control subclasses (defmethod initialize-instance :after ((self ns:ns-button) &key (allows-mixed-state nil allows-mixed-state-p) (alternate-image nil alternate-image-p) ;; ns:ns-image (alternate-title nil alternate-title-p) ;; string, attributed-string, ns:ns-string (attributed-alternate-title nil attributed-alternate-title-p) ;; string, attributed-string or Obj-C equivalents (attributed-title nil attributed-title-p) ;; string, attributed-string or Obj-C equivalents (bezel-style nil bezel-style-p) ;; number or keyword: see convert-bezel-style (bordered nil bordered-p) (button-type nil button-type-p) ;; number or keyword: see convert-button-type (image nil image-p) ;; ns:ns-image (image-position nil image-position-p) ;; single value or list, values are numbers or keyword: see convert-image-position (key-equivalent nil key-equivalent-p) (key-equivalent-modifier-mask 0 key-equivalent-modifier-mask-p) ;; number or list of keywords or keyword: :control, :alternate, or :command (shows-border-only-while-mouse-inside nil shows-border-only-while-mouse-inside-p) (sound nil sound-p) (state nil state-p) ;; number or keyword: :on, :off, or :mixed (title nil title-p) ;; string, attributed-string or Obj-C equivalents (transparent nil transparent-p) &allow-other-keys) ;; see control.lisp and view.lisp for other allowed keywords (when allows-mixed-state-p (#/setAllowsMixedState: self allows-mixed-state)) (when alternate-image-p (#/setAlternateImage: self alternate-image)) (when alternate-title-p (#/setAlternateTitle: self (coerce-obj alternate-title 'ns:ns-string))) (when attributed-alternate-title-p (#/setAttributedAlternateTitle: self (coerce-obj attributed-alternate-title 'ns:ns-attributed-string))) (when attributed-title-p (#/setAttributedTitle: self (coerce-obj attributed-title 'ns:ns-attributed-string))) (when bezel-style-p (#/setBezelStyle: self (convert-bezel-style bezel-style))) (when bordered-p (#/setBordered: self bordered)) (when button-type-p (#/setButtonType: self (convert-button-type button-type))) (when image-p (#/setImage: self image)) (when image-position-p (if (listp image-position) (dolist (ip image-position) (#/setImagePosition: self (convert-image-position ip))) (#/setImagePosition: self (convert-image-position image-position)))) (when key-equivalent-p (#/setKeyEquivalent: self (coerce-obj key-equivalent 'ns:ns-string))) (when key-equivalent-modifier-mask-p (#/setKeyEquivalentModifierMask: self (convert-key-modifier-mask key-equivalent-modifier-mask))) (when shows-border-only-while-mouse-inside-p (#/setShowsBorderOnlyWhileMouseInside: self shows-border-only-while-mouse-inside)) (when (and sound-p (typep sound 'ns:ns-sound)) (#/setSound: self sound)) (when state-p (#/setState: self (convert-state state))) (when title-p (#/setTitle: self (coerce-obj title 'ns:ns-string))) (when transparent-p (#/setTransparent: self transparent)) self) (defmethod initialize-instance :after ((self ns:ns-color-well) &key (bordered nil bordered-p) (color nil color-p) ;; ns:ns-color or keyword acceptable to (coerce-obj <keyword> 'ns:ns-color) &allow-other-keys) (when bordered-p (#/setBordered: self bordered)) (when color-p (#/setColor: self (coerce-obj color 'ns:ns-color)))) (defmethod initialize-instance :after ((self ns:ns-outline-view) &key (autoresizes-outline-column nil autoresizes-outline-column-p) (autosave-expanded-items nil autosave-expanded-items-p) (indentation-marker-follows-cell nil indentation-marker-follows-cell-p) (indentation-per-level nil indentation-per-level-p) (outline-table-column nil outline-table-column-p) ;; ns:ns-table-column &allow-other-keys) (when autoresizes-outline-column-p (#/setAutoresizesOutlineColumn: self autoresizes-outline-column)) (when autosave-expanded-items-p (#/setAutosaveExpandedItems: self autosave-expanded-items)) (when indentation-marker-follows-cell-p (#/setIndentationMarkerFollowsCell: self indentation-marker-follows-cell)) (when indentation-per-level-p (#/setIndentationPerLevel: self (cgfloat indentation-per-level))) (when outline-table-column-p (#/setOutlineTableColumn: self outline-table-column))) (defmethod initialize-instance :after ((self ns:ns-slider) &key (allows-tick-mark-values-only nil allows-tick-mark-values-only-p) (alt-increment-value 1 alt-increment-value-p) (image nil image-p) ;; ns:ns-image (max-value nil max-value-p) (min-value nil min-value-p) (number-of-tick-marks 0 number-of-tick-marks-p) ;; integer &allow-other-keys) ;; see control.lisp and view.lisp for other allowed keywords (when allows-tick-mark-values-only-p (#/setAllowsTickMarkValuesOnly: self allows-tick-mark-values-only)) (when (and alt-increment-value-p (numberp alt-increment-value)) (#/setAltIncrementValue: self (cgfloat alt-increment-value))) (when image-p (#/setImage: self image)) (when (and max-value-p (numberp max-value)) (#/setMaxValue: self (cgfloat max-value))) (when (and min-value-p (numberp min-value)) (#/setMinValue: self (cgfloat min-value))) (when (and number-of-tick-marks-p (numberp number-of-tick-marks)) (#/setNumberOfTickMarks: self (truncate number-of-tick-marks))) self) (defmethod initialize-instance :after ((self ns:ns-table-view) &key (columns nil columns-p) ;; list of ns:ns-table-columns (allows-column-reordering nil allows-column-reordering-p) (allows-column-resizing nil allows-column-resizing-p) (allows-column-selection nil allows-column-selection-p) (allows-empty-selection nil allows-empty-selection-p) (allows-multiple-selection nil allows-multiple-selection-p) (allows-type-select nil allows-type-select-p) (autosave-name nil autosave-name-p) ;; string or ns:ns-string (autosave-table-columns nil autosave-table-columns-p) (background-color nil background-color-p) ;; ns:ns-color or keyword acceptable to (coerce-obj <keyword> 'ns:ns-color) (column-autoresizing-style nil column-autoresizing-style-p) ;; number or keyword: see convert-table-col-resizing (corner-view nil corner-view-p) ;; ns:ns-view (data-source nil data-source-p) ;; ns:ns-object which conforms to NSTableViewDataSource protocol (delegate nil delegate-p) ;; ns:ns-object which conforms to NSTableViewDelegate protocol (double-action nil double-action-p) ;; string (dragging-destination-feedback-style nil dragging-destination-feedback-style-p) ;; number or :none :regular :source-list (dragging-source-operation-mask nil dragging-source-operation-mask-p) ;; number or keyword: see convert-table-drag-src-op (floats-group-rows nil floats-group-rows-p) (grid-color nil grid-color-p) ;; ns:ns-color or keyword acceptable to (coerce-obj <keyword> 'ns:ns-color) (grid-style-mask nil grid-style-mask-p) ;; number or keyword or list of keywords: see convert-grid-style (header-view nil header-view-p) ;; ns:ns-table-header-view (intercell-spacing nil intercell-spacing-p) ;; ns:ns-size or list: (width height) (row-height nil row-height-p) ;; number (row-size-style nil row-size-style-p) ;; number or keyword: see convert-row-size-style (selection-highlight-style nil selection-highlight-style-p) ;; number or keyword: see convert-selection-highlight-style (sort-descriptors nil sort-descriptors-p) ;; list, 1D array, or ns:ns-array of ns:ns-sort-descriptor objects (uses-alternating-row-background-colors nil uses-alternating-row-background-colors-p) (vertical-motion-can-begin-drag nil vertical-motion-can-begin-drag-p) &allow-other-keys) (when columns-p ;; must do this first because other parameters only affect columns that already exist (dolist (col columns) (#/addTableColumn: self col))) (when allows-column-reordering-p (#/setAllowsColumnReordering: self allows-column-reordering)) (when allows-column-resizing-p (#/setAllowsColumnResizing: self allows-column-resizing)) (when allows-column-selection-p (#/setAllowsColumnSelection: self allows-column-selection)) (when allows-empty-selection-p (#/setAllowsEmptySelection: self allows-empty-selection)) (when allows-multiple-selection-p (#/setAllowsMultipleSelection: self allows-multiple-selection)) (when allows-type-select-p (#/setAllowsTypeSelect: self allows-type-select)) (when autosave-name-p (#/setAutosaveName: self (coerce-obj autosave-name 'ns:ns-string))) (when autosave-table-columns-p (#/setAutosaveTableColumns: self autosave-table-columns)) (when background-color-p (#/setBackgroundColor: self (coerce-obj background-color 'ns:ns-color))) (when column-autoresizing-style-p (#/setColumnAutoresizingStyle: self (convert-table-col-resizing column-autoresizing-style))) (when corner-view-p (#/setCornerView: self corner-view)) (when data-source-p (#/setDataSource: self data-source)) (when delegate-p (#/setDelegate: self delegate)) (when double-action-p (#/setDoubleAction: self (get-selector double-action))) (when dragging-destination-feedback-style-p (#/setDraggingDestinationFeedbackStyle: self (convert-table-drag-feedback-style dragging-destination-feedback-style))) (when dragging-source-operation-mask-p (#/setDraggingSourceOperationMask:forLocal: self (convert-table-drag-src-op dragging-source-operation-mask) t)) (when floats-group-rows-p (#/setFloatsGroupRows: self floats-group-rows)) (when grid-color-p (#/setGridColor: self (coerce-obj grid-color 'ns:ns-color))) (when grid-style-mask-p (#/setGridStyleMask: self (convert-grid-styles grid-style-mask))) (when header-view-p (#/setHeaderView: self header-view)) (when intercell-spacing-p (#/setIntercellSpacing: self (coerce-obj intercell-spacing 'ns:ns-size))) (when row-height-p (#/setRowHeight: self (cgfloat row-height))) (when row-size-style-p (#/setRowSizeStyle: self (convert-row-size-style row-size-style))) (when selection-highlight-style-p (#/setSelectionHighlightStyle: self (convert-selection-highlight-style selection-highlight-style))) (when sort-descriptors-p (#/setSortDescriptors: self (coerce-obj sort-descriptors 'ns:ns-array))) (when uses-alternating-row-background-colors-p (#/setUsesAlternatingRowBackgroundColors: self uses-alternating-row-background-colors)) (when vertical-motion-can-begin-drag-p (#/setVerticalMotionCanBeginDrag: self vertical-motion-can-begin-drag))) (defmethod initialize-instance :after ((self ns:ns-text-field) &key (bezeled nil bezeled-p) (bezel-style nil bezel-style-p) ;; number or keyword: see values in convert-text-bezel-style above (bordered nil bordered-p) (delegate nil delegate-p) ;; ns:ns-object (draws-background nil draws-background-p) (editable nil editable-p) (imports-graphics nil imports-graphics-p) (preferred-max-layout-width nil preferred-max-layout-width-p) (selectable nil selectable-p) (text-color nil text-color-p) ;; ns:ns-color or keyword acceptable to (coerce-obj <keyword> 'ns:ns-color) &allow-other-keys) ;; see control.lisp and view.lisp for other allowed keywords (when bezeled-p (#/setBezeled: self bezeled)) (when bezel-style-p (#/setBezelStyle: self (convert-text-bezel-style bezel-style))) (when bordered-p (#/setBordered: self bordered)) (when delegate-p (#/setDelegate: self delegate)) (when draws-background-p (#/setDrawsBackground: self draws-background)) (when editable-p (#/setEditable: self editable)) (when imports-graphics-p (#/setImportsGraphics: self imports-graphics)) (when preferred-max-layout-width-p (#/setPreferredMaxLayoutWidth: self preferred-max-layout-width)) (when selectable-p (#/setSelectable: self selectable)) (when text-color-p (#/setTextColor: self (coerce-obj text-color 'ns:ns-color)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; ns-window subclasses (defmethod initialize-instance :after ((self ns:ns-panel) &key (floating-panel nil floating-panel-p) (works-when-modal nil works-when-modal-p) &allow-other-keys) ;; see window.lisp for other allowed keywords (when floating-panel-p (#/setFloatingPanel: self floating-panel)) (when works-when-modal-p (#/setWorksWhenModal: self works-when-modal))) (defmethod initialize-instance :after ((self ns:ns-save-panel) &key (accessory-view nil accessory-view-p) ;; ns-view object (allowed-file-types (%null-ptr)) ;; list of strings of allowed file types (allows-other-file-types nil allows-other-file-types-p) (can-create-directories nil can-create-directories-p) (can-select-hidden-extension nil can-select-hidden-extension-p) (delegate nil delegate-p) ;; NSOpenSavePanelDelegate object (directory-url nil directory-url-p) ;; ns:ns-url (extension-hidden nil extension-hidden-p) (message nil message-p) (name-field-label nil name-field-label-p) (name-field-string-value nil name-field-string-value-p) (prompt nil prompt-p) (shows-hidden-files nil shows-hidden-files-p) ;;(shows-tag-field nil shows-tag-field-p) ;;(tag-names nil tag-names-p) ;; list of strings (title nil title-p) ;; string (treats-file-packages-as-directories nil treats-file-packages-as-directories-p) &allow-other-keys) ;; see window.lisp for other allowed keywords (when accessory-view-p (#/setAccessoryView: self accessory-view)) (#/setAllowedFileTypes: self (if allowed-file-types (coerce-obj allowed-file-types 'ns:ns-array) (%null-ptr))) (when allows-other-file-types-p (#/setAllowsOtherFileTypes: self allows-other-file-types)) (when can-create-directories-p (#/setCanCreateDirectories: self can-create-directories)) (when can-select-hidden-extension-p (#/setCanSelectHiddenExtension: self can-select-hidden-extension)) (when delegate-p (#/setDelegate: self delegate)) (when directory-url-p (#/setDirectoryURL: self directory-url)) (when extension-hidden-p (#/setExtensionHidden: self extension-hidden)) (when message-p (#/setMessage: self (coerce-obj message 'ns:ns-string))) (when name-field-label-p (#/setNameFieldLabel: self (coerce-obj name-field-label 'ns:ns-string))) (when name-field-string-value-p (#/setNameFieldStringValue: self (coerce-obj name-field-string-value 'ns:ns-string))) (when prompt-p (#/setPrompt: self (coerce-obj prompt 'ns:ns-string))) (when shows-hidden-files-p (#/setShowsHiddenFiles: self shows-hidden-files)) ;;(when shows-tag-field-p ;; (#/setShowsTagField: self shows-tag-field)) ;;(when tag-names-p ;; (#/setTagNames: self (coerce-obj tag-names 'ns:ns-array))) (when title-p (#/setTitle: self (coerce-obj title 'ns:ns-string))) (when treats-file-packages-as-directories-p (#/setTreatsFilePackagesAsDirectories: self treats-file-packages-as-directories))) ;;; NOTE: you should not create an ns-open-panel using make-instance. Instead use make-open-panel ;;; loaded from open-panel.lisp. That will avoid getting a rash of CG trace messages logged to the ;;; system log (I found this the hard way). Retaining an ns-open-panel in any fashion will cause ;;; the log messages. (defmethod initialize-instance :after ((self ns:ns-open-panel) &key (allows-multiple-selection nil allows-multiple-selection-p) (can-choose-directories nil can-choose-directories-p) (can-choose-files nil can-choose-files-p) (resolves-aliases nil resolves-aliases-p) &allow-other-keys) (when allows-multiple-selection-p (#/setAllowsMultipleSelection: self allows-multiple-selection)) (when can-choose-directories-p (#/setCanChooseDirectories: self can-choose-directories)) (when can-choose-files-p (#/setCanChooseFiles: self can-choose-files)) (when resolves-aliases-p (#/setResolvesAliases: self resolves-aliases))) (provide :objc-initialize)
true
;; objc-initialize.lisp #| The MIT license. Copyright (c) 2013 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. |# #| WARNING: This will replace CCL-defined initialize-instance :after methods for ns:ns-window and ns:ns-view which are defined in cocoa-window.lisp. While I made every effort to ensure compatibility with those methods and have experienced no difficulty when running with my replacements, if you have other code that depends on specific keywords defined in those routines, you may have to either modify your code or not load this file. This file provides initialize-instance :after methods for many standard Objective-C classes, especially ns:ns-view subclasses, but it is not a comprehensive list. The norm in Lisp is to call make-instance and provide all necessary initialization values as keywords. In Objective-C the norm is to provide a few initWith... methods that supply only a limited number of initialization parameters. The developer is then expected to customize those objects by using any number of set... methods. We could certainly do the same in Lisp, but to make life more natural I have created these initialize-instance :after methods. The idea is that you can do something like the following: (make-instance '<ns-object-class-name> {:key val}*) Most common sorts of argument types needed for the Objective-C methods are automatically converted from corresponding Lisp types provided in the make-instance call. Many sorts of constants are automatically converted from keyword equivalents (see the convert... methods for those values). If their superclass also defines the initialize-instance :after method then of course it will be called as well. Each method defines keywords corresponding to set... methods that are specific to that class. So in an initialize-instance :after method for any object you can use keywords for that class or any of its superclasses. Many supporting functions named convert-... will convert keyword arguments. If the meaning of them is not clear, you should consult Apple documentation for additional information. The function initialize-keys is provided to give you a list of valid keywords for any object that you might want to initialize. Note that these methods will NOT be called if you create instances using normal Objective-C forms such as (#/init (#/alloc <class>)) They will only be invoked if you specifically call make-instance ... Final suggestions. If you execute any make-instance forms from the Lisp listener for these classes (especially classes associated withwindows or views) you should wrap the call with a (on-main-thread ... ) form (defined in ns-object-utils.lisp). This assures that the objects are created on the main thread, which is increasingly necessary for Objective-C objects created at runtime. Objects returned by these methods will typically be owned by the caller and you must explicitly (#/release <object) when you are done with it to avoid a memory leak. Note that a memory leak is much better than trying to reference a ptr to an object that was released prematurely. Such a reference is likely to cause a runtime exception. |# (assert (>= #$NSAppKitVersionNumber #$NSAppKitVersionNumber10_7)) (eval-when (:compile-toplevel :load-toplevel :execute) (require :interface-packages) (require :coerce-obj) (require :selector-utils) (require :list-utils) (require :file-directory-utils)) (in-package :iu) ;; convert- ... functions (defun convert-animation-behavior (ab-key) (if (numberp ab-key) ab-key (ecase ab-key (:default #$NSWindowAnimationBehaviorDefault) (:none #$NSWindowAnimationBehaviorNone) (:document-window #$NSWindowAnimationBehaviorDocumentWindow) (:utility-window #$NSWindowAnimationBehaviorUtilityWindow) (:alert-panel #$NSWindowAnimationBehaviorAlertPanel)))) (defun convert-bezel-style (style-key) (if (numberp style-key) style-key (ecase style-key (:rounded #$NSRoundedBezelStyle) (:regular-square #$NSRegularSquareBezelStyle) (:thick-square #$NSThickSquareBezelStyle) (:thicker-square #$NSThickerSquareBezelStyle) (:disclosure #$NSDisclosureBezelStyle) (:shadowless-square #$NSShadowlessSquareBezelStyle) (:circular #$NSCircularBezelStyle) (:textured-square #$NSTexturedSquareBezelStyle) (:help-button #$NSHelpButtonBezelStyle) (:small-square #$NSSmallSquareBezelStyle) (:textured-rounded #$NSTexturedRoundedBezelStyle) (:round-rect #$NSRoundRectBezelStyle) (:recessed #$NSRecessedBezelStyle) (:rounded-disclosure #$NSRoundedDisclosureBezelStyle) (:inline #$NSInlineBezelStyle) (:small-icon-button #$NSSmallIconButtonBezelStyle)))) (defun convert-border (border-key) (if (numberp border-key) border-key (ecase border-key (:line #$NSLineBorder) (:bezel #$NSBezelBorder) (:groove #$NSGrooveBorder) (:none #$NSNoBorder)))) (defun convert-box-type (bt-key) (if (numberp bt-key) bt-key (ecase bt-key (:primary #$NSBoxPrimary) (:secondary #$NSBoxSecondary) (:separator #$NSBoxSeparator) (:old-style #$NSBoxOldStyle) (:custom #$NSBoxCustom)))) (defun convert-button-type (type-key) (if (numberp type-key) type-key (ecase type-key (:momentary-light #$NSMomentaryLightButton) (:push-on-push-off #$NSPushOnPushOffButton) (:toggle #$NSToggleButton) (:switch #$NSSwitchButton) (:radio #$NSRadioButton) (:momentary-change #$NSMomentaryChangeButton) (:on-off #$NSOnOffButton) (:momentary-push-in #$NSMomentaryPushInButton) (:momentary-push #$NSMomentaryPushButton)))) (defun convert-collection-behavior (c-key) (cond ((listp c-key) (apply #'logior (mapcar #'convert-collection-behavior c-key))) ((numberp c-key) c-key) (t (ecase c-key (:default #$NSWindowCollectionBehaviorDefault) (:can-join-all-spaces #$NSWindowCollectionBehaviorCanJoinAllSpaces) (:move-to-active-space #$NSWindowCollectionBehaviorMoveToActiveSpace) (:managed #$NSWindowCollectionBehaviorManaged) (:transient #$NSWindowCollectionBehaviorTransient) (:stationary #$NSWindowCollectionBehaviorStationary) (:participates-in-cycle #$NSWindowCollectionBehaviorParticipatesInCycle) (:ignores-cycle #$NSWindowCollectionBehaviorIgnoresCycle) (:full-screen-primary #$NSWindowCollectionBehaviorFullScreenPrimary) (:full-screen-auxiliary #$NSWindowCollectionBehaviorFullScreenAuxiliary))))) (defun convert-column-resizing (cr-key) (if (numberp cr-key) cr-key (ecase cr-key (:no-resizing #$NSTableColumnNoResizing) (:auto-resizing #$NSTableColumnAutoresizingMask) (:user-resizing #$NSTableColumnUserResizingMask)))) (defun convert-cursor (cursor-key) ;; not all applicable to scroll-views, but included for completeness and use elsewhere (if (numberp cursor-key) cursor-key (ecase cursor-key (:arrow (#/arrowCursor ns:ns-cursor)) (:closed-hand (#/closedHandCursor ns:ns-cursor)) (:contextual-menu (#/contextualMenuCursor ns:ns-cursor)) (:crosshair (#/crosshairCursor ns:ns-cursor)) (:current (#/currentCursor ns:ns-cursor)) (:current-system (#/currentSystemCursor ns:ns-cursor)) (:disappearing-item (#/disappearingItemCursor ns:ns-cursor)) (:drag-copy (#/dragCopyCursor ns:ns-cursor)) (:drag-link (#/dragLinkCursor ns:ns-cursor)) (:ibeam (#/IBeamCursor ns:ns-cursor)) (:ibeam-for-vertical (#/IBeamCursorForVerticalLayout ns:ns-cursor)) (:open-hand (#/openHandCursor ns:ns-cursor)) (:op-not-allowed (#/operationNotAllowedCursor ns:ns-cursor)) (:pointing-hand (#/pointingHandCursor ns:ns-cursor)) (:resize-down (#/resizeDownCursor ns:ns-cursor)) (:resize-left (#/resizeLeftCursor ns:ns-cursor)) (:resize-left-right (#/resizeLeftRightCursor ns:ns-cursor)) (:resize-right (#/resizeRightCursor ns:ns-cursor)) (:resize-up (#/resizeUpCursor ns:ns-cursor)) (:resize-up-down (#/resizeUpDownCursor ns:ns-cursor))))) (defun convert-date-style (ds-key) (if (numberp ds-key) ds-key (ecase ds-key (:none #$NSDateFormatterNoStyle) (:short #$NSDateFormatterShortStyle) (:medium #$NSDateFormatterMediumStyle) (:long #$NSDateFormatterLongStyle) (:full #$NSDateFormatterFullStyle)))) (defun convert-elasticity (e-key) (if (numberp e-key) e-key (ecase e-key (:automatic #$NSScrollElasticityAutomatic) (:none #$NSScrollElasticityNone) (:allowed #$NSScrollElasticityAllowed)))) (defun convert-find-bar-position (find-key) (if (numberp find-key) find-key (ecase find-key (:above-ruler #$NSScrollViewFindBarPositionAboveHorizontalRuler) (:above-content #$NSScrollViewFindBarPositionAboveContent) (:below-content #$NSScrollViewFindBarPositionBelowContent)))) (defun convert-focus-ring-type (fr-key) (if (numberp fr-key) fr-key (ecase fr-key (:default #$NSFocusRingTypeDefault) (:none #$NSFocusRingTypeNone) (:exterior #$NSFocusRingTypeExterior)))) (defun convert-grid-style (s-key) (if (numberp s-key) s-key (ecase s-key (:none #$NSTableViewGridNone) (:solid-vertical #$NSTableViewSolidVerticalGridLineMask) (:solid-horizontal #$NSTableViewSolidHorizontalGridLineMask) (:dashed-horizontal #$NSTableViewDashedHorizontalGridLineMask)))) (defun convert-grid-styles (style) (if (listp style) (apply #'logior (mapcar #'convert-grid-style style)) (convert-grid-style style))) (defun convert-image-position (i-key) #| Together, NSCellHasImageOnLeftOrBottom, NSCellHasImageHorizontal, and NSCellHasOverlappingImage control the position of the cell’s image and text. To place the image above, set none of them. To place the image below, set NSCellHasImageOnLeftOrBottom. To place the image to the right, set NSCellHasImageHorizontal. To place the image to the left, set NSCellHasImageHorizontal and NSCellHasImageOnLeftOrBottom. To place the image directly over, set NSCellHasOverlappingImage. |# (if (numberp i-key) i-key (ecase i-key (:no-image #$NSNoImage) (:image-only #$NSImageOnly) (:image-left #$NSImageLeft) (:image-right #$NSImageRight) (:image-below #$NSImageBelow) (:image-above #$NSImageAbove) (:image-overlaps #$NSImageOverlaps)))) (defun convert-key-modifier-mask (mod-key) (cond ((listp mod-key) (apply #'logior (mapcar #'convert-key-modifier-mask mod-key))) ((numberp mod-key) mod-key) (t (ecase mod-key (:shift #$NSShiftKeyMask) (:control #$NSControlKeyMask) (:alternate #$NSAlternateKeyMask) (:option #$NSAlternateKeyMask) ;; same as alt key (:command #$NSCommandKeyMask))))) (defun convert-knob-style (k-key) (if (numberp k-key) k-key (ecase k-key (:default #$NSScrollerKnobStyleDefault) (:dark #$NSScrollerKnobStyleDark) (:light #$NSScrollerKnobStyleLight)))) (defun convert-number-style (ns-key) (if (numberp ns-key) ns-key (ecase ns-key (:none #$NSNumberFormatterNoStyle) (:decimal #$NSNumberFormatterDecimalStyle) (:currency #$NSNumberFormatterCurrencyStyle) (:percent #$NSNumberFormatterPercentStyle) (:scientific #$NSNumberFormatterScientificStyle) (:spell-out #$NSNumberFormatterSpellOutStyle)))) (defun convert-padding-position (pp-key) (if (numberp pp-key) pp-key (ecase pp-key (:before-prefix #$NSNumberFormatterPadBeforePrefix) (:after-prefix #$NSNumberFormatterPadAfterPrefix) (:before-suffix #$NSNumberFormatterPadBeforeSuffix) (:after-suffix #$NSNumberFormatterPadAfterSuffix)))) (defun convert-resizing-mask (rs-key) (cond ((listp rs-key) (apply #'logior (mapcar #'convert-resizing-mask rs-key))) ((numberp rs-key) rs-key) (t (ecase rs-key (:not-sizable #$NSViewNotSizable) (:min-x-margin #$NSViewMinXMargin) (:width-sizable #$NSViewWidthSizable) (:max-x-margin #$NSViewMaxXMargin) (:min-y-margin #$NSViewMinYMargin) (:height-sizable #$NSViewHeightSizable) (:max-y-margin #$NSViewMaxYMargin))))) (defun convert-row-size-style (rss-key) (if (numberp rss-key) rss-key (ecase rss-key (:default #$NSTableViewRowSizeStyleDefault) (:custom #$NSTableViewRowSizeStyleCustom) (:small #$NSTableViewRowSizeStyleSmall) (:medium #$NSTableViewRowSizeStyleMedium) (:large #$NSTableViewRowSizeStyleLarge)))) (defun convert-rounding-mode (rm-key) (if (numberp rm-key) rm-key (ecase rm-key (:ceiling #$NSNumberFormatterRoundCeiling) (:floor #$NSNumberFormatterRoundFloor) (:down #$NSNumberFormatterRoundDown) (:up #$NSNumberFormatterRoundUp) (:half-even #$NSNumberFormatterRoundHalfEven) (:half-down #$NSNumberFormatterRoundHalfDown) (:half-up #$NSNumberFormatterRoundHalfUp)))) (defun convert-scroller-style (style-key) (if (numberp style-key) style-key (ecase style-key (:legacy #$NSScrollerStyleLegacy) (:overlay #$NSScrollerStyleOverlay)))) (defun convert-selection-highlight-style (shs-key) (if (numberp shs-key) shs-key (ecase shs-key (:none #$NSTableViewSelectionHighlightStyleNone) (:regular #$NSTableViewSelectionHighlightStyleRegular) (:source-list #$NSTableViewSelectionHighlightStyleSourceList)))) (defun convert-sharing-type (st-key) (if (numberp st-key) st-key (ecase st-key (:none #$NSWindowSharingNone) (:read-only #$NSWindowSharingReadOnly) (:read-write #$NSWindowSharingReadWrite)))) (defun convert-state (st-key) (if (numberp st-key) st-key (ecase st-key (:on #$NSOnState) (:off #$NSOffState) (:mixed #$NSMixedState)))) (defun convert-table-col-resizing (tcr-key) (if (numberp tcr-key) tcr-key (ecase tcr-key (:none #$NSTableViewNoColumnAutoresizing) (:uniform #$NSTableViewUniformColumnAutoresizingStyle) (:sequential-column #$NSTableViewSequentialColumnAutoresizingStyle) (:reverse-sequential-column #$NSTableViewReverseSequentialColumnAutoresizingStyle) (:last-column-only #$NSTableViewLastColumnOnlyAutoresizingStyle) (:first-column-only #$NSTableViewFirstColumnOnlyAutoresizingStyle)))) (defun convert-table-drag-feedback-style (td-key) (if (numberp td-key) td-key (ecase td-key (:none #$NSTableViewDraggingDestinationFeedbackStyleNone) (:regular #$NSTableViewDraggingDestinationFeedbackStyleRegular) (:source-list #$NSTableViewDraggingDestinationFeedbackStyleSourceList)))) (defun convert-table-drag-src-op (td-key) (if (numberp td-key) td-key (ecase td-key (:none #$NSDragOperationNone) (:copy #$NSDragOperationCopy) (:link #$NSDragOperationLink) (:generic #$NSDragOperationGeneric) (:private #$NSDragOperationPrivate) (:move #$NSDragOperationMove) (:delete #$NSDragOperationDelete) (:every #$NSDragOperationEvery)))) (defun convert-text-alignment (al-key) (if (numberp al-key) al-key (ecase al-key (:left #$NSLeftTextAlignment) (:right #$NSRightTextAlignment) (:center #$NSCenterTextAlignment) (:justified #$NSJustifiedTextAlignment) (:natural #$NSNaturalTextAlignment)))) (defun convert-text-bezel-style (b-key) (if (numberp b-key) b-key (ecase b-key (:square #$NSTextFieldSquareBezel) (:rounded #$NSTextFieldRoundedBezel)))) (defun convert-text-checking-type (type) (ecase type (:all-system #$NSTextCheckingAllSystemTypes) (:all-custom #$NSTextCheckingAllCustomTypes) (:all #$NSTextCheckingAllTypes))) (defun convert-text-checking-types (types) (typecase types (number types) (keyword (convert-text-checking-type types)) (list (apply #'logior (mapcar #'convert-text-checking-type types))) (t types))) ;; let it error (defun convert-text-orientation (o-key) ;; should be one of :horizontal, :h, :vertical, or :v (if (numberp o-key) o-key (ecase o-key ((:vertical :v) #$NSTextLayoutOrientationVertical) ((:horizontal :h) #$NSTextLayoutOrientationHorizontal)))) (defun convert-title-position (tp-key) (if (numberp tp-key) tp-key (ecase tp-key (:none #$NSNoTitle) (:above-top #$NSAboveTop) (:at-top #$NSAtTop) (:below-top #$NSBelowTop) (:above-bottom #$NSAboveBottom) (:at-bottom #$NSAtBottom) (:below-bottom #$NSBelowBottom)))) (defun convert-window-backing-loc (wb-key) (if (numberp wb-key) wb-key (ecase wb-key (:default #$NSWindowBackingLocationDefault) (:video-memory #$NSWindowBackingLocationVideoMemory) (:main-memory #$NSWindowBackingLocationMainMemory)))) (defun convert-window-depth (wd-key) (if (numberp wd-key) wd-key (ecase wd-key (:rgb-24 #$NSWindowDepthTwentyfourBitRGB) (:rgb-64 #$NSWindowDepthSixtyfourBitRGB) (:rgb-128 #$NSWindowDepthOnehundredtwentyeightBitRGB)))) (defun convert-window-level (wl-key) ;; For some reason the defined constants are not in the CCL interface database, but I found ;; http://dev.dartmouth.edu/svn/softdev/email/blitz/clients/BlitzMail/tags/start/projDev%20Mac%20CIncludes/CGWindowLevel.h ;; which provided the mechanism to derive the values. (if (numberp wl-key) wl-key (ecase wl-key (:normal (#_CGWindowLevelForKey #$kCGNormalWindowLevelKey)) ;; #$NSNormalWindowLevel (:floating (#_CGWindowLevelForKey #$kCGFloatingWindowLevelKey)) ;; #$NSFloatingWindowLevel (:submenu (#_CGWindowLevelForKey #$kCGTornOffMenuWindowLevelKey)) ;; #$NSSubmenuWindowLevel (same as torn-off) (:torn-off-menu (#_CGWindowLevelForKey #$kCGTornOffMenuWindowLevelKey)) ;; #$NSTornOffMenuWindowLevel (:main-menu (#_CGWindowLevelForKey #$kCGMainMenuWindowLevelKey)) ;; #$NSMainMenuWindowLevel (:status (#_CGWindowLevelForKey #$kCGStatusWindowLevelKey)) ;; #$NSStatusWindowLevel (:modal-panel (#_CGWindowLevelForKey #$kCGModalPanelWindowLevelKey)) ;; #$NSModalPanelWindowLevel (:pop-up-menu (#_CGWindowLevelForKey #$kCGPopUpMenuWindowLevelKey)) ;; #$NSPopUpMenuWindowLevel (:screen-saver (#_CGWindowLevelForKey #$kCGScreenSaverWindowLevelKey)) ;; #$NSScreenSaverWindowLevel (:dock-window (#_CGWindowLevelForKey #$kCGDockWindowLevelKey))))) ;; #$NSDockWindowLevel (defun convert-writing-direction (wd-key) (if (numberp wd-key) wd-key (ecase wd-key (:natural #$NSWritingDirectionNatural) (:left-to-right #$NSWritingDirectionLeftToRight) (:right-to-left #$NSWritingDirectionRightToLeft)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; ns-object subclasses (defmethod initialize-instance :after ((self ns:ns-document) &key (display-name nil display-name-p) ;; string or ns:ns-string (draft nil draft-p) (has-undo-manager nil has-undo-manager-p) (print-info nil print-info-p) ;; ns:ns-print-info object (undo-manager nil undo-manager-p) ;; ns:ns-undo-manager object &allow-other-keys) (when display-name-p (#/setDisplayName: self (coerce-obj display-name 'ns:ns-string))) (when draft-p (#/setDraft: self draft)) (when has-undo-manager-p (#/setHasUndoManager: self has-undo-manager)) (when print-info-p (#/setPrintInfo: self print-info)) (when undo-manager-p (#/setUndoManager: self undo-manager))) (defmethod initialize-instance :after ((self ns:ns-menu) &key (allows-context-menu-plug-ins nil allows-context-menu-plug-ins-p) (autoenables-items nil autoenables-items-p) (delegate nil delegate-p) ;; an object that follows the NSMenuDelegate protocol (font nil font-p) ;; ns:ns-font (minimum-width nil minimum-width-p) ;; number coerceable to a double float (shows-state-column nil shows-state-column-p) (title nil title-p) ;; string, attributed-string, ns:ns-string (menu-items nil menu-items-p) ;; list of ns:ns-menu-item &allow-other-keys) (when allows-context-menu-plug-ins-p (#/setAllowsContextMenuPlugIns: self allows-context-menu-plug-ins)) (when autoenables-items-p (#/setAutoenablesItems: self autoenables-items)) (when delegate-p (#/setDelegate: self delegate)) (when font-p (#/setFont: self font)) (when minimum-width-p (#/setMinimumWidth: self (cgfloat minimum-width))) (when shows-state-column-p (#/setShowsStateColumn: self shows-state-column)) (when title-p (#/setTitle: self (coerce-obj title 'ns:ns-string))) (when menu-items-p (dolist (mi menu-items) (#/addItem: self mi)))) (defmethod initialize-instance :after ((self ns:ns-menu-item) &key (action nil action-p) ;; string or objective-c selector (alternate nil alternate-p) (attributed-title nil attributed-title-p) (enabled nil enabled-p) (hidden nil hidden-p) (image nil image-p) ;; ns:ns-image (indentation-level nil indentation-level-p) ;; integer (key-equivalent nil key-equivalent-p) ;; string, attributed-string, ns:ns-string (key-equivalent-modifier-mask nil key-equivalent-modifier-mask-p) (mixed-state-image nil mixed-state-image-p) ;; ns:ns-image (off-state-image nil off-state-image-p) ;; ns:ns-image (on-state-image nil on-state-image-p) ;; ns:ns-image (represented-object nil represented-object-p) ;; ns-ns-object (state nil state-p) ;; one of :on :off :mixed (submenu nil submenu-p) ;; ns:ns-menu (tag nil tag-p) ;; integer (target nil target-p) ;; ns-ns-object (title nil title-p) ;; string, attributed-string, ns:ns-string (tool-tip nil tool-tip-p) ;; string, attributed-string, ns:ns-string (view nil view-p) ;; ns:ns-view &allow-other-keys) (when action-p (#/setAction: self (get-selector action))) (when alternate-p (#/setAlternate: self alternate)) (when attributed-title-p (#/setAttributedTitle: self (coerce-obj attributed-title 'ns:ns-attributed-string))) (when enabled-p (#/setEnabled: self enabled)) (when hidden-p (#/setHidden: self hidden)) (when image-p (#/setImage: self image)) (when indentation-level-p (#/setIndentationLevel: self indentation-level)) (when key-equivalent-p (#/setKeyEquivalent: self (coerce-obj key-equivalent 'ns:ns-string))) (when key-equivalent-modifier-mask-p (#/setKeyEquivalentModifierMask: self (convert-key-modifier-mask key-equivalent-modifier-mask))) (when mixed-state-image-p (#/setMixedStateImage: self mixed-state-image)) (when off-state-image-p (#/setOffStateImage: self off-state-image)) (when on-state-image-p (#/setOnStateImage: self on-state-image)) (when represented-object-p (#/setRepresentedObject: self represented-object)) (when state-p (#/setState: self (convert-state state))) (when submenu-p (#/setSubmenu: self submenu)) (when tag-p (#/setTag: self tag)) (when target-p (#/setTarget: self target)) (when title-p (#/setTitle: self (coerce-obj title 'ns:ns-string))) (when tool-tip-p (#/setToolTip: self (coerce-obj tool-tip 'ns:ns-string))) (when view-p (#/setView: self view))) (defmethod initialize-instance :after ((self ns:ns-table-column) &key (column-title nil column-title-p) ;; string or ns:ns-string (data-cell nil data-cell-p) ;; ns:ns-cell (editable nil editable-p) (formatter nil formatter-p) ;; ns:ns-formatter (header-cell nil header-cell-p) ;; ns:ns-cell (header-tool-tip nil header-tool-tip-p) ;; string or ns:ns-string (hidden nil hidden-p) (identifier nil identifier-p) ;; string or ns:ns-string (max-width nil max-width-p) ;; number (min-width nil min-width-p) ;; number (resizing-mask nil resizing-mask-p) ;; number or keyword: :no-resizing :auto-resizing :user-resizing (sort-descriptor-prototype nil sort-descriptor-prototype-p) ;; ns:ns-sort-descriptor (width nil width-p) ;; number (wraps nil wraps-p) &allow-other-keys) (when column-title-p (#/setStringValue: (#/headerCell self) (coerce-obj column-title 'ns:ns-string))) (when data-cell-p (#/setDataCell: self data-cell)) (when editable-p (#/setEditable: self editable)) (when formatter-p (#/setFormatter: (#/dataCell self) formatter)) (when header-cell-p (#/setHeaderCell: self header-cell)) (when header-tool-tip-p (#/setHeaderToolTip: self (coerce-obj header-tool-tip 'ns:ns-string))) (when hidden-p (#/setHidden: self hidden)) (when identifier-p (#/setIdentifier: self (coerce-obj identifier 'ns:ns-string))) (when max-width-p (#/setMaxWidth: self (cgfloat max-width))) (when min-width-p (#/setMinWidth: self (cgfloat min-width))) (when resizing-mask-p (#/setResizingMask: self (convert-column-resizing resizing-mask))) (when sort-descriptor-prototype-p (#/setSortDescriptorPrototype: self sort-descriptor-prototype)) (when width-p (#/setWidth: self (cgfloat width))) (when wraps-p (#/setWraps: (#/dataCell self) wraps))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; ns-formatter subclasses (defmethod initialize-instance :after ((self ns:ns-date-formatter) &key (calendar nil calendar-p) ;; ns:ns-calendar (date-format nil date-format-p) ;; string or ns:ns-string (date-style nil date-style-p) ;; number or keyword: :none :short :medium :long :full (default-date nil default-date-p) ;; lisp date or ns:ns-date (does-relative-date-formatting nil does-relative-date-formatting-p) (era-symbols nil era-symbols-p) ;; list of strings or ns:ns-string objects (gregorian-start-date nil gregorian-start-date-p) ;; lisp date or ns:ns-date (lenient nil lenient-p) (locale nil locale-p) ;; ns:ns-locale (long-era-symbols nil long-era-symbols-p) ;; list of strings or ns:ns-string objects (month-symbols nil month-symbols-p) ;; list of strings or ns:ns-string objects (pm-symbol nil pm-symbol-p) ;; string or ns:ns-string (quarter-symbols nil quarter-symbols-p) ;; list of strings or ns:ns-string objects (short-month-symbols nil short-month-symbols-p) ;; list of strings or ns:ns-string objects (short-quarter-symbols nil short-quarter-symbols-p) ;; list of strings or ns:ns-string objects (short-standalone-month-symbols nil short-standalone-month-symbols-p) ;; list of strings or ns:ns-string objects (short-standalone-quarter-symbols nil short-standalone-quarter-symbols-p) ;; list of strings or ns:ns-string objects (short-standalone-weekday-symbols nil short-standalone-weekday-symbols-p) ;; list of strings or ns:ns-string objects (short-weekday-symbols nil short-weekday-symbols-p) ;; list of strings or ns:ns-string objects (standalone-month-symbols nil standalone-month-symbols-p) ;; list of strings or ns:ns-string objects (standalone-quarter-symbols nil standalone-quarter-symbols-p) ;; list of strings or ns:ns-string objects (standalone-weekday-symbols nil standalone-weekday-symbols-p) ;; list of strings or ns:ns-string objects (time-style nil time-style-p) ;; number or keyword: :none :short :medium :long :full (time-zone nil time-zone-p) ;; ns:ns-time-zone (two-digit-start-date nil two-digit-start-date-p) ;; lisp date or ns:ns-date (very-short-month-symbols nil very-short-month-symbols-p) ;; list of strings or ns:ns-string objects (very-short-standalone-month-symbols nil very-short-standalone-month-symbols-p) ;; list of strings or ns:ns-string objects (very-short-standalone-weekday-symbols nil very-short-standalone-weekday-symbols-p) ;; list of strings or ns:ns-string objects (very-short-weekday-symbols nil very-short-weekday-symbols-p) ;; list of strings or ns:ns-string objects (weekday-symbols nil weekday-symbols-p) ;; list of strings or ns:ns-string objects &allow-other-keys) (when calendar-p (#/setCalendar: self calendar)) (when date-format-p (#/setDateFormat: self (coerce-obj date-format 'ns:ns-string))) (when date-style-p (#/setDateStyle: self (convert-date-style date-style))) (when default-date-p (#/setDefaultDate: self (coerce-obj default-date 'ns:ns-date))) (when does-relative-date-formatting-p (#/setDoesRelativeDateFormatting: self does-relative-date-formatting)) (when era-symbols-p (#/setEraSymbols: self (coerce-obj era-symbols 'ns:ns-array))) (when gregorian-start-date-p (#/setGregorianStartDate: self (coerce-obj gregorian-start-date 'ns:ns-date))) (when lenient-p (#/setLenient: self lenient)) (when locale-p (#/setLocale: self locale)) (when long-era-symbols-p (#/setLongEraSymbols: self (coerce-obj long-era-symbols 'ns:ns-array))) (when month-symbols-p (#/setMonthSymbols: self (coerce-obj month-symbols 'ns:ns-array))) (when pm-symbol-p (#/setPMSymbol: self (coerce-obj pm-symbol 'ns:ns-string))) (when quarter-symbols-p (#/setQuarterSymbols: self (coerce-obj quarter-symbols 'ns:ns-array))) (when short-month-symbols-p (#/setShortMonthSymbols: self (coerce-obj short-month-symbols 'ns:ns-array))) (when short-quarter-symbols-p (#/setShortQuarterSymbols: self (coerce-obj short-quarter-symbols 'ns:ns-array))) (when short-standalone-month-symbols-p (#/setShortStandaloneMonthSymbols: self (coerce-obj short-standalone-month-symbols 'ns:ns-array))) (when short-standalone-quarter-symbols-p (#/setShortStandaloneQuarterSymbols: self (coerce-obj short-standalone-quarter-symbols 'ns:ns-array))) (when short-standalone-weekday-symbols-p (#/setShortStandaloneWeekdaySymbols: self (coerce-obj short-standalone-weekday-symbols 'ns:ns-array))) (when short-weekday-symbols-p (#/setShortWeekdaySymbols: self (coerce-obj short-weekday-symbols 'ns:ns-array))) (when standalone-month-symbols-p (#/setStandaloneMonthSymbols: self (coerce-obj standalone-month-symbols 'ns:ns-array))) (when standalone-quarter-symbols-p (#/setStandaloneQuarterSymbols: self (coerce-obj standalone-quarter-symbols 'ns:ns-array))) (when standalone-weekday-symbols-p (#/setStandaloneWeekdaySymbols: self (coerce-obj standalone-weekday-symbols 'ns:ns-array))) (when time-style-p (#/setTimeStyle: self (convert-date-style time-style))) ;; date and time use same constants (when time-zone-p (#/setTimeZone: self time-zone)) (when two-digit-start-date-p (#/setTwoDigitStartDate: self (coerce-obj two-digit-start-date 'ns:ns-date))) (when very-short-month-symbols-p (#/setVeryShortMonthSymbols: self (coerce-obj very-short-month-symbols 'ns:ns-array))) (when very-short-standalone-month-symbols-p (#/setVeryShortStandaloneMonthSymbols: self (coerce-obj very-short-standalone-month-symbols 'ns:ns-array))) (when very-short-standalone-weekday-symbols-p (#/setVeryShortStandaloneWeekdaySymbols: self (coerce-obj very-short-standalone-weekday-symbols 'ns:ns-array))) (when very-short-weekday-symbols-p (#/setVeryShortWeekdaySymbols: self (coerce-obj very-short-weekday-symbols 'ns:ns-array))) (when weekday-symbols-p (#/setWeekdaySymbols: self (coerce-obj weekday-symbols 'ns:ns-array)))) (defmethod initialize-instance :after ((self ns:ns-number-formatter) &key (allows-floats nil allows-floats-p) (always-shows-decimal-separator nil always-shows-decimal-separator-p) (attributed-string-for-nil nil attributed-string-for-nil-p) ;; string attributed-string ns:ns-string or ns:ns-attributed-string (attributed-string-for-not-a-number nil attributed-string-for-not-a-number-p) ;; string attributed-string ns:ns-string or ns:ns-attributed-string (attributed-string-for-zero nil attributed-string-for-zero-p) ;; string attributed-string ns:ns-string or ns:ns-attributed-string (currency-decimal-separator nil currency-decimal-separator-p) ;; string or ns:ns-string (currency-grouping-separator nil currency-grouping-separator-p) ;; string or ns:ns-string (currency-symbol nil currency-symbol-p) ;; string or ns:ns-string (decimal-separator nil decimal-separator-p) ;; string or ns:ns-string (exponent-symbol nil exponent-symbol-p) ;; string or ns:ns-string (format nil format-p) ;; string or ns:ns-string (format-width nil format-width-p) ;; integer (generates-decimal-numbers nil generates-decimal-numbers-p) (grouping-separator nil grouping-separator-p) ;; string or ns:ns-string (grouping-size nil grouping-size-p) ;; integer (has-thousand-separators nil has-thousand-separators-p) (international-currency-symbol nil international-currency-symbol-p) ;; string or ns:ns-string (lenient nil lenient-p) (locale nil locale-p) ;; ns:ns-locale (localizes-format nil localizes-format-p) (maximum nil maximum-p) ;; number (maximum-fraction-digits nil maximum-fraction-digits-p) ;; integer (maximum-integer-digits nil maximum-integer-digits-p) ;; integer (maximum-significant-digits nil maximum-significant-digits-p) ;; integer (minimum nil minimum-p) ;; number (minimum-fraction-digits nil minimum-fraction-digits-p) ;; integer (minimum-integer-digits nil minimum-integer-digits-p) ;; integer (minimum-significant-digits nil minimum-significant-digits-p) ;; integer (minus-sign nil minus-sign-p) ;; string or ns:ns-string (multiplier nil multiplier-p) ;; number (negative-format nil negative-format-p) ;; string or ns:ns-string (negative-infinity-symbol nil negative-infinity-symbol-p) ;; string or ns:ns-string (negative-prefix nil negative-prefix-p) ;; string or ns:ns-string (negative-suffix nil negative-suffix-p) ;; string or ns:ns-string (nil-symbol nil nil-symbol-p) ;; string or ns:ns-string (not-a-number-symbol nil not-a-number-symbol-p) ;; string or ns:ns-string (number-style nil number-style-p) ;; number or keyword: :none :decimal :currency :percent :scientific :spell-out (padding-character nil padding-character-p) ;; string or ns:ns-string (padding-position nil padding-position-p) ;; number or keyword: :before-prefix :after-prefix :before-suffix :after-suffix (partial-string-validation-enabled nil partial-string-validation-enabled-p) (percent-symbol nil percent-symbol-p) ;; string or ns:ns-string (per-mill-symbol nil per-mill-symbol-p) ;; string or ns:ns-string (plus-sign nil plus-sign-p) ;; string or ns:ns-string (positive-format nil positive-format-p) ;; string or ns:ns-string (positive-infinity-symbol nil positive-infinity-symbol-p) ;; string or ns:ns-string (positive-prefix nil positive-prefix-p) ;; string or ns:ns-string (positive-suffix nil positive-suffix-p) ;; string or ns:ns-string (rounding-behavior nil rounding-behavior-p) ;; ns:ns-decimal-number-handler (rounding-increment nil rounding-increment-p) ;; number (rounding-mode nil rounding-mode-p) ;; number or keyword: :ceiling :floor :down :up :half-even :half-down :half-up (secondary-grouping-size nil secondary-grouping-size-p) ;; integer (text-attributes-for-negative-infinity nil text-attributes-for-negative-infinity-p) ;; assoc-list, hash-table, or ns:ns-dictionary of attribute-value pairs (text-attributes-for-negative-values nil text-attributes-for-negative-values-p) ;; assoc-list, hash-table, or ns:ns-dictionary of attribute-value pairs (text-attributes-for-nil nil text-attributes-for-nil-p) ;; assoc-list, hash-table, or ns:ns-dictionary of attribute-value pairs (text-attributes-for-not-a-number nil text-attributes-for-not-a-number-p) ;; assoc-list, hash-table, or ns:ns-dictionary of attribute-value pairs (text-attributes-for-positive-infinity nil text-attributes-for-positive-infinity-p) ;; assoc-list, hash-table, or ns:ns-dictionary of attribute-value pairs (text-attributes-for-positive-values nil text-attributes-for-positive-values-p) ;; assoc-list, hash-table, or ns:ns-dictionary of attribute-value pairs (text-attributes-for-zero nil text-attributes-for-zero-p) ;; assoc-list, hash-table, or ns:ns-dictionary of attribute-value pairs (thousand-separator nil thousand-separator-p) ;; string or ns:ns-string (uses-grouping-separator nil uses-grouping-separator-p) (uses-significant-digits nil uses-significant-digits-p) (zero-symbol nil zero-symbol-p) ;; string or ns:ns-string &allow-other-keys) ;; set basic style first, permitting modifications with other keywords (when number-style-p (#/setNumberStyle: self (convert-number-style number-style))) (when allows-floats-p (#/setAllowsFloats: self allows-floats)) (when always-shows-decimal-separator-p (#/setAlwaysShowsDecimalSeparator: self always-shows-decimal-separator)) (when attributed-string-for-nil-p (#/setAttributedStringForNil: self (coerce-obj attributed-string-for-nil 'ns:ns-attributed-string))) (when attributed-string-for-not-a-number-p (#/setAttributedStringForNotANumber: self (coerce-obj attributed-string-for-not-a-number 'ns:ns-attributed-string))) (when attributed-string-for-zero-p (#/setAttributedStringForZero: self (coerce-obj attributed-string-for-zero 'ns:ns-attributed-string))) (when currency-decimal-separator-p (#/setCurrencyDecimalSeparator: self (coerce-obj currency-decimal-separator 'ns:ns-string))) (when currency-grouping-separator-p (#/setCurrencyGroupingSeparator: self (coerce-obj currency-grouping-separator 'ns:ns-string))) (when currency-symbol-p (#/setCurrencySymbol: self (coerce-obj currency-symbol 'ns:ns-string))) (when decimal-separator-p (#/setDecimalSeparator: self (coerce-obj decimal-separator 'ns:ns-string))) (when exponent-symbol-p (#/setExponentSymbol: self (coerce-obj exponent-symbol 'ns:ns-string))) (when format-p (#/setFormat: self (coerce-obj format 'ns:ns-string))) (when format-width-p (#/setFormatWidth: self (coerce format-width 'integer))) (when generates-decimal-numbers-p (#/setGeneratesDecimalNumbers: self generates-decimal-numbers)) (when grouping-separator-p (#/setGroupingSeparator: self (coerce-obj grouping-separator 'ns:ns-string))) (when grouping-size-p (#/setGroupingSize: self (coerce grouping-size 'integer))) (when has-thousand-separators-p (#/setHasThousandSeparators: self has-thousand-separators)) (when international-currency-symbol-p (#/setInternationalCurrencySymbol: self (coerce-obj international-currency-symbol 'ns:ns-string))) (when lenient-p (#/setLenient: self lenient)) (when locale-p (#/setLocale: self locale)) (when localizes-format-p (#/setLocalizesFormat: self localizes-format)) (when maximum-p (#/setMaximum: self (coerce-obj maximum 'ns:ns-number))) (when maximum-fraction-digits-p (#/setMaximumFractionDigits: self (coerce maximum-fraction-digits 'integer))) (when maximum-integer-digits-p (#/setMaximumIntegerDigits: self (coerce maximum-integer-digits 'integer))) (when maximum-significant-digits-p (#/setMaximumSignificantDigits: self (coerce maximum-significant-digits 'integer))) (when minimum-p (#/setMinimum: self (coerce-obj minimum 'ns:ns-number))) (when minimum-fraction-digits-p (#/setMinimumFractionDigits: self (coerce minimum-fraction-digits 'integer))) (when minimum-integer-digits-p (#/setMinimumIntegerDigits: self (coerce minimum-integer-digits 'integer))) (when minimum-significant-digits-p (#/setMinimumSignificantDigits: self (coerce minimum-significant-digits 'integer))) (when minus-sign-p (#/setMinusSign: self (coerce-obj minus-sign 'ns:ns-string))) (when multiplier-p (#/setMultiplier: self (coerce-obj multiplier 'ns:ns-number))) (when negative-format-p (#/setNegativeFormat: self (coerce-obj negative-format 'ns:ns-string))) (when negative-infinity-symbol-p (#/setNegativeInfinitySymbol: self (coerce-obj negative-infinity-symbol 'ns:ns-string))) (when negative-prefix-p (#/setNegativePrefix: self (coerce-obj negative-prefix 'ns:ns-string))) (when negative-suffix-p (#/setNegativeSuffix: self (coerce-obj negative-suffix 'ns:ns-string))) (when nil-symbol-p (#/setNilSymbol: self (coerce-obj nil-symbol 'ns:ns-string))) (when not-a-number-symbol-p (#/setNotANumberSymbol: self (coerce-obj not-a-number-symbol 'ns:ns-string))) (when padding-character-p (#/setPaddingCharacter: self (coerce-obj padding-character 'ns:ns-string))) (when padding-position-p (#/setPaddingPosition: self (convert-padding-position padding-position))) (when partial-string-validation-enabled-p (#/setPartialStringValidationEnabled: self partial-string-validation-enabled)) (when percent-symbol-p (#/setPercentSymbol: self (coerce-obj percent-symbol 'ns:ns-string))) (when per-mill-symbol-p (#/setPerMillSymbol: self (coerce-obj per-mill-symbol 'ns:ns-string))) (when plus-sign-p (#/setPlusSign: self (coerce-obj plus-sign 'ns:ns-string))) (when positive-format-p (#/setPositiveFormat: self (coerce-obj positive-format 'ns:ns-string))) (when positive-infinity-symbol-p (#/setPositiveInfinitySymbol: self (coerce-obj positive-infinity-symbol 'ns:ns-string))) (when positive-prefix-p (#/setPositivePrefix: self (coerce-obj positive-prefix 'ns:ns-string))) (when positive-suffix-p (#/setPositiveSuffix: self (coerce-obj positive-suffix 'ns:ns-string))) (when rounding-behavior-p (#/setRoundingBehavior: self rounding-behavior)) (when rounding-increment-p (#/setRoundingIncrement: self (coerce-obj rounding-increment 'ns:ns-number))) (when rounding-mode-p (#/setRoundingMode: self (convert-rounding-mode rounding-mode))) (when secondary-grouping-size-p (#/setSecondaryGroupingSize: self (coerce secondary-grouping-size 'integer))) (when text-attributes-for-negative-infinity-p (#/setTextAttributesForNegativeInfinity: self (coerce-obj text-attributes-for-negative-infinity 'ns:ns-dictionary))) (when text-attributes-for-negative-values-p (#/setTextAttributesForNegativeValues: self (coerce-obj text-attributes-for-negative-values 'ns:ns-dictionary))) (when text-attributes-for-nil-p (#/setTextAttributesForNil: self (coerce-obj text-attributes-for-nil 'ns:ns-dictionary))) (when text-attributes-for-not-a-number-p (#/setTextAttributesForNotANumber: self (coerce-obj text-attributes-for-not-a-number 'ns:ns-dictionary))) (when text-attributes-for-positive-infinity-p (#/setTextAttributesForPositiveInfinity: self (coerce-obj text-attributes-for-positive-infinity 'ns:ns-dictionary))) (when text-attributes-for-positive-values-p (#/setTextAttributesForPositiveValues: self (coerce-obj text-attributes-for-positive-values 'ns:ns-dictionary))) (when text-attributes-for-zero-p (#/setTextAttributesForZero: self (coerce-obj text-attributes-for-zero 'ns:ns-dictionary))) (when thousand-separator-p (#/setThousandSeparator: self (coerce-obj thousand-separator 'ns:ns-string))) (when uses-grouping-separator-p (#/setUsesGroupingSeparator: self uses-grouping-separator)) (when uses-significant-digits-p (#/setUsesSignificantDigits: self uses-significant-digits)) (when zero-symbol-p (#/setZeroSymbol: self (coerce-obj zero-symbol 'ns:ns-string)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; ns-responder subclasses (defmethod initialize-instance :after ((self ns:ns-view) &key (accepts-touch-events nil accepts-touch-events-p) (alpha-value 0 alpha-value-p) (animations nil animations-p) (autoresizes-subviews nil autoresizes-subviews-p) (autoresizing-mask 0 autoresizing-mask-p) ;; number or list of resizing keys: see convert-resizing-mask (bounds 0 bounds-p) ;; ns:ns-rectangle or list: (x y width height) (bounds-origin 0 bounds-origin-p) ;; ns:ns-point or list: (x y) (bounds-rotation 0 bounds-rotation-p) ;; angle in degrees (bounds-size 0 bounds-size-p) ;; ns:ns-size or list: (width height) (can-draw-concurrently nil can-draw-concurrently-p) (focus-ring-type nil focus-ring-type-p) ;; number or keyword: see convert-focus-ring-type (frame nil frame-p) ;; ns:ns-rect (frame-center-rotation nil frame-center-rotation-p) ;; angle in degrees (frame-origin nil frame-origin-p) ;; ns:ns-point or list: (x y) (frame-rotation nil frame-rotation-p) ;; angle in degrees (frame-size nil frame-size-p) ;; ns:ns-size or list: (width height) (hidden nil hidden-p) (layer nil layer-p) ;; CALayer (posts-bounds-changed-notifications nil posts-bounds-changed-notifications-p) (posts-frame-changed-notifications nil posts-frame-changed-notifications-p) (shadow nil shadow-p) ;; ns:ns-shadow (subviews nil subviews-p) ;; list of subviews (tool-tip "" tool-tip-p) ;; string (wants-resting-touches nil wants-resting-touches-p) &allow-other-keys) (when accepts-touch-events-p (#/setAcceptsTouchEvents: self accepts-touch-events)) (when alpha-value-p (#/setAlphaValue: self (cgfloat alpha-value))) (when animations-p (#/setAnimations: self (coerce-obj animations 'ns:ns-dictionary))) (when autoresizes-subviews-p (#/setAutoresizesSubviews: self autoresizes-subviews)) (when autoresizing-mask-p (#/setAutoresizingMask: self (convert-resizing-mask autoresizing-mask))) (when bounds-p (#/setBounds: self (coerce-obj bounds 'ns:ns-rect))) (when bounds-origin-p (#/setBoundsOrigin: self (coerce-obj bounds-origin 'ns:ns-point))) (when bounds-rotation-p (#/setBoundsRotation: self (cgfloat bounds-rotation))) (when bounds-size-p (#/setBoundsSize: self (coerce-obj bounds-size 'ns:ns-size))) (when can-draw-concurrently-p (#/setCanDrawConcurrently: self can-draw-concurrently)) (when focus-ring-type-p (#/setFocusRingType: self (convert-focus-ring-type focus-ring-type))) (when frame-p (#/setFrame: self (coerce-obj frame 'ns:ns-rect))) (when frame-center-rotation-p (#/setFrameCenterRotation: self (cgfloat frame-center-rotation))) (when frame-origin-p (#/setFrameOrigin: self (coerce-obj frame-origin 'ns:ns-point))) (when frame-rotation-p (#/setFrameRotation: self (cgfloat frame-rotation))) (when frame-size-p (#/setFrameSize: self (coerce-obj frame-size 'ns:ns-size))) (when hidden-p (#/setHidden: self hidden)) (when layer-p (#/setLayer: self layer)) (when posts-bounds-changed-notifications-p (#/setPostsBoundsChangedNotifications: self posts-bounds-changed-notifications)) (when posts-frame-changed-notifications-p (#/setPostsFrameChangedNotifications: self posts-frame-changed-notifications)) (when shadow-p (#/setShadow: self shadow)) (when subviews-p (#/setSubviews: self (coerce-obj subviews 'ns:ns-array))) (when tool-tip-p (#/setToolTip: self (coerce-obj tool-tip 'ns:ns-string))) (when wants-resting-touches-p (#/setWantsRestingTouches: self wants-resting-touches))) (defmethod initialize-instance :after ((self ns:ns-window) &key (accepts-mouse-moved-events nil accepts-mouse-moved-events-p) (allows-concurrent-view-drawing nil allows-concurrent-view-drawing-p) (allows-tool-tips-when-application-is-inactive nil allows-tool-tips-when-application-is-inactive-p) (alpha-value 0 alpha-value-p) (animation-behavior nil animation-behavior-p) ;; number or keyword: see convert-animation-behavior (aspect-ratio nil aspect-ratio-p) ;; ns:ns-size or list: (width height) (autodisplay nil autodisplay-p) (background-color nil background-color-p) ;; ns:ns-color or keyword acceptable to (coerce-obj <keyword> 'ns:ns-color) (can-become-visible-without-login nil can-become-visible-without-login-p) (can-hide nil can-hide-p) (collection-behavior nil collection-behavior-p) ;; number, keyword, or list of keywords: see convert-collection-bahavior (color-space nil color-space-p) ;; ns:ns-color-space (content-aspect-ratio nil content-aspect-ratio-p) ;; ns:ns-size or list: (width height) (content-max-size nil content-max-size-p) ;; ns:ns-size or list: (width height) (content-min-size nil content-min-size-p) (content-resize-increments nil content-resize-increments-p) ;; ns:ns-size or list: (width height) (content-size nil content-size-p) ;; ns:ns-size or list: (width height) (content-view nil content-view-p) ;; ns:ns-view (content-subviews nil content-subviews-p) ;; a list of subviews to add to the window's content view (default-button-cell nil default-button-cell-p) ;; ns:ns-button-cell (delegate nil delegate-p) ;; ns:ns-object (depth-limit nil depth-limit-p) ;; number or keyword: :rgb-24, :rgb-64 or :rgb-128 (displays-when-screen-profile-changes nil displays-when-screen-profile-changes-p) (dynamic-depth-limit nil dynamic-depth-limit-p) ;; t or nil (excluded-from-windows-menu nil excluded-from-windows-menu-p) (frame nil frame-p) ;; ns:ns-rect or (frame-autosave-name nil frame-autosave-name-p) ;; string or ns:ns-string (frame-from-string nil frame-from-string-p) ;; string or ns:ns-string (frame-origin nil frame-origin-p) ;; ns-point or list: (x y) (frame-top-left-point nil frame-top-left-point-p) ;; ns-point or list: (x y) (frame-using-name nil frame-using-name-p) ;; string or ns:ns-string (has-shadow nil has-shadow-p) (hides-on-deactivate nil hides-on-deactivate-p) (ignores-mouse-events nil ignores-mouse-events-p) (initial-first-responder nil initial-first-responder-p) ;; ns:ns-view (level nil level-p) ;; number or keyword: see convert-window-level (max-size nil max-size-p) ;; ns:ns-size or list: (width height) (miniwindow-image nil miniwindow-image-p) ;; ns:ns-image (miniwindow-title nil miniwindow-title-p) ;; string or ns:ns-string (min-size nil min-size-p) ;; ns:ns-size or list: (width height) (movable nil movable-p) (movable-by-window-background nil movable-by-window-background-p) (one-shot nil one-shot-p) (opaque nil opaque-p) (preferred-backing-location nil preferred-backing-location-p) ;; number or keyword: :default :video-memory :main-memory (preserves-content-during-live-resize nil preserves-content-during-live-resize-p) (prevents-application-termination-when-modal nil prevents-application-termination-when-modal-p) (released-when-closed nil released-when-closed-p) (represented-filename nil represented-filename-p) ;; string or ns:ns-string (represented-url nil represented-url-p) ;; ns:ns-url (resize-increments nil resize-increments-p) ;; ns-size or list: (width height) (restorable nil restorable-p) (restoration-class nil restoration-class-p) ;; class that conforms to the NSWindowRestoration protocol (sharing-type nil sharing-type-p) ;; number or keyword: see convert-sharing-type (shows-resize-indicator nil shows-resize-indicator-p) (shows-toolbar-button nil shows-toolbar-button-p) (titled t titled-p) (closable t closable-p) (resizable t resizable-p) (miniaturizable t miniaturizable-p) (title nil title-p) ;; string or ns:ns-string (title-with-represented-filename nil title-with-represented-filename-p) ;; string or ns:ns-string (toolbar nil toolbar-p) ;; ns:ns-toolbar (window-controller nil window-controller-p) ;; ns:ns-window-controller &allow-other-keys) (when accepts-mouse-moved-events-p (#/setAcceptsMouseMovedEvents: self accepts-mouse-moved-events)) (when allows-concurrent-view-drawing-p (#/setAllowsConcurrentViewDrawing: self allows-concurrent-view-drawing)) (when allows-tool-tips-when-application-is-inactive-p (#/setAllowsToolTipsWhenApplicationIsInactive: self allows-tool-tips-when-application-is-inactive)) (when alpha-value-p (#/setAlphaValue: self (cgfloat alpha-value))) (when animation-behavior-p (#/setAnimationBehavior: self (convert-animation-behavior animation-behavior))) (when aspect-ratio-p (#/setAspectRatio: self (coerce-obj aspect-ratio 'ns:ns-size))) (when autodisplay-p (#/setAutodisplay: self autodisplay)) (when background-color-p (#/setBackgroundColor: self (coerce-obj background-color 'ns:ns-color))) (when can-become-visible-without-login-p (#/setCanBecomeVisibleWithoutLogin: self can-become-visible-without-login)) (when can-hide-p (#/setCanHide: self can-hide)) (when collection-behavior-p (#/setCollectionBehavior: self (convert-collection-behavior collection-behavior))) (when color-space-p (#/setColorSpace: self color-space)) (when content-aspect-ratio-p (#/setContentAspectRatio: self (coerce-obj content-aspect-ratio 'ns:ns-size))) (when content-max-size-p (#/setContentMaxSize: self (coerce-obj content-max-size 'ns:ns-size))) (when content-min-size-p (#/setContentMinSize: self (coerce-obj content-min-size 'ns:ns-size))) (when content-resize-increments-p (#/setContentResizeIncrements: self (coerce-obj content-resize-increments 'ns:ns-size))) (when content-size-p (#/setContentSize: self (coerce-obj content-size 'ns:ns-size))) (when content-view-p (#/setContentView: self content-view)) (when content-subviews-p (let ((cv (#/contentView self))) (dolist (sv content-subviews) (#/addSubview: cv sv)))) (when default-button-cell-p (#/setDefaultButtonCell: self default-button-cell)) (when delegate-p (#/setDelegate: self delegate)) (when depth-limit-p (#/setDepthLimit: self (convert-window-depth depth-limit))) (when displays-when-screen-profile-changes-p (#/setDisplaysWhenScreenProfileChanges: self displays-when-screen-profile-changes)) (when dynamic-depth-limit-p (#/setDynamicDepthLimit: self dynamic-depth-limit)) (when excluded-from-windows-menu-p (#/setExcludedFromWindowsMenu: self excluded-from-windows-menu)) (when frame-p (#/setFrame:display: self (coerce-obj frame 'ns:ns-rect) #$NO)) (when frame-autosave-name-p (#/setFrameAutosaveName: self (coerce-obj frame-autosave-name 'ns:ns-string))) (when frame-from-string-p (#/setFrameFromString: self (coerce-obj frame-from-string 'ns:ns-string))) (when frame-origin-p (#/setFrameOrigin: self (coerce-obj frame-origin 'ns:ns-point))) (when frame-top-left-point-p (#/setFrameTopLeftPoint: self (coerce-obj frame-top-left-point 'ns:ns-point))) (when frame-using-name-p (#/setFrameUsingName: self (coerce-obj frame-using-name 'ns:ns-string))) (when has-shadow-p (#/setHasShadow: self has-shadow)) (when hides-on-deactivate-p (#/setHidesOnDeactivate: self hides-on-deactivate)) (when ignores-mouse-events-p (#/setIgnoresMouseEvents: self ignores-mouse-events)) (when initial-first-responder-p (#/setInitialFirstResponder: self initial-first-responder)) (when level-p (#/setLevel: self (convert-window-level level))) (when max-size-p (#/setMaxSize: self (coerce-obj max-size 'ns:ns-size))) (when miniwindow-image-p (#/setMiniwindowImage: self miniwindow-image)) (when miniwindow-title-p (#/setMiniwindowTitle: self (coerce-obj miniwindow-title 'ns:ns-string))) (when min-size-p (#/setMinSize: self (coerce-obj min-size 'ns:ns-size))) (when movable-p (#/setMovable: self movable)) (when movable-by-window-background-p (#/setMovableByWindowBackground: self movable-by-window-background)) (when one-shot-p (#/setOneShot: self one-shot)) (when opaque-p (#/setOpaque: self opaque)) (when preferred-backing-location-p (#/setPreferredBackingLocation: self (convert-window-backing-loc preferred-backing-location))) (when preserves-content-during-live-resize-p (#/setPreservesContentDuringLiveResize: self preserves-content-during-live-resize)) (when prevents-application-termination-when-modal-p (#/setPreventsApplicationTerminationWhenModal: self prevents-application-termination-when-modal)) (when released-when-closed-p (#/setReleasedWhenClosed: self released-when-closed)) (when represented-filename-p (#/setRepresentedFilename: self (coerce-obj represented-filename 'ns:ns-string))) (when represented-url-p (#/setRepresentedURL: self represented-url)) (when resize-increments-p (#/setResizeIncrements: self (coerce-obj resize-increments 'ns:ns-size))) (when restorable-p (#/setRestorable: self restorable)) (when restoration-class-p (#/setRestorationClass: self restoration-class)) (when sharing-type-p (#/setSharingType: self (convert-sharing-type sharing-type))) (when shows-resize-indicator-p (#/setShowsResizeIndicator: self shows-resize-indicator)) (when (or titled-p closable-p resizable-p miniaturizable-p) (#/setStyleMask: self (+ (if titled #$NSTitledWindowMask 0) (if closable #$NSClosableWindowMask 0) (if resizable #$NSResizableWindowMask 0) (if miniaturizable #$NSMiniaturizableWindowMask 0)))) (when (and title-p title) ;; need the title check for back compatibility with initialize-instance :after method ;; defined in cocoa-window.lisp which this will replace (#/setTitle: self (coerce-obj title 'ns:ns-string))) (when title-with-represented-filename-p (#/setTitleWithRepresentedFilename: self (coerce-obj title-with-represented-filename 'ns:ns-string))) (when toolbar-p (#/setToolbar: self toolbar)) (when shows-toolbar-button-p (#/setShowsToolbarButton: self shows-toolbar-button)) (when window-controller-p (#/setWindowController: self window-controller))) (defmethod initialize-instance :after ((self ns:ns-window-controller) &key (window nil window-p) &allow-other-keys) (when window-p (#/initWithWindow: self window))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; ns-view subclasses (defmethod initialize-instance :after ((self ns:ns-box) &key (border-color nil border-color-p) ;; ns:ns-color or keyword (border-type nil border-type-p) ;; number or keyword (border-width nil border-width-p) ;; number (box-type nil box-type-p) ;; number or keyword (content-view nil content-view-p) ;; ns:ns-view (content-view-margins nil content-view-margins-p) ;; ns:ns-size or list of the form (width height) (corner-radius nil corner-radius-p) ;; number (fill-color nil fill-color-p) ;; ns:ns-color or keyword (title nil title-p) ;; string, ns:ns-string (title-font nil title-font-p) ;; ns:ns-font (title-position nil title-position-p) ;; title-position keyword (transparent nil transparent-p) &allow-other-keys) (when border-color-p (#/setBorderColor: self (coerce-obj border-color 'ns:ns-color))) (when border-type-p (#/setBorderType: self (convert-border border-type))) (when border-width-p (#/setBorderWidth: self (cgfloat border-width))) (when box-type-p (#/setBoxType: self (convert-box-type box-type))) (when content-view-p (#/setContentView: self content-view)) (when content-view-margins-p (#/setContentViewMargins: self (coerce-obj content-view-margins 'ns:ns-size)) (#/sizeToFit self)) (when corner-radius-p (#/setCornerRadius: self (cgfloat corner-radius))) (when fill-color-p (#/setFillColor: self (coerce-obj fill-color 'ns:ns-color))) (when title-p (#/setTitle: self (coerce-obj title 'ns:ns-string))) (when title-font-p (#/setTitleFont: self title-font)) (when title-position-p (#/setTitlePosition: self (convert-title-position title-position))) (when transparent-p (#/setTransparent: self transparent))) (defmethod initialize-instance :after ((self ns:ns-combo-box) &key (button-bordered nil button-bordered-p) (completes nil completes-p) (data-source nil data-source-p) ;; object that conforms to the NSComboBoxDataSource protocol (delegate nil delegate-p) ;; object that conforms to the NSComboBoxDelegate protocol (has-vertical-scroller nil has-vertical-scroller-p) (intercell-spacing nil intercell-spacing-p) ;; ns:ns-size or list of the form (width height) (item-height nil item-height-p) ;; number coercable to a double-float (items-with-object-values nil items-with-object-values-p) ;; list of strings or numbers (number-of-visible-items nil number-of-visible-items-p) ;; integer number (uses-data-source nil uses-data-source-p) &allow-other-keys) (when button-bordered-p (#/setButtonBordered: self button-bordered)) (when completes-p (#/setCompletes: self completes)) (when uses-data-source-p ;; must come before data-source (#/setUsesDataSource: self uses-data-source)) (when data-source-p (#/setDataSource: self data-source)) (when delegate-p (#/setDelegate: self delegate)) (when has-vertical-scroller-p (#/setHasVerticalScroller: self has-vertical-scroller)) (when intercell-spacing-p (#/setIntercellSpacing: self (coerce-obj intercell-spacing 'ns:ns-size))) (when item-height-p (#/setItemHeight: self (cgfloat item-height))) (when items-with-object-values-p (#/addItemsWithObjectValues: self (coerce-obj items-with-object-values 'ns:ns-array))) (when number-of-visible-items-p (#/setNumberOfVisibleItems: self (coerce number-of-visible-items 'integer)))) (defmethod initialize-instance :after ((self ns:ns-control) &key (action nil action-p) ;; string (alignment :natural alignment-p) ;; number or keyword defined in convert-text-alignment (allows-undo nil allows-undo-p) (attributed-string-value "" attributed-string-value-p) ;; string or attributed-string (base-writing-direction :natural base-writing-direction-p) ;; number or keyword from convert-writing-direction (continuous nil continuous-p) (initial-value nil initial-value-p) ;; numeric value (enabled t enabled-p) (font nil font-p) ;; ns:ns-font (formatter nil formatter-p) ;; ns:ns-formatter, see formatters.lisp (ignores-multi-click t ignores-multi-click-p) (refuses-first-responder nil refuses-first-responder-p) (tag 0 tag-p) ;; integer (target nil target-p) ;; ns:ns-object &allow-other-keys) ;; see view.lisp for other allowed keywords (when action-p (#/setAction: self (get-selector action))) (when alignment-p (#/setAlignment: self (convert-text-alignment alignment))) (when allows-undo-p (#/setAllowsUndo: (#/cell self) allows-undo)) (when attributed-string-value-p (#/setAttributedStringValue: self (coerce-obj attributed-string-value 'ns:ns-attributed-string))) (when base-writing-direction-p (#/setBaseWritingDirection: self (convert-writing-direction base-writing-direction))) (when continuous-p (#/setContinuous: self continuous)) (when initial-value-p (cond ((floatp initial-value) (#/setFloatValue: self initial-value)) ((integerp initial-value) (#/setIntegerValue: self initial-value)) ((typep initial-value 'double-float) (#/setDoubleValue: self initial-value)) ((numberp initial-value) (#/setFloatValue: self (float initial-value))) ((stringp initial-value) (#/setStringValue: self (coerce-obj initial-value 'ns:ns-string))) ((typep initial-value 'ns:ns-object) (#/setObjectValue: self initial-value)))) (when enabled-p (#/setEnabled: self enabled)) (when (and font-p (typep font 'ns:ns-font)) (#/setFont: self font)) (when (and formatter-p (typep formatter 'ns:ns-formatter)) (#/setFormatter: self formatter)) (when ignores-multi-click-p (#/setIgnoresMultiClick: self ignores-multi-click)) (when refuses-first-responder-p (#/setRefusesFirstResponder: self refuses-first-responder)) (when (and tag-p (numberp tag)) (#/setTag: self (truncate tag))) (when (and target-p (typep target 'ns:ns-object)) (#/setTarget: self target))) (defmethod initialize-instance :after ((self ns:ns-scroll-view) &key (autohides-scrollers t autohides-scrollers-p) ;; t or nil (background-color nil background-color-p) ;; ns:ns-color or keyword acceptable to (coerce-obj <keyword> 'ns:ns-color) (border-type nil border-type-p) ;; number or keyword: see convert-border (content-view nil content-view-p) (document-cursor nil document-cursor-p) ;; number or keyword: see convert-cursor (document-view nil document-view-p) ;; the view that will be scrolled (draws-background nil draws-background-p) (find-bar-position nil find-bar-position-p) ;; number or keyword: see convert-find-bar-position (has-horizontal-ruler nil has-horizontal-ruler-p) ;; t or nil (has-horizontal-scroller nil has-horizontal-scroller-p) ;; t or nil (has-vertical-ruler nil has-vertical-ruler-p) ;; t or nil (has-vertical-scroller nil has-vertical-scroller-p) ;; t or nil (horizontal-line-scroll nil horizontal-line-scroll-p) ;; points to scroll (horizontal-page-scroll nil horizontal-page-scroll-p) ;; points to scroll (horizontal-ruler-view nil horizontal-ruler-view-p) ;; ns:ns-ruler-view (horizontal-scroll-elasticity nil horizontal-scroll-elasticity-p) ;; number or keyword: see convert-elasticity (horizontal-scroller nil horizontal-scroller-p) ;; ns:ns-scroller (line-scroll nil line-scroll-p) ;; points to scroll in both h and v (page-scroll nil page-scroll-p) ;; points to scroll in both h and v (rulers-visible nil rulers-visible-p) (scroller-knob-style nil scroller-knob-style-p) ;; number or keyword: see convert-knob-style (scroller-style nil scroller-style-p) ;; number or keyword: see convert-scroller-style (scrolls-dynamically t scrolls-dynamically-p) ;; t or nil whether to redraw while scrolling (uses-predominant-axis-scrolling t uses-predominant-axis-scrolling-p) ;; t or nil (vertical-line-scroll nil vertical-line-scroll-p) ;; points to scroll (vertical-page-scroll nil vertical-page-scroll-p) ;; points to scroll (vertical-ruler-view nil vertical-ruler-view-p) ;; ns:ns-ruler-view (vertical-scroll-elasticity nil vertical-scroll-elasticity-p) ;; number or keyword: see convert-elasticity (vertical-scroller nil vertical-scroller-p) ;; ns:ns-scroller &allow-other-keys) (when autohides-scrollers-p (#/setAutohidesScrollers: self autohides-scrollers)) (when background-color-p (#/setBackgroundColor: self (coerce-obj background-color 'ns:ns-color))) (when border-type-p (#/setBorderType: self (convert-border border-type))) (when content-view-p (#/setContentView: self content-view)) (when document-cursor-p (#/setDocumentCursor: self (convert-cursor document-cursor))) (when document-view-p (#/setDocumentView: self document-view)) (when draws-background-p (#/setDrawsBackground: self draws-background)) (when find-bar-position-p (#/setFindBarPosition: self (convert-find-bar-position find-bar-position))) (when has-horizontal-ruler-p (#/setHasHorizontalRuler: self has-horizontal-ruler)) (when has-horizontal-scroller-p (#/setHasHorizontalScroller: self has-horizontal-scroller)) (when has-vertical-ruler-p (#/setHasVerticalRuler: self has-vertical-ruler)) (when has-vertical-scroller-p (#/setHasVerticalScroller: self has-vertical-scroller)) (when horizontal-line-scroll-p (#/setHorizontalLineScroll: self (cgfloat horizontal-line-scroll))) (when horizontal-page-scroll-p (#/setHorizontalPageScroll: self (cgfloat horizontal-page-scroll))) (when horizontal-ruler-view-p (#/setHorizontalRulerView: self horizontal-ruler-view)) (when horizontal-scroll-elasticity-p (#/setHorizontalScrollElasticity: self (convert-elasticity horizontal-scroll-elasticity))) (when horizontal-scroller-p (#/setHorizontalScroller: self horizontal-scroller)) (when line-scroll-p (#/setLineScroll: self (cgfloat line-scroll))) (when page-scroll-p (#/setPageScroll: self (cgfloat page-scroll))) (when rulers-visible-p (#/setRulersVisible: self rulers-visible)) (when scroller-knob-style-p (#/setScrollerKnobStyle: self (convert-knob-style scroller-knob-style))) (when scroller-style-p (#/setScrollerStyle: self (convert-scroller-style scroller-style))) (when scrolls-dynamically-p (#/setScrollsDynamically: self scrolls-dynamically)) (when uses-predominant-axis-scrolling-p (#/setUsesPredominantAxisScrolling: self uses-predominant-axis-scrolling)) (when vertical-line-scroll-p (#/setVerticalLineScroll: self (cgfloat vertical-line-scroll))) (when vertical-page-scroll-p (#/setVerticalPageScroll: self (cgfloat vertical-page-scroll))) (when vertical-ruler-view-p (#/setVerticalRulerView: self vertical-ruler-view)) (when vertical-scroll-elasticity-p (#/setVerticalScrollElasticity: self (convert-elasticity vertical-scroll-elasticity))) (when vertical-scroller-p (#/setVerticalScroller: self vertical-scroller)) self) (defmethod initialize-instance :after ((self ns:ns-text) &key (alignment nil alignment-p) (background-color nil background-color-p) ;; ns:ns-color or keyword convertible by coerce-obj (base-writing-direction nil base-writing-direction-p) ;; number or keyword from convert-writing-direction (delegate nil delegate-p) ;; any ns:ns-object (draws-background nil draws-background-p) (editable nil editable-p) (field-editor nil field-editor-p) (font nil font-p) ;; ns:ns-font (horizontally-resizable nil horizontally-resizable-p) (imports-graphics nil imports-graphics-p) (max-size nil max-size-p) ;; ns:ns-size or list of the form (<width> <height>) (min-size nil min-size-p) ;; ns:ns-size or list of the form (<width> <height>) (rich-text nil rich-text-p) (selectable nil selectable-p) (string nil string-p) ;; string, attributed-string, or ns:ns-string (text-color nil text-color-p) ;; ns:ns-color or keyword convertible by coerce-obj (uses-font-panel nil uses-font-panel-p) (vertically-resizable nil vertically-resizable-p) &allow-other-keys) ;; see control.lisp and view.lisp for other allowed keywords (when alignment-p (#/setAlignment: self (convert-text-alignment alignment))) (when background-color-p (#/setBackgroundColor: self (coerce-obj background-color 'ns:ns-color))) (when base-writing-direction-p (#/setBaseWritingDirection: self (convert-writing-direction base-writing-direction))) (when delegate-p (#/setDelegate: self delegate)) (when draws-background-p (#/setDrawsBackground: self draws-background)) (when editable-p (#/setEditable: self editable)) (when field-editor-p (#/setFieldEditor: self field-editor)) (when font-p (#/setFont: self font)) (when horizontally-resizable-p (#/setHorizontallyResizable: self horizontally-resizable)) (when imports-graphics-p (#/setImportsGraphics: self imports-graphics)) (when max-size-p (#/setMaxSize: self (coerce-obj max-size 'ns:ns-size))) (when min-size-p (#/setMinSize: self (coerce-obj min-size 'ns:ns-size))) (when rich-text-p (#/setRichText: self rich-text)) (when selectable-p (#/setSelectable: self selectable)) (when string-p (if rich-text-p (#/setAttributedString: (#/textStorage self) (coerce-obj string 'ns:ns-attributed-string)) (#/setString: self (coerce-obj string 'ns:ns-string)))) (when text-color-p (#/setTextColor: self (coerce-obj text-color 'ns:ns-color))) (when uses-font-panel-p (#/setUsesFontPanel: self uses-font-panel)) (when vertically-resizable-p (#/setVerticallyResizable: self vertically-resizable))) (defmethod initialize-instance :after ((self ns:ns-text-view) &key (delegate nil delegate-p) ;; ns:ns-object (displayes-link-tool-tips nil displayes-link-tool-tips-p) (draws-background nil draws-background-p) (editable nil editable-p) (enabled-text-checking-types nil enabled-text-checking-types-p) ;; keyword or list of keywords or number (field-editor nil field-editor-p) (grammar-checking-enabled nil grammar-checking-enabled-p) (imports-graphics nil imports-graphics-p) (incremental-searching-enabled nil incremental-searching-enabled-p) (insertion-point-color nil insertion-point-color-p) ;; ns:ns-color or keyword acceptable to (coerce-obj <keyword> 'ns:ns-color) (layout-orientation nil layout-orientation-p) ;; number or keyword: :h :horizontal :v :vertical (link-text-attributes nil link-text-attributes-p) ;; assoc-list, hash-table, or ns:ns-dictionary of attribute-value pairs (marked-text-attributes nil marked-text-attributes-p) ;; assoc-list, hash-table, or ns:ns-dictionary of attribute-value pairs (rich-text nil rich-text-p) (ruler-visible nil ruler-visible-p) (selectable nil selectable-p) (selected-text-attributes nil selected-text-attributes-p) ;; assoc-list, hash-table, or ns:ns-dictionary of attribute-value pairs (smart-insert-delete-enabled nil smart-insert-delete-enabled-p) (text-container nil text-container-p) ;; ns:ns-text-container (text-container-inset nil text-container-inset-p) ;; ns:ns-size or list: (width height) (uses-find-bar nil uses-find-bar-p) (uses-find-panel nil uses-find-panel-p) (uses-font-panel nil uses-font-panel-p) (uses-inspector-bar nil uses-inspector-bar-p) (uses-ruler nil uses-ruler-p) &allow-other-keys) ;; see control.lisp and view.lisp for other allowed keywords (when delegate-p (#/setDelegate: self delegate)) (when displayes-link-tool-tips-p (#/setDisplaysLinkToolTips: self displayes-link-tool-tips)) (when draws-background-p (#/setDrawsBackground: self draws-background)) (when editable-p (#/setEditable: self editable)) (when enabled-text-checking-types-p (#/setEnabledTextCheckingTypes: self (convert-text-checking-types enabled-text-checking-types))) (when field-editor-p (#/setFieldEditor: self field-editor)) (when grammar-checking-enabled-p (#/setGrammarCheckingEnabled: self grammar-checking-enabled)) (when imports-graphics-p (#/setImportsGraphics: self imports-graphics)) (when incremental-searching-enabled-p (#/setIncrementalSearchingEnabled: self incremental-searching-enabled)) (when insertion-point-color-p (#/setInsertionPointColor: self (coerce-obj insertion-point-color 'ns:ns-color))) (when layout-orientation-p (#/setLayoutOrientation: self (convert-text-orientation layout-orientation))) (when link-text-attributes-p (#/setLinkTextAttributes: self (coerce-obj link-text-attributes 'ns:ns-dictionary))) (when marked-text-attributes-p (#/setMarkedTextAttributes: self (coerce-obj marked-text-attributes 'ns:ns-dictionary))) (when rich-text-p (#/setRichText: self rich-text)) (when ruler-visible-p (#/setRulerVisible: self ruler-visible)) (when selectable-p (#/setSelectable: self selectable)) (when selected-text-attributes-p (#/setSelectedTextAttributes: self (coerce-obj selected-text-attributes 'ns:ns-dictionary))) (when smart-insert-delete-enabled-p (#/setSmartInsertDeleteEnabled: self smart-insert-delete-enabled)) (when text-container-p (#/setTextContainer: self text-container)) (when text-container-inset-p (#/setTextContainerInset: self (coerce-obj text-container-inset 'ns:ns-size))) (when uses-find-bar-p (#/setUsesFindBar: self uses-find-bar)) (when uses-find-panel-p (#/setUsesFindPanel: self uses-find-panel)) (when uses-font-panel-p (#/setUsesFontPanel: self uses-font-panel)) (when uses-inspector-bar-p (#/setUsesInspectorBar: self uses-inspector-bar)) (when uses-ruler-p (#/setUsesRuler: self uses-ruler))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; ns-control subclasses (defmethod initialize-instance :after ((self ns:ns-button) &key (allows-mixed-state nil allows-mixed-state-p) (alternate-image nil alternate-image-p) ;; ns:ns-image (alternate-title nil alternate-title-p) ;; string, attributed-string, ns:ns-string (attributed-alternate-title nil attributed-alternate-title-p) ;; string, attributed-string or Obj-C equivalents (attributed-title nil attributed-title-p) ;; string, attributed-string or Obj-C equivalents (bezel-style nil bezel-style-p) ;; number or keyword: see convert-bezel-style (bordered nil bordered-p) (button-type nil button-type-p) ;; number or keyword: see convert-button-type (image nil image-p) ;; ns:ns-image (image-position nil image-position-p) ;; single value or list, values are numbers or keyword: see convert-image-position (key-equivalent nil key-equivalent-p) (key-equivalent-modifier-mask 0 key-equivalent-modifier-mask-p) ;; number or list of keywords or keyword: :control, :alternate, or :command (shows-border-only-while-mouse-inside nil shows-border-only-while-mouse-inside-p) (sound nil sound-p) (state nil state-p) ;; number or keyword: :on, :off, or :mixed (title nil title-p) ;; string, attributed-string or Obj-C equivalents (transparent nil transparent-p) &allow-other-keys) ;; see control.lisp and view.lisp for other allowed keywords (when allows-mixed-state-p (#/setAllowsMixedState: self allows-mixed-state)) (when alternate-image-p (#/setAlternateImage: self alternate-image)) (when alternate-title-p (#/setAlternateTitle: self (coerce-obj alternate-title 'ns:ns-string))) (when attributed-alternate-title-p (#/setAttributedAlternateTitle: self (coerce-obj attributed-alternate-title 'ns:ns-attributed-string))) (when attributed-title-p (#/setAttributedTitle: self (coerce-obj attributed-title 'ns:ns-attributed-string))) (when bezel-style-p (#/setBezelStyle: self (convert-bezel-style bezel-style))) (when bordered-p (#/setBordered: self bordered)) (when button-type-p (#/setButtonType: self (convert-button-type button-type))) (when image-p (#/setImage: self image)) (when image-position-p (if (listp image-position) (dolist (ip image-position) (#/setImagePosition: self (convert-image-position ip))) (#/setImagePosition: self (convert-image-position image-position)))) (when key-equivalent-p (#/setKeyEquivalent: self (coerce-obj key-equivalent 'ns:ns-string))) (when key-equivalent-modifier-mask-p (#/setKeyEquivalentModifierMask: self (convert-key-modifier-mask key-equivalent-modifier-mask))) (when shows-border-only-while-mouse-inside-p (#/setShowsBorderOnlyWhileMouseInside: self shows-border-only-while-mouse-inside)) (when (and sound-p (typep sound 'ns:ns-sound)) (#/setSound: self sound)) (when state-p (#/setState: self (convert-state state))) (when title-p (#/setTitle: self (coerce-obj title 'ns:ns-string))) (when transparent-p (#/setTransparent: self transparent)) self) (defmethod initialize-instance :after ((self ns:ns-color-well) &key (bordered nil bordered-p) (color nil color-p) ;; ns:ns-color or keyword acceptable to (coerce-obj <keyword> 'ns:ns-color) &allow-other-keys) (when bordered-p (#/setBordered: self bordered)) (when color-p (#/setColor: self (coerce-obj color 'ns:ns-color)))) (defmethod initialize-instance :after ((self ns:ns-outline-view) &key (autoresizes-outline-column nil autoresizes-outline-column-p) (autosave-expanded-items nil autosave-expanded-items-p) (indentation-marker-follows-cell nil indentation-marker-follows-cell-p) (indentation-per-level nil indentation-per-level-p) (outline-table-column nil outline-table-column-p) ;; ns:ns-table-column &allow-other-keys) (when autoresizes-outline-column-p (#/setAutoresizesOutlineColumn: self autoresizes-outline-column)) (when autosave-expanded-items-p (#/setAutosaveExpandedItems: self autosave-expanded-items)) (when indentation-marker-follows-cell-p (#/setIndentationMarkerFollowsCell: self indentation-marker-follows-cell)) (when indentation-per-level-p (#/setIndentationPerLevel: self (cgfloat indentation-per-level))) (when outline-table-column-p (#/setOutlineTableColumn: self outline-table-column))) (defmethod initialize-instance :after ((self ns:ns-slider) &key (allows-tick-mark-values-only nil allows-tick-mark-values-only-p) (alt-increment-value 1 alt-increment-value-p) (image nil image-p) ;; ns:ns-image (max-value nil max-value-p) (min-value nil min-value-p) (number-of-tick-marks 0 number-of-tick-marks-p) ;; integer &allow-other-keys) ;; see control.lisp and view.lisp for other allowed keywords (when allows-tick-mark-values-only-p (#/setAllowsTickMarkValuesOnly: self allows-tick-mark-values-only)) (when (and alt-increment-value-p (numberp alt-increment-value)) (#/setAltIncrementValue: self (cgfloat alt-increment-value))) (when image-p (#/setImage: self image)) (when (and max-value-p (numberp max-value)) (#/setMaxValue: self (cgfloat max-value))) (when (and min-value-p (numberp min-value)) (#/setMinValue: self (cgfloat min-value))) (when (and number-of-tick-marks-p (numberp number-of-tick-marks)) (#/setNumberOfTickMarks: self (truncate number-of-tick-marks))) self) (defmethod initialize-instance :after ((self ns:ns-table-view) &key (columns nil columns-p) ;; list of ns:ns-table-columns (allows-column-reordering nil allows-column-reordering-p) (allows-column-resizing nil allows-column-resizing-p) (allows-column-selection nil allows-column-selection-p) (allows-empty-selection nil allows-empty-selection-p) (allows-multiple-selection nil allows-multiple-selection-p) (allows-type-select nil allows-type-select-p) (autosave-name nil autosave-name-p) ;; string or ns:ns-string (autosave-table-columns nil autosave-table-columns-p) (background-color nil background-color-p) ;; ns:ns-color or keyword acceptable to (coerce-obj <keyword> 'ns:ns-color) (column-autoresizing-style nil column-autoresizing-style-p) ;; number or keyword: see convert-table-col-resizing (corner-view nil corner-view-p) ;; ns:ns-view (data-source nil data-source-p) ;; ns:ns-object which conforms to NSTableViewDataSource protocol (delegate nil delegate-p) ;; ns:ns-object which conforms to NSTableViewDelegate protocol (double-action nil double-action-p) ;; string (dragging-destination-feedback-style nil dragging-destination-feedback-style-p) ;; number or :none :regular :source-list (dragging-source-operation-mask nil dragging-source-operation-mask-p) ;; number or keyword: see convert-table-drag-src-op (floats-group-rows nil floats-group-rows-p) (grid-color nil grid-color-p) ;; ns:ns-color or keyword acceptable to (coerce-obj <keyword> 'ns:ns-color) (grid-style-mask nil grid-style-mask-p) ;; number or keyword or list of keywords: see convert-grid-style (header-view nil header-view-p) ;; ns:ns-table-header-view (intercell-spacing nil intercell-spacing-p) ;; ns:ns-size or list: (width height) (row-height nil row-height-p) ;; number (row-size-style nil row-size-style-p) ;; number or keyword: see convert-row-size-style (selection-highlight-style nil selection-highlight-style-p) ;; number or keyword: see convert-selection-highlight-style (sort-descriptors nil sort-descriptors-p) ;; list, 1D array, or ns:ns-array of ns:ns-sort-descriptor objects (uses-alternating-row-background-colors nil uses-alternating-row-background-colors-p) (vertical-motion-can-begin-drag nil vertical-motion-can-begin-drag-p) &allow-other-keys) (when columns-p ;; must do this first because other parameters only affect columns that already exist (dolist (col columns) (#/addTableColumn: self col))) (when allows-column-reordering-p (#/setAllowsColumnReordering: self allows-column-reordering)) (when allows-column-resizing-p (#/setAllowsColumnResizing: self allows-column-resizing)) (when allows-column-selection-p (#/setAllowsColumnSelection: self allows-column-selection)) (when allows-empty-selection-p (#/setAllowsEmptySelection: self allows-empty-selection)) (when allows-multiple-selection-p (#/setAllowsMultipleSelection: self allows-multiple-selection)) (when allows-type-select-p (#/setAllowsTypeSelect: self allows-type-select)) (when autosave-name-p (#/setAutosaveName: self (coerce-obj autosave-name 'ns:ns-string))) (when autosave-table-columns-p (#/setAutosaveTableColumns: self autosave-table-columns)) (when background-color-p (#/setBackgroundColor: self (coerce-obj background-color 'ns:ns-color))) (when column-autoresizing-style-p (#/setColumnAutoresizingStyle: self (convert-table-col-resizing column-autoresizing-style))) (when corner-view-p (#/setCornerView: self corner-view)) (when data-source-p (#/setDataSource: self data-source)) (when delegate-p (#/setDelegate: self delegate)) (when double-action-p (#/setDoubleAction: self (get-selector double-action))) (when dragging-destination-feedback-style-p (#/setDraggingDestinationFeedbackStyle: self (convert-table-drag-feedback-style dragging-destination-feedback-style))) (when dragging-source-operation-mask-p (#/setDraggingSourceOperationMask:forLocal: self (convert-table-drag-src-op dragging-source-operation-mask) t)) (when floats-group-rows-p (#/setFloatsGroupRows: self floats-group-rows)) (when grid-color-p (#/setGridColor: self (coerce-obj grid-color 'ns:ns-color))) (when grid-style-mask-p (#/setGridStyleMask: self (convert-grid-styles grid-style-mask))) (when header-view-p (#/setHeaderView: self header-view)) (when intercell-spacing-p (#/setIntercellSpacing: self (coerce-obj intercell-spacing 'ns:ns-size))) (when row-height-p (#/setRowHeight: self (cgfloat row-height))) (when row-size-style-p (#/setRowSizeStyle: self (convert-row-size-style row-size-style))) (when selection-highlight-style-p (#/setSelectionHighlightStyle: self (convert-selection-highlight-style selection-highlight-style))) (when sort-descriptors-p (#/setSortDescriptors: self (coerce-obj sort-descriptors 'ns:ns-array))) (when uses-alternating-row-background-colors-p (#/setUsesAlternatingRowBackgroundColors: self uses-alternating-row-background-colors)) (when vertical-motion-can-begin-drag-p (#/setVerticalMotionCanBeginDrag: self vertical-motion-can-begin-drag))) (defmethod initialize-instance :after ((self ns:ns-text-field) &key (bezeled nil bezeled-p) (bezel-style nil bezel-style-p) ;; number or keyword: see values in convert-text-bezel-style above (bordered nil bordered-p) (delegate nil delegate-p) ;; ns:ns-object (draws-background nil draws-background-p) (editable nil editable-p) (imports-graphics nil imports-graphics-p) (preferred-max-layout-width nil preferred-max-layout-width-p) (selectable nil selectable-p) (text-color nil text-color-p) ;; ns:ns-color or keyword acceptable to (coerce-obj <keyword> 'ns:ns-color) &allow-other-keys) ;; see control.lisp and view.lisp for other allowed keywords (when bezeled-p (#/setBezeled: self bezeled)) (when bezel-style-p (#/setBezelStyle: self (convert-text-bezel-style bezel-style))) (when bordered-p (#/setBordered: self bordered)) (when delegate-p (#/setDelegate: self delegate)) (when draws-background-p (#/setDrawsBackground: self draws-background)) (when editable-p (#/setEditable: self editable)) (when imports-graphics-p (#/setImportsGraphics: self imports-graphics)) (when preferred-max-layout-width-p (#/setPreferredMaxLayoutWidth: self preferred-max-layout-width)) (when selectable-p (#/setSelectable: self selectable)) (when text-color-p (#/setTextColor: self (coerce-obj text-color 'ns:ns-color)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; ns-window subclasses (defmethod initialize-instance :after ((self ns:ns-panel) &key (floating-panel nil floating-panel-p) (works-when-modal nil works-when-modal-p) &allow-other-keys) ;; see window.lisp for other allowed keywords (when floating-panel-p (#/setFloatingPanel: self floating-panel)) (when works-when-modal-p (#/setWorksWhenModal: self works-when-modal))) (defmethod initialize-instance :after ((self ns:ns-save-panel) &key (accessory-view nil accessory-view-p) ;; ns-view object (allowed-file-types (%null-ptr)) ;; list of strings of allowed file types (allows-other-file-types nil allows-other-file-types-p) (can-create-directories nil can-create-directories-p) (can-select-hidden-extension nil can-select-hidden-extension-p) (delegate nil delegate-p) ;; NSOpenSavePanelDelegate object (directory-url nil directory-url-p) ;; ns:ns-url (extension-hidden nil extension-hidden-p) (message nil message-p) (name-field-label nil name-field-label-p) (name-field-string-value nil name-field-string-value-p) (prompt nil prompt-p) (shows-hidden-files nil shows-hidden-files-p) ;;(shows-tag-field nil shows-tag-field-p) ;;(tag-names nil tag-names-p) ;; list of strings (title nil title-p) ;; string (treats-file-packages-as-directories nil treats-file-packages-as-directories-p) &allow-other-keys) ;; see window.lisp for other allowed keywords (when accessory-view-p (#/setAccessoryView: self accessory-view)) (#/setAllowedFileTypes: self (if allowed-file-types (coerce-obj allowed-file-types 'ns:ns-array) (%null-ptr))) (when allows-other-file-types-p (#/setAllowsOtherFileTypes: self allows-other-file-types)) (when can-create-directories-p (#/setCanCreateDirectories: self can-create-directories)) (when can-select-hidden-extension-p (#/setCanSelectHiddenExtension: self can-select-hidden-extension)) (when delegate-p (#/setDelegate: self delegate)) (when directory-url-p (#/setDirectoryURL: self directory-url)) (when extension-hidden-p (#/setExtensionHidden: self extension-hidden)) (when message-p (#/setMessage: self (coerce-obj message 'ns:ns-string))) (when name-field-label-p (#/setNameFieldLabel: self (coerce-obj name-field-label 'ns:ns-string))) (when name-field-string-value-p (#/setNameFieldStringValue: self (coerce-obj name-field-string-value 'ns:ns-string))) (when prompt-p (#/setPrompt: self (coerce-obj prompt 'ns:ns-string))) (when shows-hidden-files-p (#/setShowsHiddenFiles: self shows-hidden-files)) ;;(when shows-tag-field-p ;; (#/setShowsTagField: self shows-tag-field)) ;;(when tag-names-p ;; (#/setTagNames: self (coerce-obj tag-names 'ns:ns-array))) (when title-p (#/setTitle: self (coerce-obj title 'ns:ns-string))) (when treats-file-packages-as-directories-p (#/setTreatsFilePackagesAsDirectories: self treats-file-packages-as-directories))) ;;; NOTE: you should not create an ns-open-panel using make-instance. Instead use make-open-panel ;;; loaded from open-panel.lisp. That will avoid getting a rash of CG trace messages logged to the ;;; system log (I found this the hard way). Retaining an ns-open-panel in any fashion will cause ;;; the log messages. (defmethod initialize-instance :after ((self ns:ns-open-panel) &key (allows-multiple-selection nil allows-multiple-selection-p) (can-choose-directories nil can-choose-directories-p) (can-choose-files nil can-choose-files-p) (resolves-aliases nil resolves-aliases-p) &allow-other-keys) (when allows-multiple-selection-p (#/setAllowsMultipleSelection: self allows-multiple-selection)) (when can-choose-directories-p (#/setCanChooseDirectories: self can-choose-directories)) (when can-choose-files-p (#/setCanChooseFiles: self can-choose-files)) (when resolves-aliases-p (#/setResolvesAliases: self resolves-aliases))) (provide :objc-initialize)
[ { "context": "ense. See the file books/3BSD-mod.txt.\n;\n; Author: Eric Smith ([email protected])\n\n;;;;;;;;;;;;;;;;;;;;;;;", "end": 177, "score": 0.9995275735855103, "start": 167, "tag": "NAME", "value": "Eric Smith" }, { "context": " file books/3BSD-mod.txt.\n;\n; Author: Eric Smith ([email protected])\n\n;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;", "end": 201, "score": 0.9999296069145203, "start": 179, "tag": "EMAIL", "value": "[email protected]" } ]
books/kestrel/utilities/file-existsp.lisp
mayankmanj/acl2
305
; A tool to tell whether a file exists ; ; Copyright (C) 2015-2021 Kestrel Institute ; ; License: A 3-clause BSD license. See the file books/3BSD-mod.txt. ; ; Author: Eric Smith ([email protected]) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (in-package "ACL2") ;; Returns (mv existsp state). Other options for doing this would include ;; making a system call (slow because it forks the ACL2 process), calling ;; oslib::regular-file-p, or calling oslib::path-exists-p. This seems to also ;; work for relative paths, but I am not sure what they are relative to (seems ;; to not be the CBD, perhaps it's the directory in which ACL2 was started). ;; This calls file-write-date$ and so assumes that a file has a write date if ;; and only if it exists. (defund file-existsp (absolute-path state) (declare (xargs :stobjs state :guard (stringp absolute-path))) (mv-let (file-date state) (file-write-date$ absolute-path state) (mv (if file-date t nil) state)))
72837
; A tool to tell whether a file exists ; ; Copyright (C) 2015-2021 Kestrel Institute ; ; License: A 3-clause BSD license. See the file books/3BSD-mod.txt. ; ; Author: <NAME> (<EMAIL>) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (in-package "ACL2") ;; Returns (mv existsp state). Other options for doing this would include ;; making a system call (slow because it forks the ACL2 process), calling ;; oslib::regular-file-p, or calling oslib::path-exists-p. This seems to also ;; work for relative paths, but I am not sure what they are relative to (seems ;; to not be the CBD, perhaps it's the directory in which ACL2 was started). ;; This calls file-write-date$ and so assumes that a file has a write date if ;; and only if it exists. (defund file-existsp (absolute-path state) (declare (xargs :stobjs state :guard (stringp absolute-path))) (mv-let (file-date state) (file-write-date$ absolute-path state) (mv (if file-date t nil) state)))
true
; A tool to tell whether a file exists ; ; Copyright (C) 2015-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 "ACL2") ;; Returns (mv existsp state). Other options for doing this would include ;; making a system call (slow because it forks the ACL2 process), calling ;; oslib::regular-file-p, or calling oslib::path-exists-p. This seems to also ;; work for relative paths, but I am not sure what they are relative to (seems ;; to not be the CBD, perhaps it's the directory in which ACL2 was started). ;; This calls file-write-date$ and so assumes that a file has a write date if ;; and only if it exists. (defund file-existsp (absolute-path state) (declare (xargs :stobjs state :guard (stringp absolute-path))) (mv-let (file-date state) (file-write-date$ absolute-path state) (mv (if file-date t nil) state)))
[ { "context": "onway's Game of Life in Common Lisp. \"\n :author \"Andreas Ruscheinski <[email protected]>\"\n :license ", "end": 195, "score": 0.9998960494995117, "start": 176, "tag": "NAME", "value": "Andreas Ruscheinski" }, { "context": "in Common Lisp. \"\n :author \"Andreas Ruscheinski <[email protected]>\"\n :license \"MIT\"\n :version \"0.0.1\"\n :serial ", "end": 231, "score": 0.999932050704956, "start": 197, "tag": "EMAIL", "value": "[email protected]" }, { "context": "lementation of Conway's Game of Life.\"\n :author \"Andreas Ruscheinski <[email protected]>\"\n :license ", "end": 627, "score": 0.9999009370803833, "start": 608, "tag": "NAME", "value": "Andreas Ruscheinski" }, { "context": "'s Game of Life.\"\n :author \"Andreas Ruscheinski <[email protected]>\"\n :license \"MIT\"\n :version \"0.0.1\"\n :serial ", "end": 663, "score": 0.9999330639839172, "start": 629, "tag": "EMAIL", "value": "[email protected]" }, { "context": " Game of Life using oldschool opengl.\"\n :author \"Andreas Ruscheinski <[email protected]>\"\n :license ", "end": 974, "score": 0.999900221824646, "start": 955, "tag": "NAME", "value": "Andreas Ruscheinski" }, { "context": "ldschool opengl.\"\n :author \"Andreas Ruscheinski <[email protected]>\"\n :license \"MIT\"\n :version \"0.0.1\"\n :serial ", "end": 1010, "score": 0.999931812286377, "start": 976, "tag": "EMAIL", "value": "[email protected]" }, { "context": "der Conway's Game of Life using SDL2.\"\n :author \"Andreas Ruscheinski <[email protected]>\"\n :license ", "end": 1386, "score": 0.9998988509178162, "start": 1367, "tag": "NAME", "value": "Andreas Ruscheinski" }, { "context": "Life using SDL2.\"\n :author \"Andreas Ruscheinski <[email protected]>\"\n :license \"MIT\"\n :version \"0.0.1\"\n :serial ", "end": 1422, "score": 0.9999327063560486, "start": 1388, "tag": "EMAIL", "value": "[email protected]" }, { "context": "r Conway's Game of Life using sketch.\"\n :author \"Andreas Ruscheinski <[email protected]>\"\n :license ", "end": 1804, "score": 0.9998878240585327, "start": 1785, "tag": "NAME", "value": "Andreas Ruscheinski" }, { "context": "fe using sketch.\"\n :author \"Andreas Ruscheinski <[email protected]>\"\n :license \"MIT\"\n :version \"0.0.1\"\n :serial ", "end": 1840, "score": 0.9999249577522278, "start": 1806, "tag": "EMAIL", "value": "[email protected]" } ]
gol-render-demos.asd
aruscher/gol-render-demos
0
;;;; gol-render-demos.asd (asdf:defsystem #:gol-render-demos :description "A collection of different approaches to render Conway's Game of Life in Common Lisp. " :author "Andreas Ruscheinski <[email protected]>" :license "MIT" :version "0.0.1" :serial t :pathname "" :depends-on ("gol-render-demos/game" "gol-render-demos/oldschool-opengl" "gol-render-demos/sdl2kit" "gol-render-demos/sketch") :components ()) (asdf:defsystem #:gol-render-demos/game :description "A basic implementation of Conway's Game of Life." :author "Andreas Ruscheinski <[email protected]>" :license "MIT" :version "0.0.1" :serial t :pathname "game/" :components ((:file "package") (:file "game"))) (asdf:defsystem #:gol-render-demos/oldschool-opengl :description "An implementation to render Conway's Game of Life using oldschool opengl." :author "Andreas Ruscheinski <[email protected]>" :license "MIT" :version "0.0.1" :serial t :pathname "oldschool-opengl/" :depends-on ("sdl2kit" "cl-opengl" "gol-render-demos/game") :components ((:file "package") (:file "oldschool-opengl"))) (asdf:defsystem #:gol-render-demos/sdl2kit :description "An implementation to render Conway's Game of Life using SDL2." :author "Andreas Ruscheinski <[email protected]>" :license "MIT" :version "0.0.1" :serial t :pathname "sdl2kit/" :depends-on ("sdl2kit" "gol-render-demos/game") :components ((:file "package") (:file "2d-window") (:file "sdl2kit"))) (asdf:defsystem #:gol-render-demos/sketch :description "An implementation to render Conway's Game of Life using sketch." :author "Andreas Ruscheinski <[email protected]>" :license "MIT" :version "0.0.1" :serial t :pathname "sketch/" :depends-on ("sketch" "gol-render-demos/game") :components ((:file "package") (:file "sketch")))
24606
;;;; gol-render-demos.asd (asdf:defsystem #:gol-render-demos :description "A collection of different approaches to render Conway's Game of Life in Common Lisp. " :author "<NAME> <<EMAIL>>" :license "MIT" :version "0.0.1" :serial t :pathname "" :depends-on ("gol-render-demos/game" "gol-render-demos/oldschool-opengl" "gol-render-demos/sdl2kit" "gol-render-demos/sketch") :components ()) (asdf:defsystem #:gol-render-demos/game :description "A basic implementation of Conway's Game of Life." :author "<NAME> <<EMAIL>>" :license "MIT" :version "0.0.1" :serial t :pathname "game/" :components ((:file "package") (:file "game"))) (asdf:defsystem #:gol-render-demos/oldschool-opengl :description "An implementation to render Conway's Game of Life using oldschool opengl." :author "<NAME> <<EMAIL>>" :license "MIT" :version "0.0.1" :serial t :pathname "oldschool-opengl/" :depends-on ("sdl2kit" "cl-opengl" "gol-render-demos/game") :components ((:file "package") (:file "oldschool-opengl"))) (asdf:defsystem #:gol-render-demos/sdl2kit :description "An implementation to render Conway's Game of Life using SDL2." :author "<NAME> <<EMAIL>>" :license "MIT" :version "0.0.1" :serial t :pathname "sdl2kit/" :depends-on ("sdl2kit" "gol-render-demos/game") :components ((:file "package") (:file "2d-window") (:file "sdl2kit"))) (asdf:defsystem #:gol-render-demos/sketch :description "An implementation to render Conway's Game of Life using sketch." :author "<NAME> <<EMAIL>>" :license "MIT" :version "0.0.1" :serial t :pathname "sketch/" :depends-on ("sketch" "gol-render-demos/game") :components ((:file "package") (:file "sketch")))
true
;;;; gol-render-demos.asd (asdf:defsystem #:gol-render-demos :description "A collection of different approaches to render Conway's Game of Life in Common Lisp. " :author "PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>" :license "MIT" :version "0.0.1" :serial t :pathname "" :depends-on ("gol-render-demos/game" "gol-render-demos/oldschool-opengl" "gol-render-demos/sdl2kit" "gol-render-demos/sketch") :components ()) (asdf:defsystem #:gol-render-demos/game :description "A basic implementation of Conway's Game of Life." :author "PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>" :license "MIT" :version "0.0.1" :serial t :pathname "game/" :components ((:file "package") (:file "game"))) (asdf:defsystem #:gol-render-demos/oldschool-opengl :description "An implementation to render Conway's Game of Life using oldschool opengl." :author "PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>" :license "MIT" :version "0.0.1" :serial t :pathname "oldschool-opengl/" :depends-on ("sdl2kit" "cl-opengl" "gol-render-demos/game") :components ((:file "package") (:file "oldschool-opengl"))) (asdf:defsystem #:gol-render-demos/sdl2kit :description "An implementation to render Conway's Game of Life using SDL2." :author "PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>" :license "MIT" :version "0.0.1" :serial t :pathname "sdl2kit/" :depends-on ("sdl2kit" "gol-render-demos/game") :components ((:file "package") (:file "2d-window") (:file "sdl2kit"))) (asdf:defsystem #:gol-render-demos/sketch :description "An implementation to render Conway's Game of Life using sketch." :author "PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>" :license "MIT" :version "0.0.1" :serial t :pathname "sketch/" :depends-on ("sketch" "gol-render-demos/game") :components ((:file "package") (:file "sketch")))
[ { "context": "he LICENSE file distributed with ACL2.\n;\n; Author: Eric McCarthy ([email protected])\n\n;;;;;;;;;;;;;;;;;;;;;;;;;", "end": 206, "score": 0.9997506141662598, "start": 193, "tag": "NAME", "value": "Eric McCarthy" }, { "context": "distributed with ACL2.\n;\n; Author: Eric McCarthy ([email protected])\n\n;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;", "end": 228, "score": 0.9999327063560486, "start": 208, "tag": "EMAIL", "value": "[email protected]" }, { "context": "ssage, expected k, expected signature)\n;;; (0x1, \"Satoshi Nakamoto\", 0x8F8A276C19F4149656B280621E358CCE24F5F52542772", "end": 3823, "score": 0.9997172951698303, "start": 3807, "tag": "NAME", "value": "Satoshi Nakamoto" }, { "context": "d9e5\"),\n(defconst *test-1-1*\n (list #x1\n \"Satoshi Nakamoto\"\n #x8F8A276C19F4149656B280621E358CCE24F5F5", "end": 4085, "score": 0.9994750618934631, "start": 4069, "tag": "NAME", "value": "Satoshi Nakamoto" }, { "context": " in time, like tears in rain. Time to die...\", 0x38AA22D72376B4DBC472E06C3BA403EE0A394DA63FC58D88686C611ABA98D6B3, \"8600dbd41e348fe5c9465ab92d23", "end": 4498, "score": 0.8524466156959534, "start": 4454, "tag": "KEY", "value": "8AA22D72376B4DBC472E06C3BA403EE0A394DA63FC58" }, { "context": ", 0x38AA22D72376B4DBC472E06C3BA403EE0A394DA63FC58D88686C611ABA98D6B3, \"8600dbd41e348fe5c9465ab92d23e3db8b98b873", "end": 4510, "score": 0.821416974067688, "start": 4499, "tag": "KEY", "value": "88686C611AB" }, { "context": "472E06C3BA403EE0A394DA63FC58D88686C611ABA98D6B3, \"8600dbd41e348fe5c9465ab92d23e3db8b98b873beecd930736488696438cb6b547fe64427496db33bf66019dacbf0039c04199abb0122918601db38a72cfc21\"),\n(defconst *test-1-2*\n (list #x1\n \"All ", "end": 4648, "score": 0.9997172355651855, "start": 4520, "tag": "KEY", "value": "8600dbd41e348fe5c9465ab92d23e3db8b98b873beecd930736488696438cb6b547fe64427496db33bf66019dacbf0039c04199abb0122918601db38a72cfc21" }, { "context": "3BA403EE0A394DA63FC58D88686C611ABA98D6B3\n \"8600dbd41e348fe5c9465ab92d23e3db8b98b873beecd930736488696438cb6b547fe64427496db33bf66019dacbf0039c04199abb0122918601db38a72cfc21\"))\n\n;;; (private key, message, expected k, expect", "end": 4982, "score": 0.9997201561927795, "start": 4854, "tag": "KEY", "value": "8600dbd41e348fe5c9465ab92d23e3db8b98b873beecd930736488696438cb6b547fe64427496db33bf66019dacbf0039c04199abb0122918601db38a72cfc21" }, { "context": "FFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364140, \"Satoshi Nakamoto\", 0x33A19B60E25FB6F4435AF53A3D42D493644827367E645", "end": 5136, "score": 0.8034446835517883, "start": 5120, "tag": "NAME", "value": "Satoshi Nakamoto" }, { "context": "FFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364140\n \"Satoshi Nakamoto\"\n #x33A19B60E25FB6F4435AF53A3D42D493644827", "end": 5461, "score": 0.9996584057807922, "start": 5445, "tag": "NAME", "value": "Satoshi Nakamoto" }, { "context": "ey, message, expected k, expected signature)\n;;; (0xf8b8af8ce3c7cca5e300d33939540c10d45ce001b8f252bfbc57ba0342904181, \"Alan Turing\", 0x525A82B70E67874398067543FD84C83", "end": 5810, "score": 0.9843369126319885, "start": 5744, "tag": "KEY", "value": "0xf8b8af8ce3c7cca5e300d33939540c10d45ce001b8f252bfbc57ba0342904181" }, { "context": "n Turing\", 0x525A82B70E67874398067543FD84C83D30C175FDC45FDEEE082FE13B1D7CFDF1, \"7063ae83e7f62bbb17179", "end": 5867, "score": 0.995984673500061, "start": 5866, "tag": "KEY", "value": "5" }, { "context": "8067543FD84C83D30C175FDC45FDEEE082FE13B1D7CFDF1, \"7063ae83e7f62bbb171798131b4a0564b956930092b33b07b395615d9ec7e15c58dfcc1e00a35e1572f366ffe34ba0fc47db1e7189759b9fb233c5b05ab388ea\"),\n(defconst *test-1-4*\n (list #xf8b8af8ce3c7cca", "end": 6024, "score": 0.999663233757019, "start": 5896, "tag": "KEY", "value": "7063ae83e7f62bbb171798131b4a0564b956930092b33b07b395615d9ec7e15c58dfcc1e00a35e1572f366ffe34ba0fc47db1e7189759b9fb233c5b05ab388ea" }, { "context": "b233c5b05ab388ea\"),\n(defconst *test-1-4*\n (list #xf8b8af8ce3c7cca5e300d33939540c10d45ce001b8f252bfbc57ba0342904181\n \"Alan Turing\"\n #x525A82B70E6787439", "end": 6123, "score": 0.9245147109031677, "start": 6058, "tag": "KEY", "value": "xf8b8af8ce3c7cca5e300d33939540c10d45ce001b8f252bfbc57ba0342904181" }, { "context": "39540c10d45ce001b8f252bfbc57ba0342904181\n \"Alan Turing\"\n #x525A82B70E67874398067543FD84C83D30C175", "end": 6144, "score": 0.9996820688247681, "start": 6133, "tag": "NAME", "value": "Alan Turing" }, { "context": "bc57ba0342904181\n \"Alan Turing\"\n #x525A82B70E67874398067543FD84C83D30C175FDC45FDEEE082FE13B1D7CFDF1\n \"7063ae83e7f62bbb171798131b4a0564b9569", "end": 6217, "score": 0.6115447878837585, "start": 6157, "tag": "KEY", "value": "25A82B70E67874398067543FD84C83D30C175FDC45FDEEE082FE13B1D7CF" }, { "context": "FD84C83D30C175FDC45FDEEE082FE13B1D7CFDF1\n \"7063ae83e7f62bbb171798131b4a0564b956930092b33b07b395615d9ec7e15c58dfcc1e00a35e1572f366ffe34ba0fc47db1e7189759b9fb233c5b05ab388ea\"))\n\n;;; (private key, message, expected k, expect", "end": 6358, "score": 0.9997069835662842, "start": 6230, "tag": "KEY", "value": "7063ae83e7f62bbb171798131b4a0564b956930092b33b07b395615d9ec7e15c58dfcc1e00a35e1572f366ffe34ba0fc47db1e7189759b9fb233c5b05ab388ea" }, { "context": "ey, message, expected k, expected signature)\n;;; (0xe91671c46231f833a6406ccbea0e3e392c76c167bac1cb013f6f1013980455c2, \"There is a computer disease that anybody who wo", "end": 6493, "score": 0.9910796284675598, "start": 6427, "tag": "KEY", "value": "0xe91671c46231f833a6406ccbea0e3e392c76c167bac1cb013f6f1013980455c2" }, { "context": "233F2521BE018D9318639D5B8BBD6374A8A59232D16AD3D, \"b552edd27580141f3b2a5463048cb7cd3e047b97c9f98076c32dbdf85a68718b279fa72dd19bfae05577e06c7c0c1900c371fcd5893f7e1d56a37d30174671f6\")\n(defconst *test-1-5*\n (list #xe91671c46231f833", "end": 6903, "score": 0.9995530843734741, "start": 6775, "tag": "KEY", "value": "b552edd27580141f3b2a5463048cb7cd3e047b97c9f98076c32dbdf85a68718b279fa72dd19bfae05577e06c7c0c1900c371fcd5893f7e1d56a37d30174671f6" }, { "context": "1BE018D9318639D5B8BBD6374A8A59232D16AD3D\n \"b552edd27580141f3b2a5463048cb7cd3e047b97c9f98076c32dbdf85a68718b279fa72dd19bfae05577e06c7c0c1900c371fcd5893f7e1d56a37d30174671f6\"))\n\n\n;;; ----------------------------------------", "end": 7432, "score": 0.9995282888412476, "start": 7304, "tag": "KEY", "value": "b552edd27580141f3b2a5463048cb7cd3e047b97c9f98076c32dbdf85a68718b279fa72dd19bfae05577e06c7c0c1900c371fcd5893f7e1d56a37d30174671f6" }, { "context": "hp?topic=285142.msg3300992#msg3300992\nSubmitted by plaprade and double-checked by fpgaminer.\n\nplaprade states", "end": 9171, "score": 0.9769269824028015, "start": 9163, "tag": "USERNAME", "value": "plaprade" }, { "context": "300992\nSubmitted by plaprade and double-checked by fpgaminer.\n\nplaprade states:\n\"The test vectors are fully ca", "end": 9203, "score": 0.9996011257171631, "start": 9194, "tag": "USERNAME", "value": "fpgaminer" }, { "context": "8ab58c74f27c41a7fdb5696ad4e6108c96f807982866f785d3f6418d24163ddae117b7db4d5fdf0071de069fa54342262\"\n \"3044022033a69cd2065432a30f3d1ce4eb0d59b8a", "end": 10036, "score": 0.9825617074966431, "start": 9989, "tag": "KEY", "value": "f6418d24163ddae117b7db4d5fdf0071de069fa54342262" }, { "context": "24163ddae117b7db4d5fdf0071de069fa54342262\"\n \"3044022033a69cd2065432a30f3d1ce4eb0d59b8ab58c74f27c41a7fdb5696ad4e6108c902206f807982866f785d3f6418d24163ddae117b7db4d5fdf0071de069fa54342262\"\n )\n ( \"fffffffffffffffffffffffffffffffebaa", "end": 10185, "score": 0.9775611758232117, "start": 10045, "tag": "KEY", "value": "3044022033a69cd2065432a30f3d1ce4eb0d59b8ab58c74f27c41a7fdb5696ad4e6108c902206f807982866f785d3f6418d24163ddae117b7db4d5fdf0071de069fa54342262" }, { "context": "ffffffffebaaedce6af48a03bbfd25e8cd0364140\"\n \"L5oLkpV3aqBjhki6LmvChTCV6odsp4SXM6FfU2Gppt5kFLaHLuZ9\"\n \"Equations are more important to me, becau", "end": 10325, "score": 0.9889547824859619, "start": 10273, "tag": "KEY", "value": "L5oLkpV3aqBjhki6LmvChTCV6odsp4SXM6FfU2Gppt5kFLaHLuZ9" }, { "context": "ut an equation is something for eternity.\"\n \"54c4a33c6423d689378f160a7ff8b61330444abb58fb470f96ea16d99d4a2fed07082304410efa6b2943111b6a4e0aaa7b7db55a07e9861d1fb3cb1f421044a5\"\n \"3044022054c4a33c6423d689378f160a7ff8b6133", "end": 10586, "score": 0.9986222982406616, "start": 10458, "tag": "KEY", "value": "54c4a33c6423d689378f160a7ff8b61330444abb58fb470f96ea16d99d4a2fed07082304410efa6b2943111b6a4e0aaa7b7db55a07e9861d1fb3cb1f421044a5" }, { "context": "b6a4e0aaa7b7db55a07e9861d1fb3cb1f421044a5\"\n \"3044022054c4a33c6423d689378f160a7ff8b61330444abb58fb470f96ea16d99d4a2fed022007082304410efa6b2943111b6a4e0aaa7b7db55a07e9861d1fb3cb1f421044a5\"\n )\n ( \"fffffffffffffffffffffffffffffff", "end": 10731, "score": 0.9984862804412842, "start": 10595, "tag": "KEY", "value": "3044022054c4a33c6423d689378f160a7ff8b61330444abb58fb470f96ea16d99d4a2fed022007082304410efa6b2943111b6a4e0aaa7b7db55a07e9861d1fb3cb1f4210" }, { "context": "ress.\"\n \"c0dafec8251f1d5010289d210232220b03202cba34ec11fec58b3e93a85b91d375afdc06b7d6322a590955bf264e7aaa155847f614d80078a90292fe205064d3\"\n \"3045022100c0dafec8251f1d5010289d210232220", "end": 11628, "score": 0.9988577365875244, "start": 11536, "tag": "KEY", "value": "2cba34ec11fec58b3e93a85b91d375afdc06b7d6322a590955bf264e7aaa155847f614d80078a90292fe205064d3" }, { "context": "f264e7aaa155847f614d80078a90292fe205064d3\"\n \"3045022100c0dafec8251f1d5010289d210232220b03202cba34ec11fec58b3e93a85b91d3022075afdc06b7d6322a590955bf264e7aaa155847f614d80078a90292fe205064d3\"\n )\n ( \"69ec59eaa1f4f2e36b639716b7c30ca86d9", "end": 11779, "score": 0.9990884065628052, "start": 11637, "tag": "KEY", "value": "3045022100c0dafec8251f1d5010289d210232220b03202cba34ec11fec58b3e93a85b91d3022075afdc06b7d6322a590955bf264e7aaa155847f614d80078a90292fe205064d3" }, { "context": "aaa155847f614d80078a90292fe205064d3\"\n )\n ( \"69ec59eaa1f4f2e36b639716b7c30ca86d9a5375c7b38d8918bd9c0ebc80ba64\"\n \"KzmcSTRmg8Gtoq8jbBCwsrvgiTKRrewQXniAHHTf7", "end": 11858, "score": 0.9996185898780823, "start": 11794, "tag": "KEY", "value": "69ec59eaa1f4f2e36b639716b7c30ca86d9a5375c7b38d8918bd9c0ebc80ba64" }, { "context": "6b7c30ca86d9a5375c7b38d8918bd9c0ebc80ba64\"\n \"KzmcSTRmg8Gtoq8jbBCwsrvgiTKRrewQXniAHHTf7hsten8MZmBB\"\n \"Computer science is no more about compute", "end": 11919, "score": 0.9103571176528931, "start": 11867, "tag": "KEY", "value": "KzmcSTRmg8Gtoq8jbBCwsrvgiTKRrewQXniAHHTf7hsten8MZmBB" }, { "context": "uters than astronomy is about telescopes.\"\n \"7186363571d65e084e7f02b0b77c3ec44fb1b257dee26274c38c928986fea45d0de0b38e06807e46bda1f1e293f4f6323e854c86d58abdd00c46c16441085df6\"\n \"304402207186363571d65e084e7f02b0b77c3ec44", "end": 12144, "score": 0.9972529411315918, "start": 12016, "tag": "KEY", "value": "7186363571d65e084e7f02b0b77c3ec44fb1b257dee26274c38c928986fea45d0de0b38e06807e46bda1f1e293f4f6323e854c86d58abdd00c46c16441085df6" }, { "context": "293f4f6323e854c86d58abdd00c46c16441085df6\"\n \"304402207186363571d65e084e7f02b0b77c3ec44fb1b257dee26274c38c928986fea45d02200de0b38e06807e46bda1f1e293f4f6323e854c86d58abdd00c46c16441085df6\"\n )\n ( \"00000000000000000000000000007246174", "end": 12293, "score": 0.9753265380859375, "start": 12153, "tag": "KEY", "value": "304402207186363571d65e084e7f02b0b77c3ec44fb1b257dee26274c38c928986fea45d02200de0b38e06807e46bda1f1e293f4f6323e854c86d58abdd00c46c16441085df6" }, { "context": "0007246174ab1e92e9149c6e446fe194d072637\"\n \"KwDiBf89QgGbjEhKnhXJwe1E2mCa8asowBrSKuCaBV6EsPYEAFZ8\"\n", "end": 12385, "score": 0.55318284034729, "start": 12383, "tag": "KEY", "value": "Di" }, { "context": "246174ab1e92e9149c6e446fe194d072637\"\n \"KwDiBf89QgGbjEhKnhXJwe1E2mCa8asowBrSKuCaBV6EsPYEAFZ8\"\n ", "end": 12389, "score": 0.6700030565261841, "start": 12387, "tag": "KEY", "value": "89" }, { "context": "b1e92e9149c6e446fe194d072637\"\n \"KwDiBf89QgGbjEhKnhXJwe1E2mCa8asowBrSKuCaBV6EsPYEAFZ8\"\n \"...if", "end": 12397, "score": 0.5840325355529785, "start": 12394, "tag": "KEY", "value": "EhK" }, { "context": "e9149c6e446fe194d072637\"\n \"KwDiBf89QgGbjEhKnhXJwe1E2mCa8asowBrSKuCaBV6EsPYEAFZ8\"\n \"...if you ar", "end": 12404, "score": 0.6659602522850037, "start": 12399, "tag": "KEY", "value": "XJwe1" }, { "context": "6e446fe194d072637\"\n \"KwDiBf89QgGbjEhKnhXJwe1E2mCa8asowBrSKuCaBV6EsPYEAFZ8\"\n \"...if you aren", "end": 12406, "score": 0.8344910144805908, "start": 12405, "tag": "KEY", "value": "2" }, { "context": "6fe194d072637\"\n \"KwDiBf89QgGbjEhKnhXJwe1E2mCa8asowBrSKuCaBV6EsPYEAFZ8\"\n \"...if you aren't, ", "end": 12410, "score": 0.6917997598648071, "start": 12409, "tag": "KEY", "value": "8" }, { "context": "194d072637\"\n \"KwDiBf89QgGbjEhKnhXJwe1E2mCa8asowBrSKuCaBV6EsPYEAFZ8\"\n \"...if you aren't, at a", "end": 12414, "score": 0.591855525970459, "start": 12412, "tag": "KEY", "value": "ow" }, { "context": "072637\"\n \"KwDiBf89QgGbjEhKnhXJwe1E2mCa8asowBrSKuCaBV6EsPYEAFZ8\"\n \"...if you aren't, at any g", "end": 12418, "score": 0.5303732752799988, "start": 12416, "tag": "KEY", "value": "SK" }, { "context": "7\"\n \"KwDiBf89QgGbjEhKnhXJwe1E2mCa8asowBrSKuCaBV6EsPYEAFZ8\"\n \"...if you aren't, at any given time, sca", "end": 12432, "score": 0.670319676399231, "start": 12421, "tag": "KEY", "value": "BV6EsPYEAFZ" }, { "context": " you're not learning anywhere near enough\"\n \"fbfe5076a15860ba8ed00e75e9bd22e05d230f02a936b653eb55b61c99dda4870e68880ebb0050fe4312b1b1eb0899e1b82da89baa5b895f612619edf34cbd37\"\n \"3045022100fbfe5076a15860ba8ed00e75e9bd22e", "end": 12716, "score": 0.9887347221374512, "start": 12588, "tag": "KEY", "value": "fbfe5076a15860ba8ed00e75e9bd22e05d230f02a936b653eb55b61c99dda4870e68880ebb0050fe4312b1b1eb0899e1b82da89baa5b895f612619edf34cbd37" }, { "context": "1eb0899e1b82da89baa5b895f612619edf34cbd37\"\n \"3045022100fbfe5076a15860ba8ed00e75e9bd22e05d230f02a936b653eb55b61c99dda48702200e68880ebb0050fe4312b1b1eb0899e1b82da89baa5b895f612619edf34cbd37\"\n )\n ( \"00000000000000000000000000000000000", "end": 12867, "score": 0.9786572456359863, "start": 12725, "tag": "KEY", "value": "3045022100fbfe5076a15860ba8ed00e75e9bd22e05d230f02a936b653eb55b61c99dda48702200e68880ebb0050fe4312b1b1eb0899e1b82da89baa5b895f612619edf34cbd37" }, { "context": "0000000000000000000056916d0f9b31dc9b637f3\"\n \"KwDiBf89QgGbjEhKnhXJuH7LrciVrZiib5S9h4knkymNojPUVsWN\"\n \"The question of whether computers can thi", "end": 13007, "score": 0.7727352380752563, "start": 12955, "tag": "KEY", "value": "KwDiBf89QgGbjEhKnhXJuH7LrciVrZiib5S9h4knkymNojPUVsWN" }, { "context": " question of whether submarines can swim.\"\n \"cde1302d83f8dd835d89aef803c74a119f561fbaef3eb9129e45f30de86abbf906ce643f5049ee1f27890467b77a6a8e11ec4661cc38cd8badf90115fbd03cef\"\n \"3045022100cde1302d83f8dd835d89aef803c74a1", "end": 13249, "score": 0.6344069242477417, "start": 13121, "tag": "KEY", "value": "cde1302d83f8dd835d89aef803c74a119f561fbaef3eb9129e45f30de86abbf906ce643f5049ee1f27890467b77a6a8e11ec4661cc38cd8badf90115fbd03cef" }, { "context": "7b77a6a8e11ec4661cc38cd8badf90115fbd03cef\"\n \"3045022100cde1302d83f8dd835d89aef803c74a119f561fbaef3eb9129e45f30de86abbf9022006ce643f5049ee1f27890467b77a6a8e11ec4661cc38cd8badf90115fbd03cef\"\n )\n ))\n\n;; ", "end": 13367, "score": 0.6804088354110718, "start": 13258, "tag": "KEY", "value": "3045022100cde1302d83f8dd835d89aef803c74a119f561fbaef3eb9129e45f30de86abbf9022006ce643f5049ee1f27890467b77a6a8" }, { "context": "45f30de86abbf9022006ce643f5049ee1f27890467b77a6a8e11ec4661cc38cd8badf90115fbd03cef\"\n )\n ))\n\n;; Ori", "end": 13370, "score": 0.5543471574783325, "start": 13368, "tag": "KEY", "value": "11" }, { "context": "0de86abbf9022006ce643f5049ee1f27890467b77a6a8e11ec4661cc38cd8badf90115fbd03cef\"\n )\n ))\n\n;; Originally: \"(PrvKey HEX, PrvKey ", "end": 13400, "score": 0.5871938467025757, "start": 13372, "tag": "KEY", "value": "4661cc38cd8badf90115fbd03cef" } ]
books/kestrel/crypto/ecdsa/deterministic-ecdsa-secp256k1-tests.lisp
mayankmanj/acl2
305
; Tests of the RFC 6979 Deterministic ECDSA formalization. ; ; Copyright (C) 2019 Kestrel Institute ; ; License: A 3-clause BSD license. See the LICENSE file distributed with ACL2. ; ; Author: Eric McCarthy ([email protected]) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (in-package "ECDSA") (include-book "deterministic-ecdsa-secp256k1") (include-book "deterministic-ecdsa-exposing-k-secp256k1") (include-book "std/strings/hex" :dir :system) ; for str::strval16 (include-book "kestrel/utilities/strings/hexstrings" :dir :system) ; for hexstring=>ubyte8s (include-book "kestrel/utilities/bytes-as-digits" :dir :system) ; for bebytes=>nat ;;; ---------------------------------------------------------------- ;;; Test utilities (defun string=>bits (str) (bytes-to-bits (acl2::string=>nats str))) (defun r-s-string-to-r-s-list (r-s-string) (if (and (stringp r-s-string) (equal (length r-s-string) 128)) (list (str::strval16 (subseq r-s-string 0 64)) (str::strval16 (subseq r-s-string 64 128))) nil)) ;;; Test the routine that generates (r,s) given k. (defun test--ecdsa-sign-given-k--sha-256 (testcase) ;; testcase is (<private-key> <message> <expected-k> <expected-signature>) (b* (((mv error? & & r s) ;; an enhancement would be to test the returned x-index and y-even? too (ecdsa-sign-given-k (acl2::bytes-to-bits (sha2::sha-256-bytes (acl2::string=>nats (second testcase)))) (first testcase) (third testcase))) ;; adjust tests now that ECDSA-SIGN-GIVEN-K no longer keeps s < q/2: ((mv & & r s) (ecdsa-ensure-s-below-q/2 0 nil r s))) (and (eq error? nil) (equal (list r s) (r-s-string-to-r-s-list (fourth testcase)))))) ;;; Test full signature generation (defun test--ecdsa-sign-deterministic--sha-256 (testcase) (b* (((mv error? & & r s) ;; an enhancement would be to test the returned x-index and y-even? too (ecdsa-sign-deterministic-sha-256 (string=>bits (second testcase)) (first testcase) t t))) (and (eq error? nil) (equal (list r s) (r-s-string-to-r-s-list (fourth testcase)))))) ;;; Test full signature generation while also checking k (defun test--ecdsa-sign-deterministic-exposing-k--sha-256 (testcase) (b* (((mv error? & & r s k) ;; an enhancement would be to test the returned x-index and y-even? too (ecdsa-sign-deterministic-sha-256-exposing-k (string=>bits (second testcase)) (first testcase) t))) (and (eq error? nil) (equal (list r s k) (append (r-s-string-to-r-s-list (fourth testcase)) (list (third testcase))))))) ;;; ---------------------------------------------------------------- ;;; Test cases ;;; -------------------------------- ;;; Group 1 ;;; Using sha-256 for the message hash. ;;; ;;; This group tests deterministic-ecdsa, but these test cases ;;; are not directly usable for Ethereum, which ;;; hashes the message with keccak-256 before ;;; calling ECDSASIGN. #|| From https://bitcointalk.org/index.php?topic=285142.0;all The first set of test vectors did not take into account the restriction that s < q/2. This is the corrected set of test vectors that are suitable for the additional step of inverting s when s > q/2. # Test Vectors for RFC 6979 ECDSA, secp256k1, SHA-256 # (private key, message, expected k, expected signature) test_vectors = [ .. ] Original content duplicated in below comments, above each test case. ||# ;;; (private key, message, expected k, expected signature) ;;; (0x1, "Satoshi Nakamoto", 0x8F8A276C19F4149656B280621E358CCE24F5F52542772691EE69063B74F15D15, "934b1ea10a4b3c1757e2b0c017d0b6143ce3c9a7e6a4a49860d7a6ab210ee3d82442ce9d2b916064108014783e923ec36b49743e2ffa1c4496f01a512aafd9e5"), (defconst *test-1-1* (list #x1 "Satoshi Nakamoto" #x8F8A276C19F4149656B280621E358CCE24F5F52542772691EE69063B74F15D15 "934b1ea10a4b3c1757e2b0c017d0b6143ce3c9a7e6a4a49860d7a6ab210ee3d82442ce9d2b916064108014783e923ec36b49743e2ffa1c4496f01a512aafd9e5")) ;;; (private key, message, expected k, expected signature) ;;; (0x1, "All those moments will be lost in time, like tears in rain. Time to die...", 0x38AA22D72376B4DBC472E06C3BA403EE0A394DA63FC58D88686C611ABA98D6B3, "8600dbd41e348fe5c9465ab92d23e3db8b98b873beecd930736488696438cb6b547fe64427496db33bf66019dacbf0039c04199abb0122918601db38a72cfc21"), (defconst *test-1-2* (list #x1 "All those moments will be lost in time, like tears in rain. Time to die..." #x38AA22D72376B4DBC472E06C3BA403EE0A394DA63FC58D88686C611ABA98D6B3 "8600dbd41e348fe5c9465ab92d23e3db8b98b873beecd930736488696438cb6b547fe64427496db33bf66019dacbf0039c04199abb0122918601db38a72cfc21")) ;;; (private key, message, expected k, expected signature) ;;; (0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364140, "Satoshi Nakamoto", 0x33A19B60E25FB6F4435AF53A3D42D493644827367E6453928554F43E49AA6F90, "fd567d121db66e382991534ada77a6bd3106f0a1098c231e47993447cd6af2d06b39cd0eb1bc8603e159ef5c20a5c8ad685a45b06ce9bebed3f153d10d93bed5"), (defconst *test-1-3* (list #xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364140 "Satoshi Nakamoto" #x33A19B60E25FB6F4435AF53A3D42D493644827367E6453928554F43E49AA6F90 "fd567d121db66e382991534ada77a6bd3106f0a1098c231e47993447cd6af2d06b39cd0eb1bc8603e159ef5c20a5c8ad685a45b06ce9bebed3f153d10d93bed5")) ;;; (private key, message, expected k, expected signature) ;;; (0xf8b8af8ce3c7cca5e300d33939540c10d45ce001b8f252bfbc57ba0342904181, "Alan Turing", 0x525A82B70E67874398067543FD84C83D30C175FDC45FDEEE082FE13B1D7CFDF1, "7063ae83e7f62bbb171798131b4a0564b956930092b33b07b395615d9ec7e15c58dfcc1e00a35e1572f366ffe34ba0fc47db1e7189759b9fb233c5b05ab388ea"), (defconst *test-1-4* (list #xf8b8af8ce3c7cca5e300d33939540c10d45ce001b8f252bfbc57ba0342904181 "Alan Turing" #x525A82B70E67874398067543FD84C83D30C175FDC45FDEEE082FE13B1D7CFDF1 "7063ae83e7f62bbb171798131b4a0564b956930092b33b07b395615d9ec7e15c58dfcc1e00a35e1572f366ffe34ba0fc47db1e7189759b9fb233c5b05ab388ea")) ;;; (private key, message, expected k, expected signature) ;;; (0xe91671c46231f833a6406ccbea0e3e392c76c167bac1cb013f6f1013980455c2, "There is a computer disease that anybody who works with computers knows about. It's a very serious disease and it interferes completely with the work. The trouble with computers is that you 'play' with them!", 0x1F4B84C23A86A221D233F2521BE018D9318639D5B8BBD6374A8A59232D16AD3D, "b552edd27580141f3b2a5463048cb7cd3e047b97c9f98076c32dbdf85a68718b279fa72dd19bfae05577e06c7c0c1900c371fcd5893f7e1d56a37d30174671f6") (defconst *test-1-5* (list #xe91671c46231f833a6406ccbea0e3e392c76c167bac1cb013f6f1013980455c2 "There is a computer disease that anybody who works with computers knows about. It's a very serious disease and it interferes completely with the work. The trouble with computers is that you 'play' with them!" #x1F4B84C23A86A221D233F2521BE018D9318639D5B8BBD6374A8A59232D16AD3D "b552edd27580141f3b2a5463048cb7cd3e047b97c9f98076c32dbdf85a68718b279fa72dd19bfae05577e06c7c0c1900c371fcd5893f7e1d56a37d30174671f6")) ;;; ---------------------------------------------------------------- ;;; Run tests ;;; Run tests of the core routine ECDSA-SIGN-GIVEN-K ;;; (assert-event (test--ecdsa-sign-given-k--sha-256 *test-1-1*)) (assert-event (test--ecdsa-sign-given-k--sha-256 *test-1-2*)) (assert-event (test--ecdsa-sign-given-k--sha-256 *test-1-3*)) (assert-event (test--ecdsa-sign-given-k--sha-256 *test-1-4*)) (assert-event (test--ecdsa-sign-given-k--sha-256 *test-1-5*)) ;;; Run tests of the main interface ECDSA-SIGN-DETERMINISTIC ;;; (assert-event (test--ecdsa-sign-deterministic--sha-256 *test-1-1*)) (assert-event (test--ecdsa-sign-deterministic--sha-256 *test-1-2*)) (assert-event (test--ecdsa-sign-deterministic--sha-256 *test-1-3*)) (assert-event (test--ecdsa-sign-deterministic--sha-256 *test-1-4*)) (assert-event (test--ecdsa-sign-deterministic--sha-256 *test-1-5*)) ;;; Run tests of ECDSA-SIGN-DETERMINISTIC-EXPOSING-K ;;; to make sure we generate k correctly. ;;; (assert-event (test--ecdsa-sign-deterministic-exposing-k--sha-256 *test-1-1*)) (assert-event (test--ecdsa-sign-deterministic-exposing-k--sha-256 *test-1-2*)) (assert-event (test--ecdsa-sign-deterministic-exposing-k--sha-256 *test-1-3*)) (assert-event (test--ecdsa-sign-deterministic-exposing-k--sha-256 *test-1-4*)) (assert-event (test--ecdsa-sign-deterministic-exposing-k--sha-256 *test-1-5*)) ;;; -------------------------------- ;;; Group 2 ;;; Also using sha-256 for the message hash. ;;; ;;; This group tests deterministic-ecdsa, but these test cases ;;; are not directly usable for Ethereum, which ;;; hashes the message with keccak-256 before ;;; calling ECDSASIGN. #|| From https://bitcointalk.org/index.php?topic=285142.msg3300992#msg3300992 Submitted by plaprade and double-checked by fpgaminer. plaprade states: "The test vectors are fully canonical signatures with S components <= order/2. They contain both vectors were the S component had to be flipped and not flipped." EM: The original content had commas separating items in each tuple. I removed those and added the defconst. "Haskoin test vectors for RFC 6979 ECDSA (secp256k1, SHA-256)" "(PrvKey HEX, PrvKey WIF, message, R || S as HEX, sig as DER)" ||# (defconst *haskoin-tests-rfc-6979-ecdsa-secp256k1-sha-256* '( ( "0000000000000000000000000000000000000000000000000000000000000001" "KwDiBf89QgGbjEhKnhXJuH7LrciVrZi3qYjgd9M7rFU73sVHnoWn" "Everything should be made as simple as possible, but not simpler." "33a69cd2065432a30f3d1ce4eb0d59b8ab58c74f27c41a7fdb5696ad4e6108c96f807982866f785d3f6418d24163ddae117b7db4d5fdf0071de069fa54342262" "3044022033a69cd2065432a30f3d1ce4eb0d59b8ab58c74f27c41a7fdb5696ad4e6108c902206f807982866f785d3f6418d24163ddae117b7db4d5fdf0071de069fa54342262" ) ( "fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364140" "L5oLkpV3aqBjhki6LmvChTCV6odsp4SXM6FfU2Gppt5kFLaHLuZ9" "Equations are more important to me, because politics is for the present, but an equation is something for eternity." "54c4a33c6423d689378f160a7ff8b61330444abb58fb470f96ea16d99d4a2fed07082304410efa6b2943111b6a4e0aaa7b7db55a07e9861d1fb3cb1f421044a5" "3044022054c4a33c6423d689378f160a7ff8b61330444abb58fb470f96ea16d99d4a2fed022007082304410efa6b2943111b6a4e0aaa7b7db55a07e9861d1fb3cb1f421044a5" ) ( "fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364140" "L5oLkpV3aqBjhki6LmvChTCV6odsp4SXM6FfU2Gppt5kFLaHLuZ9" "Not only is the Universe stranger than we think, it is stranger than we can think." "ff466a9f1b7b273e2f4c3ffe032eb2e814121ed18ef84665d0f515360dab3dd06fc95f5132e5ecfdc8e5e6e616cc77151455d46ed48f5589b7db7771a332b283" "3045022100ff466a9f1b7b273e2f4c3ffe032eb2e814121ed18ef84665d0f515360dab3dd002206fc95f5132e5ecfdc8e5e6e616cc77151455d46ed48f5589b7db7771a332b283" ) ( "0000000000000000000000000000000000000000000000000000000000000001" "KwDiBf89QgGbjEhKnhXJuH7LrciVrZi3qYjgd9M7rFU73sVHnoWn" "How wonderful that we have met with a paradox. Now we have some hope of making progress." "c0dafec8251f1d5010289d210232220b03202cba34ec11fec58b3e93a85b91d375afdc06b7d6322a590955bf264e7aaa155847f614d80078a90292fe205064d3" "3045022100c0dafec8251f1d5010289d210232220b03202cba34ec11fec58b3e93a85b91d3022075afdc06b7d6322a590955bf264e7aaa155847f614d80078a90292fe205064d3" ) ( "69ec59eaa1f4f2e36b639716b7c30ca86d9a5375c7b38d8918bd9c0ebc80ba64" "KzmcSTRmg8Gtoq8jbBCwsrvgiTKRrewQXniAHHTf7hsten8MZmBB" "Computer science is no more about computers than astronomy is about telescopes." "7186363571d65e084e7f02b0b77c3ec44fb1b257dee26274c38c928986fea45d0de0b38e06807e46bda1f1e293f4f6323e854c86d58abdd00c46c16441085df6" "304402207186363571d65e084e7f02b0b77c3ec44fb1b257dee26274c38c928986fea45d02200de0b38e06807e46bda1f1e293f4f6323e854c86d58abdd00c46c16441085df6" ) ( "00000000000000000000000000007246174ab1e92e9149c6e446fe194d072637" "KwDiBf89QgGbjEhKnhXJwe1E2mCa8asowBrSKuCaBV6EsPYEAFZ8" "...if you aren't, at any given time, scandalized by code you wrote five or even three years ago, you're not learning anywhere near enough" "fbfe5076a15860ba8ed00e75e9bd22e05d230f02a936b653eb55b61c99dda4870e68880ebb0050fe4312b1b1eb0899e1b82da89baa5b895f612619edf34cbd37" "3045022100fbfe5076a15860ba8ed00e75e9bd22e05d230f02a936b653eb55b61c99dda48702200e68880ebb0050fe4312b1b1eb0899e1b82da89baa5b895f612619edf34cbd37" ) ( "000000000000000000000000000000000000000000056916d0f9b31dc9b637f3" "KwDiBf89QgGbjEhKnhXJuH7LrciVrZiib5S9h4knkymNojPUVsWN" "The question of whether computers can think is like the question of whether submarines can swim." "cde1302d83f8dd835d89aef803c74a119f561fbaef3eb9129e45f30de86abbf906ce643f5049ee1f27890467b77a6a8e11ec4661cc38cd8badf90115fbd03cef" "3045022100cde1302d83f8dd835d89aef803c74a119f561fbaef3eb9129e45f30de86abbf9022006ce643f5049ee1f27890467b77a6a8e11ec4661cc38cd8badf90115fbd03cef" ) )) ;; Originally: "(PrvKey HEX, PrvKey WIF, message, R || S as HEX, sig as DER)" ;; We ignore the "PrvKeyWIF HEX" and the "sig as DER". (defun run-haskoin-testcase (testcase) (b* (((mv error? & & r s) (ecdsa-sign-deterministic-sha-256 (string=>bits (third testcase)) ; message (acl2::bebytes=>nat (acl2::hexstring=>ubyte8s (first testcase))) ; private key t t))) (and (eq error? nil) (equal (list r s) (r-s-string-to-r-s-list (fourth testcase)))))) (defun run-haskoin-testcases (testcases) (if (null testcases) T (and (run-haskoin-testcase (car testcases)) (run-haskoin-testcases (cdr testcases))))) (acl2::assert! (run-haskoin-testcases *haskoin-tests-rfc-6979-ecdsa-secp256k1-sha-256*))
4281
; Tests of the RFC 6979 Deterministic ECDSA formalization. ; ; Copyright (C) 2019 Kestrel Institute ; ; License: A 3-clause BSD license. See the LICENSE file distributed with ACL2. ; ; Author: <NAME> (<EMAIL>) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (in-package "ECDSA") (include-book "deterministic-ecdsa-secp256k1") (include-book "deterministic-ecdsa-exposing-k-secp256k1") (include-book "std/strings/hex" :dir :system) ; for str::strval16 (include-book "kestrel/utilities/strings/hexstrings" :dir :system) ; for hexstring=>ubyte8s (include-book "kestrel/utilities/bytes-as-digits" :dir :system) ; for bebytes=>nat ;;; ---------------------------------------------------------------- ;;; Test utilities (defun string=>bits (str) (bytes-to-bits (acl2::string=>nats str))) (defun r-s-string-to-r-s-list (r-s-string) (if (and (stringp r-s-string) (equal (length r-s-string) 128)) (list (str::strval16 (subseq r-s-string 0 64)) (str::strval16 (subseq r-s-string 64 128))) nil)) ;;; Test the routine that generates (r,s) given k. (defun test--ecdsa-sign-given-k--sha-256 (testcase) ;; testcase is (<private-key> <message> <expected-k> <expected-signature>) (b* (((mv error? & & r s) ;; an enhancement would be to test the returned x-index and y-even? too (ecdsa-sign-given-k (acl2::bytes-to-bits (sha2::sha-256-bytes (acl2::string=>nats (second testcase)))) (first testcase) (third testcase))) ;; adjust tests now that ECDSA-SIGN-GIVEN-K no longer keeps s < q/2: ((mv & & r s) (ecdsa-ensure-s-below-q/2 0 nil r s))) (and (eq error? nil) (equal (list r s) (r-s-string-to-r-s-list (fourth testcase)))))) ;;; Test full signature generation (defun test--ecdsa-sign-deterministic--sha-256 (testcase) (b* (((mv error? & & r s) ;; an enhancement would be to test the returned x-index and y-even? too (ecdsa-sign-deterministic-sha-256 (string=>bits (second testcase)) (first testcase) t t))) (and (eq error? nil) (equal (list r s) (r-s-string-to-r-s-list (fourth testcase)))))) ;;; Test full signature generation while also checking k (defun test--ecdsa-sign-deterministic-exposing-k--sha-256 (testcase) (b* (((mv error? & & r s k) ;; an enhancement would be to test the returned x-index and y-even? too (ecdsa-sign-deterministic-sha-256-exposing-k (string=>bits (second testcase)) (first testcase) t))) (and (eq error? nil) (equal (list r s k) (append (r-s-string-to-r-s-list (fourth testcase)) (list (third testcase))))))) ;;; ---------------------------------------------------------------- ;;; Test cases ;;; -------------------------------- ;;; Group 1 ;;; Using sha-256 for the message hash. ;;; ;;; This group tests deterministic-ecdsa, but these test cases ;;; are not directly usable for Ethereum, which ;;; hashes the message with keccak-256 before ;;; calling ECDSASIGN. #|| From https://bitcointalk.org/index.php?topic=285142.0;all The first set of test vectors did not take into account the restriction that s < q/2. This is the corrected set of test vectors that are suitable for the additional step of inverting s when s > q/2. # Test Vectors for RFC 6979 ECDSA, secp256k1, SHA-256 # (private key, message, expected k, expected signature) test_vectors = [ .. ] Original content duplicated in below comments, above each test case. ||# ;;; (private key, message, expected k, expected signature) ;;; (0x1, "<NAME>", 0x8F8A276C19F4149656B280621E358CCE24F5F52542772691EE69063B74F15D15, "934b1ea10a4b3c1757e2b0c017d0b6143ce3c9a7e6a4a49860d7a6ab210ee3d82442ce9d2b916064108014783e923ec36b49743e2ffa1c4496f01a512aafd9e5"), (defconst *test-1-1* (list #x1 "<NAME>" #x8F8A276C19F4149656B280621E358CCE24F5F52542772691EE69063B74F15D15 "934b1ea10a4b3c1757e2b0c017d0b6143ce3c9a7e6a4a49860d7a6ab210ee3d82442ce9d2b916064108014783e923ec36b49743e2ffa1c4496f01a512aafd9e5")) ;;; (private key, message, expected k, expected signature) ;;; (0x1, "All those moments will be lost in time, like tears in rain. Time to die...", 0x3<KEY>D<KEY>A98D6B3, "<KEY>"), (defconst *test-1-2* (list #x1 "All those moments will be lost in time, like tears in rain. Time to die..." #x38AA22D72376B4DBC472E06C3BA403EE0A394DA63FC58D88686C611ABA98D6B3 "<KEY>")) ;;; (private key, message, expected k, expected signature) ;;; (0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364140, "<NAME>", 0x33A19B60E25FB6F4435AF53A3D42D493644827367E6453928554F43E49AA6F90, "fd567d121db66e382991534ada77a6bd3106f0a1098c231e47993447cd6af2d06b39cd0eb1bc8603e159ef5c20a5c8ad685a45b06ce9bebed3f153d10d93bed5"), (defconst *test-1-3* (list #xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364140 "<NAME>" #x33A19B60E25FB6F4435AF53A3D42D493644827367E6453928554F43E49AA6F90 "fd567d121db66e382991534ada77a6bd3106f0a1098c231e47993447cd6af2d06b39cd0eb1bc8603e159ef5c20a5c8ad685a45b06ce9bebed3f153d10d93bed5")) ;;; (private key, message, expected k, expected signature) ;;; (<KEY>, "Alan Turing", 0x525A82B70E67874398067543FD84C83D30C17<KEY>FDC45FDEEE082FE13B1D7CFDF1, "<KEY>"), (defconst *test-1-4* (list #<KEY> "<NAME>" #x5<KEY>DF1 "<KEY>")) ;;; (private key, message, expected k, expected signature) ;;; (<KEY>, "There is a computer disease that anybody who works with computers knows about. It's a very serious disease and it interferes completely with the work. The trouble with computers is that you 'play' with them!", 0x1F4B84C23A86A221D233F2521BE018D9318639D5B8BBD6374A8A59232D16AD3D, "<KEY>") (defconst *test-1-5* (list #xe91671c46231f833a6406ccbea0e3e392c76c167bac1cb013f6f1013980455c2 "There is a computer disease that anybody who works with computers knows about. It's a very serious disease and it interferes completely with the work. The trouble with computers is that you 'play' with them!" #x1F4B84C23A86A221D233F2521BE018D9318639D5B8BBD6374A8A59232D16AD3D "<KEY>")) ;;; ---------------------------------------------------------------- ;;; Run tests ;;; Run tests of the core routine ECDSA-SIGN-GIVEN-K ;;; (assert-event (test--ecdsa-sign-given-k--sha-256 *test-1-1*)) (assert-event (test--ecdsa-sign-given-k--sha-256 *test-1-2*)) (assert-event (test--ecdsa-sign-given-k--sha-256 *test-1-3*)) (assert-event (test--ecdsa-sign-given-k--sha-256 *test-1-4*)) (assert-event (test--ecdsa-sign-given-k--sha-256 *test-1-5*)) ;;; Run tests of the main interface ECDSA-SIGN-DETERMINISTIC ;;; (assert-event (test--ecdsa-sign-deterministic--sha-256 *test-1-1*)) (assert-event (test--ecdsa-sign-deterministic--sha-256 *test-1-2*)) (assert-event (test--ecdsa-sign-deterministic--sha-256 *test-1-3*)) (assert-event (test--ecdsa-sign-deterministic--sha-256 *test-1-4*)) (assert-event (test--ecdsa-sign-deterministic--sha-256 *test-1-5*)) ;;; Run tests of ECDSA-SIGN-DETERMINISTIC-EXPOSING-K ;;; to make sure we generate k correctly. ;;; (assert-event (test--ecdsa-sign-deterministic-exposing-k--sha-256 *test-1-1*)) (assert-event (test--ecdsa-sign-deterministic-exposing-k--sha-256 *test-1-2*)) (assert-event (test--ecdsa-sign-deterministic-exposing-k--sha-256 *test-1-3*)) (assert-event (test--ecdsa-sign-deterministic-exposing-k--sha-256 *test-1-4*)) (assert-event (test--ecdsa-sign-deterministic-exposing-k--sha-256 *test-1-5*)) ;;; -------------------------------- ;;; Group 2 ;;; Also using sha-256 for the message hash. ;;; ;;; This group tests deterministic-ecdsa, but these test cases ;;; are not directly usable for Ethereum, which ;;; hashes the message with keccak-256 before ;;; calling ECDSASIGN. #|| From https://bitcointalk.org/index.php?topic=285142.msg3300992#msg3300992 Submitted by plaprade and double-checked by fpgaminer. plaprade states: "The test vectors are fully canonical signatures with S components <= order/2. They contain both vectors were the S component had to be flipped and not flipped." EM: The original content had commas separating items in each tuple. I removed those and added the defconst. "Haskoin test vectors for RFC 6979 ECDSA (secp256k1, SHA-256)" "(PrvKey HEX, PrvKey WIF, message, R || S as HEX, sig as DER)" ||# (defconst *haskoin-tests-rfc-6979-ecdsa-secp256k1-sha-256* '( ( "0000000000000000000000000000000000000000000000000000000000000001" "KwDiBf89QgGbjEhKnhXJuH7LrciVrZi3qYjgd9M7rFU73sVHnoWn" "Everything should be made as simple as possible, but not simpler." "33a69cd2065432a30f3d1ce4eb0d59b8ab58c74f27c41a7fdb5696ad4e6108c96f807982866f785d3<KEY>" "<KEY>" ) ( "fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364140" "<KEY>" "Equations are more important to me, because politics is for the present, but an equation is something for eternity." "<KEY>" "<KEY>44a5" ) ( "fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364140" "L5oLkpV3aqBjhki6LmvChTCV6odsp4SXM6FfU2Gppt5kFLaHLuZ9" "Not only is the Universe stranger than we think, it is stranger than we can think." "ff466a9f1b7b273e2f4c3ffe032eb2e814121ed18ef84665d0f515360dab3dd06fc95f5132e5ecfdc8e5e6e616cc77151455d46ed48f5589b7db7771a332b283" "3045022100ff466a9f1b7b273e2f4c3ffe032eb2e814121ed18ef84665d0f515360dab3dd002206fc95f5132e5ecfdc8e5e6e616cc77151455d46ed48f5589b7db7771a332b283" ) ( "0000000000000000000000000000000000000000000000000000000000000001" "KwDiBf89QgGbjEhKnhXJuH7LrciVrZi3qYjgd9M7rFU73sVHnoWn" "How wonderful that we have met with a paradox. Now we have some hope of making progress." "c0dafec8251f1d5010289d210232220b0320<KEY>" "<KEY>" ) ( "<KEY>" "<KEY>" "Computer science is no more about computers than astronomy is about telescopes." "<KEY>" "<KEY>" ) ( "00000000000000000000000000007246174ab1e92e9149c6e446fe194d072637" "Kw<KEY>Bf<KEY>QgGbj<KEY>nh<KEY>E<KEY>mCa<KEY>as<KEY>Br<KEY>uCa<KEY>8" "...if you aren't, at any given time, scandalized by code you wrote five or even three years ago, you're not learning anywhere near enough" "<KEY>" "<KEY>" ) ( "000000000000000000000000000000000000000000056916d0f9b31dc9b637f3" "<KEY>" "The question of whether computers can think is like the question of whether submarines can swim." "<KEY>" "<KEY>e<KEY>ec<KEY>" ) )) ;; Originally: "(PrvKey HEX, PrvKey WIF, message, R || S as HEX, sig as DER)" ;; We ignore the "PrvKeyWIF HEX" and the "sig as DER". (defun run-haskoin-testcase (testcase) (b* (((mv error? & & r s) (ecdsa-sign-deterministic-sha-256 (string=>bits (third testcase)) ; message (acl2::bebytes=>nat (acl2::hexstring=>ubyte8s (first testcase))) ; private key t t))) (and (eq error? nil) (equal (list r s) (r-s-string-to-r-s-list (fourth testcase)))))) (defun run-haskoin-testcases (testcases) (if (null testcases) T (and (run-haskoin-testcase (car testcases)) (run-haskoin-testcases (cdr testcases))))) (acl2::assert! (run-haskoin-testcases *haskoin-tests-rfc-6979-ecdsa-secp256k1-sha-256*))
true
; Tests of the RFC 6979 Deterministic ECDSA formalization. ; ; Copyright (C) 2019 Kestrel Institute ; ; 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 "ECDSA") (include-book "deterministic-ecdsa-secp256k1") (include-book "deterministic-ecdsa-exposing-k-secp256k1") (include-book "std/strings/hex" :dir :system) ; for str::strval16 (include-book "kestrel/utilities/strings/hexstrings" :dir :system) ; for hexstring=>ubyte8s (include-book "kestrel/utilities/bytes-as-digits" :dir :system) ; for bebytes=>nat ;;; ---------------------------------------------------------------- ;;; Test utilities (defun string=>bits (str) (bytes-to-bits (acl2::string=>nats str))) (defun r-s-string-to-r-s-list (r-s-string) (if (and (stringp r-s-string) (equal (length r-s-string) 128)) (list (str::strval16 (subseq r-s-string 0 64)) (str::strval16 (subseq r-s-string 64 128))) nil)) ;;; Test the routine that generates (r,s) given k. (defun test--ecdsa-sign-given-k--sha-256 (testcase) ;; testcase is (<private-key> <message> <expected-k> <expected-signature>) (b* (((mv error? & & r s) ;; an enhancement would be to test the returned x-index and y-even? too (ecdsa-sign-given-k (acl2::bytes-to-bits (sha2::sha-256-bytes (acl2::string=>nats (second testcase)))) (first testcase) (third testcase))) ;; adjust tests now that ECDSA-SIGN-GIVEN-K no longer keeps s < q/2: ((mv & & r s) (ecdsa-ensure-s-below-q/2 0 nil r s))) (and (eq error? nil) (equal (list r s) (r-s-string-to-r-s-list (fourth testcase)))))) ;;; Test full signature generation (defun test--ecdsa-sign-deterministic--sha-256 (testcase) (b* (((mv error? & & r s) ;; an enhancement would be to test the returned x-index and y-even? too (ecdsa-sign-deterministic-sha-256 (string=>bits (second testcase)) (first testcase) t t))) (and (eq error? nil) (equal (list r s) (r-s-string-to-r-s-list (fourth testcase)))))) ;;; Test full signature generation while also checking k (defun test--ecdsa-sign-deterministic-exposing-k--sha-256 (testcase) (b* (((mv error? & & r s k) ;; an enhancement would be to test the returned x-index and y-even? too (ecdsa-sign-deterministic-sha-256-exposing-k (string=>bits (second testcase)) (first testcase) t))) (and (eq error? nil) (equal (list r s k) (append (r-s-string-to-r-s-list (fourth testcase)) (list (third testcase))))))) ;;; ---------------------------------------------------------------- ;;; Test cases ;;; -------------------------------- ;;; Group 1 ;;; Using sha-256 for the message hash. ;;; ;;; This group tests deterministic-ecdsa, but these test cases ;;; are not directly usable for Ethereum, which ;;; hashes the message with keccak-256 before ;;; calling ECDSASIGN. #|| From https://bitcointalk.org/index.php?topic=285142.0;all The first set of test vectors did not take into account the restriction that s < q/2. This is the corrected set of test vectors that are suitable for the additional step of inverting s when s > q/2. # Test Vectors for RFC 6979 ECDSA, secp256k1, SHA-256 # (private key, message, expected k, expected signature) test_vectors = [ .. ] Original content duplicated in below comments, above each test case. ||# ;;; (private key, message, expected k, expected signature) ;;; (0x1, "PI:NAME:<NAME>END_PI", 0x8F8A276C19F4149656B280621E358CCE24F5F52542772691EE69063B74F15D15, "934b1ea10a4b3c1757e2b0c017d0b6143ce3c9a7e6a4a49860d7a6ab210ee3d82442ce9d2b916064108014783e923ec36b49743e2ffa1c4496f01a512aafd9e5"), (defconst *test-1-1* (list #x1 "PI:NAME:<NAME>END_PI" #x8F8A276C19F4149656B280621E358CCE24F5F52542772691EE69063B74F15D15 "934b1ea10a4b3c1757e2b0c017d0b6143ce3c9a7e6a4a49860d7a6ab210ee3d82442ce9d2b916064108014783e923ec36b49743e2ffa1c4496f01a512aafd9e5")) ;;; (private key, message, expected k, expected signature) ;;; (0x1, "All those moments will be lost in time, like tears in rain. Time to die...", 0x3PI:KEY:<KEY>END_PIDPI:KEY:<KEY>END_PIA98D6B3, "PI:KEY:<KEY>END_PI"), (defconst *test-1-2* (list #x1 "All those moments will be lost in time, like tears in rain. Time to die..." #x38AA22D72376B4DBC472E06C3BA403EE0A394DA63FC58D88686C611ABA98D6B3 "PI:KEY:<KEY>END_PI")) ;;; (private key, message, expected k, expected signature) ;;; (0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364140, "PI:NAME:<NAME>END_PI", 0x33A19B60E25FB6F4435AF53A3D42D493644827367E6453928554F43E49AA6F90, "fd567d121db66e382991534ada77a6bd3106f0a1098c231e47993447cd6af2d06b39cd0eb1bc8603e159ef5c20a5c8ad685a45b06ce9bebed3f153d10d93bed5"), (defconst *test-1-3* (list #xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364140 "PI:NAME:<NAME>END_PI" #x33A19B60E25FB6F4435AF53A3D42D493644827367E6453928554F43E49AA6F90 "fd567d121db66e382991534ada77a6bd3106f0a1098c231e47993447cd6af2d06b39cd0eb1bc8603e159ef5c20a5c8ad685a45b06ce9bebed3f153d10d93bed5")) ;;; (private key, message, expected k, expected signature) ;;; (PI:KEY:<KEY>END_PI, "Alan Turing", 0x525A82B70E67874398067543FD84C83D30C17PI:KEY:<KEY>END_PIFDC45FDEEE082FE13B1D7CFDF1, "PI:KEY:<KEY>END_PI"), (defconst *test-1-4* (list #PI:KEY:<KEY>END_PI "PI:NAME:<NAME>END_PI" #x5PI:KEY:<KEY>END_PIDF1 "PI:KEY:<KEY>END_PI")) ;;; (private key, message, expected k, expected signature) ;;; (PI:KEY:<KEY>END_PI, "There is a computer disease that anybody who works with computers knows about. It's a very serious disease and it interferes completely with the work. The trouble with computers is that you 'play' with them!", 0x1F4B84C23A86A221D233F2521BE018D9318639D5B8BBD6374A8A59232D16AD3D, "PI:KEY:<KEY>END_PI") (defconst *test-1-5* (list #xe91671c46231f833a6406ccbea0e3e392c76c167bac1cb013f6f1013980455c2 "There is a computer disease that anybody who works with computers knows about. It's a very serious disease and it interferes completely with the work. The trouble with computers is that you 'play' with them!" #x1F4B84C23A86A221D233F2521BE018D9318639D5B8BBD6374A8A59232D16AD3D "PI:KEY:<KEY>END_PI")) ;;; ---------------------------------------------------------------- ;;; Run tests ;;; Run tests of the core routine ECDSA-SIGN-GIVEN-K ;;; (assert-event (test--ecdsa-sign-given-k--sha-256 *test-1-1*)) (assert-event (test--ecdsa-sign-given-k--sha-256 *test-1-2*)) (assert-event (test--ecdsa-sign-given-k--sha-256 *test-1-3*)) (assert-event (test--ecdsa-sign-given-k--sha-256 *test-1-4*)) (assert-event (test--ecdsa-sign-given-k--sha-256 *test-1-5*)) ;;; Run tests of the main interface ECDSA-SIGN-DETERMINISTIC ;;; (assert-event (test--ecdsa-sign-deterministic--sha-256 *test-1-1*)) (assert-event (test--ecdsa-sign-deterministic--sha-256 *test-1-2*)) (assert-event (test--ecdsa-sign-deterministic--sha-256 *test-1-3*)) (assert-event (test--ecdsa-sign-deterministic--sha-256 *test-1-4*)) (assert-event (test--ecdsa-sign-deterministic--sha-256 *test-1-5*)) ;;; Run tests of ECDSA-SIGN-DETERMINISTIC-EXPOSING-K ;;; to make sure we generate k correctly. ;;; (assert-event (test--ecdsa-sign-deterministic-exposing-k--sha-256 *test-1-1*)) (assert-event (test--ecdsa-sign-deterministic-exposing-k--sha-256 *test-1-2*)) (assert-event (test--ecdsa-sign-deterministic-exposing-k--sha-256 *test-1-3*)) (assert-event (test--ecdsa-sign-deterministic-exposing-k--sha-256 *test-1-4*)) (assert-event (test--ecdsa-sign-deterministic-exposing-k--sha-256 *test-1-5*)) ;;; -------------------------------- ;;; Group 2 ;;; Also using sha-256 for the message hash. ;;; ;;; This group tests deterministic-ecdsa, but these test cases ;;; are not directly usable for Ethereum, which ;;; hashes the message with keccak-256 before ;;; calling ECDSASIGN. #|| From https://bitcointalk.org/index.php?topic=285142.msg3300992#msg3300992 Submitted by plaprade and double-checked by fpgaminer. plaprade states: "The test vectors are fully canonical signatures with S components <= order/2. They contain both vectors were the S component had to be flipped and not flipped." EM: The original content had commas separating items in each tuple. I removed those and added the defconst. "Haskoin test vectors for RFC 6979 ECDSA (secp256k1, SHA-256)" "(PrvKey HEX, PrvKey WIF, message, R || S as HEX, sig as DER)" ||# (defconst *haskoin-tests-rfc-6979-ecdsa-secp256k1-sha-256* '( ( "0000000000000000000000000000000000000000000000000000000000000001" "KwDiBf89QgGbjEhKnhXJuH7LrciVrZi3qYjgd9M7rFU73sVHnoWn" "Everything should be made as simple as possible, but not simpler." "33a69cd2065432a30f3d1ce4eb0d59b8ab58c74f27c41a7fdb5696ad4e6108c96f807982866f785d3PI:KEY:<KEY>END_PI" "PI:KEY:<KEY>END_PI" ) ( "fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364140" "PI:KEY:<KEY>END_PI" "Equations are more important to me, because politics is for the present, but an equation is something for eternity." "PI:KEY:<KEY>END_PI" "PI:KEY:<KEY>END_PI44a5" ) ( "fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364140" "L5oLkpV3aqBjhki6LmvChTCV6odsp4SXM6FfU2Gppt5kFLaHLuZ9" "Not only is the Universe stranger than we think, it is stranger than we can think." "ff466a9f1b7b273e2f4c3ffe032eb2e814121ed18ef84665d0f515360dab3dd06fc95f5132e5ecfdc8e5e6e616cc77151455d46ed48f5589b7db7771a332b283" "3045022100ff466a9f1b7b273e2f4c3ffe032eb2e814121ed18ef84665d0f515360dab3dd002206fc95f5132e5ecfdc8e5e6e616cc77151455d46ed48f5589b7db7771a332b283" ) ( "0000000000000000000000000000000000000000000000000000000000000001" "KwDiBf89QgGbjEhKnhXJuH7LrciVrZi3qYjgd9M7rFU73sVHnoWn" "How wonderful that we have met with a paradox. Now we have some hope of making progress." "c0dafec8251f1d5010289d210232220b0320PI:KEY:<KEY>END_PI" "PI:KEY:<KEY>END_PI" ) ( "PI:KEY:<KEY>END_PI" "PI:KEY:<KEY>END_PI" "Computer science is no more about computers than astronomy is about telescopes." "PI:KEY:<KEY>END_PI" "PI:KEY:<KEY>END_PI" ) ( "00000000000000000000000000007246174ab1e92e9149c6e446fe194d072637" "KwPI:KEY:<KEY>END_PIBfPI:KEY:<KEY>END_PIQgGbjPI:KEY:<KEY>END_PInhPI:KEY:<KEY>END_PIEPI:KEY:<KEY>END_PImCaPI:KEY:<KEY>END_PIasPI:KEY:<KEY>END_PIBrPI:KEY:<KEY>END_PIuCaPI:KEY:<KEY>END_PI8" "...if you aren't, at any given time, scandalized by code you wrote five or even three years ago, you're not learning anywhere near enough" "PI:KEY:<KEY>END_PI" "PI:KEY:<KEY>END_PI" ) ( "000000000000000000000000000000000000000000056916d0f9b31dc9b637f3" "PI:KEY:<KEY>END_PI" "The question of whether computers can think is like the question of whether submarines can swim." "PI:KEY:<KEY>END_PI" "PI:KEY:<KEY>END_PIePI:KEY:<KEY>END_PIecPI:KEY:<KEY>END_PI" ) )) ;; Originally: "(PrvKey HEX, PrvKey WIF, message, R || S as HEX, sig as DER)" ;; We ignore the "PrvKeyWIF HEX" and the "sig as DER". (defun run-haskoin-testcase (testcase) (b* (((mv error? & & r s) (ecdsa-sign-deterministic-sha-256 (string=>bits (third testcase)) ; message (acl2::bebytes=>nat (acl2::hexstring=>ubyte8s (first testcase))) ; private key t t))) (and (eq error? nil) (equal (list r s) (r-s-string-to-r-s-list (fourth testcase)))))) (defun run-haskoin-testcases (testcases) (if (null testcases) T (and (run-haskoin-testcase (car testcases)) (run-haskoin-testcases (cdr testcases))))) (acl2::assert! (run-haskoin-testcases *haskoin-tests-rfc-6979-ecdsa-secp256k1-sha-256*))
[ { "context": "sd)\n\n(defsystem t-lack-middleware-csrf\n :author \"Eitaro Fukamachi\"\n :license \"LLGPL\"\n :depends-on (:lack\n ", "end": 184, "score": 0.9998819231987, "start": 168, "tag": "NAME", "value": "Eitaro Fukamachi" } ]
bundle-libs/software/lack-20190521-git/t-lack-middleware-csrf.asd
dbym4820/photon
4
(in-package :cl-user) (defpackage t-lack-middleware-csrf-asd (:use :cl :asdf)) (in-package :t-lack-middleware-csrf-asd) (defsystem t-lack-middleware-csrf :author "Eitaro Fukamachi" :license "LLGPL" :depends-on (:lack :lack-test :lack-request :lack-middleware-csrf :prove :cl-ppcre) :components ((:test-file "t/middleware/csrf")) :defsystem-depends-on (:prove-asdf) :perform (test-op :after (op c) (funcall (intern #.(string :run-test-system) :prove) c)))
16650
(in-package :cl-user) (defpackage t-lack-middleware-csrf-asd (:use :cl :asdf)) (in-package :t-lack-middleware-csrf-asd) (defsystem t-lack-middleware-csrf :author "<NAME>" :license "LLGPL" :depends-on (:lack :lack-test :lack-request :lack-middleware-csrf :prove :cl-ppcre) :components ((:test-file "t/middleware/csrf")) :defsystem-depends-on (:prove-asdf) :perform (test-op :after (op c) (funcall (intern #.(string :run-test-system) :prove) c)))
true
(in-package :cl-user) (defpackage t-lack-middleware-csrf-asd (:use :cl :asdf)) (in-package :t-lack-middleware-csrf-asd) (defsystem t-lack-middleware-csrf :author "PI:NAME:<NAME>END_PI" :license "LLGPL" :depends-on (:lack :lack-test :lack-request :lack-middleware-csrf :prove :cl-ppcre) :components ((:test-file "t/middleware/csrf")) :defsystem-depends-on (:prove-asdf) :perform (test-op :after (op c) (funcall (intern #.(string :run-test-system) :prove) c)))
[ { "context": ";; Copyright 2010-2018 Ben Lambert\n\n;; Licensed under the Apache License, Version 2.", "end": 34, "score": 0.999828577041626, "start": 23, "tag": "NAME", "value": "Ben Lambert" } ]
src/util.lisp
belambert/lisp-asr
10
;; 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. (defun truncate-list (list maximum-length) "Returns a subsequence of the list, with a max length as specified. If the max length is null then returns the original list." (if maximum-length (subseq list 0 (min maximum-length (length list))) list)) (defun text-file->line-list (filename &key (external-format :utf-8)) "Quickly read an entire text file (UTF-8) into memory, and split it up by newlines." (with-open-file (file filename :direction :input :external-format external-format) (let ((char-array (make-array (the fixnum (file-length file)) :element-type 'character))) (read-sequence char-array file) (split-string #\Newline char-array)))) (defun gzip-file->line-list (filename) "Open and decompress a gzipped file, then return a list of lines." (with-open-file (s filename :element-type '(unsigned-byte 8)) (let* ((gzip-length (file-length s)) (gzip-seq (make-array (the fixnum gzip-length) :element-type '(unsigned-byte 8)))) (read-sequence gzip-seq s) (let* ((unzipped-seq (gzip-stream:gunzip-sequence gzip-seq)) (unzipped-length (length unzipped-seq)) (unzipped-string (make-array unzipped-length :element-type 'character))) (declare ((array (unsigned-byte 8)) unzipped-seq) (simple-string unzipped-string)) (map-into unzipped-string 'code-char unzipped-seq) (split-string #\Newline unzipped-string))))) (defun file->line-list (filename &key (external-format :utf-8) (gzip nil gzip-supplied-p)) "Read a file that may or may not be gzipped, and return a list of the lines. Automatically detects if it's a gzip file by the extension (at the end of the filename), but this can be overridden by supplying the argument :gzip." (let ((gzip-p (if (pathnamep filename) (string-equal (pathname-type filename) "gz") (alexandria:ends-with-subseq ".gz" filename :test #'char-equal)))) (when gzip-supplied-p (setf gzip-p gzip)) (if gzip-p (gzip-file->line-list filename) (text-file->line-list filename :external-format external-format)))) (defun remove-duplicates-fast (list &key (ht-test 'equalp) key) "Faster than the built in REMOVE-DUPLICATES on long lists. Sacrifices memory use to speed up time, by creating an aux hash table. It's faster to just build a new list than to try to remove them from the original list... at least without some major bookkeeping..." (unless list (return-from remove-duplicates-fast list)) (let ((ht (make-hash-table :test ht-test :size (length list))) (new-list '())) (loop for item in list for compare-item = (if key (funcall key item) item) do (unless (gethash compare-item ht) (push item new-list) (setf (gethash compare-item ht) t))) (nreverse new-list))) (defun nintersection-fast (list-1 list-2 &key (ht-test 'equalp)) "Faster than the built-in INTERSECTION for long lists. Creates a hash table to speed up comparisons. ht-test is a HASHTABLE test, not an equality function operator. The current version is *not destructive*, and is the same as INTERSECTION-FAST." (let ((ht (make-hash-table :test ht-test)) (new-list '())) (dolist (item list-1) (setf (gethash item ht) t)) (dolist (item list-2) (when (gethash item ht) (push item new-list))) new-list)) (defun intersection-fast (list-1 list-2 &key (ht-test 'equalp)) "Faster than the built-in INTERSECTION for long lists. Creates a hash table to speed up comparisons. ht-test is a HASHTABLE test, not an equality function operator." ;;(nintersection-fast (copy-seq list-1) list-2 :ht-test ht-test) (nintersection-fast list-1 list-2 :ht-test ht-test))
33852
;; 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. (defun truncate-list (list maximum-length) "Returns a subsequence of the list, with a max length as specified. If the max length is null then returns the original list." (if maximum-length (subseq list 0 (min maximum-length (length list))) list)) (defun text-file->line-list (filename &key (external-format :utf-8)) "Quickly read an entire text file (UTF-8) into memory, and split it up by newlines." (with-open-file (file filename :direction :input :external-format external-format) (let ((char-array (make-array (the fixnum (file-length file)) :element-type 'character))) (read-sequence char-array file) (split-string #\Newline char-array)))) (defun gzip-file->line-list (filename) "Open and decompress a gzipped file, then return a list of lines." (with-open-file (s filename :element-type '(unsigned-byte 8)) (let* ((gzip-length (file-length s)) (gzip-seq (make-array (the fixnum gzip-length) :element-type '(unsigned-byte 8)))) (read-sequence gzip-seq s) (let* ((unzipped-seq (gzip-stream:gunzip-sequence gzip-seq)) (unzipped-length (length unzipped-seq)) (unzipped-string (make-array unzipped-length :element-type 'character))) (declare ((array (unsigned-byte 8)) unzipped-seq) (simple-string unzipped-string)) (map-into unzipped-string 'code-char unzipped-seq) (split-string #\Newline unzipped-string))))) (defun file->line-list (filename &key (external-format :utf-8) (gzip nil gzip-supplied-p)) "Read a file that may or may not be gzipped, and return a list of the lines. Automatically detects if it's a gzip file by the extension (at the end of the filename), but this can be overridden by supplying the argument :gzip." (let ((gzip-p (if (pathnamep filename) (string-equal (pathname-type filename) "gz") (alexandria:ends-with-subseq ".gz" filename :test #'char-equal)))) (when gzip-supplied-p (setf gzip-p gzip)) (if gzip-p (gzip-file->line-list filename) (text-file->line-list filename :external-format external-format)))) (defun remove-duplicates-fast (list &key (ht-test 'equalp) key) "Faster than the built in REMOVE-DUPLICATES on long lists. Sacrifices memory use to speed up time, by creating an aux hash table. It's faster to just build a new list than to try to remove them from the original list... at least without some major bookkeeping..." (unless list (return-from remove-duplicates-fast list)) (let ((ht (make-hash-table :test ht-test :size (length list))) (new-list '())) (loop for item in list for compare-item = (if key (funcall key item) item) do (unless (gethash compare-item ht) (push item new-list) (setf (gethash compare-item ht) t))) (nreverse new-list))) (defun nintersection-fast (list-1 list-2 &key (ht-test 'equalp)) "Faster than the built-in INTERSECTION for long lists. Creates a hash table to speed up comparisons. ht-test is a HASHTABLE test, not an equality function operator. The current version is *not destructive*, and is the same as INTERSECTION-FAST." (let ((ht (make-hash-table :test ht-test)) (new-list '())) (dolist (item list-1) (setf (gethash item ht) t)) (dolist (item list-2) (when (gethash item ht) (push item new-list))) new-list)) (defun intersection-fast (list-1 list-2 &key (ht-test 'equalp)) "Faster than the built-in INTERSECTION for long lists. Creates a hash table to speed up comparisons. ht-test is a HASHTABLE test, not an equality function operator." ;;(nintersection-fast (copy-seq list-1) list-2 :ht-test ht-test) (nintersection-fast list-1 list-2 :ht-test ht-test))
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. (defun truncate-list (list maximum-length) "Returns a subsequence of the list, with a max length as specified. If the max length is null then returns the original list." (if maximum-length (subseq list 0 (min maximum-length (length list))) list)) (defun text-file->line-list (filename &key (external-format :utf-8)) "Quickly read an entire text file (UTF-8) into memory, and split it up by newlines." (with-open-file (file filename :direction :input :external-format external-format) (let ((char-array (make-array (the fixnum (file-length file)) :element-type 'character))) (read-sequence char-array file) (split-string #\Newline char-array)))) (defun gzip-file->line-list (filename) "Open and decompress a gzipped file, then return a list of lines." (with-open-file (s filename :element-type '(unsigned-byte 8)) (let* ((gzip-length (file-length s)) (gzip-seq (make-array (the fixnum gzip-length) :element-type '(unsigned-byte 8)))) (read-sequence gzip-seq s) (let* ((unzipped-seq (gzip-stream:gunzip-sequence gzip-seq)) (unzipped-length (length unzipped-seq)) (unzipped-string (make-array unzipped-length :element-type 'character))) (declare ((array (unsigned-byte 8)) unzipped-seq) (simple-string unzipped-string)) (map-into unzipped-string 'code-char unzipped-seq) (split-string #\Newline unzipped-string))))) (defun file->line-list (filename &key (external-format :utf-8) (gzip nil gzip-supplied-p)) "Read a file that may or may not be gzipped, and return a list of the lines. Automatically detects if it's a gzip file by the extension (at the end of the filename), but this can be overridden by supplying the argument :gzip." (let ((gzip-p (if (pathnamep filename) (string-equal (pathname-type filename) "gz") (alexandria:ends-with-subseq ".gz" filename :test #'char-equal)))) (when gzip-supplied-p (setf gzip-p gzip)) (if gzip-p (gzip-file->line-list filename) (text-file->line-list filename :external-format external-format)))) (defun remove-duplicates-fast (list &key (ht-test 'equalp) key) "Faster than the built in REMOVE-DUPLICATES on long lists. Sacrifices memory use to speed up time, by creating an aux hash table. It's faster to just build a new list than to try to remove them from the original list... at least without some major bookkeeping..." (unless list (return-from remove-duplicates-fast list)) (let ((ht (make-hash-table :test ht-test :size (length list))) (new-list '())) (loop for item in list for compare-item = (if key (funcall key item) item) do (unless (gethash compare-item ht) (push item new-list) (setf (gethash compare-item ht) t))) (nreverse new-list))) (defun nintersection-fast (list-1 list-2 &key (ht-test 'equalp)) "Faster than the built-in INTERSECTION for long lists. Creates a hash table to speed up comparisons. ht-test is a HASHTABLE test, not an equality function operator. The current version is *not destructive*, and is the same as INTERSECTION-FAST." (let ((ht (make-hash-table :test ht-test)) (new-list '())) (dolist (item list-1) (setf (gethash item ht) t)) (dolist (item list-2) (when (gethash item ht) (push item new-list))) new-list)) (defun intersection-fast (list-1 list-2 &key (ht-test 'equalp)) "Faster than the built-in INTERSECTION for long lists. Creates a hash table to speed up comparisons. ht-test is a HASHTABLE test, not an equality function operator." ;;(nintersection-fast (copy-seq list-1) list-2 :ht-test ht-test) (nintersection-fast list-1 list-2 :ht-test ht-test))
[ { "context": "ary for script reading and executing.\"\n :author \"Isoraķatheð Zorethan <[email protected]>\"\n :license \"M", "end": 141, "score": 0.9998935461044312, "start": 121, "tag": "NAME", "value": "Isoraķatheð Zorethan" }, { "context": " and executing.\"\n :author \"Isoraķatheð Zorethan <[email protected]>\"\n :license \"MIT\"\n :version \"0.0.1\"\n :serial ", "end": 174, "score": 0.9999309778213501, "start": 143, "tag": "EMAIL", "value": "[email protected]" } ]
sclript.asd
isoraqathedh/sclript
5
;;;; sclript.asd (asdf:defsystem #:sclript :description "Common library for script reading and executing." :author "Isoraķatheð Zorethan <[email protected]>" :license "MIT" :version "0.0.1" :serial t :components ((:file "package") (:file "sclript")))
31221
;;;; sclript.asd (asdf:defsystem #:sclript :description "Common library for script reading and executing." :author "<NAME> <<EMAIL>>" :license "MIT" :version "0.0.1" :serial t :components ((:file "package") (:file "sclript")))
true
;;;; sclript.asd (asdf:defsystem #:sclript :description "Common library for script reading and executing." :author "PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>" :license "MIT" :version "0.0.1" :serial t :components ((:file "package") (:file "sclript")))
[ { "context": "anteau\n :description \"cl-portmanteau\"\n :author \"Sergey Polzunov <[email protected]>\"\n :license \"OSI approved 3", "end": 88, "score": 0.9998884201049805, "start": 73, "tag": "NAME", "value": "Sergey Polzunov" }, { "context": "tion \"cl-portmanteau\"\n :author \"Sergey Polzunov <[email protected]>\"\n :license \"OSI approved 3-clause 'New BSD Lice", "end": 109, "score": 0.9999251365661621, "start": 90, "tag": "EMAIL", "value": "[email protected]" } ]
portmanteau.asd
traut/cl-portmanteau
1
(asdf:defsystem #:portmanteau :description "cl-portmanteau" :author "Sergey Polzunov <[email protected]>" :license "OSI approved 3-clause 'New BSD License'" :in-order-to ((test-op (test-op #:portmanteau-tests))) :depends-on (#:vom) :serial t :components ((:file "portmanteau")))
23062
(asdf:defsystem #:portmanteau :description "cl-portmanteau" :author "<NAME> <<EMAIL>>" :license "OSI approved 3-clause 'New BSD License'" :in-order-to ((test-op (test-op #:portmanteau-tests))) :depends-on (#:vom) :serial t :components ((:file "portmanteau")))
true
(asdf:defsystem #:portmanteau :description "cl-portmanteau" :author "PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>" :license "OSI approved 3-clause 'New BSD License'" :in-order-to ((test-op (test-op #:portmanteau-tests))) :depends-on (#:vom) :serial t :components ((:file "portmanteau")))
[ { "context": "isp\n\n;;;; Copyright (c) 2012 -- 2014 \"the Phoeron\" Colin J.E. Lupton <//thephoeron.com>\n;;;; See LICENSE for additiona", "end": 161, "score": 0.9998674392700195, "start": 144, "tag": "NAME", "value": "Colin J.E. Lupton" } ]
web.lisp
thephoeron/REDSHIFTNET
2
;;;; -*- Mode: LISP; Syntax: COMMON-LISP; Package: REDSHIFTNET; Base: 10 -*- ;;;; file: web.lisp ;;;; Copyright (c) 2012 -- 2014 "the Phoeron" Colin J.E. Lupton <//thephoeron.com> ;;;; See LICENSE for additional information. (in-package :redshiftnet) ;;;; Default Splash Page (define-easy-handler (splash-page :uri "/") () (cl-who:with-html-output-to-string (s) (:html (:head (:title "REDSHIFTNET") (:link :rel "stylesheet" :href "/static/css/parallax.styles.css") (:link :rel "stylesheet" :href "/rsn-splash-page.css" :type "text/css" :media "screen")) (:body :style "border: 0; padding: 0; margin: 0; overflow: hidden;" ;:onLoad "init();" (:div :id "fullxy" (:ul :id "scene" (:li :class "layer" :data-depth "0.10" (:img :id "starfield" :src "/static/images/red-starfield-1920x1200.jpg")) (:li :class "layer" :data-depth "0.40" (:canvas :id "theMatrix")) (:li :class "layer" :data-depth "0.50" (:table :style "width: 100%; height: 100%; display: block; margin-top: 10%; margin-left: 0;" (:tr (:td :style "width: 100%; height: 100%; text-align: center; vertical-align: middle;" (:img :id "logo" :src "/static/images/black-sun.png" :align "center" :style "height: 640px; width: auto; margin: auto; opacity: 0.75;"))))) (:li :class "layer" :data-depth "0.80" (:table :style "width: 100%; height: 100%; display: block; margin-top: 10%; margin-left: 0;" (:tr (:td :style "width: 100%; height: 100%; text-align: center; vertical-align: middle;" (:img :src "/static/images/redshiftnet_text_logo_big.png" :align "center" :style "width: 960px; height: auto; margin: auto;"))))))) (:div :id "copyright" :style "position: fixed; bottom: 0; height: 75px; width: 100%; color: #AF0000;" (:p :align "center" (:a :href "http://common-lisp.net" :class "tip" :title "Crafted in Common Lisp" (str (format nil "(~C)" #\GREEK_SMALL_LETTER_LAMDA))) :br "Copyright &copy; 2012 &mdash; 2013, \"the Phoeron\" (//thephoeron.com/) &mdash; All Rights Reserved. " "Powered by " (:a :href "http://www.sbcl.org/" :target "_blank" (fmt "~A" (lisp-implementation-type))) " " (fmt "v~A, " (lisp-implementation-version)) "and " (:a :href "http://redshiftnet.com/" :target "_blank" (fmt "~A" (server-type))) " " (fmt "v~A." (server-version)) :br (:a :href "http://www.catb.org/hacker-emblem/" (:img :src "/static/images/hacker.png" :alt "hacker emblem web badge" :class "emblem")) (:a :href "http://www.lisp.org/" (:img :src "/static/images/lambda-lisp.png" :alt "lambda lisp web badge" :class "emblem")) (:a :href "http://www.common-lisp.org/" (:img :src "/static/images/lisp-lizard.png" :alt "lizard lisp web badge" :class "emblem")) (:a :href "http://www.webfaction.com/?affiliate=thephoeron" :target "_blank" (:img :src "/static/images/webfaction.png" :class "emblem" :alt "WebFaction -- Smarter Web Hosting")) )) (:script :type "text/javascript" :src "https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js") (:script :type "text/javascript" :src "//jqueryrotate.googlecode.com/svn/trunk/jQueryRotate.js") (:script :type "text/javascript" :src "/static/js/parallax/deploy/jquery.parallax.min.js") (:script :type "text/javascript" :src "/js/redshiftnet.js") (:script :type "text/javascript" :src "/static/js/redbinarymatrix.js") (:script :type "text/javascript" "$('#scene').parallax(); var rotation = function (){ $('#logo').rotate({ angle:0, animateTo:360, callback: rotation, duration: 49000, easing: function (x,t,b,c,d){ // t: current time, b: begInnIng value, c: change In value, d: duration return c*(t/d)+b; } }); } rotation();"))))) ;; EOF
75715
;;;; -*- Mode: LISP; Syntax: COMMON-LISP; Package: REDSHIFTNET; Base: 10 -*- ;;;; file: web.lisp ;;;; Copyright (c) 2012 -- 2014 "the Phoeron" <NAME> <//thephoeron.com> ;;;; See LICENSE for additional information. (in-package :redshiftnet) ;;;; Default Splash Page (define-easy-handler (splash-page :uri "/") () (cl-who:with-html-output-to-string (s) (:html (:head (:title "REDSHIFTNET") (:link :rel "stylesheet" :href "/static/css/parallax.styles.css") (:link :rel "stylesheet" :href "/rsn-splash-page.css" :type "text/css" :media "screen")) (:body :style "border: 0; padding: 0; margin: 0; overflow: hidden;" ;:onLoad "init();" (:div :id "fullxy" (:ul :id "scene" (:li :class "layer" :data-depth "0.10" (:img :id "starfield" :src "/static/images/red-starfield-1920x1200.jpg")) (:li :class "layer" :data-depth "0.40" (:canvas :id "theMatrix")) (:li :class "layer" :data-depth "0.50" (:table :style "width: 100%; height: 100%; display: block; margin-top: 10%; margin-left: 0;" (:tr (:td :style "width: 100%; height: 100%; text-align: center; vertical-align: middle;" (:img :id "logo" :src "/static/images/black-sun.png" :align "center" :style "height: 640px; width: auto; margin: auto; opacity: 0.75;"))))) (:li :class "layer" :data-depth "0.80" (:table :style "width: 100%; height: 100%; display: block; margin-top: 10%; margin-left: 0;" (:tr (:td :style "width: 100%; height: 100%; text-align: center; vertical-align: middle;" (:img :src "/static/images/redshiftnet_text_logo_big.png" :align "center" :style "width: 960px; height: auto; margin: auto;"))))))) (:div :id "copyright" :style "position: fixed; bottom: 0; height: 75px; width: 100%; color: #AF0000;" (:p :align "center" (:a :href "http://common-lisp.net" :class "tip" :title "Crafted in Common Lisp" (str (format nil "(~C)" #\GREEK_SMALL_LETTER_LAMDA))) :br "Copyright &copy; 2012 &mdash; 2013, \"the Phoeron\" (//thephoeron.com/) &mdash; All Rights Reserved. " "Powered by " (:a :href "http://www.sbcl.org/" :target "_blank" (fmt "~A" (lisp-implementation-type))) " " (fmt "v~A, " (lisp-implementation-version)) "and " (:a :href "http://redshiftnet.com/" :target "_blank" (fmt "~A" (server-type))) " " (fmt "v~A." (server-version)) :br (:a :href "http://www.catb.org/hacker-emblem/" (:img :src "/static/images/hacker.png" :alt "hacker emblem web badge" :class "emblem")) (:a :href "http://www.lisp.org/" (:img :src "/static/images/lambda-lisp.png" :alt "lambda lisp web badge" :class "emblem")) (:a :href "http://www.common-lisp.org/" (:img :src "/static/images/lisp-lizard.png" :alt "lizard lisp web badge" :class "emblem")) (:a :href "http://www.webfaction.com/?affiliate=thephoeron" :target "_blank" (:img :src "/static/images/webfaction.png" :class "emblem" :alt "WebFaction -- Smarter Web Hosting")) )) (:script :type "text/javascript" :src "https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js") (:script :type "text/javascript" :src "//jqueryrotate.googlecode.com/svn/trunk/jQueryRotate.js") (:script :type "text/javascript" :src "/static/js/parallax/deploy/jquery.parallax.min.js") (:script :type "text/javascript" :src "/js/redshiftnet.js") (:script :type "text/javascript" :src "/static/js/redbinarymatrix.js") (:script :type "text/javascript" "$('#scene').parallax(); var rotation = function (){ $('#logo').rotate({ angle:0, animateTo:360, callback: rotation, duration: 49000, easing: function (x,t,b,c,d){ // t: current time, b: begInnIng value, c: change In value, d: duration return c*(t/d)+b; } }); } rotation();"))))) ;; EOF
true
;;;; -*- Mode: LISP; Syntax: COMMON-LISP; Package: REDSHIFTNET; Base: 10 -*- ;;;; file: web.lisp ;;;; Copyright (c) 2012 -- 2014 "the Phoeron" PI:NAME:<NAME>END_PI <//thephoeron.com> ;;;; See LICENSE for additional information. (in-package :redshiftnet) ;;;; Default Splash Page (define-easy-handler (splash-page :uri "/") () (cl-who:with-html-output-to-string (s) (:html (:head (:title "REDSHIFTNET") (:link :rel "stylesheet" :href "/static/css/parallax.styles.css") (:link :rel "stylesheet" :href "/rsn-splash-page.css" :type "text/css" :media "screen")) (:body :style "border: 0; padding: 0; margin: 0; overflow: hidden;" ;:onLoad "init();" (:div :id "fullxy" (:ul :id "scene" (:li :class "layer" :data-depth "0.10" (:img :id "starfield" :src "/static/images/red-starfield-1920x1200.jpg")) (:li :class "layer" :data-depth "0.40" (:canvas :id "theMatrix")) (:li :class "layer" :data-depth "0.50" (:table :style "width: 100%; height: 100%; display: block; margin-top: 10%; margin-left: 0;" (:tr (:td :style "width: 100%; height: 100%; text-align: center; vertical-align: middle;" (:img :id "logo" :src "/static/images/black-sun.png" :align "center" :style "height: 640px; width: auto; margin: auto; opacity: 0.75;"))))) (:li :class "layer" :data-depth "0.80" (:table :style "width: 100%; height: 100%; display: block; margin-top: 10%; margin-left: 0;" (:tr (:td :style "width: 100%; height: 100%; text-align: center; vertical-align: middle;" (:img :src "/static/images/redshiftnet_text_logo_big.png" :align "center" :style "width: 960px; height: auto; margin: auto;"))))))) (:div :id "copyright" :style "position: fixed; bottom: 0; height: 75px; width: 100%; color: #AF0000;" (:p :align "center" (:a :href "http://common-lisp.net" :class "tip" :title "Crafted in Common Lisp" (str (format nil "(~C)" #\GREEK_SMALL_LETTER_LAMDA))) :br "Copyright &copy; 2012 &mdash; 2013, \"the Phoeron\" (//thephoeron.com/) &mdash; All Rights Reserved. " "Powered by " (:a :href "http://www.sbcl.org/" :target "_blank" (fmt "~A" (lisp-implementation-type))) " " (fmt "v~A, " (lisp-implementation-version)) "and " (:a :href "http://redshiftnet.com/" :target "_blank" (fmt "~A" (server-type))) " " (fmt "v~A." (server-version)) :br (:a :href "http://www.catb.org/hacker-emblem/" (:img :src "/static/images/hacker.png" :alt "hacker emblem web badge" :class "emblem")) (:a :href "http://www.lisp.org/" (:img :src "/static/images/lambda-lisp.png" :alt "lambda lisp web badge" :class "emblem")) (:a :href "http://www.common-lisp.org/" (:img :src "/static/images/lisp-lizard.png" :alt "lizard lisp web badge" :class "emblem")) (:a :href "http://www.webfaction.com/?affiliate=thephoeron" :target "_blank" (:img :src "/static/images/webfaction.png" :class "emblem" :alt "WebFaction -- Smarter Web Hosting")) )) (:script :type "text/javascript" :src "https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js") (:script :type "text/javascript" :src "//jqueryrotate.googlecode.com/svn/trunk/jQueryRotate.js") (:script :type "text/javascript" :src "/static/js/parallax/deploy/jquery.parallax.min.js") (:script :type "text/javascript" :src "/js/redshiftnet.js") (:script :type "text/javascript" :src "/static/js/redbinarymatrix.js") (:script :type "text/javascript" "$('#scene').parallax(); var rotation = function (){ $('#logo').rotate({ angle:0, animateTo:360, callback: rotation, duration: 49000, easing: function (x,t,b,c,d){ // t: current time, b: begInnIng value, c: change In value, d: duration return c*(t/d)+b; } }); } rotation();"))))) ;; EOF
[ { "context": "(defun test-usti ()\n (=wait ((ans))\n (send \"[email protected]\"\n `(send ,(usti =wait-cont) 15))\n (", "end": 12451, "score": 0.9998777508735657, "start": 12434, "tag": "EMAIL", "value": "[email protected]" } ]
Actors/actor-bridge.lisp
dbmcclain/Lisp-Actors
43
;; actor-bridge.lisp -- The bridge needed to allow Actors to remotely interact ;; ;; When an Actor target is a string specified as ;; "service@ip-addr:port" this package re-routes the SEND/ASK to a ;; socket interface, connecting first to a remote server if needed. ;; ;; Keeps a local record of pending callbacks, and serializes them by ;; using a unique string for remote reference. ;; ;; DM/RAL 10/20 ;; ----------------------------------------------------------------------------- (in-package :actors/bridge) (eval-when (:compile-toplevel :load-toplevel :execute) (import '( um:if-let um:when-let um:recover-ans-or-exn actors/network:open-connection actors/network:socket-send ))) ;; --------------------------------------------------------------------------------- ;; The "Bridge" - a resident agent for transparent SEND/ASK across a ;; network connection to foreign Actors. A foreign Actor is identified ;; by IP Addr, Port, and Service name - aka PROXY, ;; ;; When a network connection becomes established, an entry is made in ;; the DESTS map, relating the stated IP Addr with the Actor ;; responsible for comms across that connection. ;; ;; When a caller wants to send a message across the network ;; connection, and include a reply-to callback, it must represent that ;; callback closure using a UUID. The foreign system can forward reply ;; SENDS to that closure using the UUID. Back at the original sender ;; side, that UUID can be translated back into the actual closure code ;; to perform. ;; ;; Users can produce UUID -> Continuation mappings for other purposes ;; than a reply-to address. In that case, the Handler will be NIL. ;; ;; These UUID -> Continuation mappings are ephemeral, being removed ;; from the map upon invocation. ;; (define-actor-class actor-bridge () ((conts ;; mapping UUID -> (Network Intf, Continuation) ;; Network Intf = Connecction handling Actor, or NIL ;; Continuation = lambda closure :accessor actor-bridge-conts :initform (maps:empty)) (dests ;; mapping IP Addr -> Network Intf ;; IP Addr = upper case string ;; Network Intf = Connection handling Actor :accessor actor-bridge-dests :initform (maps:empty)) )) (defglobal-var *bridge* (make-instance 'actor-bridge)) (defmacro in-bridge (slots &body body) `(perform-in-actor *bridge* (with-slots ,slots *bridge* ,@body))) (defmacro ask-bridge (slots &body body) `(query-actor *bridge* (with-slots ,slots *bridge* ,@body))) ;; -------------------------------------------------------------------------------- ;; Actor PROXY addresses (defun parse-destination (dest) (check-type dest string) (let ((pos-at (position #\@ dest)) (pos-colon (position #\: dest)) start service ip-addr ip-port) (if pos-at (setf service (string-upcase (subseq dest 0 pos-at)) start (1+ pos-at)) (setf start 0)) (if pos-colon (setf ip-addr (string-upcase (subseq dest start (- pos-colon start))) ip-port (parse-integer (subseq dest (1+ pos-colon)))) (setf ip-addr (string-upcase (subseq dest start)))) (values service ip-addr ip-port))) (defstruct (proxy (:constructor %make-proxy)) (ip nil :read-only t) (port nil :read-only t) (service nil :read-only t)) (defun make-proxy (&key ip port service addr) (when addr (multiple-value-bind (aservice aip aport) (parse-destination addr) (setf ip aip port aport service aservice))) (%make-proxy :ip (string-upcase (or ip (machine-instance))) :port (etypecase port (null nil) (integer port) (string (parse-integer port))) :service (etypecase service (null (error "Service must be provided")) (symbol (string service)) (string (string-upcase service)) (uuid:uuid service)))) ;; ------------------------------------------- ;; Bridge Actor internal functions (defun find-handler (dest-ip dest-port) ;; Find and return the Network Handler Actor for a stated IP ;; Address. If not present in the map, then try to open a connection ;; to the server at that IP Addr. If a connection can be opened, it ;; will self-register in this map. (or (maps:find (actor-bridge-dests (current-actor)) dest-ip) (open-connection dest-ip dest-port))) (defun call-with-valid-ip (service ip port fn) ;; Find or create a connection Actor for the IP Addr. If successful, ;; then execute the fn with the service and connection handler Actor ;; as arguments. (when (and service ip) (when-let (handler (find-handler ip port)) (funcall fn service handler)))) (defgeneric call-with-valid-dest (dest fn) (:method ((dest string) fn) (multiple-value-bind (service dest-ip dest-port) (parse-destination dest) (call-with-valid-ip service dest-ip dest-port fn))) (:method ((dest proxy) fn) (with-slots (service ip port) dest (call-with-valid-ip service ip port fn)))) (defmacro with-valid-dest ((service handler) dest &body body) `(call-with-valid-dest ,dest (lambda (,service ,handler) ,@body))) (defun find-and-remove-usti (usti) ;; find the indicated continuation closure and remove its mapping ;; before sending it back to the caller (with-slots (conts) *bridge* (when-let (cont (second (maps:find conts usti))) (maps:removef conts usti) cont))) (defun create-and-add-usti (obj &optional handler) ;; construct an ephemeral UUID -> Continuation mapping, including ;; the handler if specified. Return the UUID representing the ;; continuation for the other side of the connection. (with-slots (conts) *bridge* (let ((usti (uuid:make-v1-uuid))) (maps:addf conts usti (list handler obj)) usti))) ;; --------------------------------------------------------------------- ;; Register / Connect to socket handler (defun bridge-register (ip-addr handler) ;; called by socket handler to register a new connection (in-bridge (dests) (maps:addf dests (string-upcase ip-addr) handler) )) (defun bridge-unregister (handler) ;; called by socket handler on socket shutdown to remove all ;; mappings that indicate the handler Actor (in-bridge (dests conts) (maps:iter dests (lambda (k v) (when (eq handler v) (maps:removef dests k)))) (maps:iter conts (lambda (k v) (when (eq handler (first v)) (maps:removef conts k)))) )) (defun bridge-reset () ;; called when *all* socket I/O is shutdown (in-bridge (dests conts) (setf conts (maps:empty) dests (maps:empty)) )) ;; ----------------------------------------------------------------------- (defun forward-query (handler service cont &rest msg) ;; we should already be running in Bridge (let ((usti (create-and-add-usti cont handler))) (apply #'socket-send handler 'actors/internal-message/bridge:forwarding-ask service usti msg))) (defun bridge-forward-message (dest &rest msg) ;; called by SEND as a last resort (in-bridge () (with-valid-dest (service handler) dest (case (car msg) ((actors/internal-message:ask) ;; form was (ASK reply-to &rest actual-message) (apply #'forward-query handler service (cdr msg))) (otherwise (apply #'socket-send handler 'actors/internal-message/bridge:forwarding-send service msg)) )))) (=defun bridge-ask-query (dest &rest msg) ;; called by ASK as a last resort (in-bridge () (with-valid-dest (service handler) dest (apply #'forward-query handler service =bind-cont msg) ))) (defun bridge-handle-reply (usti &rest reply) ;; called by socket handler when a reply arrives (in-bridge () (when-let (cont (find-and-remove-usti usti)) (apply cont reply)))) ;; ----------------------------------------------------------------------- ;; Default services: ECHO and EVAL (register-actor :echo (make-actor (lambda (&rest msg) msg))) ;; ----------------------------------------------------------------- (defun cmpfn (&rest args) (compile nil `(lambda () ,@args))) (register-actor :eval (make-actor (lambda (&rest msg) (funcall (apply #'cmpfn msg))))) ;; ---------------------------------------------------------------------- ;; SEND across network connections - never blocks. (defmethod send ((str string) &rest message) (let (actor) (cond ((setf actor (find-actor str)) (apply #'send actor message)) ((find #\@ str) (apply #'bridge-forward-message str message)) (t (call-next-method)) ))) (defmethod send ((usti uuid:uuid) &rest message) (if-let (actor (find-actor usti)) (apply #'send actor message) (call-next-method))) (defmethod send ((proxy proxy) &rest message) (apply #'bridge-forward-message proxy message)) ;; ------------------------------------------ ;; Blocking ASK across network connections (defun network-ask (dest &rest message) ;; Blocking ASK across a network connection (=wait ((ans) :timeout *timeout* :errorp t) (=apply #'bridge-ask-query dest message) (recover-ans-or-exn ans))) (defmethod ask ((str string) &rest message) (let (actor) (cond ((setf actor (find-actor str)) (apply #'ask actor message)) ((find #\@ str) (apply #'network-ask str message)) (t (call-next-method)) ))) (defmethod ask ((usti uuid:uuid) &rest message) (if-let (actor (find-actor usti)) (apply #'ask actor message) (call-next-method))) (defmethod ask ((proxy proxy) &rest message) (apply #'network-ask proxy message)) ;; ----------------------------------------------- ;; Non-blocking ASK across network connections (=defun network-ask-nb (dest &rest message) ;; Non-blocking ASK across a network connection (=bind (ans) (=apply #'bridge-ask-query dest message) (=values (recover-ans-or-exn ans)))) (=defmethod =ask ((str string) &rest message) (let (actor) (cond ((setf actor (find-actor str)) (=apply #'=ask actor message)) ((find #\@ str) (=apply #'network-ask-nb str message)) (t (call-next-method)) ))) (=defmethod =ask ((usti uuid:uuid) &rest message) (if-let (actor (find-actor usti)) (=apply #'=ask actor message) (call-next-method))) (=defmethod =ask ((proxy proxy) &rest message) (=apply #'network-ask-nb proxy message)) ;; -------------------------------------------------------------------------------- ;; USTI - Universal Send-Target Identifier ;; ;; While ASK uses a known syntax, where the reply-to field is in a ;; known position of the message, and the Bridge takes care of ;; translating that into a USTI for network transmission, we need ;; something else for general messages that may contain a callback to ;; some closure or mailbox. ;; ;; In that case, it is up to the caller to form an explicit USTI in ;; the message, which will be looked up on return. ;; ;; Here we use UUID's for USTI's. UUID's have a very short network ;; encoding, compared to some struct that would enclose a UUID to ;; serve as a USTI type envelope. Since USTI's are only used as ;; targets of SEND across a network connection, it seems reasonable to ;; just use UUID's here. (defgeneric usti (obj) (:method ((obj proxy)) obj) (:method ((obj string)) (make-proxy :service obj)) (:method ((obj symbol)) (make-proxy :service obj)) (:method ((obj uuid:uuid)) (make-proxy :service obj)) (:method ((obj actor)) (make-proxy :service (ensured-identifier obj))) (:method (obj) (make-proxy :service (ask-bridge () (create-and-add-usti obj)) ))) (defmethod find-actor ((usti uuid:uuid)) (or (when (uuid:one-of-mine? usti) (ask-bridge () (find-and-remove-usti usti))) (call-next-method))) #| (defun test-usti () (=wait ((ans)) (send "[email protected]" `(send ,(usti =wait-cont) 15)) (print ans))) (test-usti) |#
61956
;; actor-bridge.lisp -- The bridge needed to allow Actors to remotely interact ;; ;; When an Actor target is a string specified as ;; "service@ip-addr:port" this package re-routes the SEND/ASK to a ;; socket interface, connecting first to a remote server if needed. ;; ;; Keeps a local record of pending callbacks, and serializes them by ;; using a unique string for remote reference. ;; ;; DM/RAL 10/20 ;; ----------------------------------------------------------------------------- (in-package :actors/bridge) (eval-when (:compile-toplevel :load-toplevel :execute) (import '( um:if-let um:when-let um:recover-ans-or-exn actors/network:open-connection actors/network:socket-send ))) ;; --------------------------------------------------------------------------------- ;; The "Bridge" - a resident agent for transparent SEND/ASK across a ;; network connection to foreign Actors. A foreign Actor is identified ;; by IP Addr, Port, and Service name - aka PROXY, ;; ;; When a network connection becomes established, an entry is made in ;; the DESTS map, relating the stated IP Addr with the Actor ;; responsible for comms across that connection. ;; ;; When a caller wants to send a message across the network ;; connection, and include a reply-to callback, it must represent that ;; callback closure using a UUID. The foreign system can forward reply ;; SENDS to that closure using the UUID. Back at the original sender ;; side, that UUID can be translated back into the actual closure code ;; to perform. ;; ;; Users can produce UUID -> Continuation mappings for other purposes ;; than a reply-to address. In that case, the Handler will be NIL. ;; ;; These UUID -> Continuation mappings are ephemeral, being removed ;; from the map upon invocation. ;; (define-actor-class actor-bridge () ((conts ;; mapping UUID -> (Network Intf, Continuation) ;; Network Intf = Connecction handling Actor, or NIL ;; Continuation = lambda closure :accessor actor-bridge-conts :initform (maps:empty)) (dests ;; mapping IP Addr -> Network Intf ;; IP Addr = upper case string ;; Network Intf = Connection handling Actor :accessor actor-bridge-dests :initform (maps:empty)) )) (defglobal-var *bridge* (make-instance 'actor-bridge)) (defmacro in-bridge (slots &body body) `(perform-in-actor *bridge* (with-slots ,slots *bridge* ,@body))) (defmacro ask-bridge (slots &body body) `(query-actor *bridge* (with-slots ,slots *bridge* ,@body))) ;; -------------------------------------------------------------------------------- ;; Actor PROXY addresses (defun parse-destination (dest) (check-type dest string) (let ((pos-at (position #\@ dest)) (pos-colon (position #\: dest)) start service ip-addr ip-port) (if pos-at (setf service (string-upcase (subseq dest 0 pos-at)) start (1+ pos-at)) (setf start 0)) (if pos-colon (setf ip-addr (string-upcase (subseq dest start (- pos-colon start))) ip-port (parse-integer (subseq dest (1+ pos-colon)))) (setf ip-addr (string-upcase (subseq dest start)))) (values service ip-addr ip-port))) (defstruct (proxy (:constructor %make-proxy)) (ip nil :read-only t) (port nil :read-only t) (service nil :read-only t)) (defun make-proxy (&key ip port service addr) (when addr (multiple-value-bind (aservice aip aport) (parse-destination addr) (setf ip aip port aport service aservice))) (%make-proxy :ip (string-upcase (or ip (machine-instance))) :port (etypecase port (null nil) (integer port) (string (parse-integer port))) :service (etypecase service (null (error "Service must be provided")) (symbol (string service)) (string (string-upcase service)) (uuid:uuid service)))) ;; ------------------------------------------- ;; Bridge Actor internal functions (defun find-handler (dest-ip dest-port) ;; Find and return the Network Handler Actor for a stated IP ;; Address. If not present in the map, then try to open a connection ;; to the server at that IP Addr. If a connection can be opened, it ;; will self-register in this map. (or (maps:find (actor-bridge-dests (current-actor)) dest-ip) (open-connection dest-ip dest-port))) (defun call-with-valid-ip (service ip port fn) ;; Find or create a connection Actor for the IP Addr. If successful, ;; then execute the fn with the service and connection handler Actor ;; as arguments. (when (and service ip) (when-let (handler (find-handler ip port)) (funcall fn service handler)))) (defgeneric call-with-valid-dest (dest fn) (:method ((dest string) fn) (multiple-value-bind (service dest-ip dest-port) (parse-destination dest) (call-with-valid-ip service dest-ip dest-port fn))) (:method ((dest proxy) fn) (with-slots (service ip port) dest (call-with-valid-ip service ip port fn)))) (defmacro with-valid-dest ((service handler) dest &body body) `(call-with-valid-dest ,dest (lambda (,service ,handler) ,@body))) (defun find-and-remove-usti (usti) ;; find the indicated continuation closure and remove its mapping ;; before sending it back to the caller (with-slots (conts) *bridge* (when-let (cont (second (maps:find conts usti))) (maps:removef conts usti) cont))) (defun create-and-add-usti (obj &optional handler) ;; construct an ephemeral UUID -> Continuation mapping, including ;; the handler if specified. Return the UUID representing the ;; continuation for the other side of the connection. (with-slots (conts) *bridge* (let ((usti (uuid:make-v1-uuid))) (maps:addf conts usti (list handler obj)) usti))) ;; --------------------------------------------------------------------- ;; Register / Connect to socket handler (defun bridge-register (ip-addr handler) ;; called by socket handler to register a new connection (in-bridge (dests) (maps:addf dests (string-upcase ip-addr) handler) )) (defun bridge-unregister (handler) ;; called by socket handler on socket shutdown to remove all ;; mappings that indicate the handler Actor (in-bridge (dests conts) (maps:iter dests (lambda (k v) (when (eq handler v) (maps:removef dests k)))) (maps:iter conts (lambda (k v) (when (eq handler (first v)) (maps:removef conts k)))) )) (defun bridge-reset () ;; called when *all* socket I/O is shutdown (in-bridge (dests conts) (setf conts (maps:empty) dests (maps:empty)) )) ;; ----------------------------------------------------------------------- (defun forward-query (handler service cont &rest msg) ;; we should already be running in Bridge (let ((usti (create-and-add-usti cont handler))) (apply #'socket-send handler 'actors/internal-message/bridge:forwarding-ask service usti msg))) (defun bridge-forward-message (dest &rest msg) ;; called by SEND as a last resort (in-bridge () (with-valid-dest (service handler) dest (case (car msg) ((actors/internal-message:ask) ;; form was (ASK reply-to &rest actual-message) (apply #'forward-query handler service (cdr msg))) (otherwise (apply #'socket-send handler 'actors/internal-message/bridge:forwarding-send service msg)) )))) (=defun bridge-ask-query (dest &rest msg) ;; called by ASK as a last resort (in-bridge () (with-valid-dest (service handler) dest (apply #'forward-query handler service =bind-cont msg) ))) (defun bridge-handle-reply (usti &rest reply) ;; called by socket handler when a reply arrives (in-bridge () (when-let (cont (find-and-remove-usti usti)) (apply cont reply)))) ;; ----------------------------------------------------------------------- ;; Default services: ECHO and EVAL (register-actor :echo (make-actor (lambda (&rest msg) msg))) ;; ----------------------------------------------------------------- (defun cmpfn (&rest args) (compile nil `(lambda () ,@args))) (register-actor :eval (make-actor (lambda (&rest msg) (funcall (apply #'cmpfn msg))))) ;; ---------------------------------------------------------------------- ;; SEND across network connections - never blocks. (defmethod send ((str string) &rest message) (let (actor) (cond ((setf actor (find-actor str)) (apply #'send actor message)) ((find #\@ str) (apply #'bridge-forward-message str message)) (t (call-next-method)) ))) (defmethod send ((usti uuid:uuid) &rest message) (if-let (actor (find-actor usti)) (apply #'send actor message) (call-next-method))) (defmethod send ((proxy proxy) &rest message) (apply #'bridge-forward-message proxy message)) ;; ------------------------------------------ ;; Blocking ASK across network connections (defun network-ask (dest &rest message) ;; Blocking ASK across a network connection (=wait ((ans) :timeout *timeout* :errorp t) (=apply #'bridge-ask-query dest message) (recover-ans-or-exn ans))) (defmethod ask ((str string) &rest message) (let (actor) (cond ((setf actor (find-actor str)) (apply #'ask actor message)) ((find #\@ str) (apply #'network-ask str message)) (t (call-next-method)) ))) (defmethod ask ((usti uuid:uuid) &rest message) (if-let (actor (find-actor usti)) (apply #'ask actor message) (call-next-method))) (defmethod ask ((proxy proxy) &rest message) (apply #'network-ask proxy message)) ;; ----------------------------------------------- ;; Non-blocking ASK across network connections (=defun network-ask-nb (dest &rest message) ;; Non-blocking ASK across a network connection (=bind (ans) (=apply #'bridge-ask-query dest message) (=values (recover-ans-or-exn ans)))) (=defmethod =ask ((str string) &rest message) (let (actor) (cond ((setf actor (find-actor str)) (=apply #'=ask actor message)) ((find #\@ str) (=apply #'network-ask-nb str message)) (t (call-next-method)) ))) (=defmethod =ask ((usti uuid:uuid) &rest message) (if-let (actor (find-actor usti)) (=apply #'=ask actor message) (call-next-method))) (=defmethod =ask ((proxy proxy) &rest message) (=apply #'network-ask-nb proxy message)) ;; -------------------------------------------------------------------------------- ;; USTI - Universal Send-Target Identifier ;; ;; While ASK uses a known syntax, where the reply-to field is in a ;; known position of the message, and the Bridge takes care of ;; translating that into a USTI for network transmission, we need ;; something else for general messages that may contain a callback to ;; some closure or mailbox. ;; ;; In that case, it is up to the caller to form an explicit USTI in ;; the message, which will be looked up on return. ;; ;; Here we use UUID's for USTI's. UUID's have a very short network ;; encoding, compared to some struct that would enclose a UUID to ;; serve as a USTI type envelope. Since USTI's are only used as ;; targets of SEND across a network connection, it seems reasonable to ;; just use UUID's here. (defgeneric usti (obj) (:method ((obj proxy)) obj) (:method ((obj string)) (make-proxy :service obj)) (:method ((obj symbol)) (make-proxy :service obj)) (:method ((obj uuid:uuid)) (make-proxy :service obj)) (:method ((obj actor)) (make-proxy :service (ensured-identifier obj))) (:method (obj) (make-proxy :service (ask-bridge () (create-and-add-usti obj)) ))) (defmethod find-actor ((usti uuid:uuid)) (or (when (uuid:one-of-mine? usti) (ask-bridge () (find-and-remove-usti usti))) (call-next-method))) #| (defun test-usti () (=wait ((ans)) (send "<EMAIL>" `(send ,(usti =wait-cont) 15)) (print ans))) (test-usti) |#
true
;; actor-bridge.lisp -- The bridge needed to allow Actors to remotely interact ;; ;; When an Actor target is a string specified as ;; "service@ip-addr:port" this package re-routes the SEND/ASK to a ;; socket interface, connecting first to a remote server if needed. ;; ;; Keeps a local record of pending callbacks, and serializes them by ;; using a unique string for remote reference. ;; ;; DM/RAL 10/20 ;; ----------------------------------------------------------------------------- (in-package :actors/bridge) (eval-when (:compile-toplevel :load-toplevel :execute) (import '( um:if-let um:when-let um:recover-ans-or-exn actors/network:open-connection actors/network:socket-send ))) ;; --------------------------------------------------------------------------------- ;; The "Bridge" - a resident agent for transparent SEND/ASK across a ;; network connection to foreign Actors. A foreign Actor is identified ;; by IP Addr, Port, and Service name - aka PROXY, ;; ;; When a network connection becomes established, an entry is made in ;; the DESTS map, relating the stated IP Addr with the Actor ;; responsible for comms across that connection. ;; ;; When a caller wants to send a message across the network ;; connection, and include a reply-to callback, it must represent that ;; callback closure using a UUID. The foreign system can forward reply ;; SENDS to that closure using the UUID. Back at the original sender ;; side, that UUID can be translated back into the actual closure code ;; to perform. ;; ;; Users can produce UUID -> Continuation mappings for other purposes ;; than a reply-to address. In that case, the Handler will be NIL. ;; ;; These UUID -> Continuation mappings are ephemeral, being removed ;; from the map upon invocation. ;; (define-actor-class actor-bridge () ((conts ;; mapping UUID -> (Network Intf, Continuation) ;; Network Intf = Connecction handling Actor, or NIL ;; Continuation = lambda closure :accessor actor-bridge-conts :initform (maps:empty)) (dests ;; mapping IP Addr -> Network Intf ;; IP Addr = upper case string ;; Network Intf = Connection handling Actor :accessor actor-bridge-dests :initform (maps:empty)) )) (defglobal-var *bridge* (make-instance 'actor-bridge)) (defmacro in-bridge (slots &body body) `(perform-in-actor *bridge* (with-slots ,slots *bridge* ,@body))) (defmacro ask-bridge (slots &body body) `(query-actor *bridge* (with-slots ,slots *bridge* ,@body))) ;; -------------------------------------------------------------------------------- ;; Actor PROXY addresses (defun parse-destination (dest) (check-type dest string) (let ((pos-at (position #\@ dest)) (pos-colon (position #\: dest)) start service ip-addr ip-port) (if pos-at (setf service (string-upcase (subseq dest 0 pos-at)) start (1+ pos-at)) (setf start 0)) (if pos-colon (setf ip-addr (string-upcase (subseq dest start (- pos-colon start))) ip-port (parse-integer (subseq dest (1+ pos-colon)))) (setf ip-addr (string-upcase (subseq dest start)))) (values service ip-addr ip-port))) (defstruct (proxy (:constructor %make-proxy)) (ip nil :read-only t) (port nil :read-only t) (service nil :read-only t)) (defun make-proxy (&key ip port service addr) (when addr (multiple-value-bind (aservice aip aport) (parse-destination addr) (setf ip aip port aport service aservice))) (%make-proxy :ip (string-upcase (or ip (machine-instance))) :port (etypecase port (null nil) (integer port) (string (parse-integer port))) :service (etypecase service (null (error "Service must be provided")) (symbol (string service)) (string (string-upcase service)) (uuid:uuid service)))) ;; ------------------------------------------- ;; Bridge Actor internal functions (defun find-handler (dest-ip dest-port) ;; Find and return the Network Handler Actor for a stated IP ;; Address. If not present in the map, then try to open a connection ;; to the server at that IP Addr. If a connection can be opened, it ;; will self-register in this map. (or (maps:find (actor-bridge-dests (current-actor)) dest-ip) (open-connection dest-ip dest-port))) (defun call-with-valid-ip (service ip port fn) ;; Find or create a connection Actor for the IP Addr. If successful, ;; then execute the fn with the service and connection handler Actor ;; as arguments. (when (and service ip) (when-let (handler (find-handler ip port)) (funcall fn service handler)))) (defgeneric call-with-valid-dest (dest fn) (:method ((dest string) fn) (multiple-value-bind (service dest-ip dest-port) (parse-destination dest) (call-with-valid-ip service dest-ip dest-port fn))) (:method ((dest proxy) fn) (with-slots (service ip port) dest (call-with-valid-ip service ip port fn)))) (defmacro with-valid-dest ((service handler) dest &body body) `(call-with-valid-dest ,dest (lambda (,service ,handler) ,@body))) (defun find-and-remove-usti (usti) ;; find the indicated continuation closure and remove its mapping ;; before sending it back to the caller (with-slots (conts) *bridge* (when-let (cont (second (maps:find conts usti))) (maps:removef conts usti) cont))) (defun create-and-add-usti (obj &optional handler) ;; construct an ephemeral UUID -> Continuation mapping, including ;; the handler if specified. Return the UUID representing the ;; continuation for the other side of the connection. (with-slots (conts) *bridge* (let ((usti (uuid:make-v1-uuid))) (maps:addf conts usti (list handler obj)) usti))) ;; --------------------------------------------------------------------- ;; Register / Connect to socket handler (defun bridge-register (ip-addr handler) ;; called by socket handler to register a new connection (in-bridge (dests) (maps:addf dests (string-upcase ip-addr) handler) )) (defun bridge-unregister (handler) ;; called by socket handler on socket shutdown to remove all ;; mappings that indicate the handler Actor (in-bridge (dests conts) (maps:iter dests (lambda (k v) (when (eq handler v) (maps:removef dests k)))) (maps:iter conts (lambda (k v) (when (eq handler (first v)) (maps:removef conts k)))) )) (defun bridge-reset () ;; called when *all* socket I/O is shutdown (in-bridge (dests conts) (setf conts (maps:empty) dests (maps:empty)) )) ;; ----------------------------------------------------------------------- (defun forward-query (handler service cont &rest msg) ;; we should already be running in Bridge (let ((usti (create-and-add-usti cont handler))) (apply #'socket-send handler 'actors/internal-message/bridge:forwarding-ask service usti msg))) (defun bridge-forward-message (dest &rest msg) ;; called by SEND as a last resort (in-bridge () (with-valid-dest (service handler) dest (case (car msg) ((actors/internal-message:ask) ;; form was (ASK reply-to &rest actual-message) (apply #'forward-query handler service (cdr msg))) (otherwise (apply #'socket-send handler 'actors/internal-message/bridge:forwarding-send service msg)) )))) (=defun bridge-ask-query (dest &rest msg) ;; called by ASK as a last resort (in-bridge () (with-valid-dest (service handler) dest (apply #'forward-query handler service =bind-cont msg) ))) (defun bridge-handle-reply (usti &rest reply) ;; called by socket handler when a reply arrives (in-bridge () (when-let (cont (find-and-remove-usti usti)) (apply cont reply)))) ;; ----------------------------------------------------------------------- ;; Default services: ECHO and EVAL (register-actor :echo (make-actor (lambda (&rest msg) msg))) ;; ----------------------------------------------------------------- (defun cmpfn (&rest args) (compile nil `(lambda () ,@args))) (register-actor :eval (make-actor (lambda (&rest msg) (funcall (apply #'cmpfn msg))))) ;; ---------------------------------------------------------------------- ;; SEND across network connections - never blocks. (defmethod send ((str string) &rest message) (let (actor) (cond ((setf actor (find-actor str)) (apply #'send actor message)) ((find #\@ str) (apply #'bridge-forward-message str message)) (t (call-next-method)) ))) (defmethod send ((usti uuid:uuid) &rest message) (if-let (actor (find-actor usti)) (apply #'send actor message) (call-next-method))) (defmethod send ((proxy proxy) &rest message) (apply #'bridge-forward-message proxy message)) ;; ------------------------------------------ ;; Blocking ASK across network connections (defun network-ask (dest &rest message) ;; Blocking ASK across a network connection (=wait ((ans) :timeout *timeout* :errorp t) (=apply #'bridge-ask-query dest message) (recover-ans-or-exn ans))) (defmethod ask ((str string) &rest message) (let (actor) (cond ((setf actor (find-actor str)) (apply #'ask actor message)) ((find #\@ str) (apply #'network-ask str message)) (t (call-next-method)) ))) (defmethod ask ((usti uuid:uuid) &rest message) (if-let (actor (find-actor usti)) (apply #'ask actor message) (call-next-method))) (defmethod ask ((proxy proxy) &rest message) (apply #'network-ask proxy message)) ;; ----------------------------------------------- ;; Non-blocking ASK across network connections (=defun network-ask-nb (dest &rest message) ;; Non-blocking ASK across a network connection (=bind (ans) (=apply #'bridge-ask-query dest message) (=values (recover-ans-or-exn ans)))) (=defmethod =ask ((str string) &rest message) (let (actor) (cond ((setf actor (find-actor str)) (=apply #'=ask actor message)) ((find #\@ str) (=apply #'network-ask-nb str message)) (t (call-next-method)) ))) (=defmethod =ask ((usti uuid:uuid) &rest message) (if-let (actor (find-actor usti)) (=apply #'=ask actor message) (call-next-method))) (=defmethod =ask ((proxy proxy) &rest message) (=apply #'network-ask-nb proxy message)) ;; -------------------------------------------------------------------------------- ;; USTI - Universal Send-Target Identifier ;; ;; While ASK uses a known syntax, where the reply-to field is in a ;; known position of the message, and the Bridge takes care of ;; translating that into a USTI for network transmission, we need ;; something else for general messages that may contain a callback to ;; some closure or mailbox. ;; ;; In that case, it is up to the caller to form an explicit USTI in ;; the message, which will be looked up on return. ;; ;; Here we use UUID's for USTI's. UUID's have a very short network ;; encoding, compared to some struct that would enclose a UUID to ;; serve as a USTI type envelope. Since USTI's are only used as ;; targets of SEND across a network connection, it seems reasonable to ;; just use UUID's here. (defgeneric usti (obj) (:method ((obj proxy)) obj) (:method ((obj string)) (make-proxy :service obj)) (:method ((obj symbol)) (make-proxy :service obj)) (:method ((obj uuid:uuid)) (make-proxy :service obj)) (:method ((obj actor)) (make-proxy :service (ensured-identifier obj))) (:method (obj) (make-proxy :service (ask-bridge () (create-and-add-usti obj)) ))) (defmethod find-actor ((usti uuid:uuid)) (or (when (uuid:one-of-mine? usti) (ask-bridge () (find-and-remove-usti usti))) (call-next-method))) #| (defun test-usti () (=wait ((ans)) (send "PI:EMAIL:<EMAIL>END_PI" `(send ,(usti =wait-cont) 15)) (print ans))) (test-usti) |#
[ { "context": "(defsystem \"specialization-store\"\n :author \"Mark Cox\"\n :description \"The specialization store system ", "end": 53, "score": 0.999844491481781, "start": 45, "tag": "NAME", "value": "Mark Cox" } ]
specialization-store.asd
markcox80/specialization-store
31
(defsystem "specialization-store" :author "Mark Cox" :description "The specialization store system provides a new kind of function, called a store function, whose behavior depends on the types of objects passed to the function." :depends-on ("specialization-store-features" "introspect-environment" "alexandria") :license "Simplified BSD License variant" :version "0.0.5" :serial t :components ((:module "src" :serial t :components ((:file "packages") (:file "common") (:file "lambda-lists") (:file "dispatch") (:file "dispatch-fixed-arity") (:file "dispatch-variable-arity") (:file "protocols") (:file "standard-store")))) :in-order-to ((test-op (test-op "specialization-store-tests"))))
66702
(defsystem "specialization-store" :author "<NAME>" :description "The specialization store system provides a new kind of function, called a store function, whose behavior depends on the types of objects passed to the function." :depends-on ("specialization-store-features" "introspect-environment" "alexandria") :license "Simplified BSD License variant" :version "0.0.5" :serial t :components ((:module "src" :serial t :components ((:file "packages") (:file "common") (:file "lambda-lists") (:file "dispatch") (:file "dispatch-fixed-arity") (:file "dispatch-variable-arity") (:file "protocols") (:file "standard-store")))) :in-order-to ((test-op (test-op "specialization-store-tests"))))
true
(defsystem "specialization-store" :author "PI:NAME:<NAME>END_PI" :description "The specialization store system provides a new kind of function, called a store function, whose behavior depends on the types of objects passed to the function." :depends-on ("specialization-store-features" "introspect-environment" "alexandria") :license "Simplified BSD License variant" :version "0.0.5" :serial t :components ((:module "src" :serial t :components ((:file "packages") (:file "common") (:file "lambda-lists") (:file "dispatch") (:file "dispatch-fixed-arity") (:file "dispatch-variable-arity") (:file "protocols") (:file "standard-store")))) :in-order-to ((test-op (test-op "specialization-store-tests"))))
[ { "context": "#|\nCopyright (c) 2016 Thomas W. Lynch and Reasoning Technology Inc.\nReleased under the ", "end": 37, "score": 0.9998486042022705, "start": 22, "tag": "NAME", "value": "Thomas W. Lynch" } ]
deprecated/src-list/list-haz-tm-type.lisp
Antigonus/tm
6
#| Copyright (c) 2016 Thomas W. Lynch and Reasoning Technology Inc. Released under the MIT License (MIT) See LICENSE.txt The haz machine is both a solo and an nd machine combined. |# (in-package #:tm) ;;-------------------------------------------------------------------------------- ;; a specialization ;; (def-type list-haz-tm (haz-tape-machine list-solo-tm list-nd-tm)())
91161
#| Copyright (c) 2016 <NAME> and Reasoning Technology Inc. Released under the MIT License (MIT) See LICENSE.txt The haz machine is both a solo and an nd machine combined. |# (in-package #:tm) ;;-------------------------------------------------------------------------------- ;; a specialization ;; (def-type list-haz-tm (haz-tape-machine list-solo-tm list-nd-tm)())
true
#| Copyright (c) 2016 PI:NAME:<NAME>END_PI and Reasoning Technology Inc. Released under the MIT License (MIT) See LICENSE.txt The haz machine is both a solo and an nd machine combined. |# (in-package #:tm) ;;-------------------------------------------------------------------------------- ;; a specialization ;; (def-type list-haz-tm (haz-tape-machine list-solo-tm list-nd-tm)())
[ { "context": ";;; (c) 2013-2017 Vsevolod Dyomkin\n\n(in-package #:nlp.util)\n(named-readtables:in-rea", "end": 34, "score": 0.999853789806366, "start": 18, "tag": "NAME", "value": "Vsevolod Dyomkin" } ]
src/util/misc.lisp
vseloved/cl-nlp
167
;;; (c) 2013-2017 Vsevolod Dyomkin (in-package #:nlp.util) (named-readtables:in-readtable rutilsx-readtable) (declaim (inline filler)) ;;; Some aliasing (rename-package "CL-PPCRE" "CL-PPCRE" '("PPCRE" "RE")) (define-condition nlp-error (simple-error) ()) (define-condition not-implemented-error (simple-error) ()) (defun ending-word-p (word) "Check if string WORD is some kind of a period char or a paragraph mark." (or (every 'period-char-p word) (string= "¶" word))) (defun filler (n &optional (fill-char #\Space)) "Produce an N-element filler string of FILL-CHAR's." (if (and (numberp n) (plusp n)) (make-string n :initial-element fill-char) "")) (defun shorter? (list n) "Tests if LIST has at least N elements." (let ((tail list)) (loop :repeat (1- n) :do (setf tail (cdr tail))) (null tail))) (defun uniq (seq &key raw (test 'equal)) "Return only unique elements from SEQ either as a new list or as hash-table if RAW is set. TEST should be a hash-table test." (let ((uniqs (make-hash-table :test test))) (etypecase seq (list (dolist (elt seq) (:+ (get# elt uniqs 0)))) (vector (dovec (elt seq) (:+ (get# elt uniqs 0))))) (if raw uniqs (ht-keys uniqs)))) (defun bound-equal (obj specimen) "Checks is OBJ has all the slots with values provided by SPECIMEN hash-table." (maphash ^(unless (equal (slot-value obj %) %%) (return-from bound-equal nil)) specimen)) (defun timestamp () "Return current timestamp as string." (mv-bind (sec min hour day month year) (decode-universal-time (get-universal-time)) (fmt "~A~2,'0D~2,'0D~2,'0D~2,'0D~2,'0D" year month day hour min sec))) (defgeneric ss (obj) (:documentation "Get a short string from an object") (:method (obj) (string obj)))
30296
;;; (c) 2013-2017 <NAME> (in-package #:nlp.util) (named-readtables:in-readtable rutilsx-readtable) (declaim (inline filler)) ;;; Some aliasing (rename-package "CL-PPCRE" "CL-PPCRE" '("PPCRE" "RE")) (define-condition nlp-error (simple-error) ()) (define-condition not-implemented-error (simple-error) ()) (defun ending-word-p (word) "Check if string WORD is some kind of a period char or a paragraph mark." (or (every 'period-char-p word) (string= "¶" word))) (defun filler (n &optional (fill-char #\Space)) "Produce an N-element filler string of FILL-CHAR's." (if (and (numberp n) (plusp n)) (make-string n :initial-element fill-char) "")) (defun shorter? (list n) "Tests if LIST has at least N elements." (let ((tail list)) (loop :repeat (1- n) :do (setf tail (cdr tail))) (null tail))) (defun uniq (seq &key raw (test 'equal)) "Return only unique elements from SEQ either as a new list or as hash-table if RAW is set. TEST should be a hash-table test." (let ((uniqs (make-hash-table :test test))) (etypecase seq (list (dolist (elt seq) (:+ (get# elt uniqs 0)))) (vector (dovec (elt seq) (:+ (get# elt uniqs 0))))) (if raw uniqs (ht-keys uniqs)))) (defun bound-equal (obj specimen) "Checks is OBJ has all the slots with values provided by SPECIMEN hash-table." (maphash ^(unless (equal (slot-value obj %) %%) (return-from bound-equal nil)) specimen)) (defun timestamp () "Return current timestamp as string." (mv-bind (sec min hour day month year) (decode-universal-time (get-universal-time)) (fmt "~A~2,'0D~2,'0D~2,'0D~2,'0D~2,'0D" year month day hour min sec))) (defgeneric ss (obj) (:documentation "Get a short string from an object") (:method (obj) (string obj)))
true
;;; (c) 2013-2017 PI:NAME:<NAME>END_PI (in-package #:nlp.util) (named-readtables:in-readtable rutilsx-readtable) (declaim (inline filler)) ;;; Some aliasing (rename-package "CL-PPCRE" "CL-PPCRE" '("PPCRE" "RE")) (define-condition nlp-error (simple-error) ()) (define-condition not-implemented-error (simple-error) ()) (defun ending-word-p (word) "Check if string WORD is some kind of a period char or a paragraph mark." (or (every 'period-char-p word) (string= "¶" word))) (defun filler (n &optional (fill-char #\Space)) "Produce an N-element filler string of FILL-CHAR's." (if (and (numberp n) (plusp n)) (make-string n :initial-element fill-char) "")) (defun shorter? (list n) "Tests if LIST has at least N elements." (let ((tail list)) (loop :repeat (1- n) :do (setf tail (cdr tail))) (null tail))) (defun uniq (seq &key raw (test 'equal)) "Return only unique elements from SEQ either as a new list or as hash-table if RAW is set. TEST should be a hash-table test." (let ((uniqs (make-hash-table :test test))) (etypecase seq (list (dolist (elt seq) (:+ (get# elt uniqs 0)))) (vector (dovec (elt seq) (:+ (get# elt uniqs 0))))) (if raw uniqs (ht-keys uniqs)))) (defun bound-equal (obj specimen) "Checks is OBJ has all the slots with values provided by SPECIMEN hash-table." (maphash ^(unless (equal (slot-value obj %) %%) (return-from bound-equal nil)) specimen)) (defun timestamp () "Return current timestamp as string." (mv-bind (sec min hour day month year) (decode-universal-time (get-universal-time)) (fmt "~A~2,'0D~2,'0D~2,'0D~2,'0D~2,'0D" year month day hour min sec))) (defgeneric ss (obj) (:documentation "Get a short string from an object") (:method (obj) (string obj)))
[ { "context": "Lisp; Package: CCL -*-\n;;;\n;;; Copyright 1994-2009 Clozure Associates\n;;;\n;;; Licensed under the Apache License, Versio", "end": 82, "score": 0.9557292461395264, "start": 64, "tag": "NAME", "value": "Clozure Associates" } ]
level-0/l0-def.lisp
digikar99/ccl
732
;;;-*- Mode: Lisp; Package: CCL -*- ;;; ;;; Copyright 1994-2009 Clozure Associates ;;; ;;; Licensed under the Apache License, Version 2.0 (the "License"); ;;; you may not use this file except in compliance with the License. ;;; You may obtain a copy of the License at ;;; ;;; http://www.apache.org/licenses/LICENSE-2.0 ;;; ;;; Unless required by applicable law or agreed to in writing, software ;;; distributed under the License is distributed on an "AS IS" BASIS, ;;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ;;; See the License for the specific language governing permissions and ;;; limitations under the License. (in-package "CCL") ;;; primitives that manipulate function & variable definitions. (defun functionp (arg) "Return true if OBJECT is a FUNCTION, and NIL otherwise." (functionp arg)) (defun lfunp (arg) (functionp arg)) (defun %proclaim-special (sym &optional initp) (let* ((oldbits (%symbol-bits sym))) (declare (fixnum oldbits)) (%symbol-bits sym (bitset $sym_vbit_special oldbits)) initp)) (setq *lfun-names* (make-hash-table :test 'eq :weak t)) (defun lookup-lfun-name (lfun) (gethash lfun *lfun-names*)) (defun function-name (fun) (or (and (functionp fun) (lfun-name fun)) (if (compiled-function-p (setq fun (closure-function fun))) (lfun-name fun)))) (defun bootstrapping-fmakunbound (name) (when (consp name) (unless (eq (%car name) 'setf) (error "Function spec handler not loaded yet")) (setq name (setf-function-name (cadr name)))) (%unfhave name) name) ;;; redefined in sysutils. (%fhave 'fmakunbound #'bootstrapping-fmakunbound) (defun bootstrapping-fset (name fn) (fmakunbound name) (%fhave name fn) fn) ;Redefined in sysutils. (%fhave 'fset #'bootstrapping-fset) (defun fset-symbol (name fn) (fset (require-type name 'symbol) fn)) (defun bootstrapping-record-source-file (fn &optional type) (declare (ignore fn type)) nil) ;Redefined in l1-utils. (%fhave 'record-source-file #'bootstrapping-record-source-file) (setq *fasload-print* nil) (setq *save-doc-strings* t) (%fhave '%defun-encapsulated-maybe ;Redefined in encapsulate (qlfun bootstrapping-defun-encapsulated (name fn) (declare (ignore name fn)) nil)) (%fhave 'encapsulated-function-name ;Redefined in encapsulate - used in l1-io (qlfun bootstrapping-encapsulated-function-name (fn) (declare (ignore fn)) nil)) (%fhave 'set-function-info (qlfun set-function-info (name info) (if (typep info 'string) (set-documentation name 'function info)) name)) (defun %defun (named-fn &optional info) (unless (typep named-fn 'function) (dbg named-fn)) (let* ((name (function-name named-fn))) (unless (and name (or (symbolp name) (setf-function-name-p name))) (dbg named-fn)) (record-source-file name 'function) (when (not (%defun-encapsulated-maybe name named-fn)) (when (and (symbolp name) (macro-function name nil)) (warn "The macro ~s is being redefined as a function." name) (fmakunbound name)) (fset name named-fn)) (set-function-info name info) (when *fasload-print* (format t "~&~S~%" name)) name)) (defun validate-function-name (name) (if (symbolp name) name (if (setf-function-name-p name) (setf-function-name (cadr name)) (report-bad-arg name 'function-name)))) ;;; There are three kinds of things which can go in the function ;;; cell of a symbol: 1) A function. 2) The thing which is the ;;; value of %unbound-function%: a 1-element vector whose 0th ;;; element is a code vector which causes an "undefined function" ;;; error to be signalled. 3) A macro or special-form definition, ;;; which is a 2-element vector whose 0th element is a code vector ;;; which signals a "can't apply macro or special form" error when ;;; executed and whose 1st element is a macro or special-operator ;;; name. It doesn't matter what type of gvector cases 2 and 3 ;;; are. Once that's decided, it wouldn't hurt if %FHAVE ;;; typechecked its second arg. (defun %fhave (name def) (let* ((fname (validate-function-name name))) (setf (%svref (symptr->symvector (%symbol->symptr fname)) target::symbol.fcell-cell) def))) ;;; FBOUNDP is true of any symbol whose function-cell contains something other ;;; than %unbound-function%; we expect FBOUNDP to return that something. (defun fboundp (name) "Return true if name has a global function definition." (let* ((fname (validate-function-name name)) (def (%svref (symptr->symvector (%symbol->symptr fname)) target::symbol.fcell-cell))) (unless (eq def %unbound-function%) def))) ;;; %UNFHAVE doesn't seem to want to deal with SETF names or function specs. ;;; Who does ? (defun %unfhave (sym) (let* ((symvec (symptr->symvector (%symbol->symptr sym))) (old (%svref symvec target::symbol.fcell-cell)) (unbound %unbound-function%)) (setf (%svref symvec target::symbol.fcell-cell) unbound) (not (eq old unbound)))) ;;; It's guaranteed that lfun-bits is a fixnum. Might be a 30-bit fixnum ... (defun lfun-vector-name (fun &optional (new-name nil set-name-p)) (let* ((bits (lfun-bits fun))) (declare (fixnum bits)) (if (and (logbitp $lfbits-gfn-bit bits) (not (logbitp $lfbits-method-bit bits))) (progn (if set-name-p (%gf-name fun new-name) (%gf-name fun))) (let* ((has-name-cell (not (logbitp $lfbits-noname-bit bits)))) (if has-name-cell (let* ((lfv (lfun-vector fun)) (name-idx (- (the fixnum (uvsize lfv)) 2)) (old-name (%svref lfv name-idx))) (declare (fixnum name-idx)) (if (and set-name-p (not (eq old-name new-name))) (setf (%svref lfv name-idx) new-name)) old-name)))))) (defun lfun-name (fun &optional (new-name nil set-name-p)) (multiple-value-bind (stored-name stored?) (lookup-lfun-name fun) (unless stored? (setq stored-name (lfun-vector-name fun))) (when (and set-name-p (neq new-name stored-name)) (if (and stored? (eq new-name (lfun-vector-name fun))) (remhash fun *lfun-names*) (if (logbitp $lfbits-noname-bit (the fixnum (lfun-bits fun))) ; no name-cell in function vector. (puthash fun *lfun-names* new-name) (lfun-vector-name fun new-name)))) stored-name)) (defun lfun-bits (function &optional new) (unless (functionp function) (setq function (require-type function 'function))) (let* ((lfv (lfun-vector function)) (idx (1- (the fixnum (uvsize lfv)))) (old (%svref lfv idx))) (declare (fixnum idx)) (if new (setf (%svref lfv idx) new)) old)) (defun %macro-have (symbol macro-function) (declare (special %macro-code%)) ; magically set by xloader. (%fhave symbol #-arm-target (vector %macro-code% macro-function) #+arm-target (%fix-fn-entrypoint (gvector :pseudofunction 0 %macro-code% macro-function)))) (defun special-operator-p (symbol) "If the symbol globally names a special form, return T, otherwise NIL." (let ((def (fboundp symbol))) (and #-arm-target (typep def 'simple-vector) #+arm-target (= (typecode def) arm::subtag-pseudofunction) (not (lfunp #-arm-target (svref def 1) #+arm-target (uvref def 2)))))) (defun special-form-p (x) (special-operator-p x)) (defun setf-function-name-p (thing) (and (consp thing) (consp (%cdr thing)) (null (%cddr thing)) (eq (%car thing) 'setf) (symbolp (%cadr thing)))) (defun macro-function (form &optional env) "If SYMBOL names a macro in ENV, returns the expansion function, else returns NIL. If ENV is unspecified or NIL, use the global environment only." (setq form (require-type form 'symbol)) (when env ;; A definition-environment isn't a lexical environment, but it can ;; be an ancestor of one. (unless (istruct-typep env 'lexical-environment) (report-bad-arg env 'lexical-environment)) (let ((cell nil)) (tagbody top (if (setq cell (%cdr (assq form (lexenv.functions env)))) (return-from macro-function (if (eq (car cell) 'macro) (%cdr cell)))) (unless (listp (setq env (lexenv.parent-env env))) (go top))))) ;; Not found in env, look in function cell. (%global-macro-function form)) (defun %fixnum-ref-macptr (fixnum &optional (offset 0)) (%int-to-ptr (%fixnum-ref-natural fixnum offset))) (defun %fixnum-set-macptr (fixnum offset &optional (newval offset newval-p)) (%fixnum-set-natural fixnum (if newval-p offset 0) (%ptr-to-int newval)) newval) (defun nth-catch-frame-tag (n) (declare (fixnum n)) (let* ((frame (%catch-top (%current-tcr)))) (dotimes (i n (%svref frame target::catch-frame.catch-tag-cell)) (setq frame (%svref frame target::catch-frame.link-cell))))) ;;; This function is magic, and it can only be called from ;;; an unwind-protect cleanup form (making it even more magic.) ;;; If we can tell that we reached the unwind-protect via THROW, ;;; return a list of the target catch tag and all values being ;;; thrown. #+x86-target (defun %throwing-through-cleanup-p () ;; when we enter and unwind-protect cleanup on x8664, the ;; top frame on the tstack contains state information that's ;; used both by THROW and by normal exit from the protected ;; form. That state information contains a count of the number ;; of catch/unwind-protect frames still to be processed (non-zero ;; only in the case where we're actually throwing), the value(s) ;; being thrown, and a return address that isn't interesting to ;; us. It's an historical accident that that information is stored ;; differently in the cases where a single value is being thrown ;; and multiple values are thrown. ;; A tstack frame is always doubleword aligned, and the first two ;; words are a backpointer to the previous tstack frame and a ;; pointer into the main lisp stack. In the single value case, ;; we then have 3 words: return address, frame count, value; ;; in the multiple-value we have 3 fixed words (value count, ;; return address, frame count) with the values following the ;; frame count (value 0 follows immediately.) ;; A cleanup form is always called from either .SPnthrowvalues ;; of .SPnthrow1value, and those subprims can be called either ;; by .SPthrow (in which case the return address in the frame ;; will have no function associated with it) or by Lisp code ;; (in which case it will.) ;; We (have to) just assume that the frame on top of the temp ;; stack is context info for the nthrow stuff. Tracing this ;; function may violate this assumption and cause misbehavior ;; here. (let* ((frame (%current-tsp)) (single-value-case (not (typep (%lisp-word-ref frame 2) 'fixnum))) (frame-count (%lisp-word-ref frame (if single-value-case 3 4))) (throwing (null (%return-address-function (if single-value-case (%lisp-word-ref frame 2) (%lisp-word-ref frame 3)))))) (declare (fixnum frame)) (if throwing (collect ((info)) (info (nth-catch-frame-tag frame-count)) (if single-value-case (info (%lisp-word-ref frame 4)) (let* ((valptr (+ frame 5))) (declare (fixnum valptr)) (dotimes (i (%lisp-word-ref frame 2)) (declare (fixnum i)) (info (%lisp-word-ref valptr i))))) (info))))) ;;; end of l0-def.lisp
96904
;;;-*- Mode: Lisp; Package: CCL -*- ;;; ;;; Copyright 1994-2009 <NAME> ;;; ;;; Licensed under the Apache License, Version 2.0 (the "License"); ;;; you may not use this file except in compliance with the License. ;;; You may obtain a copy of the License at ;;; ;;; http://www.apache.org/licenses/LICENSE-2.0 ;;; ;;; Unless required by applicable law or agreed to in writing, software ;;; distributed under the License is distributed on an "AS IS" BASIS, ;;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ;;; See the License for the specific language governing permissions and ;;; limitations under the License. (in-package "CCL") ;;; primitives that manipulate function & variable definitions. (defun functionp (arg) "Return true if OBJECT is a FUNCTION, and NIL otherwise." (functionp arg)) (defun lfunp (arg) (functionp arg)) (defun %proclaim-special (sym &optional initp) (let* ((oldbits (%symbol-bits sym))) (declare (fixnum oldbits)) (%symbol-bits sym (bitset $sym_vbit_special oldbits)) initp)) (setq *lfun-names* (make-hash-table :test 'eq :weak t)) (defun lookup-lfun-name (lfun) (gethash lfun *lfun-names*)) (defun function-name (fun) (or (and (functionp fun) (lfun-name fun)) (if (compiled-function-p (setq fun (closure-function fun))) (lfun-name fun)))) (defun bootstrapping-fmakunbound (name) (when (consp name) (unless (eq (%car name) 'setf) (error "Function spec handler not loaded yet")) (setq name (setf-function-name (cadr name)))) (%unfhave name) name) ;;; redefined in sysutils. (%fhave 'fmakunbound #'bootstrapping-fmakunbound) (defun bootstrapping-fset (name fn) (fmakunbound name) (%fhave name fn) fn) ;Redefined in sysutils. (%fhave 'fset #'bootstrapping-fset) (defun fset-symbol (name fn) (fset (require-type name 'symbol) fn)) (defun bootstrapping-record-source-file (fn &optional type) (declare (ignore fn type)) nil) ;Redefined in l1-utils. (%fhave 'record-source-file #'bootstrapping-record-source-file) (setq *fasload-print* nil) (setq *save-doc-strings* t) (%fhave '%defun-encapsulated-maybe ;Redefined in encapsulate (qlfun bootstrapping-defun-encapsulated (name fn) (declare (ignore name fn)) nil)) (%fhave 'encapsulated-function-name ;Redefined in encapsulate - used in l1-io (qlfun bootstrapping-encapsulated-function-name (fn) (declare (ignore fn)) nil)) (%fhave 'set-function-info (qlfun set-function-info (name info) (if (typep info 'string) (set-documentation name 'function info)) name)) (defun %defun (named-fn &optional info) (unless (typep named-fn 'function) (dbg named-fn)) (let* ((name (function-name named-fn))) (unless (and name (or (symbolp name) (setf-function-name-p name))) (dbg named-fn)) (record-source-file name 'function) (when (not (%defun-encapsulated-maybe name named-fn)) (when (and (symbolp name) (macro-function name nil)) (warn "The macro ~s is being redefined as a function." name) (fmakunbound name)) (fset name named-fn)) (set-function-info name info) (when *fasload-print* (format t "~&~S~%" name)) name)) (defun validate-function-name (name) (if (symbolp name) name (if (setf-function-name-p name) (setf-function-name (cadr name)) (report-bad-arg name 'function-name)))) ;;; There are three kinds of things which can go in the function ;;; cell of a symbol: 1) A function. 2) The thing which is the ;;; value of %unbound-function%: a 1-element vector whose 0th ;;; element is a code vector which causes an "undefined function" ;;; error to be signalled. 3) A macro or special-form definition, ;;; which is a 2-element vector whose 0th element is a code vector ;;; which signals a "can't apply macro or special form" error when ;;; executed and whose 1st element is a macro or special-operator ;;; name. It doesn't matter what type of gvector cases 2 and 3 ;;; are. Once that's decided, it wouldn't hurt if %FHAVE ;;; typechecked its second arg. (defun %fhave (name def) (let* ((fname (validate-function-name name))) (setf (%svref (symptr->symvector (%symbol->symptr fname)) target::symbol.fcell-cell) def))) ;;; FBOUNDP is true of any symbol whose function-cell contains something other ;;; than %unbound-function%; we expect FBOUNDP to return that something. (defun fboundp (name) "Return true if name has a global function definition." (let* ((fname (validate-function-name name)) (def (%svref (symptr->symvector (%symbol->symptr fname)) target::symbol.fcell-cell))) (unless (eq def %unbound-function%) def))) ;;; %UNFHAVE doesn't seem to want to deal with SETF names or function specs. ;;; Who does ? (defun %unfhave (sym) (let* ((symvec (symptr->symvector (%symbol->symptr sym))) (old (%svref symvec target::symbol.fcell-cell)) (unbound %unbound-function%)) (setf (%svref symvec target::symbol.fcell-cell) unbound) (not (eq old unbound)))) ;;; It's guaranteed that lfun-bits is a fixnum. Might be a 30-bit fixnum ... (defun lfun-vector-name (fun &optional (new-name nil set-name-p)) (let* ((bits (lfun-bits fun))) (declare (fixnum bits)) (if (and (logbitp $lfbits-gfn-bit bits) (not (logbitp $lfbits-method-bit bits))) (progn (if set-name-p (%gf-name fun new-name) (%gf-name fun))) (let* ((has-name-cell (not (logbitp $lfbits-noname-bit bits)))) (if has-name-cell (let* ((lfv (lfun-vector fun)) (name-idx (- (the fixnum (uvsize lfv)) 2)) (old-name (%svref lfv name-idx))) (declare (fixnum name-idx)) (if (and set-name-p (not (eq old-name new-name))) (setf (%svref lfv name-idx) new-name)) old-name)))))) (defun lfun-name (fun &optional (new-name nil set-name-p)) (multiple-value-bind (stored-name stored?) (lookup-lfun-name fun) (unless stored? (setq stored-name (lfun-vector-name fun))) (when (and set-name-p (neq new-name stored-name)) (if (and stored? (eq new-name (lfun-vector-name fun))) (remhash fun *lfun-names*) (if (logbitp $lfbits-noname-bit (the fixnum (lfun-bits fun))) ; no name-cell in function vector. (puthash fun *lfun-names* new-name) (lfun-vector-name fun new-name)))) stored-name)) (defun lfun-bits (function &optional new) (unless (functionp function) (setq function (require-type function 'function))) (let* ((lfv (lfun-vector function)) (idx (1- (the fixnum (uvsize lfv)))) (old (%svref lfv idx))) (declare (fixnum idx)) (if new (setf (%svref lfv idx) new)) old)) (defun %macro-have (symbol macro-function) (declare (special %macro-code%)) ; magically set by xloader. (%fhave symbol #-arm-target (vector %macro-code% macro-function) #+arm-target (%fix-fn-entrypoint (gvector :pseudofunction 0 %macro-code% macro-function)))) (defun special-operator-p (symbol) "If the symbol globally names a special form, return T, otherwise NIL." (let ((def (fboundp symbol))) (and #-arm-target (typep def 'simple-vector) #+arm-target (= (typecode def) arm::subtag-pseudofunction) (not (lfunp #-arm-target (svref def 1) #+arm-target (uvref def 2)))))) (defun special-form-p (x) (special-operator-p x)) (defun setf-function-name-p (thing) (and (consp thing) (consp (%cdr thing)) (null (%cddr thing)) (eq (%car thing) 'setf) (symbolp (%cadr thing)))) (defun macro-function (form &optional env) "If SYMBOL names a macro in ENV, returns the expansion function, else returns NIL. If ENV is unspecified or NIL, use the global environment only." (setq form (require-type form 'symbol)) (when env ;; A definition-environment isn't a lexical environment, but it can ;; be an ancestor of one. (unless (istruct-typep env 'lexical-environment) (report-bad-arg env 'lexical-environment)) (let ((cell nil)) (tagbody top (if (setq cell (%cdr (assq form (lexenv.functions env)))) (return-from macro-function (if (eq (car cell) 'macro) (%cdr cell)))) (unless (listp (setq env (lexenv.parent-env env))) (go top))))) ;; Not found in env, look in function cell. (%global-macro-function form)) (defun %fixnum-ref-macptr (fixnum &optional (offset 0)) (%int-to-ptr (%fixnum-ref-natural fixnum offset))) (defun %fixnum-set-macptr (fixnum offset &optional (newval offset newval-p)) (%fixnum-set-natural fixnum (if newval-p offset 0) (%ptr-to-int newval)) newval) (defun nth-catch-frame-tag (n) (declare (fixnum n)) (let* ((frame (%catch-top (%current-tcr)))) (dotimes (i n (%svref frame target::catch-frame.catch-tag-cell)) (setq frame (%svref frame target::catch-frame.link-cell))))) ;;; This function is magic, and it can only be called from ;;; an unwind-protect cleanup form (making it even more magic.) ;;; If we can tell that we reached the unwind-protect via THROW, ;;; return a list of the target catch tag and all values being ;;; thrown. #+x86-target (defun %throwing-through-cleanup-p () ;; when we enter and unwind-protect cleanup on x8664, the ;; top frame on the tstack contains state information that's ;; used both by THROW and by normal exit from the protected ;; form. That state information contains a count of the number ;; of catch/unwind-protect frames still to be processed (non-zero ;; only in the case where we're actually throwing), the value(s) ;; being thrown, and a return address that isn't interesting to ;; us. It's an historical accident that that information is stored ;; differently in the cases where a single value is being thrown ;; and multiple values are thrown. ;; A tstack frame is always doubleword aligned, and the first two ;; words are a backpointer to the previous tstack frame and a ;; pointer into the main lisp stack. In the single value case, ;; we then have 3 words: return address, frame count, value; ;; in the multiple-value we have 3 fixed words (value count, ;; return address, frame count) with the values following the ;; frame count (value 0 follows immediately.) ;; A cleanup form is always called from either .SPnthrowvalues ;; of .SPnthrow1value, and those subprims can be called either ;; by .SPthrow (in which case the return address in the frame ;; will have no function associated with it) or by Lisp code ;; (in which case it will.) ;; We (have to) just assume that the frame on top of the temp ;; stack is context info for the nthrow stuff. Tracing this ;; function may violate this assumption and cause misbehavior ;; here. (let* ((frame (%current-tsp)) (single-value-case (not (typep (%lisp-word-ref frame 2) 'fixnum))) (frame-count (%lisp-word-ref frame (if single-value-case 3 4))) (throwing (null (%return-address-function (if single-value-case (%lisp-word-ref frame 2) (%lisp-word-ref frame 3)))))) (declare (fixnum frame)) (if throwing (collect ((info)) (info (nth-catch-frame-tag frame-count)) (if single-value-case (info (%lisp-word-ref frame 4)) (let* ((valptr (+ frame 5))) (declare (fixnum valptr)) (dotimes (i (%lisp-word-ref frame 2)) (declare (fixnum i)) (info (%lisp-word-ref valptr i))))) (info))))) ;;; end of l0-def.lisp
true
;;;-*- Mode: Lisp; Package: CCL -*- ;;; ;;; Copyright 1994-2009 PI:NAME:<NAME>END_PI ;;; ;;; Licensed under the Apache License, Version 2.0 (the "License"); ;;; you may not use this file except in compliance with the License. ;;; You may obtain a copy of the License at ;;; ;;; http://www.apache.org/licenses/LICENSE-2.0 ;;; ;;; Unless required by applicable law or agreed to in writing, software ;;; distributed under the License is distributed on an "AS IS" BASIS, ;;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ;;; See the License for the specific language governing permissions and ;;; limitations under the License. (in-package "CCL") ;;; primitives that manipulate function & variable definitions. (defun functionp (arg) "Return true if OBJECT is a FUNCTION, and NIL otherwise." (functionp arg)) (defun lfunp (arg) (functionp arg)) (defun %proclaim-special (sym &optional initp) (let* ((oldbits (%symbol-bits sym))) (declare (fixnum oldbits)) (%symbol-bits sym (bitset $sym_vbit_special oldbits)) initp)) (setq *lfun-names* (make-hash-table :test 'eq :weak t)) (defun lookup-lfun-name (lfun) (gethash lfun *lfun-names*)) (defun function-name (fun) (or (and (functionp fun) (lfun-name fun)) (if (compiled-function-p (setq fun (closure-function fun))) (lfun-name fun)))) (defun bootstrapping-fmakunbound (name) (when (consp name) (unless (eq (%car name) 'setf) (error "Function spec handler not loaded yet")) (setq name (setf-function-name (cadr name)))) (%unfhave name) name) ;;; redefined in sysutils. (%fhave 'fmakunbound #'bootstrapping-fmakunbound) (defun bootstrapping-fset (name fn) (fmakunbound name) (%fhave name fn) fn) ;Redefined in sysutils. (%fhave 'fset #'bootstrapping-fset) (defun fset-symbol (name fn) (fset (require-type name 'symbol) fn)) (defun bootstrapping-record-source-file (fn &optional type) (declare (ignore fn type)) nil) ;Redefined in l1-utils. (%fhave 'record-source-file #'bootstrapping-record-source-file) (setq *fasload-print* nil) (setq *save-doc-strings* t) (%fhave '%defun-encapsulated-maybe ;Redefined in encapsulate (qlfun bootstrapping-defun-encapsulated (name fn) (declare (ignore name fn)) nil)) (%fhave 'encapsulated-function-name ;Redefined in encapsulate - used in l1-io (qlfun bootstrapping-encapsulated-function-name (fn) (declare (ignore fn)) nil)) (%fhave 'set-function-info (qlfun set-function-info (name info) (if (typep info 'string) (set-documentation name 'function info)) name)) (defun %defun (named-fn &optional info) (unless (typep named-fn 'function) (dbg named-fn)) (let* ((name (function-name named-fn))) (unless (and name (or (symbolp name) (setf-function-name-p name))) (dbg named-fn)) (record-source-file name 'function) (when (not (%defun-encapsulated-maybe name named-fn)) (when (and (symbolp name) (macro-function name nil)) (warn "The macro ~s is being redefined as a function." name) (fmakunbound name)) (fset name named-fn)) (set-function-info name info) (when *fasload-print* (format t "~&~S~%" name)) name)) (defun validate-function-name (name) (if (symbolp name) name (if (setf-function-name-p name) (setf-function-name (cadr name)) (report-bad-arg name 'function-name)))) ;;; There are three kinds of things which can go in the function ;;; cell of a symbol: 1) A function. 2) The thing which is the ;;; value of %unbound-function%: a 1-element vector whose 0th ;;; element is a code vector which causes an "undefined function" ;;; error to be signalled. 3) A macro or special-form definition, ;;; which is a 2-element vector whose 0th element is a code vector ;;; which signals a "can't apply macro or special form" error when ;;; executed and whose 1st element is a macro or special-operator ;;; name. It doesn't matter what type of gvector cases 2 and 3 ;;; are. Once that's decided, it wouldn't hurt if %FHAVE ;;; typechecked its second arg. (defun %fhave (name def) (let* ((fname (validate-function-name name))) (setf (%svref (symptr->symvector (%symbol->symptr fname)) target::symbol.fcell-cell) def))) ;;; FBOUNDP is true of any symbol whose function-cell contains something other ;;; than %unbound-function%; we expect FBOUNDP to return that something. (defun fboundp (name) "Return true if name has a global function definition." (let* ((fname (validate-function-name name)) (def (%svref (symptr->symvector (%symbol->symptr fname)) target::symbol.fcell-cell))) (unless (eq def %unbound-function%) def))) ;;; %UNFHAVE doesn't seem to want to deal with SETF names or function specs. ;;; Who does ? (defun %unfhave (sym) (let* ((symvec (symptr->symvector (%symbol->symptr sym))) (old (%svref symvec target::symbol.fcell-cell)) (unbound %unbound-function%)) (setf (%svref symvec target::symbol.fcell-cell) unbound) (not (eq old unbound)))) ;;; It's guaranteed that lfun-bits is a fixnum. Might be a 30-bit fixnum ... (defun lfun-vector-name (fun &optional (new-name nil set-name-p)) (let* ((bits (lfun-bits fun))) (declare (fixnum bits)) (if (and (logbitp $lfbits-gfn-bit bits) (not (logbitp $lfbits-method-bit bits))) (progn (if set-name-p (%gf-name fun new-name) (%gf-name fun))) (let* ((has-name-cell (not (logbitp $lfbits-noname-bit bits)))) (if has-name-cell (let* ((lfv (lfun-vector fun)) (name-idx (- (the fixnum (uvsize lfv)) 2)) (old-name (%svref lfv name-idx))) (declare (fixnum name-idx)) (if (and set-name-p (not (eq old-name new-name))) (setf (%svref lfv name-idx) new-name)) old-name)))))) (defun lfun-name (fun &optional (new-name nil set-name-p)) (multiple-value-bind (stored-name stored?) (lookup-lfun-name fun) (unless stored? (setq stored-name (lfun-vector-name fun))) (when (and set-name-p (neq new-name stored-name)) (if (and stored? (eq new-name (lfun-vector-name fun))) (remhash fun *lfun-names*) (if (logbitp $lfbits-noname-bit (the fixnum (lfun-bits fun))) ; no name-cell in function vector. (puthash fun *lfun-names* new-name) (lfun-vector-name fun new-name)))) stored-name)) (defun lfun-bits (function &optional new) (unless (functionp function) (setq function (require-type function 'function))) (let* ((lfv (lfun-vector function)) (idx (1- (the fixnum (uvsize lfv)))) (old (%svref lfv idx))) (declare (fixnum idx)) (if new (setf (%svref lfv idx) new)) old)) (defun %macro-have (symbol macro-function) (declare (special %macro-code%)) ; magically set by xloader. (%fhave symbol #-arm-target (vector %macro-code% macro-function) #+arm-target (%fix-fn-entrypoint (gvector :pseudofunction 0 %macro-code% macro-function)))) (defun special-operator-p (symbol) "If the symbol globally names a special form, return T, otherwise NIL." (let ((def (fboundp symbol))) (and #-arm-target (typep def 'simple-vector) #+arm-target (= (typecode def) arm::subtag-pseudofunction) (not (lfunp #-arm-target (svref def 1) #+arm-target (uvref def 2)))))) (defun special-form-p (x) (special-operator-p x)) (defun setf-function-name-p (thing) (and (consp thing) (consp (%cdr thing)) (null (%cddr thing)) (eq (%car thing) 'setf) (symbolp (%cadr thing)))) (defun macro-function (form &optional env) "If SYMBOL names a macro in ENV, returns the expansion function, else returns NIL. If ENV is unspecified or NIL, use the global environment only." (setq form (require-type form 'symbol)) (when env ;; A definition-environment isn't a lexical environment, but it can ;; be an ancestor of one. (unless (istruct-typep env 'lexical-environment) (report-bad-arg env 'lexical-environment)) (let ((cell nil)) (tagbody top (if (setq cell (%cdr (assq form (lexenv.functions env)))) (return-from macro-function (if (eq (car cell) 'macro) (%cdr cell)))) (unless (listp (setq env (lexenv.parent-env env))) (go top))))) ;; Not found in env, look in function cell. (%global-macro-function form)) (defun %fixnum-ref-macptr (fixnum &optional (offset 0)) (%int-to-ptr (%fixnum-ref-natural fixnum offset))) (defun %fixnum-set-macptr (fixnum offset &optional (newval offset newval-p)) (%fixnum-set-natural fixnum (if newval-p offset 0) (%ptr-to-int newval)) newval) (defun nth-catch-frame-tag (n) (declare (fixnum n)) (let* ((frame (%catch-top (%current-tcr)))) (dotimes (i n (%svref frame target::catch-frame.catch-tag-cell)) (setq frame (%svref frame target::catch-frame.link-cell))))) ;;; This function is magic, and it can only be called from ;;; an unwind-protect cleanup form (making it even more magic.) ;;; If we can tell that we reached the unwind-protect via THROW, ;;; return a list of the target catch tag and all values being ;;; thrown. #+x86-target (defun %throwing-through-cleanup-p () ;; when we enter and unwind-protect cleanup on x8664, the ;; top frame on the tstack contains state information that's ;; used both by THROW and by normal exit from the protected ;; form. That state information contains a count of the number ;; of catch/unwind-protect frames still to be processed (non-zero ;; only in the case where we're actually throwing), the value(s) ;; being thrown, and a return address that isn't interesting to ;; us. It's an historical accident that that information is stored ;; differently in the cases where a single value is being thrown ;; and multiple values are thrown. ;; A tstack frame is always doubleword aligned, and the first two ;; words are a backpointer to the previous tstack frame and a ;; pointer into the main lisp stack. In the single value case, ;; we then have 3 words: return address, frame count, value; ;; in the multiple-value we have 3 fixed words (value count, ;; return address, frame count) with the values following the ;; frame count (value 0 follows immediately.) ;; A cleanup form is always called from either .SPnthrowvalues ;; of .SPnthrow1value, and those subprims can be called either ;; by .SPthrow (in which case the return address in the frame ;; will have no function associated with it) or by Lisp code ;; (in which case it will.) ;; We (have to) just assume that the frame on top of the temp ;; stack is context info for the nthrow stuff. Tracing this ;; function may violate this assumption and cause misbehavior ;; here. (let* ((frame (%current-tsp)) (single-value-case (not (typep (%lisp-word-ref frame 2) 'fixnum))) (frame-count (%lisp-word-ref frame (if single-value-case 3 4))) (throwing (null (%return-address-function (if single-value-case (%lisp-word-ref frame 2) (%lisp-word-ref frame 3)))))) (declare (fixnum frame)) (if throwing (collect ((info)) (info (nth-catch-frame-tag frame-count)) (if single-value-case (info (%lisp-word-ref frame 4)) (let* ((valptr (+ frame 5))) (declare (fixnum valptr)) (dotimes (i (%lisp-word-ref frame 2)) (declare (fixnum i)) (info (%lisp-word-ref valptr i))))) (info))))) ;;; end of l0-def.lisp
[ { "context": "ense. See the file books/3BSD-mod.txt.\n;\n; Author: Eric Smith ([email protected])\n\n;;;;;;;;;;;;;;;;;;;;;;;", "end": 198, "score": 0.999238133430481, "start": 188, "tag": "NAME", "value": "Eric Smith" }, { "context": " file books/3BSD-mod.txt.\n;\n; Author: Eric Smith ([email protected])\n\n;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;", "end": 222, "score": 0.9999308586120605, "start": 200, "tag": "EMAIL", "value": "[email protected]" } ]
books/kestrel/utilities/non-trivial-bindings.lisp
mayankmanj/acl2
0
; Finding lambda bindings where vars are not bound to themselves ; ; Copyright (C) 2021 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 collect-non-trivial-bindings, but that one is in :program mode. ;; A "non-trivial binding" is a binding of some var to some value other than itself. (defund non-trivial-bindings (vars vals) (declare (xargs :guard (and (symbol-listp vars) (true-listp vals)))) (if (endp vars) nil (let ((var (first vars)) (val (first vals))) (if (equal var val) ;; trivial binding, so skip: (non-trivial-bindings (rest vars) (rest vals)) (cons (cons var val) (non-trivial-bindings (rest vars) (rest vals))))))) (defthm symbol-alistp-of-non-trivial-bindings (implies (symbol-listp vars) (symbol-alistp (non-trivial-bindings vars vals))) :hints (("Goal" :in-theory (enable non-trivial-bindings)))) (defthm symbol-listp-of-strio-cars-of-non-trivial-bindings (implies (symbol-listp vars) (symbol-listp (strip-cars (non-trivial-bindings vars vals)))) :hints (("Goal" :in-theory (enable non-trivial-bindings)))) (defthm pseudo-term-listp-of-strip-cdrs-of-trivial-bindings (implies (pseudo-term-listp vals) (pseudo-term-listp (strip-cdrs (non-trivial-bindings vars vals)))) :hints (("Goal" :in-theory (enable non-trivial-bindings))))
41230
; Finding lambda bindings where vars are not bound to themselves ; ; Copyright (C) 2021 Kestrel Institute ; ; License: A 3-clause BSD license. See the file books/3BSD-mod.txt. ; ; Author: <NAME> (<EMAIL>) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (in-package "ACL2") ;; See also collect-non-trivial-bindings, but that one is in :program mode. ;; A "non-trivial binding" is a binding of some var to some value other than itself. (defund non-trivial-bindings (vars vals) (declare (xargs :guard (and (symbol-listp vars) (true-listp vals)))) (if (endp vars) nil (let ((var (first vars)) (val (first vals))) (if (equal var val) ;; trivial binding, so skip: (non-trivial-bindings (rest vars) (rest vals)) (cons (cons var val) (non-trivial-bindings (rest vars) (rest vals))))))) (defthm symbol-alistp-of-non-trivial-bindings (implies (symbol-listp vars) (symbol-alistp (non-trivial-bindings vars vals))) :hints (("Goal" :in-theory (enable non-trivial-bindings)))) (defthm symbol-listp-of-strio-cars-of-non-trivial-bindings (implies (symbol-listp vars) (symbol-listp (strip-cars (non-trivial-bindings vars vals)))) :hints (("Goal" :in-theory (enable non-trivial-bindings)))) (defthm pseudo-term-listp-of-strip-cdrs-of-trivial-bindings (implies (pseudo-term-listp vals) (pseudo-term-listp (strip-cdrs (non-trivial-bindings vars vals)))) :hints (("Goal" :in-theory (enable non-trivial-bindings))))
true
; Finding lambda bindings where vars are not bound to themselves ; ; Copyright (C) 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 "ACL2") ;; See also collect-non-trivial-bindings, but that one is in :program mode. ;; A "non-trivial binding" is a binding of some var to some value other than itself. (defund non-trivial-bindings (vars vals) (declare (xargs :guard (and (symbol-listp vars) (true-listp vals)))) (if (endp vars) nil (let ((var (first vars)) (val (first vals))) (if (equal var val) ;; trivial binding, so skip: (non-trivial-bindings (rest vars) (rest vals)) (cons (cons var val) (non-trivial-bindings (rest vars) (rest vals))))))) (defthm symbol-alistp-of-non-trivial-bindings (implies (symbol-listp vars) (symbol-alistp (non-trivial-bindings vars vals))) :hints (("Goal" :in-theory (enable non-trivial-bindings)))) (defthm symbol-listp-of-strio-cars-of-non-trivial-bindings (implies (symbol-listp vars) (symbol-listp (strip-cars (non-trivial-bindings vars vals)))) :hints (("Goal" :in-theory (enable non-trivial-bindings)))) (defthm pseudo-term-listp-of-strip-cdrs-of-trivial-bindings (implies (pseudo-term-listp vals) (pseudo-term-listp (strip-cdrs (non-trivial-bindings vars vals)))) :hints (("Goal" :in-theory (enable non-trivial-bindings))))
[ { "context": "(WHOM THE BELL TOLLS)\n\n(intersection `(fred john mary) `(sue mary fred)) ; (FRED MARY)\n\n(union `(fred j", "end": 1189, "score": 0.9989304542541504, "start": 1186, "tag": "NAME", "value": "ary" }, { "context": "BELL TOLLS)\n\n(intersection `(fred john mary) `(sue mary fred)) ; (FRED MARY)\n\n(union `(fred john mary) `(sue m", "end": 1206, "score": 0.9909695386886597, "start": 1197, "tag": "NAME", "value": "mary fred" }, { "context": "ersection `(fred john mary) `(sue mary fred)) ; (FRED MARY)\n\n(union `(fred john mary) `(sue mary fred))", "end": 1216, "score": 0.7345561981201172, "start": 1213, "tag": "NAME", "value": "RED" }, { "context": "ection `(fred john mary) `(sue mary fred)) ; (FRED MARY)\n\n(union `(fred john mary) `(sue mary fred)) ; (F", "end": 1221, "score": 0.7523112297058105, "start": 1217, "tag": "NAME", "value": "MARY" }, { "context": "n mary) `(sue mary fred)) ; (FRED MARY)\n\n(union `(fred john mary) `(sue mary fred)) ; (FRED MARY JOHN SUE)\n\n(set-d", "end": 1247, "score": 0.9950401186943054, "start": 1233, "tag": "NAME", "value": "fred john mary" }, { "context": "ed)) ; (FRED MARY)\n\n(union `(fred john mary) `(sue mary fred)) ; (FRED MARY JOHN SUE)\n\n(set-difference `(alpha", "end": 1264, "score": 0.9982242584228516, "start": 1255, "tag": "NAME", "value": "mary fred" }, { "context": "Y)\n\n(union `(fred john mary) `(sue mary fred)) ; (FRED MARY JOHN SUE)\n\n(set-difference `(alpha bravo ", "end": 1271, "score": 0.8144610524177551, "start": 1270, "tag": "NAME", "value": "F" }, { "context": "(union `(fred john mary) `(sue mary fred)) ; (FRED MARY JOHN SUE)\n\n(set-difference `(alpha bravo charlie delta) `(", "end": 1288, "score": 0.9966953992843628, "start": 1275, "tag": "NAME", "value": "MARY JOHN SUE" }, { "context": ") ; (MS MISS MRS)\n\n(setf male-first-names\n `(john kim richard fred george)\n )\n\n(setf female-first-names\n `(jane m", "end": 1603, "score": 0.9800956845283508, "start": 1575, "tag": "NAME", "value": "john kim richard fred george" }, { "context": "george)\n )\n\n(setf female-first-names\n `(jane mary wanda barbara kim)\n )\n\n(defun malep (name)\n (and ", "end": 1662, "score": 0.9981708526611328, "start": 1647, "tag": "NAME", "value": "jane mary wanda" }, { "context": "\n\n(setf female-first-names\n `(jane mary wanda barbara kim)\n )\n\n(defun malep (name)\n (and (member name", "end": 1674, "score": 0.9263777136802673, "start": 1663, "tag": "NAME", "value": "barbara kim" }, { "context": "r name female-first-names))\n )\n )\n\n(malep `richard) ; T\n\n(defun femalep (name)\n (and (member name f", "end": 1818, "score": 0.9901366233825684, "start": 1811, "tag": "NAME", "value": "richard" }, { "context": "r name male-first-names))\n )\n )\n\n(femalep `barbara) ; T\n\n(defun give-title (name)\n \"Returns a name w", "end": 1962, "score": 0.9847136735916138, "start": 1955, "tag": "NAME", "value": "barbara" }, { "context": "ppend `(mr or ms) name))\n ))\n\n(give-title `(barbara smith)) ; (MS BARBARA SMITH)\n(give-title `(kim jo", "end": 2244, "score": 0.7963293790817261, "start": 2237, "tag": "NAME", "value": "barbara" }, { "context": "arbara smith)) ; (MS BARBARA SMITH)\n(give-title `(kim johnson)) ; (MR OR MS KIM JOHNSON)\n\n(defun gender", "end": 2291, "score": 0.9900643229484558, "start": 2288, "tag": "NAME", "value": "kim" }, { "context": "ara smith)) ; (MS BARBARA SMITH)\n(give-title `(kim johnson)) ; (MR OR MS KIM JOHNSON)\n\n(defun gender-ambigou", "end": 2299, "score": 0.8592715263366699, "start": 2292, "tag": "NAME", "value": "johnson" }, { "context": "SMITH)\n(give-title `(kim johnson)) ; (MR OR MS KIM JOHNSON)\n\n(defun gender-ambigous-names ()\n (intersection", "end": 2325, "score": 0.8074328303337097, "start": 2318, "tag": "NAME", "value": "JOHNSON" }, { "context": "female-first-names)\n )\n\n(uniquely-male-names) ; (JOHN RICHARD FRED GEOGE)\n\n; a table (association list). keys are english ", "end": 2581, "score": 0.9995348453521729, "start": 2558, "tag": "NAME", "value": "JOHN RICHARD FRED GEOGE" } ]
chapter-6/chapter6.lsp
miguelmota/common-lisp-examples
1
(cons `w `(x y z)) ; => (W X Y Z) (append `(friends romans) `(and countrymen)) (setf who `(only the good)) (append who `(die young)) (cons `rice `(and beans)) ; (RICE AND BEANS) (list `rice `(and beans)) ; (RICE (AND BEANS)) (append `rice `(and beans)) ; Error: RICE is not a list (cons `(eat at) `joes) ; ((EAT AT) . JOES) (list `(eat at) `joes) ; ((EAT AT) JOES) ; as is (append `(eat at) `joes) ; (EAT AT . JOES) (reverse `(l i v e)) ; (E V I L) (defun add-to-end (x y) (reverse (cons y (reverse x))) ) (add-to-end `(a b c) `d) ; (A B C D) (nthcdr 0 `(a b c)) ; (A B C) (nthcdr 1 `(a b c)) ; (B C) (nthcdr 3 `(a b c)) ; NIL (defun nth (n x) "Returns the Nth element of the list X, counting from 0." (car (nthcdr n x)) ) (nth 1 `(a b c)) ; (B) (last `(all is forgiven)) ; (FORGIVEN) (last `(a b c . d)) ; (C . D) (remove `a `(b a n a n a)) ; (B N N) (setf ducks `(huey dewey louie)) ; create set (member `huey ducks) ; is huey a duck? (HUEY DEWEY LOUIE) (defun beforep (x y l) "Returns true if X appears before Y in L" (member y (member x l)) ) (beforep `not `whom `(ask not for whom the bell tolls)) ; (WHOM THE BELL TOLLS) (intersection `(fred john mary) `(sue mary fred)) ; (FRED MARY) (union `(fred john mary) `(sue mary fred)) ; (FRED MARY JOHN SUE) (set-difference `(alpha bravo charlie delta) `(bravo charlie)) ; (ALPHA DELTA) (subsetp `(a i) `(a e i o u)) ; t (defun titledp (name) (member (first name) `(mr ms miss mrs)) ) (titledp `(jane doe)) ; NIL (titledp `(ms jane doe)) ; (MS MISS MRS) (setf male-first-names `(john kim richard fred george) ) (setf female-first-names `(jane mary wanda barbara kim) ) (defun malep (name) (and (member name male-first-names) (not (member name female-first-names)) ) ) (malep `richard) ; T (defun femalep (name) (and (member name female-first-names) (not (member name male-first-names)) ) ) (femalep `barbara) ; T (defun give-title (name) "Returns a name with an appropriate title on the front." (cond ((titledp name) name) ((malep (first name)) (cons `mr name)) ((femalep (first name)) (cons `ms name)) (t (append `(mr or ms) name)) )) (give-title `(barbara smith)) ; (MS BARBARA SMITH) (give-title `(kim johnson)) ; (MR OR MS KIM JOHNSON) (defun gender-ambigous-names () (intersection male-first-names female-first-names) ) (gender-ambigous-names) (defun uniquely-male-names () (set-difference male-first-names female-first-names) ) (uniquely-male-names) ; (JOHN RICHARD FRED GEOGE) ; a table (association list). keys are english words (setf words `( (one un) (two deux) (three trois) (four quatre) (five cinq) )) ; look up entry given its key (assoc `three words) ; => (THREE TROIS) (defun translate (x) (second (assoc x words)) ) (translate `one) ; => un (setf sounds `( (cow . moo) (pig . oink) (cat . meow) (dog . woof) (bird . tweet) ) ) (rassoc `woof sounds) ; => (DOG . WOOF) (setf things `( (object1 large green shiny cube) (object2 small red dull meta cube) (object3 red small dull plastic cube) (object4 small dull blue meta cube) (object5 small shiny red four-sided pyramid) (object6 large shiny green sphere) ) ) (defun description (x) (rest (assoc x things)) ) (description `object3) ; => (RED SMALL DULL PLASTIC CUBE) (defun differences (x y) (set-exclusive-or (description x) (description y) ) ) (differences `object2 `object3) ; => (METAL PLASTIC) (setf quality-table `((large . size) (small . size) (red . color) (green . color) (blue . color) (shiny . luster) (dull . luster) (metal . material) (plastic . material) (cube . shape) (sphere . shape) (pyramid . shape) (four-sided . shape) ) ) (defun quality (x) (cdr (assoc x quality-table)) ) (quality `red) ; => COLOR (defun quality-difference (x y) (quality (first (differences x y))) ) (quality-difference `object1 `object6) ; => SHAPE
72986
(cons `w `(x y z)) ; => (W X Y Z) (append `(friends romans) `(and countrymen)) (setf who `(only the good)) (append who `(die young)) (cons `rice `(and beans)) ; (RICE AND BEANS) (list `rice `(and beans)) ; (RICE (AND BEANS)) (append `rice `(and beans)) ; Error: RICE is not a list (cons `(eat at) `joes) ; ((EAT AT) . JOES) (list `(eat at) `joes) ; ((EAT AT) JOES) ; as is (append `(eat at) `joes) ; (EAT AT . JOES) (reverse `(l i v e)) ; (E V I L) (defun add-to-end (x y) (reverse (cons y (reverse x))) ) (add-to-end `(a b c) `d) ; (A B C D) (nthcdr 0 `(a b c)) ; (A B C) (nthcdr 1 `(a b c)) ; (B C) (nthcdr 3 `(a b c)) ; NIL (defun nth (n x) "Returns the Nth element of the list X, counting from 0." (car (nthcdr n x)) ) (nth 1 `(a b c)) ; (B) (last `(all is forgiven)) ; (FORGIVEN) (last `(a b c . d)) ; (C . D) (remove `a `(b a n a n a)) ; (B N N) (setf ducks `(huey dewey louie)) ; create set (member `huey ducks) ; is huey a duck? (HUEY DEWEY LOUIE) (defun beforep (x y l) "Returns true if X appears before Y in L" (member y (member x l)) ) (beforep `not `whom `(ask not for whom the bell tolls)) ; (WHOM THE BELL TOLLS) (intersection `(fred john m<NAME>) `(sue <NAME>)) ; (F<NAME> <NAME>) (union `(<NAME>) `(sue <NAME>)) ; (<NAME>RED <NAME>) (set-difference `(alpha bravo charlie delta) `(bravo charlie)) ; (ALPHA DELTA) (subsetp `(a i) `(a e i o u)) ; t (defun titledp (name) (member (first name) `(mr ms miss mrs)) ) (titledp `(jane doe)) ; NIL (titledp `(ms jane doe)) ; (MS MISS MRS) (setf male-first-names `(<NAME>) ) (setf female-first-names `(<NAME> <NAME>) ) (defun malep (name) (and (member name male-first-names) (not (member name female-first-names)) ) ) (malep `<NAME>) ; T (defun femalep (name) (and (member name female-first-names) (not (member name male-first-names)) ) ) (femalep `<NAME>) ; T (defun give-title (name) "Returns a name with an appropriate title on the front." (cond ((titledp name) name) ((malep (first name)) (cons `mr name)) ((femalep (first name)) (cons `ms name)) (t (append `(mr or ms) name)) )) (give-title `(<NAME> smith)) ; (MS BARBARA SMITH) (give-title `(<NAME> <NAME>)) ; (MR OR MS KIM <NAME>) (defun gender-ambigous-names () (intersection male-first-names female-first-names) ) (gender-ambigous-names) (defun uniquely-male-names () (set-difference male-first-names female-first-names) ) (uniquely-male-names) ; (<NAME>) ; a table (association list). keys are english words (setf words `( (one un) (two deux) (three trois) (four quatre) (five cinq) )) ; look up entry given its key (assoc `three words) ; => (THREE TROIS) (defun translate (x) (second (assoc x words)) ) (translate `one) ; => un (setf sounds `( (cow . moo) (pig . oink) (cat . meow) (dog . woof) (bird . tweet) ) ) (rassoc `woof sounds) ; => (DOG . WOOF) (setf things `( (object1 large green shiny cube) (object2 small red dull meta cube) (object3 red small dull plastic cube) (object4 small dull blue meta cube) (object5 small shiny red four-sided pyramid) (object6 large shiny green sphere) ) ) (defun description (x) (rest (assoc x things)) ) (description `object3) ; => (RED SMALL DULL PLASTIC CUBE) (defun differences (x y) (set-exclusive-or (description x) (description y) ) ) (differences `object2 `object3) ; => (METAL PLASTIC) (setf quality-table `((large . size) (small . size) (red . color) (green . color) (blue . color) (shiny . luster) (dull . luster) (metal . material) (plastic . material) (cube . shape) (sphere . shape) (pyramid . shape) (four-sided . shape) ) ) (defun quality (x) (cdr (assoc x quality-table)) ) (quality `red) ; => COLOR (defun quality-difference (x y) (quality (first (differences x y))) ) (quality-difference `object1 `object6) ; => SHAPE
true
(cons `w `(x y z)) ; => (W X Y Z) (append `(friends romans) `(and countrymen)) (setf who `(only the good)) (append who `(die young)) (cons `rice `(and beans)) ; (RICE AND BEANS) (list `rice `(and beans)) ; (RICE (AND BEANS)) (append `rice `(and beans)) ; Error: RICE is not a list (cons `(eat at) `joes) ; ((EAT AT) . JOES) (list `(eat at) `joes) ; ((EAT AT) JOES) ; as is (append `(eat at) `joes) ; (EAT AT . JOES) (reverse `(l i v e)) ; (E V I L) (defun add-to-end (x y) (reverse (cons y (reverse x))) ) (add-to-end `(a b c) `d) ; (A B C D) (nthcdr 0 `(a b c)) ; (A B C) (nthcdr 1 `(a b c)) ; (B C) (nthcdr 3 `(a b c)) ; NIL (defun nth (n x) "Returns the Nth element of the list X, counting from 0." (car (nthcdr n x)) ) (nth 1 `(a b c)) ; (B) (last `(all is forgiven)) ; (FORGIVEN) (last `(a b c . d)) ; (C . D) (remove `a `(b a n a n a)) ; (B N N) (setf ducks `(huey dewey louie)) ; create set (member `huey ducks) ; is huey a duck? (HUEY DEWEY LOUIE) (defun beforep (x y l) "Returns true if X appears before Y in L" (member y (member x l)) ) (beforep `not `whom `(ask not for whom the bell tolls)) ; (WHOM THE BELL TOLLS) (intersection `(fred john mPI:NAME:<NAME>END_PI) `(sue PI:NAME:<NAME>END_PI)) ; (FPI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI) (union `(PI:NAME:<NAME>END_PI) `(sue PI:NAME:<NAME>END_PI)) ; (PI:NAME:<NAME>END_PIRED PI:NAME:<NAME>END_PI) (set-difference `(alpha bravo charlie delta) `(bravo charlie)) ; (ALPHA DELTA) (subsetp `(a i) `(a e i o u)) ; t (defun titledp (name) (member (first name) `(mr ms miss mrs)) ) (titledp `(jane doe)) ; NIL (titledp `(ms jane doe)) ; (MS MISS MRS) (setf male-first-names `(PI:NAME:<NAME>END_PI) ) (setf female-first-names `(PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI) ) (defun malep (name) (and (member name male-first-names) (not (member name female-first-names)) ) ) (malep `PI:NAME:<NAME>END_PI) ; T (defun femalep (name) (and (member name female-first-names) (not (member name male-first-names)) ) ) (femalep `PI:NAME:<NAME>END_PI) ; T (defun give-title (name) "Returns a name with an appropriate title on the front." (cond ((titledp name) name) ((malep (first name)) (cons `mr name)) ((femalep (first name)) (cons `ms name)) (t (append `(mr or ms) name)) )) (give-title `(PI:NAME:<NAME>END_PI smith)) ; (MS BARBARA SMITH) (give-title `(PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI)) ; (MR OR MS KIM PI:NAME:<NAME>END_PI) (defun gender-ambigous-names () (intersection male-first-names female-first-names) ) (gender-ambigous-names) (defun uniquely-male-names () (set-difference male-first-names female-first-names) ) (uniquely-male-names) ; (PI:NAME:<NAME>END_PI) ; a table (association list). keys are english words (setf words `( (one un) (two deux) (three trois) (four quatre) (five cinq) )) ; look up entry given its key (assoc `three words) ; => (THREE TROIS) (defun translate (x) (second (assoc x words)) ) (translate `one) ; => un (setf sounds `( (cow . moo) (pig . oink) (cat . meow) (dog . woof) (bird . tweet) ) ) (rassoc `woof sounds) ; => (DOG . WOOF) (setf things `( (object1 large green shiny cube) (object2 small red dull meta cube) (object3 red small dull plastic cube) (object4 small dull blue meta cube) (object5 small shiny red four-sided pyramid) (object6 large shiny green sphere) ) ) (defun description (x) (rest (assoc x things)) ) (description `object3) ; => (RED SMALL DULL PLASTIC CUBE) (defun differences (x y) (set-exclusive-or (description x) (description y) ) ) (differences `object2 `object3) ; => (METAL PLASTIC) (setf quality-table `((large . size) (small . size) (red . color) (green . color) (blue . color) (shiny . luster) (dull . luster) (metal . material) (plastic . material) (cube . shape) (sphere . shape) (pyramid . shape) (four-sided . shape) ) ) (defun quality (x) (cdr (assoc x quality-table)) ) (quality `red) ; => COLOR (defun quality-difference (x y) (quality (first (differences x y))) ) (quality-difference `object1 `object6) ; => SHAPE
[ { "context": "R; Base: 10 -*-\n\n;;; Copyright (c) 1998-2014, \n;;; Volker Haarslev, Ralf Moeller, Michael Wessel. \n;;; All rights r", "end": 125, "score": 0.9998987913131714, "start": 110, "tag": "NAME", "value": "Volker Haarslev" }, { "context": ";;; Copyright (c) 1998-2014, \n;;; Volker Haarslev, Ralf Moeller, Michael Wessel. \n;;; All rights reserved.\n\n;;; ", "end": 139, "score": 0.9998911619186401, "start": 127, "tag": "NAME", "value": "Ralf Moeller" }, { "context": "(c) 1998-2014, \n;;; Volker Haarslev, Ralf Moeller, Michael Wessel. \n;;; All rights reserved.\n\n;;; Racer is distrib", "end": 155, "score": 0.9998826384544373, "start": 141, "tag": "NAME", "value": "Michael Wessel" }, { "context": "ULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL\n;;; VOLKER HAARSLEV, RALF MOELLER, NOR MICHAEL WESSEL BE LIABLE FOR A", "end": 1235, "score": 0.9998815655708313, "start": 1220, "tag": "NAME", "value": "VOLKER HAARSLEV" }, { "context": "DISCLAIMED. IN NO EVENT SHALL\n;;; VOLKER HAARSLEV, RALF MOELLER, NOR MICHAEL WESSEL BE LIABLE FOR ANY\n;;; DIRECT,", "end": 1249, "score": 0.9998816847801208, "start": 1237, "tag": "NAME", "value": "RALF MOELLER" }, { "context": "EVENT SHALL\n;;; VOLKER HAARSLEV, RALF MOELLER, NOR MICHAEL WESSEL BE LIABLE FOR ANY\n;;; DIRECT, INDIRECT, INCIDENTA", "end": 1269, "score": 0.9949460029602051, "start": 1255, "tag": "NAME", "value": "MICHAEL WESSEL" } ]
source/simplex-support.lisp
CCMMueller/Racer
93
;;; -*- Mode: Lisp; Syntax: Ansi-Common-Lisp; Package: RACER; Base: 10 -*- ;;; Copyright (c) 1998-2014, ;;; Volker Haarslev, Ralf Moeller, Michael Wessel. ;;; All rights reserved. ;;; Racer is distributed under the following BSD 3-clause license ;;; 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 Racer 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 ;;; VOLKER HAARSLEV, RALF MOELLER, NOR MICHAEL WESSEL 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 :racer) (defun role-successor-satisfiable-p (role-list concept-list successor-ind unused-1 unused-2) #+:allegro (declare (:explain :tailmerging)) (declare (ignore unused-1 unused-2)) (with-race-trace-sublevel ("role-successor-satisfiable-p" :expanded t :arguments (list role-list concept-list successor-ind *saved-ind* *saved-relation-constraints* *saved-state*) :trace-result t) (let* ((flat-concept-list (reduce #'append concept-list :initial-value nil)) (new-concept `(and . ,flat-concept-list)) (qualification (with-flatten-encodings (encode-concept-term new-concept))) (roles (mapcar #'(lambda (srole) (get-role (srole-name srole))) role-list)) (role (if (rest roles) (make-nary-and-role roles) (first roles))) (predecessor-ind (first *saved-ind*)) (state (first *saved-state*)) (params (state-parameters state)) (bottom-concept (state-bottom-concept params))) (when-race-trace t (if successor-ind (race-trace ("~&Testing ~S-successor ~S of ~S for qualification ~S~%" role successor-ind predecessor-ind new-concept)) (race-trace ("~&Testing ~S-successor of ~S for qualification ~S~%" role predecessor-ind new-concept)))) (if (eq qualification bottom-concept) nil (let ((relation-constraints (first *saved-relation-constraints*)) (all-relation-constraints (state-relation-constraints state)) (top-concept (state-top-concept params)) (relation-store (state-relation-store state))) (if (and (or all-relation-constraints (and *use-relation-store* (not (relation-store-empty-p relation-store)))) (null successor-ind) (eq qualification top-concept) (if (and *use-relation-store* (not (relation-store-empty-p relation-store))) (role-find-if-in-relation-store predecessor-ind role relation-store) (role-find-if-in-relation-constraints predecessor-ind role all-relation-constraints))) t (let ((unexpanded-exists-constraints (state-unexpanded-exists-constraints state)) (attribute-constraints (state-attribute-constraints state)) (concrete-domain-state (state-concrete-domain-state state)) (labels (state-labels state)) (indirectly-blocked-individuals (state-indirectly-blocked-individuals state)) (concept-constraint (if successor-ind (new-concept-constraint successor-ind qualification) (new-concept-constraint predecessor-ind (if (null flat-concept-list) (encode-concept-term (if (or (role-datatype role) (role-cd-attribute role)) `(d-at-least 1 ,role) `(at-least 1 ,role))) (encode-concept-term (if (or (role-datatype role) (role-cd-attribute role)) `(d-some ,role ,qualification) `(some ,role ,qualification))))))) (relation-constraint (when successor-ind (list (new-relation-constraint predecessor-ind successor-ind role)))) (expanded-constraints (state-expanded-constraints state)) (unexpanded-exists-constraints-store (state-unexpanded-exists-constraints-store state)) (new-state-1 (copy-signature-kernel-state state t))) (multiple-value-bind (remaining-exists-constraints new-unexpanded-exists-constraint-store) (if successor-ind (values unexpanded-exists-constraints unexpanded-exists-constraints-store) (if (or relation-constraints (not (relation-store-empty-p relation-store))) (remove-selected-constraints-from-constraint-store (lambda (constraint) (not (eql predecessor-ind (constraint-ind constraint)))) predecessor-ind unexpanded-exists-constraints unexpanded-exists-constraints-store (state-copy-unexpanded-exists-constraints-store-p new-state-1) new-state-1 #'reset-exists-copy) (values nil nil))) (let ((dependencies (reduce #'union role-list :key #'srole-constraints :initial-value nil))) (setf (constraint-dependencies concept-constraint) dependencies) (when relation-constraint (setf (constraint-dependencies (first relation-constraint)) dependencies))) (unless (and (eq remaining-exists-constraints unexpanded-exists-constraints) (eq unexpanded-exists-constraints-store new-unexpanded-exists-constraint-store)) (race-trace ("~&Testing with reduced exists constraints ~S / ~S, all=~S / ~S~%" remaining-exists-constraints unexpanded-exists-constraints new-unexpanded-exists-constraint-store unexpanded-exists-constraints-store))) (let ((old-merging-partitions-caching *merging-partitions-caching*)) (flet ((role-successor-satisfiable-p-continuation (sat-p xstate ignore-1 ignore-2 ignore-3) (declare (ignore xstate ignore-1 ignore-2 ignore-3)) (setf *merging-partitions-caching* old-merging-partitions-caching) (if sat-p t (progn #+:debug (assert (or (null *catching-clash-dependencies*) (and (consp *collected-dependencies*) (listp (first *collected-dependencies*))))) (when (and *catching-clash-dependencies* (consp *collected-dependencies*)) (setf (first *collected-dependencies*) (union-dependencies *catching-clash-dependencies* (first *collected-dependencies*))) (race-trace ("~&New *collected-dependencies*=~S~%" *collected-dependencies*))) nil)))) (let* ((new-state-2 (copy-to-basic-kernel-state new-state-1)) (new-partially-expanded-or-stack (push-backtrack-stack #'role-successor-satisfiable-p-continuation nil)) (new-state-3 (changed-kernel-state new-state-2 :unexpanded-exists-constraints remaining-exists-constraints :expanded-constraints expanded-constraints :relation-constraints relation-constraints :attribute-constraints attribute-constraints :concrete-domain-state concrete-domain-state :labels labels :indirectly-blocked-individuals indirectly-blocked-individuals :unexpanded-exists-constraints-store new-unexpanded-exists-constraint-store :save-completion nil :partially-expanded-or-stack new-partially-expanded-or-stack))) (setf *merging-partitions-caching* nil) ; do not cache intermediate results!!! (with-race-trace-sublevel ("added-constraints-satisfiable" :expanded nil :arguments (list concept-constraint relation-constraint new-state-3) :trace-result t) (added-constraints-satisfiable concept-constraint relation-constraint new-state-3 nil ; do not expand role-domain nil))))))))))))) (defun role-find-if-in-relation-constraints (predecessor-ind role all-relation-constraints) (loop for rel-constraint in all-relation-constraints thereis (and (eql predecessor-ind (constraint-ind-1 rel-constraint)) (member role (role-ancestors-internal (constraint-term rel-constraint)))))) (defun compute-relation-role-list (signatures top-concept at-most-bounds) (loop with rel-list = nil for signature in signatures for role = (signature-role signature) for ind-name = (first (signature-successor-ind-set signature)) do #+:debug (assert (null (rest (signature-successor-ind-set signature)))) (when ind-name (loop with parents = (if (role-internal-conjunction-p role) (role-parents-internal role) (list role)) for parent in parents for parent-name = (role-name parent) for old-srole = (find parent-name rel-list :key #'srole-name) do (if old-srole (pushnew ind-name (srole-individuals old-srole)) (multiple-value-bind (value bound) (get-at-most-bound parent (list top-concept) at-most-bounds) (push (make-srole :name parent-name :at-most value :at-least nil :ancestors (mapcar #'role-name (true-role-ancestors parent)) :descendants (mapcar #'role-name (true-role-descendants parent)) :individuals (list ind-name) :constraints (when bound (list (bound-constraint bound)))) rel-list))))) finally (return rel-list))) (defun compute-srole-list (signatures relation-role-list top-concept) (loop with at-least-list = nil with some-list = relation-role-list for signature in (remove-if #'signature-successor-ind-set signatures) for role = (signature-role signature) for role-name = (role-name (signature-role signature)) for some-constraint = (find-if #'(lambda (constraint) (when (concept-constraint-p constraint) (let ((term (constraint-term constraint))) (and (not (constraint-negated-p constraint)) (exists-concept-p term) (not (eq (concept-term term) top-concept)))))) (signature-dependencies signature)) for some-no = (when some-constraint (concept-number-restriction (constraint-term some-constraint))) for old-srole = (or (find role-name some-list :key #'srole-name) (find role-name at-least-list :key #'srole-name)) do (if some-constraint (if old-srole (progn (pushnew (list some-no (concept-term (constraint-term some-constraint))) (srole-qualified-at-least old-srole) :test #'equal) (pushnew some-constraint (srole-constraints old-srole))) (push (make-srole :name role-name #|:at-most (get-at-most-bound (signature-role signature) (list top-concept) at-most-bounds)|# :at-least nil :ancestors (mapcar #'role-name (true-role-ancestors role)) :descendants (mapcar #'role-name (true-role-descendants role)) :qualified-at-least (list (list some-no (concept-term (constraint-term some-constraint)))) :constraints (list some-constraint)) some-list)) (if old-srole (progn (unless (srole-at-least old-srole) (setf (srole-at-least old-srole) (signature-cardinality signature))) (setf (srole-all-qualifications old-srole) (append (signature-concepts signature) (srole-all-qualifications old-srole))) (setf (srole-constraints old-srole) (constraint-set-union (signature-dependencies signature) (srole-constraints old-srole)))) (push (make-srole :name role-name #|:at-most (get-at-most-bound (signature-role signature) (list top-concept) at-most-bounds)|# :at-least (signature-cardinality signature) :ancestors (mapcar #'role-name (true-role-ancestors role)) :descendants (mapcar #'role-name (true-role-descendants role)) :all-qualifications (signature-concepts signature) :constraints (signature-dependencies signature)) at-least-list))) ;(break) finally (return (append some-list at-least-list)))) (defun compute-at-most-role-list (at-most-bounds srole-list allowed-roles top-concept) (loop for at-most-bound in at-most-bounds for role = (bound-role at-most-bound) for bound = (bound-number at-most-bound) for role-name = (role-name role) for old-entry = (find role-name srole-list :key #'srole-name) if old-entry if (eq (bound-qualification at-most-bound) top-concept) when (null (srole-at-most old-entry)) do (setf (srole-at-most old-entry) bound) end else do (pushnew (list (bound-number at-most-bound) (bound-qualification at-most-bound)) (srole-qualified-at-most old-entry) :test #'equal) end else if (eq (bound-qualification at-most-bound) top-concept) collect (make-srole :name role-name :at-most bound :ancestors (filter-role-set (true-role-ancestors role) allowed-roles) :descendants (filter-role-set (true-role-descendants role) allowed-roles) :all-qualifications (list top-concept) :constraints (list (bound-constraint at-most-bound))) else collect (make-srole :name role-name :qualified-at-most (collect-at-most-bounds role at-most-bounds top-concept) :ancestors (filter-role-set (true-role-ancestors role) allowed-roles) :descendants (filter-role-set (true-role-descendants role) allowed-roles) :all-qualifications (list top-concept) :constraints (list (bound-constraint at-most-bound))))) (defun compute-remaining-role-list (allowed-roles all-roles some-ind state top-concept bottom-concept) (loop for role in allowed-roles unless (member (role-name role) all-roles :key #'srole-name) collect (let* ((concept (without-taxonomic-encoding (encode-concept-term `(at-least 1 ,role)))) (constraint (new-concept-constraint some-ind concept))) (unless (or (some-constraint-p constraint) (eq concept bottom-concept)) (error "some constraint expected, found: ~S" constraint)) (let* ((some-all-constraints (unless (eq concept bottom-concept) (get-related-all-or-some-constraints (list constraint) state))) (all-constraints (second (first some-all-constraints))) (concept-list (if (eq concept bottom-concept) (list bottom-concept) (and some-all-constraints (construct-label constraint all-constraints))))) (make-srole :name (role-name role) :at-most nil :at-least nil :ancestors (filter-role-set (true-role-ancestors role) allowed-roles) :descendants (filter-role-set (true-role-descendants role) allowed-roles) :all-qualifications (or concept-list (list top-concept)) :constraints all-constraints))))) (defun compute-saved-relation-constraints (relation-constraints some-ind allowed-roles) (loop for constraint in relation-constraints unless (and (eql (constraint-ind-1 constraint) some-ind) (member (constraint-term constraint) allowed-roles)) collect constraint)) (defun inequations-satisfied-p (signatures allowed-roles remaining-exists-constraints relation-constraints state) #+:allegro (declare (:explain :tailmerging)) (let* ((expanded-constraints (state-expanded-constraints state)) (attribute-constraints (state-attribute-constraints state)) (concrete-domain-state (state-concrete-domain-state state)) (labels (state-labels state)) (indirectly-blocked-individuals (state-indirectly-blocked-individuals state)) (some-ind (signature-ind (first signatures))) (at-most-bounds (state-at-most-bounds state)) (params (state-parameters state)) (top-concept (state-top-concept params)) (bottom-concept (state-bottom-concept params)) (relation-role-list (when (state-tbox params) (compute-relation-role-list signatures top-concept at-most-bounds))) (srole-list (compute-srole-list signatures relation-role-list top-concept)) (at-most-role-list (compute-at-most-role-list at-most-bounds srole-list allowed-roles top-concept)) (all-roles (append at-most-role-list srole-list)) (remaining-role-list (compute-remaining-role-list allowed-roles all-roles some-ind state top-concept bottom-concept)) (complete-role-list (append remaining-role-list all-roles)) (satisfiable nil) (model-list nil)) (push some-ind *saved-ind*) (push (compute-saved-relation-constraints relation-constraints some-ind allowed-roles) *saved-relation-constraints*) (push state *saved-state*) (loop for role in all-roles unless (member (srole-name role) at-most-bounds :key (lambda (x) (role-name (bound-role x)))) do (setf (srole-at-most role) nil)) #+:debug (assert (every (lambda (x) (and (member (srole-name x) (srole-ancestors x)) (member (srole-name x) (srole-descendants x)))) complete-role-list)) (race-trace ("~&Simplex: testing satisfiability of role set ~S derived from signatures ~S~%" complete-role-list signatures)) (multiple-value-setq (satisfiable model-list) (let ((*simplex-number-of-variables* 0) (*simplex-number-of-equations* 0) (*simplex-number-of-iterations* 0)) (multiple-value-bind (solvable model) (check-number-restrictions complete-role-list nil nil nil nil) (push-statistics (list *simplex-number-of-variables* *simplex-number-of-equations* *simplex-number-of-iterations*) *simplex-statistics-list*) (pop *saved-ind*) (pop *saved-relation-constraints*) (pop *saved-state*) (if solvable (progn (race-trace ("~&Simplex: role set satisfied: ~S, model=~S~%" complete-role-list model)) (values t model)) (progn (add-clash-dependencies (collect-dependencies (mapcar #'bound-constraint at-most-bounds))) (add-signature-dependencies signatures) (set-clash-reasons (nconc (reduce #'append (mapcar #'signature-dependencies signatures)) (mapcar #'bound-constraint at-most-bounds) (list relation-constraints))) nil))))) (if satisfiable (let ((new-concept-constraints nil) (new-relation-constraints nil)) (multiple-value-setq (new-concept-constraints new-relation-constraints) (generate-model-constraints some-ind model-list signatures at-most-bounds)) (flet ((inequations-satisfied-p-continuation (sat-p xstate unused-1 unused-2 unused-3) (declare (ignore unused-1 unused-2 unused-3)) (if sat-p (progn (race-trace ("~&Remaining exists constraints satisfied: ~S ~ derived constraints= ~S ~S~%" remaining-exists-constraints new-concept-constraints new-relation-constraints)) ;(break) (added-constraints-satisfiable nil nil xstate t nil)) (progn (race-trace ("~&Remaining exists constraints failed: ~S~% failed rel-constraints ~S,~ dep=~S~%" remaining-exists-constraints relation-constraints *catching-clash-dependencies*)) (setf (first *collected-dependencies*) (union-dependencies *catching-clash-dependencies* (first *collected-dependencies*))) (handle-clash-with-backtrack-state state nil nil nil nil))))) (let* ((new-state-1 (copy-to-basic-kernel-state state)) (new-partially-expanded-or-stack (push-backtrack-stack #'inequations-satisfied-p-continuation (state-partially-expanded-or-stack new-state-1))) (new-state-2 (changed-kernel-state new-state-1 :unexpanded-exists-constraints remaining-exists-constraints :expanded-constraints expanded-constraints :relation-constraints relation-constraints :attribute-constraints attribute-constraints :concrete-domain-state concrete-domain-state :labels labels :indirectly-blocked-individuals indirectly-blocked-individuals :partially-expanded-or-stack new-partially-expanded-or-stack))) (race-trace ("~&Testing satisfiability of transformed constraints ~S ~S, state=~S~%" new-concept-constraints new-relation-constraints (copy-basic-kernel-state-internal new-state-2))) (added-constraints-satisfiable new-concept-constraints new-relation-constraints new-state-2 nil ;do not expand role-domain nil)))) (handle-clash-with-backtrack-state state nil nil nil nil)))) (defun generate-model-constraints (predecessor-ind model-list signatures at-most-bounds) (loop with concept-constraints = nil with relation-constraints = nil with at-most-constraints = (mapcar #'bound-constraint at-most-bounds) for (role-list at-least-value concept-list individual-list) in model-list for successor-ind = (first individual-list) do #+:debug (assert (null (rest individual-list))) #+:debug (and successor-ind (eql at-least-value 1)) ;#-:debug (declare (ignore at-least-value)) (let* ((new-concept-list (reduce #'append concept-list :initial-value nil)) (qualification (with-flatten-encodings (encode-concept-term `(and ,@new-concept-list)))) (roles (mapcar #'(lambda (srole) (get-role (srole-name srole))) role-list)) (role (if (rest roles) (make-nary-and-role roles) (first roles))) (dependencies (loop with result = nil for signature in signatures do (loop for dependency in (signature-dependencies signature) do (setf result (union (constraint-derived-from dependency) result))) finally (return result))) (concept-constraint (if successor-ind (concluded-concept-constraint successor-ind qualification (first at-most-constraints) (rest at-most-constraints)) (concluded-concept-constraint predecessor-ind (encode-concept-term (if (or (role-datatype role) (role-cd-attribute role)) `(d-at-least ,at-least-value ,role ,qualification) `(at-least ,at-least-value ,role ,qualification))) (first at-most-constraints) (rest at-most-constraints)))) (relation-constraint (when successor-ind (let ((result (new-relation-constraint predecessor-ind successor-ind role))) (setf (constraint-dependencies result) at-most-constraints) result)))) (setf (constraint-derived-from concept-constraint) dependencies) (push concept-constraint concept-constraints) (when relation-constraint (setf (constraint-derived-from relation-constraint) dependencies) (push relation-constraint relation-constraints))) finally (return (values concept-constraints relation-constraints)))) (defun collect-at-most-bounds (role bound-list top-concept) (loop for elem in bound-list when (and (subrole-p role (bound-role elem)) (not (eq (bound-qualification elem) top-concept))) collect (list (bound-number elem) (bound-qualification elem)))) (defun get-allowed-roles (at-most-bounds exists-constraints relation-constraints) (let* ((bound-subroles (loop with result = nil for bound in at-most-bounds do (setf result (union (remove-if #'role-internal-conjunction-p (true-role-descendants (bound-role bound))) result)) finally (return result))) (constraint-superroles (loop with result = nil for constraint in exists-constraints do (setf result (union (remove-if #'role-internal-conjunction-p (true-role-ancestors (concept-role (constraint-term constraint)))) result)) finally (return result))) (all-superroles (loop with result = constraint-superroles for constraint in relation-constraints do (setf result (union (remove-if #'role-internal-conjunction-p (true-role-ancestors (constraint-term constraint))) result)) finally (return result)))) (intersection bound-subroles all-superroles))) (defun true-role-ancestors (role) (adjoin role (remove-if #'role-internal-conjunction-p (role-ancestors-internal role)))) (defun true-role-descendants (role) (adjoin role (remove-if #'role-internal-conjunction-p (role-descendants-internal role)))) (defun filter-role-set (role-set allowed-roles) (loop for role in role-set when (member role allowed-roles) collect (role-name role))) (defun compute-added-exists-constraints (ind remaining-exists-constraints allowed-roles) (loop for constraint in remaining-exists-constraints when (and (eql ind (constraint-ind constraint)) (member (concept-role (constraint-term constraint)) allowed-roles)) collect constraint)) (defun merge-constraints-simplex (ind state unused-1 unused-2 unused-3) #+:allegro (declare (:explain :tailmerging)) (declare (ignore unused-1 unused-2 unused-3)) (with-race-trace-sublevel ("merge-constraints-simplex" :arguments (list ind state) :expanded nil :trace-result t) ;(break) (let* ((relation-constraints (if (and *use-relation-store* (not (relation-store-empty-p (state-relation-store state)))) (get-all-rel-constraints (state-relation-store state)) (state-relation-constraints state))) (at-most-bounds (state-at-most-bounds state)) (true-some-constraints (state-true-some-constraints state)) (remaining-exists-constraints (get-all-expanded-constraints (state-unexpanded-exists-constraints state) (state-unexpanded-exists-constraints-store state))) (label (list* (construct-label-from-constraints (append true-some-constraints (mapcar #'bound-constraint at-most-bounds))) (construct-label-from-constraints remaining-exists-constraints) relation-constraints)) (allowed-roles (get-allowed-roles at-most-bounds true-some-constraints relation-constraints)) (added-exists-constraints (compute-added-exists-constraints ind remaining-exists-constraints allowed-roles)) (related-exists-constraints (append added-exists-constraints true-some-constraints))) (if (member label *simplex-labels* :test #'equal) (progn (race-trace ("~&Blocking merge-constraints-simplex: label=~S, *simplex-labels*=~S~%" label *simplex-labels*)) ;(break) t) (progn (push label *simplex-labels*) (let ((signatures (create-signatures ind state related-exists-constraints relation-constraints (state-at-least-bounds state) at-most-bounds (state-relation-store state)))) (if (signature-violated-p signatures at-most-bounds) (handle-clash-with-backtrack-state state nil nil nil nil) (multiple-value-bind (new-unexpanded-exists-constraints new-unexpanded-exists-constraint-store) (if added-exists-constraints (remove-constraints-from-constraint-store added-exists-constraints (state-unexpanded-exists-constraints state) (state-unexpanded-exists-constraints-store state) (state-copy-unexpanded-exists-constraints-store-p state) state #'reset-exists-copy) (values (state-unexpanded-exists-constraints state) (state-unexpanded-exists-constraints-store state))) (when-debug added-exists-constraints (race-trace ("~&Extending related exists-constraints by ~S~%" added-exists-constraints))) (race-trace ("~&Starting with signatures ~S~%" signatures)) (flet ((merge-constraints-simplex-continuation (sat-p xstate ignore-1 ignore-2 ignore-3) (declare (ignore xstate ignore-1 ignore-2 ignore-3)) (pop *simplex-labels*) (if sat-p t (handle-clash-with-backtrack-state state nil nil nil nil)))) (let* ((new-partially-expanded-or-stack (push-backtrack-stack #'merge-constraints-simplex-continuation (state-partially-expanded-or-stack state))) (new-state (changed-signature-state state :unexpanded-exists-constraints new-unexpanded-exists-constraints :unexpanded-exists-constraints-store new-unexpanded-exists-constraint-store :partially-expanded-or-stack new-partially-expanded-or-stack))) (inequations-satisfied-p signatures allowed-roles new-unexpanded-exists-constraints relation-constraints new-state)))))))))))
74702
;;; -*- Mode: Lisp; Syntax: Ansi-Common-Lisp; Package: RACER; Base: 10 -*- ;;; Copyright (c) 1998-2014, ;;; <NAME>, <NAME>, <NAME>. ;;; All rights reserved. ;;; Racer is distributed under the following BSD 3-clause license ;;; 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 Racer 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 ;;; <NAME>, <NAME>, NOR <NAME> 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 :racer) (defun role-successor-satisfiable-p (role-list concept-list successor-ind unused-1 unused-2) #+:allegro (declare (:explain :tailmerging)) (declare (ignore unused-1 unused-2)) (with-race-trace-sublevel ("role-successor-satisfiable-p" :expanded t :arguments (list role-list concept-list successor-ind *saved-ind* *saved-relation-constraints* *saved-state*) :trace-result t) (let* ((flat-concept-list (reduce #'append concept-list :initial-value nil)) (new-concept `(and . ,flat-concept-list)) (qualification (with-flatten-encodings (encode-concept-term new-concept))) (roles (mapcar #'(lambda (srole) (get-role (srole-name srole))) role-list)) (role (if (rest roles) (make-nary-and-role roles) (first roles))) (predecessor-ind (first *saved-ind*)) (state (first *saved-state*)) (params (state-parameters state)) (bottom-concept (state-bottom-concept params))) (when-race-trace t (if successor-ind (race-trace ("~&Testing ~S-successor ~S of ~S for qualification ~S~%" role successor-ind predecessor-ind new-concept)) (race-trace ("~&Testing ~S-successor of ~S for qualification ~S~%" role predecessor-ind new-concept)))) (if (eq qualification bottom-concept) nil (let ((relation-constraints (first *saved-relation-constraints*)) (all-relation-constraints (state-relation-constraints state)) (top-concept (state-top-concept params)) (relation-store (state-relation-store state))) (if (and (or all-relation-constraints (and *use-relation-store* (not (relation-store-empty-p relation-store)))) (null successor-ind) (eq qualification top-concept) (if (and *use-relation-store* (not (relation-store-empty-p relation-store))) (role-find-if-in-relation-store predecessor-ind role relation-store) (role-find-if-in-relation-constraints predecessor-ind role all-relation-constraints))) t (let ((unexpanded-exists-constraints (state-unexpanded-exists-constraints state)) (attribute-constraints (state-attribute-constraints state)) (concrete-domain-state (state-concrete-domain-state state)) (labels (state-labels state)) (indirectly-blocked-individuals (state-indirectly-blocked-individuals state)) (concept-constraint (if successor-ind (new-concept-constraint successor-ind qualification) (new-concept-constraint predecessor-ind (if (null flat-concept-list) (encode-concept-term (if (or (role-datatype role) (role-cd-attribute role)) `(d-at-least 1 ,role) `(at-least 1 ,role))) (encode-concept-term (if (or (role-datatype role) (role-cd-attribute role)) `(d-some ,role ,qualification) `(some ,role ,qualification))))))) (relation-constraint (when successor-ind (list (new-relation-constraint predecessor-ind successor-ind role)))) (expanded-constraints (state-expanded-constraints state)) (unexpanded-exists-constraints-store (state-unexpanded-exists-constraints-store state)) (new-state-1 (copy-signature-kernel-state state t))) (multiple-value-bind (remaining-exists-constraints new-unexpanded-exists-constraint-store) (if successor-ind (values unexpanded-exists-constraints unexpanded-exists-constraints-store) (if (or relation-constraints (not (relation-store-empty-p relation-store))) (remove-selected-constraints-from-constraint-store (lambda (constraint) (not (eql predecessor-ind (constraint-ind constraint)))) predecessor-ind unexpanded-exists-constraints unexpanded-exists-constraints-store (state-copy-unexpanded-exists-constraints-store-p new-state-1) new-state-1 #'reset-exists-copy) (values nil nil))) (let ((dependencies (reduce #'union role-list :key #'srole-constraints :initial-value nil))) (setf (constraint-dependencies concept-constraint) dependencies) (when relation-constraint (setf (constraint-dependencies (first relation-constraint)) dependencies))) (unless (and (eq remaining-exists-constraints unexpanded-exists-constraints) (eq unexpanded-exists-constraints-store new-unexpanded-exists-constraint-store)) (race-trace ("~&Testing with reduced exists constraints ~S / ~S, all=~S / ~S~%" remaining-exists-constraints unexpanded-exists-constraints new-unexpanded-exists-constraint-store unexpanded-exists-constraints-store))) (let ((old-merging-partitions-caching *merging-partitions-caching*)) (flet ((role-successor-satisfiable-p-continuation (sat-p xstate ignore-1 ignore-2 ignore-3) (declare (ignore xstate ignore-1 ignore-2 ignore-3)) (setf *merging-partitions-caching* old-merging-partitions-caching) (if sat-p t (progn #+:debug (assert (or (null *catching-clash-dependencies*) (and (consp *collected-dependencies*) (listp (first *collected-dependencies*))))) (when (and *catching-clash-dependencies* (consp *collected-dependencies*)) (setf (first *collected-dependencies*) (union-dependencies *catching-clash-dependencies* (first *collected-dependencies*))) (race-trace ("~&New *collected-dependencies*=~S~%" *collected-dependencies*))) nil)))) (let* ((new-state-2 (copy-to-basic-kernel-state new-state-1)) (new-partially-expanded-or-stack (push-backtrack-stack #'role-successor-satisfiable-p-continuation nil)) (new-state-3 (changed-kernel-state new-state-2 :unexpanded-exists-constraints remaining-exists-constraints :expanded-constraints expanded-constraints :relation-constraints relation-constraints :attribute-constraints attribute-constraints :concrete-domain-state concrete-domain-state :labels labels :indirectly-blocked-individuals indirectly-blocked-individuals :unexpanded-exists-constraints-store new-unexpanded-exists-constraint-store :save-completion nil :partially-expanded-or-stack new-partially-expanded-or-stack))) (setf *merging-partitions-caching* nil) ; do not cache intermediate results!!! (with-race-trace-sublevel ("added-constraints-satisfiable" :expanded nil :arguments (list concept-constraint relation-constraint new-state-3) :trace-result t) (added-constraints-satisfiable concept-constraint relation-constraint new-state-3 nil ; do not expand role-domain nil))))))))))))) (defun role-find-if-in-relation-constraints (predecessor-ind role all-relation-constraints) (loop for rel-constraint in all-relation-constraints thereis (and (eql predecessor-ind (constraint-ind-1 rel-constraint)) (member role (role-ancestors-internal (constraint-term rel-constraint)))))) (defun compute-relation-role-list (signatures top-concept at-most-bounds) (loop with rel-list = nil for signature in signatures for role = (signature-role signature) for ind-name = (first (signature-successor-ind-set signature)) do #+:debug (assert (null (rest (signature-successor-ind-set signature)))) (when ind-name (loop with parents = (if (role-internal-conjunction-p role) (role-parents-internal role) (list role)) for parent in parents for parent-name = (role-name parent) for old-srole = (find parent-name rel-list :key #'srole-name) do (if old-srole (pushnew ind-name (srole-individuals old-srole)) (multiple-value-bind (value bound) (get-at-most-bound parent (list top-concept) at-most-bounds) (push (make-srole :name parent-name :at-most value :at-least nil :ancestors (mapcar #'role-name (true-role-ancestors parent)) :descendants (mapcar #'role-name (true-role-descendants parent)) :individuals (list ind-name) :constraints (when bound (list (bound-constraint bound)))) rel-list))))) finally (return rel-list))) (defun compute-srole-list (signatures relation-role-list top-concept) (loop with at-least-list = nil with some-list = relation-role-list for signature in (remove-if #'signature-successor-ind-set signatures) for role = (signature-role signature) for role-name = (role-name (signature-role signature)) for some-constraint = (find-if #'(lambda (constraint) (when (concept-constraint-p constraint) (let ((term (constraint-term constraint))) (and (not (constraint-negated-p constraint)) (exists-concept-p term) (not (eq (concept-term term) top-concept)))))) (signature-dependencies signature)) for some-no = (when some-constraint (concept-number-restriction (constraint-term some-constraint))) for old-srole = (or (find role-name some-list :key #'srole-name) (find role-name at-least-list :key #'srole-name)) do (if some-constraint (if old-srole (progn (pushnew (list some-no (concept-term (constraint-term some-constraint))) (srole-qualified-at-least old-srole) :test #'equal) (pushnew some-constraint (srole-constraints old-srole))) (push (make-srole :name role-name #|:at-most (get-at-most-bound (signature-role signature) (list top-concept) at-most-bounds)|# :at-least nil :ancestors (mapcar #'role-name (true-role-ancestors role)) :descendants (mapcar #'role-name (true-role-descendants role)) :qualified-at-least (list (list some-no (concept-term (constraint-term some-constraint)))) :constraints (list some-constraint)) some-list)) (if old-srole (progn (unless (srole-at-least old-srole) (setf (srole-at-least old-srole) (signature-cardinality signature))) (setf (srole-all-qualifications old-srole) (append (signature-concepts signature) (srole-all-qualifications old-srole))) (setf (srole-constraints old-srole) (constraint-set-union (signature-dependencies signature) (srole-constraints old-srole)))) (push (make-srole :name role-name #|:at-most (get-at-most-bound (signature-role signature) (list top-concept) at-most-bounds)|# :at-least (signature-cardinality signature) :ancestors (mapcar #'role-name (true-role-ancestors role)) :descendants (mapcar #'role-name (true-role-descendants role)) :all-qualifications (signature-concepts signature) :constraints (signature-dependencies signature)) at-least-list))) ;(break) finally (return (append some-list at-least-list)))) (defun compute-at-most-role-list (at-most-bounds srole-list allowed-roles top-concept) (loop for at-most-bound in at-most-bounds for role = (bound-role at-most-bound) for bound = (bound-number at-most-bound) for role-name = (role-name role) for old-entry = (find role-name srole-list :key #'srole-name) if old-entry if (eq (bound-qualification at-most-bound) top-concept) when (null (srole-at-most old-entry)) do (setf (srole-at-most old-entry) bound) end else do (pushnew (list (bound-number at-most-bound) (bound-qualification at-most-bound)) (srole-qualified-at-most old-entry) :test #'equal) end else if (eq (bound-qualification at-most-bound) top-concept) collect (make-srole :name role-name :at-most bound :ancestors (filter-role-set (true-role-ancestors role) allowed-roles) :descendants (filter-role-set (true-role-descendants role) allowed-roles) :all-qualifications (list top-concept) :constraints (list (bound-constraint at-most-bound))) else collect (make-srole :name role-name :qualified-at-most (collect-at-most-bounds role at-most-bounds top-concept) :ancestors (filter-role-set (true-role-ancestors role) allowed-roles) :descendants (filter-role-set (true-role-descendants role) allowed-roles) :all-qualifications (list top-concept) :constraints (list (bound-constraint at-most-bound))))) (defun compute-remaining-role-list (allowed-roles all-roles some-ind state top-concept bottom-concept) (loop for role in allowed-roles unless (member (role-name role) all-roles :key #'srole-name) collect (let* ((concept (without-taxonomic-encoding (encode-concept-term `(at-least 1 ,role)))) (constraint (new-concept-constraint some-ind concept))) (unless (or (some-constraint-p constraint) (eq concept bottom-concept)) (error "some constraint expected, found: ~S" constraint)) (let* ((some-all-constraints (unless (eq concept bottom-concept) (get-related-all-or-some-constraints (list constraint) state))) (all-constraints (second (first some-all-constraints))) (concept-list (if (eq concept bottom-concept) (list bottom-concept) (and some-all-constraints (construct-label constraint all-constraints))))) (make-srole :name (role-name role) :at-most nil :at-least nil :ancestors (filter-role-set (true-role-ancestors role) allowed-roles) :descendants (filter-role-set (true-role-descendants role) allowed-roles) :all-qualifications (or concept-list (list top-concept)) :constraints all-constraints))))) (defun compute-saved-relation-constraints (relation-constraints some-ind allowed-roles) (loop for constraint in relation-constraints unless (and (eql (constraint-ind-1 constraint) some-ind) (member (constraint-term constraint) allowed-roles)) collect constraint)) (defun inequations-satisfied-p (signatures allowed-roles remaining-exists-constraints relation-constraints state) #+:allegro (declare (:explain :tailmerging)) (let* ((expanded-constraints (state-expanded-constraints state)) (attribute-constraints (state-attribute-constraints state)) (concrete-domain-state (state-concrete-domain-state state)) (labels (state-labels state)) (indirectly-blocked-individuals (state-indirectly-blocked-individuals state)) (some-ind (signature-ind (first signatures))) (at-most-bounds (state-at-most-bounds state)) (params (state-parameters state)) (top-concept (state-top-concept params)) (bottom-concept (state-bottom-concept params)) (relation-role-list (when (state-tbox params) (compute-relation-role-list signatures top-concept at-most-bounds))) (srole-list (compute-srole-list signatures relation-role-list top-concept)) (at-most-role-list (compute-at-most-role-list at-most-bounds srole-list allowed-roles top-concept)) (all-roles (append at-most-role-list srole-list)) (remaining-role-list (compute-remaining-role-list allowed-roles all-roles some-ind state top-concept bottom-concept)) (complete-role-list (append remaining-role-list all-roles)) (satisfiable nil) (model-list nil)) (push some-ind *saved-ind*) (push (compute-saved-relation-constraints relation-constraints some-ind allowed-roles) *saved-relation-constraints*) (push state *saved-state*) (loop for role in all-roles unless (member (srole-name role) at-most-bounds :key (lambda (x) (role-name (bound-role x)))) do (setf (srole-at-most role) nil)) #+:debug (assert (every (lambda (x) (and (member (srole-name x) (srole-ancestors x)) (member (srole-name x) (srole-descendants x)))) complete-role-list)) (race-trace ("~&Simplex: testing satisfiability of role set ~S derived from signatures ~S~%" complete-role-list signatures)) (multiple-value-setq (satisfiable model-list) (let ((*simplex-number-of-variables* 0) (*simplex-number-of-equations* 0) (*simplex-number-of-iterations* 0)) (multiple-value-bind (solvable model) (check-number-restrictions complete-role-list nil nil nil nil) (push-statistics (list *simplex-number-of-variables* *simplex-number-of-equations* *simplex-number-of-iterations*) *simplex-statistics-list*) (pop *saved-ind*) (pop *saved-relation-constraints*) (pop *saved-state*) (if solvable (progn (race-trace ("~&Simplex: role set satisfied: ~S, model=~S~%" complete-role-list model)) (values t model)) (progn (add-clash-dependencies (collect-dependencies (mapcar #'bound-constraint at-most-bounds))) (add-signature-dependencies signatures) (set-clash-reasons (nconc (reduce #'append (mapcar #'signature-dependencies signatures)) (mapcar #'bound-constraint at-most-bounds) (list relation-constraints))) nil))))) (if satisfiable (let ((new-concept-constraints nil) (new-relation-constraints nil)) (multiple-value-setq (new-concept-constraints new-relation-constraints) (generate-model-constraints some-ind model-list signatures at-most-bounds)) (flet ((inequations-satisfied-p-continuation (sat-p xstate unused-1 unused-2 unused-3) (declare (ignore unused-1 unused-2 unused-3)) (if sat-p (progn (race-trace ("~&Remaining exists constraints satisfied: ~S ~ derived constraints= ~S ~S~%" remaining-exists-constraints new-concept-constraints new-relation-constraints)) ;(break) (added-constraints-satisfiable nil nil xstate t nil)) (progn (race-trace ("~&Remaining exists constraints failed: ~S~% failed rel-constraints ~S,~ dep=~S~%" remaining-exists-constraints relation-constraints *catching-clash-dependencies*)) (setf (first *collected-dependencies*) (union-dependencies *catching-clash-dependencies* (first *collected-dependencies*))) (handle-clash-with-backtrack-state state nil nil nil nil))))) (let* ((new-state-1 (copy-to-basic-kernel-state state)) (new-partially-expanded-or-stack (push-backtrack-stack #'inequations-satisfied-p-continuation (state-partially-expanded-or-stack new-state-1))) (new-state-2 (changed-kernel-state new-state-1 :unexpanded-exists-constraints remaining-exists-constraints :expanded-constraints expanded-constraints :relation-constraints relation-constraints :attribute-constraints attribute-constraints :concrete-domain-state concrete-domain-state :labels labels :indirectly-blocked-individuals indirectly-blocked-individuals :partially-expanded-or-stack new-partially-expanded-or-stack))) (race-trace ("~&Testing satisfiability of transformed constraints ~S ~S, state=~S~%" new-concept-constraints new-relation-constraints (copy-basic-kernel-state-internal new-state-2))) (added-constraints-satisfiable new-concept-constraints new-relation-constraints new-state-2 nil ;do not expand role-domain nil)))) (handle-clash-with-backtrack-state state nil nil nil nil)))) (defun generate-model-constraints (predecessor-ind model-list signatures at-most-bounds) (loop with concept-constraints = nil with relation-constraints = nil with at-most-constraints = (mapcar #'bound-constraint at-most-bounds) for (role-list at-least-value concept-list individual-list) in model-list for successor-ind = (first individual-list) do #+:debug (assert (null (rest individual-list))) #+:debug (and successor-ind (eql at-least-value 1)) ;#-:debug (declare (ignore at-least-value)) (let* ((new-concept-list (reduce #'append concept-list :initial-value nil)) (qualification (with-flatten-encodings (encode-concept-term `(and ,@new-concept-list)))) (roles (mapcar #'(lambda (srole) (get-role (srole-name srole))) role-list)) (role (if (rest roles) (make-nary-and-role roles) (first roles))) (dependencies (loop with result = nil for signature in signatures do (loop for dependency in (signature-dependencies signature) do (setf result (union (constraint-derived-from dependency) result))) finally (return result))) (concept-constraint (if successor-ind (concluded-concept-constraint successor-ind qualification (first at-most-constraints) (rest at-most-constraints)) (concluded-concept-constraint predecessor-ind (encode-concept-term (if (or (role-datatype role) (role-cd-attribute role)) `(d-at-least ,at-least-value ,role ,qualification) `(at-least ,at-least-value ,role ,qualification))) (first at-most-constraints) (rest at-most-constraints)))) (relation-constraint (when successor-ind (let ((result (new-relation-constraint predecessor-ind successor-ind role))) (setf (constraint-dependencies result) at-most-constraints) result)))) (setf (constraint-derived-from concept-constraint) dependencies) (push concept-constraint concept-constraints) (when relation-constraint (setf (constraint-derived-from relation-constraint) dependencies) (push relation-constraint relation-constraints))) finally (return (values concept-constraints relation-constraints)))) (defun collect-at-most-bounds (role bound-list top-concept) (loop for elem in bound-list when (and (subrole-p role (bound-role elem)) (not (eq (bound-qualification elem) top-concept))) collect (list (bound-number elem) (bound-qualification elem)))) (defun get-allowed-roles (at-most-bounds exists-constraints relation-constraints) (let* ((bound-subroles (loop with result = nil for bound in at-most-bounds do (setf result (union (remove-if #'role-internal-conjunction-p (true-role-descendants (bound-role bound))) result)) finally (return result))) (constraint-superroles (loop with result = nil for constraint in exists-constraints do (setf result (union (remove-if #'role-internal-conjunction-p (true-role-ancestors (concept-role (constraint-term constraint)))) result)) finally (return result))) (all-superroles (loop with result = constraint-superroles for constraint in relation-constraints do (setf result (union (remove-if #'role-internal-conjunction-p (true-role-ancestors (constraint-term constraint))) result)) finally (return result)))) (intersection bound-subroles all-superroles))) (defun true-role-ancestors (role) (adjoin role (remove-if #'role-internal-conjunction-p (role-ancestors-internal role)))) (defun true-role-descendants (role) (adjoin role (remove-if #'role-internal-conjunction-p (role-descendants-internal role)))) (defun filter-role-set (role-set allowed-roles) (loop for role in role-set when (member role allowed-roles) collect (role-name role))) (defun compute-added-exists-constraints (ind remaining-exists-constraints allowed-roles) (loop for constraint in remaining-exists-constraints when (and (eql ind (constraint-ind constraint)) (member (concept-role (constraint-term constraint)) allowed-roles)) collect constraint)) (defun merge-constraints-simplex (ind state unused-1 unused-2 unused-3) #+:allegro (declare (:explain :tailmerging)) (declare (ignore unused-1 unused-2 unused-3)) (with-race-trace-sublevel ("merge-constraints-simplex" :arguments (list ind state) :expanded nil :trace-result t) ;(break) (let* ((relation-constraints (if (and *use-relation-store* (not (relation-store-empty-p (state-relation-store state)))) (get-all-rel-constraints (state-relation-store state)) (state-relation-constraints state))) (at-most-bounds (state-at-most-bounds state)) (true-some-constraints (state-true-some-constraints state)) (remaining-exists-constraints (get-all-expanded-constraints (state-unexpanded-exists-constraints state) (state-unexpanded-exists-constraints-store state))) (label (list* (construct-label-from-constraints (append true-some-constraints (mapcar #'bound-constraint at-most-bounds))) (construct-label-from-constraints remaining-exists-constraints) relation-constraints)) (allowed-roles (get-allowed-roles at-most-bounds true-some-constraints relation-constraints)) (added-exists-constraints (compute-added-exists-constraints ind remaining-exists-constraints allowed-roles)) (related-exists-constraints (append added-exists-constraints true-some-constraints))) (if (member label *simplex-labels* :test #'equal) (progn (race-trace ("~&Blocking merge-constraints-simplex: label=~S, *simplex-labels*=~S~%" label *simplex-labels*)) ;(break) t) (progn (push label *simplex-labels*) (let ((signatures (create-signatures ind state related-exists-constraints relation-constraints (state-at-least-bounds state) at-most-bounds (state-relation-store state)))) (if (signature-violated-p signatures at-most-bounds) (handle-clash-with-backtrack-state state nil nil nil nil) (multiple-value-bind (new-unexpanded-exists-constraints new-unexpanded-exists-constraint-store) (if added-exists-constraints (remove-constraints-from-constraint-store added-exists-constraints (state-unexpanded-exists-constraints state) (state-unexpanded-exists-constraints-store state) (state-copy-unexpanded-exists-constraints-store-p state) state #'reset-exists-copy) (values (state-unexpanded-exists-constraints state) (state-unexpanded-exists-constraints-store state))) (when-debug added-exists-constraints (race-trace ("~&Extending related exists-constraints by ~S~%" added-exists-constraints))) (race-trace ("~&Starting with signatures ~S~%" signatures)) (flet ((merge-constraints-simplex-continuation (sat-p xstate ignore-1 ignore-2 ignore-3) (declare (ignore xstate ignore-1 ignore-2 ignore-3)) (pop *simplex-labels*) (if sat-p t (handle-clash-with-backtrack-state state nil nil nil nil)))) (let* ((new-partially-expanded-or-stack (push-backtrack-stack #'merge-constraints-simplex-continuation (state-partially-expanded-or-stack state))) (new-state (changed-signature-state state :unexpanded-exists-constraints new-unexpanded-exists-constraints :unexpanded-exists-constraints-store new-unexpanded-exists-constraint-store :partially-expanded-or-stack new-partially-expanded-or-stack))) (inequations-satisfied-p signatures allowed-roles new-unexpanded-exists-constraints relation-constraints new-state)))))))))))
true
;;; -*- Mode: Lisp; Syntax: Ansi-Common-Lisp; Package: RACER; Base: 10 -*- ;;; Copyright (c) 1998-2014, ;;; PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI. ;;; All rights reserved. ;;; Racer is distributed under the following BSD 3-clause license ;;; 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 Racer 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 ;;; PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI, NOR PI:NAME:<NAME>END_PI 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 :racer) (defun role-successor-satisfiable-p (role-list concept-list successor-ind unused-1 unused-2) #+:allegro (declare (:explain :tailmerging)) (declare (ignore unused-1 unused-2)) (with-race-trace-sublevel ("role-successor-satisfiable-p" :expanded t :arguments (list role-list concept-list successor-ind *saved-ind* *saved-relation-constraints* *saved-state*) :trace-result t) (let* ((flat-concept-list (reduce #'append concept-list :initial-value nil)) (new-concept `(and . ,flat-concept-list)) (qualification (with-flatten-encodings (encode-concept-term new-concept))) (roles (mapcar #'(lambda (srole) (get-role (srole-name srole))) role-list)) (role (if (rest roles) (make-nary-and-role roles) (first roles))) (predecessor-ind (first *saved-ind*)) (state (first *saved-state*)) (params (state-parameters state)) (bottom-concept (state-bottom-concept params))) (when-race-trace t (if successor-ind (race-trace ("~&Testing ~S-successor ~S of ~S for qualification ~S~%" role successor-ind predecessor-ind new-concept)) (race-trace ("~&Testing ~S-successor of ~S for qualification ~S~%" role predecessor-ind new-concept)))) (if (eq qualification bottom-concept) nil (let ((relation-constraints (first *saved-relation-constraints*)) (all-relation-constraints (state-relation-constraints state)) (top-concept (state-top-concept params)) (relation-store (state-relation-store state))) (if (and (or all-relation-constraints (and *use-relation-store* (not (relation-store-empty-p relation-store)))) (null successor-ind) (eq qualification top-concept) (if (and *use-relation-store* (not (relation-store-empty-p relation-store))) (role-find-if-in-relation-store predecessor-ind role relation-store) (role-find-if-in-relation-constraints predecessor-ind role all-relation-constraints))) t (let ((unexpanded-exists-constraints (state-unexpanded-exists-constraints state)) (attribute-constraints (state-attribute-constraints state)) (concrete-domain-state (state-concrete-domain-state state)) (labels (state-labels state)) (indirectly-blocked-individuals (state-indirectly-blocked-individuals state)) (concept-constraint (if successor-ind (new-concept-constraint successor-ind qualification) (new-concept-constraint predecessor-ind (if (null flat-concept-list) (encode-concept-term (if (or (role-datatype role) (role-cd-attribute role)) `(d-at-least 1 ,role) `(at-least 1 ,role))) (encode-concept-term (if (or (role-datatype role) (role-cd-attribute role)) `(d-some ,role ,qualification) `(some ,role ,qualification))))))) (relation-constraint (when successor-ind (list (new-relation-constraint predecessor-ind successor-ind role)))) (expanded-constraints (state-expanded-constraints state)) (unexpanded-exists-constraints-store (state-unexpanded-exists-constraints-store state)) (new-state-1 (copy-signature-kernel-state state t))) (multiple-value-bind (remaining-exists-constraints new-unexpanded-exists-constraint-store) (if successor-ind (values unexpanded-exists-constraints unexpanded-exists-constraints-store) (if (or relation-constraints (not (relation-store-empty-p relation-store))) (remove-selected-constraints-from-constraint-store (lambda (constraint) (not (eql predecessor-ind (constraint-ind constraint)))) predecessor-ind unexpanded-exists-constraints unexpanded-exists-constraints-store (state-copy-unexpanded-exists-constraints-store-p new-state-1) new-state-1 #'reset-exists-copy) (values nil nil))) (let ((dependencies (reduce #'union role-list :key #'srole-constraints :initial-value nil))) (setf (constraint-dependencies concept-constraint) dependencies) (when relation-constraint (setf (constraint-dependencies (first relation-constraint)) dependencies))) (unless (and (eq remaining-exists-constraints unexpanded-exists-constraints) (eq unexpanded-exists-constraints-store new-unexpanded-exists-constraint-store)) (race-trace ("~&Testing with reduced exists constraints ~S / ~S, all=~S / ~S~%" remaining-exists-constraints unexpanded-exists-constraints new-unexpanded-exists-constraint-store unexpanded-exists-constraints-store))) (let ((old-merging-partitions-caching *merging-partitions-caching*)) (flet ((role-successor-satisfiable-p-continuation (sat-p xstate ignore-1 ignore-2 ignore-3) (declare (ignore xstate ignore-1 ignore-2 ignore-3)) (setf *merging-partitions-caching* old-merging-partitions-caching) (if sat-p t (progn #+:debug (assert (or (null *catching-clash-dependencies*) (and (consp *collected-dependencies*) (listp (first *collected-dependencies*))))) (when (and *catching-clash-dependencies* (consp *collected-dependencies*)) (setf (first *collected-dependencies*) (union-dependencies *catching-clash-dependencies* (first *collected-dependencies*))) (race-trace ("~&New *collected-dependencies*=~S~%" *collected-dependencies*))) nil)))) (let* ((new-state-2 (copy-to-basic-kernel-state new-state-1)) (new-partially-expanded-or-stack (push-backtrack-stack #'role-successor-satisfiable-p-continuation nil)) (new-state-3 (changed-kernel-state new-state-2 :unexpanded-exists-constraints remaining-exists-constraints :expanded-constraints expanded-constraints :relation-constraints relation-constraints :attribute-constraints attribute-constraints :concrete-domain-state concrete-domain-state :labels labels :indirectly-blocked-individuals indirectly-blocked-individuals :unexpanded-exists-constraints-store new-unexpanded-exists-constraint-store :save-completion nil :partially-expanded-or-stack new-partially-expanded-or-stack))) (setf *merging-partitions-caching* nil) ; do not cache intermediate results!!! (with-race-trace-sublevel ("added-constraints-satisfiable" :expanded nil :arguments (list concept-constraint relation-constraint new-state-3) :trace-result t) (added-constraints-satisfiable concept-constraint relation-constraint new-state-3 nil ; do not expand role-domain nil))))))))))))) (defun role-find-if-in-relation-constraints (predecessor-ind role all-relation-constraints) (loop for rel-constraint in all-relation-constraints thereis (and (eql predecessor-ind (constraint-ind-1 rel-constraint)) (member role (role-ancestors-internal (constraint-term rel-constraint)))))) (defun compute-relation-role-list (signatures top-concept at-most-bounds) (loop with rel-list = nil for signature in signatures for role = (signature-role signature) for ind-name = (first (signature-successor-ind-set signature)) do #+:debug (assert (null (rest (signature-successor-ind-set signature)))) (when ind-name (loop with parents = (if (role-internal-conjunction-p role) (role-parents-internal role) (list role)) for parent in parents for parent-name = (role-name parent) for old-srole = (find parent-name rel-list :key #'srole-name) do (if old-srole (pushnew ind-name (srole-individuals old-srole)) (multiple-value-bind (value bound) (get-at-most-bound parent (list top-concept) at-most-bounds) (push (make-srole :name parent-name :at-most value :at-least nil :ancestors (mapcar #'role-name (true-role-ancestors parent)) :descendants (mapcar #'role-name (true-role-descendants parent)) :individuals (list ind-name) :constraints (when bound (list (bound-constraint bound)))) rel-list))))) finally (return rel-list))) (defun compute-srole-list (signatures relation-role-list top-concept) (loop with at-least-list = nil with some-list = relation-role-list for signature in (remove-if #'signature-successor-ind-set signatures) for role = (signature-role signature) for role-name = (role-name (signature-role signature)) for some-constraint = (find-if #'(lambda (constraint) (when (concept-constraint-p constraint) (let ((term (constraint-term constraint))) (and (not (constraint-negated-p constraint)) (exists-concept-p term) (not (eq (concept-term term) top-concept)))))) (signature-dependencies signature)) for some-no = (when some-constraint (concept-number-restriction (constraint-term some-constraint))) for old-srole = (or (find role-name some-list :key #'srole-name) (find role-name at-least-list :key #'srole-name)) do (if some-constraint (if old-srole (progn (pushnew (list some-no (concept-term (constraint-term some-constraint))) (srole-qualified-at-least old-srole) :test #'equal) (pushnew some-constraint (srole-constraints old-srole))) (push (make-srole :name role-name #|:at-most (get-at-most-bound (signature-role signature) (list top-concept) at-most-bounds)|# :at-least nil :ancestors (mapcar #'role-name (true-role-ancestors role)) :descendants (mapcar #'role-name (true-role-descendants role)) :qualified-at-least (list (list some-no (concept-term (constraint-term some-constraint)))) :constraints (list some-constraint)) some-list)) (if old-srole (progn (unless (srole-at-least old-srole) (setf (srole-at-least old-srole) (signature-cardinality signature))) (setf (srole-all-qualifications old-srole) (append (signature-concepts signature) (srole-all-qualifications old-srole))) (setf (srole-constraints old-srole) (constraint-set-union (signature-dependencies signature) (srole-constraints old-srole)))) (push (make-srole :name role-name #|:at-most (get-at-most-bound (signature-role signature) (list top-concept) at-most-bounds)|# :at-least (signature-cardinality signature) :ancestors (mapcar #'role-name (true-role-ancestors role)) :descendants (mapcar #'role-name (true-role-descendants role)) :all-qualifications (signature-concepts signature) :constraints (signature-dependencies signature)) at-least-list))) ;(break) finally (return (append some-list at-least-list)))) (defun compute-at-most-role-list (at-most-bounds srole-list allowed-roles top-concept) (loop for at-most-bound in at-most-bounds for role = (bound-role at-most-bound) for bound = (bound-number at-most-bound) for role-name = (role-name role) for old-entry = (find role-name srole-list :key #'srole-name) if old-entry if (eq (bound-qualification at-most-bound) top-concept) when (null (srole-at-most old-entry)) do (setf (srole-at-most old-entry) bound) end else do (pushnew (list (bound-number at-most-bound) (bound-qualification at-most-bound)) (srole-qualified-at-most old-entry) :test #'equal) end else if (eq (bound-qualification at-most-bound) top-concept) collect (make-srole :name role-name :at-most bound :ancestors (filter-role-set (true-role-ancestors role) allowed-roles) :descendants (filter-role-set (true-role-descendants role) allowed-roles) :all-qualifications (list top-concept) :constraints (list (bound-constraint at-most-bound))) else collect (make-srole :name role-name :qualified-at-most (collect-at-most-bounds role at-most-bounds top-concept) :ancestors (filter-role-set (true-role-ancestors role) allowed-roles) :descendants (filter-role-set (true-role-descendants role) allowed-roles) :all-qualifications (list top-concept) :constraints (list (bound-constraint at-most-bound))))) (defun compute-remaining-role-list (allowed-roles all-roles some-ind state top-concept bottom-concept) (loop for role in allowed-roles unless (member (role-name role) all-roles :key #'srole-name) collect (let* ((concept (without-taxonomic-encoding (encode-concept-term `(at-least 1 ,role)))) (constraint (new-concept-constraint some-ind concept))) (unless (or (some-constraint-p constraint) (eq concept bottom-concept)) (error "some constraint expected, found: ~S" constraint)) (let* ((some-all-constraints (unless (eq concept bottom-concept) (get-related-all-or-some-constraints (list constraint) state))) (all-constraints (second (first some-all-constraints))) (concept-list (if (eq concept bottom-concept) (list bottom-concept) (and some-all-constraints (construct-label constraint all-constraints))))) (make-srole :name (role-name role) :at-most nil :at-least nil :ancestors (filter-role-set (true-role-ancestors role) allowed-roles) :descendants (filter-role-set (true-role-descendants role) allowed-roles) :all-qualifications (or concept-list (list top-concept)) :constraints all-constraints))))) (defun compute-saved-relation-constraints (relation-constraints some-ind allowed-roles) (loop for constraint in relation-constraints unless (and (eql (constraint-ind-1 constraint) some-ind) (member (constraint-term constraint) allowed-roles)) collect constraint)) (defun inequations-satisfied-p (signatures allowed-roles remaining-exists-constraints relation-constraints state) #+:allegro (declare (:explain :tailmerging)) (let* ((expanded-constraints (state-expanded-constraints state)) (attribute-constraints (state-attribute-constraints state)) (concrete-domain-state (state-concrete-domain-state state)) (labels (state-labels state)) (indirectly-blocked-individuals (state-indirectly-blocked-individuals state)) (some-ind (signature-ind (first signatures))) (at-most-bounds (state-at-most-bounds state)) (params (state-parameters state)) (top-concept (state-top-concept params)) (bottom-concept (state-bottom-concept params)) (relation-role-list (when (state-tbox params) (compute-relation-role-list signatures top-concept at-most-bounds))) (srole-list (compute-srole-list signatures relation-role-list top-concept)) (at-most-role-list (compute-at-most-role-list at-most-bounds srole-list allowed-roles top-concept)) (all-roles (append at-most-role-list srole-list)) (remaining-role-list (compute-remaining-role-list allowed-roles all-roles some-ind state top-concept bottom-concept)) (complete-role-list (append remaining-role-list all-roles)) (satisfiable nil) (model-list nil)) (push some-ind *saved-ind*) (push (compute-saved-relation-constraints relation-constraints some-ind allowed-roles) *saved-relation-constraints*) (push state *saved-state*) (loop for role in all-roles unless (member (srole-name role) at-most-bounds :key (lambda (x) (role-name (bound-role x)))) do (setf (srole-at-most role) nil)) #+:debug (assert (every (lambda (x) (and (member (srole-name x) (srole-ancestors x)) (member (srole-name x) (srole-descendants x)))) complete-role-list)) (race-trace ("~&Simplex: testing satisfiability of role set ~S derived from signatures ~S~%" complete-role-list signatures)) (multiple-value-setq (satisfiable model-list) (let ((*simplex-number-of-variables* 0) (*simplex-number-of-equations* 0) (*simplex-number-of-iterations* 0)) (multiple-value-bind (solvable model) (check-number-restrictions complete-role-list nil nil nil nil) (push-statistics (list *simplex-number-of-variables* *simplex-number-of-equations* *simplex-number-of-iterations*) *simplex-statistics-list*) (pop *saved-ind*) (pop *saved-relation-constraints*) (pop *saved-state*) (if solvable (progn (race-trace ("~&Simplex: role set satisfied: ~S, model=~S~%" complete-role-list model)) (values t model)) (progn (add-clash-dependencies (collect-dependencies (mapcar #'bound-constraint at-most-bounds))) (add-signature-dependencies signatures) (set-clash-reasons (nconc (reduce #'append (mapcar #'signature-dependencies signatures)) (mapcar #'bound-constraint at-most-bounds) (list relation-constraints))) nil))))) (if satisfiable (let ((new-concept-constraints nil) (new-relation-constraints nil)) (multiple-value-setq (new-concept-constraints new-relation-constraints) (generate-model-constraints some-ind model-list signatures at-most-bounds)) (flet ((inequations-satisfied-p-continuation (sat-p xstate unused-1 unused-2 unused-3) (declare (ignore unused-1 unused-2 unused-3)) (if sat-p (progn (race-trace ("~&Remaining exists constraints satisfied: ~S ~ derived constraints= ~S ~S~%" remaining-exists-constraints new-concept-constraints new-relation-constraints)) ;(break) (added-constraints-satisfiable nil nil xstate t nil)) (progn (race-trace ("~&Remaining exists constraints failed: ~S~% failed rel-constraints ~S,~ dep=~S~%" remaining-exists-constraints relation-constraints *catching-clash-dependencies*)) (setf (first *collected-dependencies*) (union-dependencies *catching-clash-dependencies* (first *collected-dependencies*))) (handle-clash-with-backtrack-state state nil nil nil nil))))) (let* ((new-state-1 (copy-to-basic-kernel-state state)) (new-partially-expanded-or-stack (push-backtrack-stack #'inequations-satisfied-p-continuation (state-partially-expanded-or-stack new-state-1))) (new-state-2 (changed-kernel-state new-state-1 :unexpanded-exists-constraints remaining-exists-constraints :expanded-constraints expanded-constraints :relation-constraints relation-constraints :attribute-constraints attribute-constraints :concrete-domain-state concrete-domain-state :labels labels :indirectly-blocked-individuals indirectly-blocked-individuals :partially-expanded-or-stack new-partially-expanded-or-stack))) (race-trace ("~&Testing satisfiability of transformed constraints ~S ~S, state=~S~%" new-concept-constraints new-relation-constraints (copy-basic-kernel-state-internal new-state-2))) (added-constraints-satisfiable new-concept-constraints new-relation-constraints new-state-2 nil ;do not expand role-domain nil)))) (handle-clash-with-backtrack-state state nil nil nil nil)))) (defun generate-model-constraints (predecessor-ind model-list signatures at-most-bounds) (loop with concept-constraints = nil with relation-constraints = nil with at-most-constraints = (mapcar #'bound-constraint at-most-bounds) for (role-list at-least-value concept-list individual-list) in model-list for successor-ind = (first individual-list) do #+:debug (assert (null (rest individual-list))) #+:debug (and successor-ind (eql at-least-value 1)) ;#-:debug (declare (ignore at-least-value)) (let* ((new-concept-list (reduce #'append concept-list :initial-value nil)) (qualification (with-flatten-encodings (encode-concept-term `(and ,@new-concept-list)))) (roles (mapcar #'(lambda (srole) (get-role (srole-name srole))) role-list)) (role (if (rest roles) (make-nary-and-role roles) (first roles))) (dependencies (loop with result = nil for signature in signatures do (loop for dependency in (signature-dependencies signature) do (setf result (union (constraint-derived-from dependency) result))) finally (return result))) (concept-constraint (if successor-ind (concluded-concept-constraint successor-ind qualification (first at-most-constraints) (rest at-most-constraints)) (concluded-concept-constraint predecessor-ind (encode-concept-term (if (or (role-datatype role) (role-cd-attribute role)) `(d-at-least ,at-least-value ,role ,qualification) `(at-least ,at-least-value ,role ,qualification))) (first at-most-constraints) (rest at-most-constraints)))) (relation-constraint (when successor-ind (let ((result (new-relation-constraint predecessor-ind successor-ind role))) (setf (constraint-dependencies result) at-most-constraints) result)))) (setf (constraint-derived-from concept-constraint) dependencies) (push concept-constraint concept-constraints) (when relation-constraint (setf (constraint-derived-from relation-constraint) dependencies) (push relation-constraint relation-constraints))) finally (return (values concept-constraints relation-constraints)))) (defun collect-at-most-bounds (role bound-list top-concept) (loop for elem in bound-list when (and (subrole-p role (bound-role elem)) (not (eq (bound-qualification elem) top-concept))) collect (list (bound-number elem) (bound-qualification elem)))) (defun get-allowed-roles (at-most-bounds exists-constraints relation-constraints) (let* ((bound-subroles (loop with result = nil for bound in at-most-bounds do (setf result (union (remove-if #'role-internal-conjunction-p (true-role-descendants (bound-role bound))) result)) finally (return result))) (constraint-superroles (loop with result = nil for constraint in exists-constraints do (setf result (union (remove-if #'role-internal-conjunction-p (true-role-ancestors (concept-role (constraint-term constraint)))) result)) finally (return result))) (all-superroles (loop with result = constraint-superroles for constraint in relation-constraints do (setf result (union (remove-if #'role-internal-conjunction-p (true-role-ancestors (constraint-term constraint))) result)) finally (return result)))) (intersection bound-subroles all-superroles))) (defun true-role-ancestors (role) (adjoin role (remove-if #'role-internal-conjunction-p (role-ancestors-internal role)))) (defun true-role-descendants (role) (adjoin role (remove-if #'role-internal-conjunction-p (role-descendants-internal role)))) (defun filter-role-set (role-set allowed-roles) (loop for role in role-set when (member role allowed-roles) collect (role-name role))) (defun compute-added-exists-constraints (ind remaining-exists-constraints allowed-roles) (loop for constraint in remaining-exists-constraints when (and (eql ind (constraint-ind constraint)) (member (concept-role (constraint-term constraint)) allowed-roles)) collect constraint)) (defun merge-constraints-simplex (ind state unused-1 unused-2 unused-3) #+:allegro (declare (:explain :tailmerging)) (declare (ignore unused-1 unused-2 unused-3)) (with-race-trace-sublevel ("merge-constraints-simplex" :arguments (list ind state) :expanded nil :trace-result t) ;(break) (let* ((relation-constraints (if (and *use-relation-store* (not (relation-store-empty-p (state-relation-store state)))) (get-all-rel-constraints (state-relation-store state)) (state-relation-constraints state))) (at-most-bounds (state-at-most-bounds state)) (true-some-constraints (state-true-some-constraints state)) (remaining-exists-constraints (get-all-expanded-constraints (state-unexpanded-exists-constraints state) (state-unexpanded-exists-constraints-store state))) (label (list* (construct-label-from-constraints (append true-some-constraints (mapcar #'bound-constraint at-most-bounds))) (construct-label-from-constraints remaining-exists-constraints) relation-constraints)) (allowed-roles (get-allowed-roles at-most-bounds true-some-constraints relation-constraints)) (added-exists-constraints (compute-added-exists-constraints ind remaining-exists-constraints allowed-roles)) (related-exists-constraints (append added-exists-constraints true-some-constraints))) (if (member label *simplex-labels* :test #'equal) (progn (race-trace ("~&Blocking merge-constraints-simplex: label=~S, *simplex-labels*=~S~%" label *simplex-labels*)) ;(break) t) (progn (push label *simplex-labels*) (let ((signatures (create-signatures ind state related-exists-constraints relation-constraints (state-at-least-bounds state) at-most-bounds (state-relation-store state)))) (if (signature-violated-p signatures at-most-bounds) (handle-clash-with-backtrack-state state nil nil nil nil) (multiple-value-bind (new-unexpanded-exists-constraints new-unexpanded-exists-constraint-store) (if added-exists-constraints (remove-constraints-from-constraint-store added-exists-constraints (state-unexpanded-exists-constraints state) (state-unexpanded-exists-constraints-store state) (state-copy-unexpanded-exists-constraints-store-p state) state #'reset-exists-copy) (values (state-unexpanded-exists-constraints state) (state-unexpanded-exists-constraints-store state))) (when-debug added-exists-constraints (race-trace ("~&Extending related exists-constraints by ~S~%" added-exists-constraints))) (race-trace ("~&Starting with signatures ~S~%" signatures)) (flet ((merge-constraints-simplex-continuation (sat-p xstate ignore-1 ignore-2 ignore-3) (declare (ignore xstate ignore-1 ignore-2 ignore-3)) (pop *simplex-labels*) (if sat-p t (handle-clash-with-backtrack-state state nil nil nil nil)))) (let* ((new-partially-expanded-or-stack (push-backtrack-stack #'merge-constraints-simplex-continuation (state-partially-expanded-or-stack state))) (new-state (changed-signature-state state :unexpanded-exists-constraints new-unexpanded-exists-constraints :unexpanded-exists-constraints-store new-unexpanded-exists-constraint-store :partially-expanded-or-stack new-partially-expanded-or-stack))) (inequations-satisfied-p signatures allowed-roles new-unexpanded-exists-constraints relation-constraints new-state)))))))))))
[ { "context": ";; Copyright 2017 Bradley Jensen\n;;\n;; Licensed under the Apache License, Version ", "end": 32, "score": 0.9998494982719421, "start": 18, "tag": "NAME", "value": "Bradley Jensen" } ]
core/lisp-interpolation.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/lisp-interpolation (:use :common-lisp :shcl/core/utility :shcl/core/lexer :shcl/core/shell-grammar :shcl/core/expand :shcl/core/exit-info :shcl/core/iterator :shcl/core/fd-table :shcl/core/shell-readtable) (:import-from :shcl/core/command #:define-special-builtin) (:import-from :shcl/core/evaluate #:evaluation-form-iterator) (:import-from :shcl/core/baking #:bake-form) (:import-from :shcl/core/posix) (:import-from :bordeaux-threads) (:import-from :babel) (:import-from :cffi) (:import-from :fset) (:export #:enable-reader-syntax #:evaluate-shell-string #:evaluate-constant-shell-string #:exit-failure #:check-result #:capture #:*splice-table*)) (in-package :shcl/core/lisp-interpolation) (defclass lisp-form (a-word) ((form :initarg :form :initform (required) :documentation "The form this token represents") (function :documentation "This function evaluates the form.")) (:documentation "A token representing a lisp form. If possible, the `function' slot should be compiled in the Lisp lexical environment where the token was used. This token always expands to one word.")) (defmethod print-object ((token lisp-form) stream) (format stream "#<~A ~A>" (class-name (class-of token)) (slot-value token 'form))) (defmethod bake-form ((lisp-form lisp-form)) `(setf (slot-value ,lisp-form 'function) (lambda () (fset:seq (make-string-fragment (format nil "~A" ,(slot-value lisp-form 'form)) :quoted t))))) (defclass lisp-splice-form (lisp-form) () (:documentation "A token representing a lisp form which evaulates to a sequence. During expansion, this token traverses the sequence returned by the lisp form and turns each element into a separate word.")) (defmethod bake-form ((lisp-form lisp-splice-form)) (let ((seq (gensym "SEQ")) (result (gensym "RESULT")) (thing (gensym "THING"))) `(setf (slot-value ,lisp-form 'function) (lambda () (let ((,seq ,(slot-value lisp-form 'form)) (,result (fset:empty-seq))) (do-iterator (,thing (iterator ,seq)) (fset:push-last ,result (make-string-fragment (format nil "~A" ,thing) :quoted t)) (fset:push-last ,result (word-boundary))) (setf ,result (fset:less-last ,result)) ,result))))) (defmethod expand ((token lisp-form)) (funcall (slot-value token 'function))) (defun read-lisp-form (stream initiation-sequence context) "Read a `lisp-form'." (declare (ignore initiation-sequence)) (let* ((form (read-preserving-whitespace stream)) (token (make-instance 'lisp-form :form form))) (shell-lexer-context-add-part context token))) (defun read-lisp-splice-form (stream initiation-sequence context) "Read a `lisp-splice-form'." (declare (ignore initiation-sequence)) (let* ((form (read-preserving-whitespace stream)) (token (make-instance 'lisp-splice-form :form form))) (shell-lexer-context-add-part context token))) (defun hash-default-handler (stream initiation-sequence context) "Read a comment" (unless (equal #\linefeed (aref initiation-sequence (- (length initiation-sequence) 1))) (read-line stream nil :eof)) (lexer-context-mark-end-of-token context)) (define-shell-readtable *splice-table-mixin* (with-dispatch-character ",") (with-default-handler "," 'read-lisp-form) (with-handler ",@" 'read-lisp-splice-form)) (define-shell-readtable *splice-table* "A shell readtable which supports injecting lisp forms." (use-table +standard-shell-readtable+) (use-table *splice-table-mixin*)) (define-shell-readtable *exit-reader-macro-table-mixin* "A readtable which allows the shell reader macro to terminate." (with-dispatch-character "#") (with-default-handler "#" 'hash-default-handler) (with-handler "#$" 'end-shell-parse)) (define-shell-readtable *interpolation-table* "A shell readtable which is suitable for use with the shell reader macro." (use-table +standard-shell-readtable+) (use-table *splice-table-mixin*) (use-table *exit-reader-macro-table-mixin*)) (defvar *proper-end-found* nil "This is used by `end-shell-parse' and `read-shell-command' to ensure that use of the #$ reader macro is properly terminated.") (defun end-shell-parse (stream initiation-sequence context) "Mark the end of a #$ reader macro form." (declare (ignore stream initiation-sequence)) (lexer-context-mark-end-of-token context) (setf *proper-end-found* t)) (defun read-shell-command (stream subchar arg) "This function implements the #$ reader macro It looks for an expression of the form #$ <shell expression> #$" (declare (ignore subchar arg)) (let ((*proper-end-found* nil)) (let* ((raw-token-iter (token-iterator stream :readtable *interpolation-table*)) (token-iter (make-iterator () (when *proper-end-found* (stop)) (multiple-value-bind (value more) (next raw-token-iter) (if more (emit value) (stop))))) (tokens (iterator-values token-iter))) (unless *proper-end-found* (error "Expected #$ before EOF")) `(parse-token-sequence ,(coerce tokens 'list))))) (defun enable-reader-syntax () "Enable use of the #$ reader macro for reading shell commands." (set-dispatch-macro-character #\# #\$ 'read-shell-command)) (defmacro evaluate-constant-shell-string (string &key (readtable *splice-table*)) "Parse the given shell command and arrange for the commands contained within to be executed at runtime. Note, embedded lisp forms will have access to the lexical environment where this form appears." (assert (typep string 'string) (string) "Only constant shell strings can be evaluated by this macro") (let ((table (typecase readtable (symbol (symbol-value readtable)) (t readtable)))) `(parse-token-sequence ,(coerce (tokens-in-string string :readtable table) 'list)))) (defun evaluate-shell-string (string &key (readtable *splice-table*)) "At runtime, parse and execute the given shell command. Note, embedded lisp forms will not have access to the lexical environment in which this function call appears. They will be evauluated in the null lexical environment." (eval `(evaluate-constant-shell-string ,string ,@(when readtable `(:readtable ,readtable))))) (define-special-builtin (builtin-eval "eval") (&rest args) "Evaluate the given arguments as a shell command." (let* (sep-needed (command (with-output-to-string (s) (dolist (word args) (unless (zerop (length word)) (when sep-needed (write-char #\space s)) (write-string word s) (setf sep-needed t)))))) (when (zerop (length command)) (return-from builtin-eval 0)) (evaluate-shell-string command :readtable +standard-shell-readtable+))) (defmacro parse-token-sequence (tokens) "This macro is responsible for parsing (at macro expansion time) a sequence of tokens and producing code which evaulates the shell command they describe." (let* ((token-iter (lookahead-iterator-wrapper (list-iterator tokens))) (commands (command-iterator token-iter)) (evaluates (iterator-values (evaluation-form-iterator commands)))) (do-iterator (value token-iter) (assert nil nil "Unconsumed token ~A found" value)) (when (zerop (length evaluates)) (setf evaluates #((truthy-exit-info)))) (apply 'progn-concatenate (coerce evaluates 'list)))) (define-condition exit-failure (error) ((info :type exit-info :initarg :info :reader exit-failure-info :documentation "Information about the process that exited abnormally")) (:report (lambda (c s) (format s "Command exited with info ~A" (exit-failure-info c)))) (:documentation "A condition that represents a command exiting with non-zero exit status.")) (defun check-result (exit-info) "Returns the given `exit-info', but signals an `exit-failure' condition if it indicates a non-zero exit status." (unless (exit-info-true-p exit-info) (cerror "Ignore error" 'exit-failure :info exit-info)) exit-info) (defgeneric decode-stream-descriptor (descriptor) (:documentation "Translate the given description of a stream into its corresponding file descriptor. This is intended to be used with `capture'.")) (defmethod decode-stream-descriptor ((descriptor integer)) descriptor) (defmethod decode-stream-descriptor ((stdout (eql :stdout))) 1) (defmethod decode-stream-descriptor ((stdout (eql :stderr))) 2) (defconstant +read-rate+ 4096 "The number of bytes that we should try to read from a pipe at once.") (defstruct place value) (defun consume (retained-fd output-place encoding) "Read from `retained-fd' and store the resulting string in `output-place'. When EOF is hit, this function will return. This function will release `retained-fd' when it finishes. `output-place' should be an instance of the `place' struct. This function is not meant to be used directly. Only `capture' should call this function." ;; Sigh. We need to collect all of the bytes from posix-read and ;; then decode it all at once. Otherwise, we might cut a character ;; in half and have decoding failures. We could try to figure out a ;; subset of the data we read that is whole and decode just that, ;; but we're probably not going to be dealing with big strings ;; anyway. So, let's just take the easy way out for now. (unwind-protect (let ((content (make-extensible-vector :element-type '(unsigned-byte 8))) (part #())) (loop :do (progn (setf part (shcl/core/posix:posix-read (fd-wrapper-value retained-fd) +read-rate+ :binary t)) (debug-log status "READ ~A BYTES" (length part)) (loop :for byte :across part :do (vector-push-extend byte content))) :while (not (zerop (length part)))) (setf (place-value output-place) (babel:octets-to-string content :encoding encoding)) (values)) (fd-wrapper-release retained-fd))) (defun %capture (streams encoding shell-command-fn) "This function implements the `capture' macro." (unless streams (funcall shell-command-fn) (return-from %capture "")) (with-fd-scope () (let ((fds (mapcar 'decode-stream-descriptor streams)) (string-result-place (make-place)) thread exit-info) (destructuring-bind (read-end write-end) (retained-fds-pipe) (unwind-protect (progn (with-fd-scope () (dolist (fd fds) (set-fd-binding fd write-end)) (fd-wrapper-retain read-end) (setf thread (bordeaux-threads:make-thread (lambda () (consume read-end string-result-place encoding)))) ;; Maybe not actually an exit-info. Still, its a ;; good name. (setf exit-info (multiple-value-list (funcall shell-command-fn)))) (fd-wrapper-release write-end) (setf write-end nil) (when thread (bordeaux-threads:join-thread thread)) (values-list (cons (place-value string-result-place) exit-info))) (when read-end (fd-wrapper-release read-end)) (when write-end (fd-wrapper-release write-end))))))) (defmacro capture ((&key (streams ''(:stdout)) (encoding 'cffi:*default-foreign-encoding*)) &body shell-command) "Capture the output of the given shell command and return it as a string. " `(%capture ,streams ,encoding (lambda () ,@shell-command))) (defmethod bake-form ((command-word command-word)) `(setf (command-word-evaluate-fn ,command-word) (lambda () (capture (:streams '(:stdout)) (parse-token-sequence ,(coerce (command-word-tokens command-word) 'list)))))) (defmethod expand ((command-word command-word)) (let* ((fn (or (command-word-evaluate-fn command-word) (error "command-word is missing its fn ~A" command-word)))) (multiple-value-bind (expansion exit-info) (funcall fn) (check-type exit-info (or null exit-info)) (values (if *split-fields* (split expansion) (fset:seq (make-string-fragment expansion))) exit-info))))
12494
;; 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/lisp-interpolation (:use :common-lisp :shcl/core/utility :shcl/core/lexer :shcl/core/shell-grammar :shcl/core/expand :shcl/core/exit-info :shcl/core/iterator :shcl/core/fd-table :shcl/core/shell-readtable) (:import-from :shcl/core/command #:define-special-builtin) (:import-from :shcl/core/evaluate #:evaluation-form-iterator) (:import-from :shcl/core/baking #:bake-form) (:import-from :shcl/core/posix) (:import-from :bordeaux-threads) (:import-from :babel) (:import-from :cffi) (:import-from :fset) (:export #:enable-reader-syntax #:evaluate-shell-string #:evaluate-constant-shell-string #:exit-failure #:check-result #:capture #:*splice-table*)) (in-package :shcl/core/lisp-interpolation) (defclass lisp-form (a-word) ((form :initarg :form :initform (required) :documentation "The form this token represents") (function :documentation "This function evaluates the form.")) (:documentation "A token representing a lisp form. If possible, the `function' slot should be compiled in the Lisp lexical environment where the token was used. This token always expands to one word.")) (defmethod print-object ((token lisp-form) stream) (format stream "#<~A ~A>" (class-name (class-of token)) (slot-value token 'form))) (defmethod bake-form ((lisp-form lisp-form)) `(setf (slot-value ,lisp-form 'function) (lambda () (fset:seq (make-string-fragment (format nil "~A" ,(slot-value lisp-form 'form)) :quoted t))))) (defclass lisp-splice-form (lisp-form) () (:documentation "A token representing a lisp form which evaulates to a sequence. During expansion, this token traverses the sequence returned by the lisp form and turns each element into a separate word.")) (defmethod bake-form ((lisp-form lisp-splice-form)) (let ((seq (gensym "SEQ")) (result (gensym "RESULT")) (thing (gensym "THING"))) `(setf (slot-value ,lisp-form 'function) (lambda () (let ((,seq ,(slot-value lisp-form 'form)) (,result (fset:empty-seq))) (do-iterator (,thing (iterator ,seq)) (fset:push-last ,result (make-string-fragment (format nil "~A" ,thing) :quoted t)) (fset:push-last ,result (word-boundary))) (setf ,result (fset:less-last ,result)) ,result))))) (defmethod expand ((token lisp-form)) (funcall (slot-value token 'function))) (defun read-lisp-form (stream initiation-sequence context) "Read a `lisp-form'." (declare (ignore initiation-sequence)) (let* ((form (read-preserving-whitespace stream)) (token (make-instance 'lisp-form :form form))) (shell-lexer-context-add-part context token))) (defun read-lisp-splice-form (stream initiation-sequence context) "Read a `lisp-splice-form'." (declare (ignore initiation-sequence)) (let* ((form (read-preserving-whitespace stream)) (token (make-instance 'lisp-splice-form :form form))) (shell-lexer-context-add-part context token))) (defun hash-default-handler (stream initiation-sequence context) "Read a comment" (unless (equal #\linefeed (aref initiation-sequence (- (length initiation-sequence) 1))) (read-line stream nil :eof)) (lexer-context-mark-end-of-token context)) (define-shell-readtable *splice-table-mixin* (with-dispatch-character ",") (with-default-handler "," 'read-lisp-form) (with-handler ",@" 'read-lisp-splice-form)) (define-shell-readtable *splice-table* "A shell readtable which supports injecting lisp forms." (use-table +standard-shell-readtable+) (use-table *splice-table-mixin*)) (define-shell-readtable *exit-reader-macro-table-mixin* "A readtable which allows the shell reader macro to terminate." (with-dispatch-character "#") (with-default-handler "#" 'hash-default-handler) (with-handler "#$" 'end-shell-parse)) (define-shell-readtable *interpolation-table* "A shell readtable which is suitable for use with the shell reader macro." (use-table +standard-shell-readtable+) (use-table *splice-table-mixin*) (use-table *exit-reader-macro-table-mixin*)) (defvar *proper-end-found* nil "This is used by `end-shell-parse' and `read-shell-command' to ensure that use of the #$ reader macro is properly terminated.") (defun end-shell-parse (stream initiation-sequence context) "Mark the end of a #$ reader macro form." (declare (ignore stream initiation-sequence)) (lexer-context-mark-end-of-token context) (setf *proper-end-found* t)) (defun read-shell-command (stream subchar arg) "This function implements the #$ reader macro It looks for an expression of the form #$ <shell expression> #$" (declare (ignore subchar arg)) (let ((*proper-end-found* nil)) (let* ((raw-token-iter (token-iterator stream :readtable *interpolation-table*)) (token-iter (make-iterator () (when *proper-end-found* (stop)) (multiple-value-bind (value more) (next raw-token-iter) (if more (emit value) (stop))))) (tokens (iterator-values token-iter))) (unless *proper-end-found* (error "Expected #$ before EOF")) `(parse-token-sequence ,(coerce tokens 'list))))) (defun enable-reader-syntax () "Enable use of the #$ reader macro for reading shell commands." (set-dispatch-macro-character #\# #\$ 'read-shell-command)) (defmacro evaluate-constant-shell-string (string &key (readtable *splice-table*)) "Parse the given shell command and arrange for the commands contained within to be executed at runtime. Note, embedded lisp forms will have access to the lexical environment where this form appears." (assert (typep string 'string) (string) "Only constant shell strings can be evaluated by this macro") (let ((table (typecase readtable (symbol (symbol-value readtable)) (t readtable)))) `(parse-token-sequence ,(coerce (tokens-in-string string :readtable table) 'list)))) (defun evaluate-shell-string (string &key (readtable *splice-table*)) "At runtime, parse and execute the given shell command. Note, embedded lisp forms will not have access to the lexical environment in which this function call appears. They will be evauluated in the null lexical environment." (eval `(evaluate-constant-shell-string ,string ,@(when readtable `(:readtable ,readtable))))) (define-special-builtin (builtin-eval "eval") (&rest args) "Evaluate the given arguments as a shell command." (let* (sep-needed (command (with-output-to-string (s) (dolist (word args) (unless (zerop (length word)) (when sep-needed (write-char #\space s)) (write-string word s) (setf sep-needed t)))))) (when (zerop (length command)) (return-from builtin-eval 0)) (evaluate-shell-string command :readtable +standard-shell-readtable+))) (defmacro parse-token-sequence (tokens) "This macro is responsible for parsing (at macro expansion time) a sequence of tokens and producing code which evaulates the shell command they describe." (let* ((token-iter (lookahead-iterator-wrapper (list-iterator tokens))) (commands (command-iterator token-iter)) (evaluates (iterator-values (evaluation-form-iterator commands)))) (do-iterator (value token-iter) (assert nil nil "Unconsumed token ~A found" value)) (when (zerop (length evaluates)) (setf evaluates #((truthy-exit-info)))) (apply 'progn-concatenate (coerce evaluates 'list)))) (define-condition exit-failure (error) ((info :type exit-info :initarg :info :reader exit-failure-info :documentation "Information about the process that exited abnormally")) (:report (lambda (c s) (format s "Command exited with info ~A" (exit-failure-info c)))) (:documentation "A condition that represents a command exiting with non-zero exit status.")) (defun check-result (exit-info) "Returns the given `exit-info', but signals an `exit-failure' condition if it indicates a non-zero exit status." (unless (exit-info-true-p exit-info) (cerror "Ignore error" 'exit-failure :info exit-info)) exit-info) (defgeneric decode-stream-descriptor (descriptor) (:documentation "Translate the given description of a stream into its corresponding file descriptor. This is intended to be used with `capture'.")) (defmethod decode-stream-descriptor ((descriptor integer)) descriptor) (defmethod decode-stream-descriptor ((stdout (eql :stdout))) 1) (defmethod decode-stream-descriptor ((stdout (eql :stderr))) 2) (defconstant +read-rate+ 4096 "The number of bytes that we should try to read from a pipe at once.") (defstruct place value) (defun consume (retained-fd output-place encoding) "Read from `retained-fd' and store the resulting string in `output-place'. When EOF is hit, this function will return. This function will release `retained-fd' when it finishes. `output-place' should be an instance of the `place' struct. This function is not meant to be used directly. Only `capture' should call this function." ;; Sigh. We need to collect all of the bytes from posix-read and ;; then decode it all at once. Otherwise, we might cut a character ;; in half and have decoding failures. We could try to figure out a ;; subset of the data we read that is whole and decode just that, ;; but we're probably not going to be dealing with big strings ;; anyway. So, let's just take the easy way out for now. (unwind-protect (let ((content (make-extensible-vector :element-type '(unsigned-byte 8))) (part #())) (loop :do (progn (setf part (shcl/core/posix:posix-read (fd-wrapper-value retained-fd) +read-rate+ :binary t)) (debug-log status "READ ~A BYTES" (length part)) (loop :for byte :across part :do (vector-push-extend byte content))) :while (not (zerop (length part)))) (setf (place-value output-place) (babel:octets-to-string content :encoding encoding)) (values)) (fd-wrapper-release retained-fd))) (defun %capture (streams encoding shell-command-fn) "This function implements the `capture' macro." (unless streams (funcall shell-command-fn) (return-from %capture "")) (with-fd-scope () (let ((fds (mapcar 'decode-stream-descriptor streams)) (string-result-place (make-place)) thread exit-info) (destructuring-bind (read-end write-end) (retained-fds-pipe) (unwind-protect (progn (with-fd-scope () (dolist (fd fds) (set-fd-binding fd write-end)) (fd-wrapper-retain read-end) (setf thread (bordeaux-threads:make-thread (lambda () (consume read-end string-result-place encoding)))) ;; Maybe not actually an exit-info. Still, its a ;; good name. (setf exit-info (multiple-value-list (funcall shell-command-fn)))) (fd-wrapper-release write-end) (setf write-end nil) (when thread (bordeaux-threads:join-thread thread)) (values-list (cons (place-value string-result-place) exit-info))) (when read-end (fd-wrapper-release read-end)) (when write-end (fd-wrapper-release write-end))))))) (defmacro capture ((&key (streams ''(:stdout)) (encoding 'cffi:*default-foreign-encoding*)) &body shell-command) "Capture the output of the given shell command and return it as a string. " `(%capture ,streams ,encoding (lambda () ,@shell-command))) (defmethod bake-form ((command-word command-word)) `(setf (command-word-evaluate-fn ,command-word) (lambda () (capture (:streams '(:stdout)) (parse-token-sequence ,(coerce (command-word-tokens command-word) 'list)))))) (defmethod expand ((command-word command-word)) (let* ((fn (or (command-word-evaluate-fn command-word) (error "command-word is missing its fn ~A" command-word)))) (multiple-value-bind (expansion exit-info) (funcall fn) (check-type exit-info (or null exit-info)) (values (if *split-fields* (split expansion) (fset:seq (make-string-fragment expansion))) exit-info))))
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/lisp-interpolation (:use :common-lisp :shcl/core/utility :shcl/core/lexer :shcl/core/shell-grammar :shcl/core/expand :shcl/core/exit-info :shcl/core/iterator :shcl/core/fd-table :shcl/core/shell-readtable) (:import-from :shcl/core/command #:define-special-builtin) (:import-from :shcl/core/evaluate #:evaluation-form-iterator) (:import-from :shcl/core/baking #:bake-form) (:import-from :shcl/core/posix) (:import-from :bordeaux-threads) (:import-from :babel) (:import-from :cffi) (:import-from :fset) (:export #:enable-reader-syntax #:evaluate-shell-string #:evaluate-constant-shell-string #:exit-failure #:check-result #:capture #:*splice-table*)) (in-package :shcl/core/lisp-interpolation) (defclass lisp-form (a-word) ((form :initarg :form :initform (required) :documentation "The form this token represents") (function :documentation "This function evaluates the form.")) (:documentation "A token representing a lisp form. If possible, the `function' slot should be compiled in the Lisp lexical environment where the token was used. This token always expands to one word.")) (defmethod print-object ((token lisp-form) stream) (format stream "#<~A ~A>" (class-name (class-of token)) (slot-value token 'form))) (defmethod bake-form ((lisp-form lisp-form)) `(setf (slot-value ,lisp-form 'function) (lambda () (fset:seq (make-string-fragment (format nil "~A" ,(slot-value lisp-form 'form)) :quoted t))))) (defclass lisp-splice-form (lisp-form) () (:documentation "A token representing a lisp form which evaulates to a sequence. During expansion, this token traverses the sequence returned by the lisp form and turns each element into a separate word.")) (defmethod bake-form ((lisp-form lisp-splice-form)) (let ((seq (gensym "SEQ")) (result (gensym "RESULT")) (thing (gensym "THING"))) `(setf (slot-value ,lisp-form 'function) (lambda () (let ((,seq ,(slot-value lisp-form 'form)) (,result (fset:empty-seq))) (do-iterator (,thing (iterator ,seq)) (fset:push-last ,result (make-string-fragment (format nil "~A" ,thing) :quoted t)) (fset:push-last ,result (word-boundary))) (setf ,result (fset:less-last ,result)) ,result))))) (defmethod expand ((token lisp-form)) (funcall (slot-value token 'function))) (defun read-lisp-form (stream initiation-sequence context) "Read a `lisp-form'." (declare (ignore initiation-sequence)) (let* ((form (read-preserving-whitespace stream)) (token (make-instance 'lisp-form :form form))) (shell-lexer-context-add-part context token))) (defun read-lisp-splice-form (stream initiation-sequence context) "Read a `lisp-splice-form'." (declare (ignore initiation-sequence)) (let* ((form (read-preserving-whitespace stream)) (token (make-instance 'lisp-splice-form :form form))) (shell-lexer-context-add-part context token))) (defun hash-default-handler (stream initiation-sequence context) "Read a comment" (unless (equal #\linefeed (aref initiation-sequence (- (length initiation-sequence) 1))) (read-line stream nil :eof)) (lexer-context-mark-end-of-token context)) (define-shell-readtable *splice-table-mixin* (with-dispatch-character ",") (with-default-handler "," 'read-lisp-form) (with-handler ",@" 'read-lisp-splice-form)) (define-shell-readtable *splice-table* "A shell readtable which supports injecting lisp forms." (use-table +standard-shell-readtable+) (use-table *splice-table-mixin*)) (define-shell-readtable *exit-reader-macro-table-mixin* "A readtable which allows the shell reader macro to terminate." (with-dispatch-character "#") (with-default-handler "#" 'hash-default-handler) (with-handler "#$" 'end-shell-parse)) (define-shell-readtable *interpolation-table* "A shell readtable which is suitable for use with the shell reader macro." (use-table +standard-shell-readtable+) (use-table *splice-table-mixin*) (use-table *exit-reader-macro-table-mixin*)) (defvar *proper-end-found* nil "This is used by `end-shell-parse' and `read-shell-command' to ensure that use of the #$ reader macro is properly terminated.") (defun end-shell-parse (stream initiation-sequence context) "Mark the end of a #$ reader macro form." (declare (ignore stream initiation-sequence)) (lexer-context-mark-end-of-token context) (setf *proper-end-found* t)) (defun read-shell-command (stream subchar arg) "This function implements the #$ reader macro It looks for an expression of the form #$ <shell expression> #$" (declare (ignore subchar arg)) (let ((*proper-end-found* nil)) (let* ((raw-token-iter (token-iterator stream :readtable *interpolation-table*)) (token-iter (make-iterator () (when *proper-end-found* (stop)) (multiple-value-bind (value more) (next raw-token-iter) (if more (emit value) (stop))))) (tokens (iterator-values token-iter))) (unless *proper-end-found* (error "Expected #$ before EOF")) `(parse-token-sequence ,(coerce tokens 'list))))) (defun enable-reader-syntax () "Enable use of the #$ reader macro for reading shell commands." (set-dispatch-macro-character #\# #\$ 'read-shell-command)) (defmacro evaluate-constant-shell-string (string &key (readtable *splice-table*)) "Parse the given shell command and arrange for the commands contained within to be executed at runtime. Note, embedded lisp forms will have access to the lexical environment where this form appears." (assert (typep string 'string) (string) "Only constant shell strings can be evaluated by this macro") (let ((table (typecase readtable (symbol (symbol-value readtable)) (t readtable)))) `(parse-token-sequence ,(coerce (tokens-in-string string :readtable table) 'list)))) (defun evaluate-shell-string (string &key (readtable *splice-table*)) "At runtime, parse and execute the given shell command. Note, embedded lisp forms will not have access to the lexical environment in which this function call appears. They will be evauluated in the null lexical environment." (eval `(evaluate-constant-shell-string ,string ,@(when readtable `(:readtable ,readtable))))) (define-special-builtin (builtin-eval "eval") (&rest args) "Evaluate the given arguments as a shell command." (let* (sep-needed (command (with-output-to-string (s) (dolist (word args) (unless (zerop (length word)) (when sep-needed (write-char #\space s)) (write-string word s) (setf sep-needed t)))))) (when (zerop (length command)) (return-from builtin-eval 0)) (evaluate-shell-string command :readtable +standard-shell-readtable+))) (defmacro parse-token-sequence (tokens) "This macro is responsible for parsing (at macro expansion time) a sequence of tokens and producing code which evaulates the shell command they describe." (let* ((token-iter (lookahead-iterator-wrapper (list-iterator tokens))) (commands (command-iterator token-iter)) (evaluates (iterator-values (evaluation-form-iterator commands)))) (do-iterator (value token-iter) (assert nil nil "Unconsumed token ~A found" value)) (when (zerop (length evaluates)) (setf evaluates #((truthy-exit-info)))) (apply 'progn-concatenate (coerce evaluates 'list)))) (define-condition exit-failure (error) ((info :type exit-info :initarg :info :reader exit-failure-info :documentation "Information about the process that exited abnormally")) (:report (lambda (c s) (format s "Command exited with info ~A" (exit-failure-info c)))) (:documentation "A condition that represents a command exiting with non-zero exit status.")) (defun check-result (exit-info) "Returns the given `exit-info', but signals an `exit-failure' condition if it indicates a non-zero exit status." (unless (exit-info-true-p exit-info) (cerror "Ignore error" 'exit-failure :info exit-info)) exit-info) (defgeneric decode-stream-descriptor (descriptor) (:documentation "Translate the given description of a stream into its corresponding file descriptor. This is intended to be used with `capture'.")) (defmethod decode-stream-descriptor ((descriptor integer)) descriptor) (defmethod decode-stream-descriptor ((stdout (eql :stdout))) 1) (defmethod decode-stream-descriptor ((stdout (eql :stderr))) 2) (defconstant +read-rate+ 4096 "The number of bytes that we should try to read from a pipe at once.") (defstruct place value) (defun consume (retained-fd output-place encoding) "Read from `retained-fd' and store the resulting string in `output-place'. When EOF is hit, this function will return. This function will release `retained-fd' when it finishes. `output-place' should be an instance of the `place' struct. This function is not meant to be used directly. Only `capture' should call this function." ;; Sigh. We need to collect all of the bytes from posix-read and ;; then decode it all at once. Otherwise, we might cut a character ;; in half and have decoding failures. We could try to figure out a ;; subset of the data we read that is whole and decode just that, ;; but we're probably not going to be dealing with big strings ;; anyway. So, let's just take the easy way out for now. (unwind-protect (let ((content (make-extensible-vector :element-type '(unsigned-byte 8))) (part #())) (loop :do (progn (setf part (shcl/core/posix:posix-read (fd-wrapper-value retained-fd) +read-rate+ :binary t)) (debug-log status "READ ~A BYTES" (length part)) (loop :for byte :across part :do (vector-push-extend byte content))) :while (not (zerop (length part)))) (setf (place-value output-place) (babel:octets-to-string content :encoding encoding)) (values)) (fd-wrapper-release retained-fd))) (defun %capture (streams encoding shell-command-fn) "This function implements the `capture' macro." (unless streams (funcall shell-command-fn) (return-from %capture "")) (with-fd-scope () (let ((fds (mapcar 'decode-stream-descriptor streams)) (string-result-place (make-place)) thread exit-info) (destructuring-bind (read-end write-end) (retained-fds-pipe) (unwind-protect (progn (with-fd-scope () (dolist (fd fds) (set-fd-binding fd write-end)) (fd-wrapper-retain read-end) (setf thread (bordeaux-threads:make-thread (lambda () (consume read-end string-result-place encoding)))) ;; Maybe not actually an exit-info. Still, its a ;; good name. (setf exit-info (multiple-value-list (funcall shell-command-fn)))) (fd-wrapper-release write-end) (setf write-end nil) (when thread (bordeaux-threads:join-thread thread)) (values-list (cons (place-value string-result-place) exit-info))) (when read-end (fd-wrapper-release read-end)) (when write-end (fd-wrapper-release write-end))))))) (defmacro capture ((&key (streams ''(:stdout)) (encoding 'cffi:*default-foreign-encoding*)) &body shell-command) "Capture the output of the given shell command and return it as a string. " `(%capture ,streams ,encoding (lambda () ,@shell-command))) (defmethod bake-form ((command-word command-word)) `(setf (command-word-evaluate-fn ,command-word) (lambda () (capture (:streams '(:stdout)) (parse-token-sequence ,(coerce (command-word-tokens command-word) 'list)))))) (defmethod expand ((command-word command-word)) (let* ((fn (or (command-word-evaluate-fn command-word) (error "command-word is missing its fn ~A" command-word)))) (multiple-value-bind (expansion exit-info) (funcall fn) (check-type exit-info (or null exit-info)) (values (if *split-fields* (split expansion) (fset:seq (make-string-fragment expansion))) exit-info))))
[ { "context": "ge: CL-USER; Base: 10 -*-\n\n;;; Copyright (c) 2004, Jochen Schmidt <[email protected]>.\n;;; All rights reserved.\n\n;;", "end": 111, "score": 0.9998462796211243, "start": 97, "tag": "NAME", "value": "Jochen Schmidt" }, { "context": ": 10 -*-\n\n;;; Copyright (c) 2004, Jochen Schmidt <[email protected]>.\n;;; All rights reserved.\n\n;;; Redistribution an", "end": 130, "score": 0.9999247193336487, "start": 113, "tag": "EMAIL", "value": "[email protected]" }, { "context": "\n (port :accessor imap-port :initarg :port)\n (username :accessor username :initarg :username)\n (passwo", "end": 3340, "score": 0.9434430599212646, "start": 3332, "tag": "USERNAME", "value": "username" }, { "context": "r imap-port :initarg :port)\n (username :accessor username :initarg :username)\n (password :accessor passwo", "end": 3359, "score": 0.9935798645019531, "start": 3351, "tag": "USERNAME", "value": "username" }, { "context": " :port)\n (username :accessor username :initarg :username)\n (password :accessor password :initarg :passwo", "end": 3378, "score": 0.9962908029556274, "start": 3370, "tag": "USERNAME", "value": "username" }, { "context": " :port port\n :username username\n :password password\n\t\t :mailbox m", "end": 4489, "score": 0.9991094470024109, "start": 4481, "tag": "USERNAME", "value": "username" }, { "context": " :username username\n :password password\n\t\t :mailbox mailbox\n :state :disc", "end": 4525, "score": 0.996853232383728, "start": 4517, "tag": "PASSWORD", "value": "password" }, { "context": " :port port\n :username username\n :password password\n\t\t :mailbox m", "end": 4894, "score": 0.9992421865463257, "start": 4886, "tag": "USERNAME", "value": "username" }, { "context": " :username username\n :password password\n\t\t :mailbox mailbox\n :state :disc", "end": 4930, "score": 0.9970512390136719, "start": 4922, "tag": "PASSWORD", "value": "password" } ]
folders/imap/folder.lisp
Ferada/mel-base
13
;;; -*- Mode: LISP; Syntax: COMMON-LISP; Package: CL-USER; Base: 10 -*- ;;; Copyright (c) 2004, Jochen Schmidt <[email protected]>. ;;; 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 :mel.folders.imap) ;;;;;;;;;;;;;;;;; ;; IMAP folder ;; ;;;;;;;;;;;;;;;;; ;; Dependencies ;; MAKE-CONNECTION (defvar *imap-debug* nil) ;;; We want to assign sequence numbers to messages of a folder. ;;; (defclass sequence-table-mixin () ((seq-table :initform (make-array 5000 :adjustable t :fill-pointer 1 :initial-element nil)))) (defmethod (setf sequence-number) (n (message message)) "Set the sequence number of a message" (with-slots (seq-table) (folder message) (unless (> (array-dimension seq-table 0) n) (adjust-array seq-table (* 2 n) :fill-pointer n)) (unless (> (length seq-table) n) (setf (fill-pointer seq-table) (1+ n))) (setf (aref seq-table n) message))) (defmethod sequence-number ((message message)) "Return the sequence number of a message. This is an O(N) operation!" (with-slots (seq-table) (folder message) (position message seq-table :test #'eq))) (defmethod sequence-number-message ((folder sequence-table-mixin) n) (with-slots (seq-table) folder (let ((message (aref seq-table n))) (unless message (error "Sequence number ~d does not reference a message" n)) message))) (defmethod expunge-sequence-number ((folder sequence-table-mixin) n) (with-slots (seq-table) folder (let ((exists (length seq-table))) (rotatef (aref seq-table n) (aref seq-table exists)) (loop for i from n below exists do (rotatef (aref seq-table i) (aref seq-table (1+ i)))) (setf (aref seq-table exists) nil) (decf (fill-pointer seq-table))))) (defmethod close-folder :after((folder sequence-table-mixin)) (with-slots (seq-table) folder (fill seq-table nil) (setf (fill-pointer seq-table) 1))) (defclass network-folder-mixin () ((connection :accessor connection) (host :accessor host :initarg :host) (port :accessor imap-port :initarg :port) (username :accessor username :initarg :username) (password :accessor password :initarg :password))) (defclass imap-folder (sequence-table-mixin network-folder-mixin eql-message-cache-mixin basic-receiver basic-sender) ((mailbox :accessor mailbox :initarg :mailbox :initform "INBOX") (capabilities :reader capabilities :initform nil) (uidvalidity :reader uidvalidity) (uid-table :accessor uid-table :initform (make-hash-table :test 'eql)) (size-table :accessor size-table :initform (make-hash-table :test 'eql)) (exists :initform 0) (recent :initform 0) (unseen :initform nil) (messages :initform nil) (last-command :initform nil :accessor last-command) (state :accessor state :initarg :state :initform :disconnected))) (defclass imaps-folder (imap-folder) ()) (defun make-imap-folder (&key (host "imap.web.de")(port 143) username password (mailbox "INBOX")) (make-instance 'imap-folder :name (format nil "imap://~A!~A@~A:~A" username password host port) :host host :port port :username username :password password :mailbox mailbox :state :disconnected)) (defun make-imaps-folder (&key (host "imap.web.de")(port 993) username password (mailbox "INBOX")) (make-instance 'imaps-folder :name (format nil "imaps://~A!~A@~A:~A" username password host port) :host host :port port :username username :password password :mailbox mailbox :state :disconnected)) (defmethod serialize-folder ((folder imap-folder) stream) (with-standard-io-syntax (write `(make-imap-folder :host ,(host folder) :port ,(imap-port folder) :username ,(username folder) :password ,(password folder)) :stream stream))) ;;;;;;;;;;;;;;;;;;; ;; IMAP Protocol ;; ; ;; ; LOGIN ;; ; SELECT ;; ; SEARCH ;; ; FETCH ;; ; CLOSE ;; ;;;;;;;;;;;;;;;;;;; ;; Atom ; atom-specials: "(){" SPACE CTL list_wildcards quoted_specials ; quoted-specials: '"\' ; list-wildcards: "%*" ; 1*(non-special) (defvar *atom-specials* '(#\( #\) #\{ #\space #\% #\* #\" #\\)) (declaim (inline atom-char-p)) (defun atom-char-p (char) (declare (optimize (speed 3) (safety 1))) (and (characterp char) (not (or (let ((code (char-code char))) (or (<= #x00 code #x1f) (= code #x7f))) (member char *atom-specials*))))) (declaim (inline atom-char-p)) (defun read-atom (stream) (declare (optimize (speed 3) (safety 1))) (let ((string (with-output-to-string (s) (loop for c = (peek-char nil stream nil nil) while (atom-char-p c) do (read-char stream)(write-char c s))))) string)) ;; Number unsigned 32 bit ; 1*(digit) (declaim (inline read-number)) (defun read-number (stream) (declare (optimize (speed 3) (safety 1))) (let ((string (with-output-to-string (s) (loop for c = (peek-char nil stream nil nil) while (and c (digit-char-p c)) do (read-char stream)(write-char c s))))) (declare (optimize (speed 3) (safety 1)) (dynamic-extent string)) (parse-integer string))) ;; String ; quoted ; '"' *(7-bit ASCII without CR LF) '"' (declaim (inline read-quoted-string)) (defun read-quoted-string (stream) (declare (optimize (speed 3) (safety 1))) (let ((char (read-char stream))) (with-output-to-string (out) (ecase char (#\" (loop for c = (read-char stream) while (case c (#\\ (write-char (read-char stream) out) t) (#\" nil) (otherwise (write-char c out) t)))))))) (define-condition imap-paren-closed () ()) (define-condition imap-bracket-closed () ()) (define-condition end-of-imap-response () ()) ; * OK [PERMANENTFLAGS (\* \Draft \Answered \Flagged \Deleted \Seen)] Limited (declaim (inline accept-char)) (defun accept-char (c stream) (declare (optimize (speed 3) (safety 1))) (let ((char (peek-char nil stream nil nil))) (if (and char (char= c char)) (read-char stream) nil))) ;; Fix keywords ;; OK NO BAD ;; (defvar *imap-read-case* :keyword) (defun convert-atom (string) (ecase *imap-read-case* (:keyword (intern (string-upcase string) :keyword)) (:upcase (string-upcase string)) (:downcase (string-downcase string) :keyword) (:preserve string))) (defun imap-read (stream &optional (eof-errorp t) eof-value) (loop for c = (peek-char nil stream eof-errorp eof-value) while (case c ((#\space #\tab) (read-char stream) t) (otherwise nil))) (let ((char (peek-char nil stream eof-errorp eof-value))) (cond #+faithful-input((accept-char #\linefeed stream) (if eof-errorp (error 'end-of-imap-response) (return-from imap-read eof-value))) #-faithful-input((char= #\return char) (read-char stream) (accept-char #\linefeed stream) (if eof-errorp (error 'end-of-imap-response) (return-from imap-read eof-value))) ((char= #\" char) (read-quoted-string stream)) ((char= #\( char) (read-char stream) (imap-read-delimited-list stream)) ((char= #\[ char) (read-char stream) (imap-read-bracket-list stream)) ((char= #\) char) (read-char stream) (signal 'imap-paren-closed)) ((char= #\] char) (read-char stream) (signal 'imap-bracket-closed)) ;; Read chunk ((char= #\{ char) (read-char stream) (let ((number (read-number stream))) (unless (accept-char #\} stream) (error "Syntax error")) #-faithful-input(unless (accept-char #\return stream) (error "Syntax error")) (unless (accept-char #\linefeed stream) (error "Syntax error")) #-faithful-input (let ((buffer (make-array number :element-type '(unsigned-byte 8)))) (read-sequence buffer stream) buffer) #+faithful-input (let ((buffer (make-array number :element-type '(unsigned-byte 8)))) (setf (stream-element-type stream) '(unsigned-byte 8)) (read-sequence buffer stream) (setf (stream-element-type stream) 'character) (map 'string (lambda (b) (code-char b)) buffer)))) ((char= #\\ char) (read-char stream) (let ((char (peek-char nil stream))) (if (eql #\* char) :* (let ((atom (read-atom stream))) (cond ((zerop (length atom)) (error "Zero length \\atom")) ((string-equal atom "NIL") nil) ((every #'digit-char-p atom) (parse-integer atom)) (t (convert-atom atom))))))) ((atom-char-p char) (let ((atom (read-atom stream))) (cond ((zerop (length atom)) (error "Zero length atom")) ((string-equal atom "NIL") nil) ((every #'digit-char-p atom) (parse-integer atom)) (t (convert-atom atom))))) (t (read-char stream))))) (declaim (inline imap-read-delimited-list)) (defun imap-read-delimited-list (stream) (declare (optimize (speed 3) (safety 1))) (let (forms) (handler-case (loop for form = (imap-read stream) do (push form forms)) (imap-paren-closed () (nreverse forms))))) (declaim (inline imap-read-bracket-list)) (defun imap-read-bracket-list (stream) (declare (optimize (speed 3) (safety 1))) (let (forms) (handler-case (loop for form = (imap-read stream) do (push form forms)) (imap-bracket-closed () (nreverse forms))))) ;; Response (declaim (inline read-response)) (defun read-response (stream) (let (result) (handler-case (let ((tag (imap-read stream))) (push tag result) (let ((*imap-read-case* (if (eq :+ tag) :preserve :keyword))) (loop for form = (imap-read stream) do (push form result)))) (end-of-imap-response () (let ((result (nreverse result))) (if *imap-debug* (print result) result)))))) (defun skip-responses (stream) (loop for response = (read-response stream) do (print response *standard-output*) (case (second response) (:ok (return nil)) ((:no :bad (error "Error on response")))))) (defmethod process-response ((folder imap-folder) &key on-recent on-unseen on-exists on-expunge on-size on-uid on-body on-list on-header on-bodystructure on-continuation) (let ((stream (ensure-connection folder))) (let (attributes part) (labels ((process-untagged-number (type arguments) (let ((number type) (atom (first arguments))) (when *imap-debug* (assert (numberp number) (number) "Is not a number") (assert (keywordp atom) (atom) "Is not an atom")) (cond ((eq :exists atom) (setf (slot-value folder 'exists) number) (when on-exists (funcall on-exists number))) ((eq :recent atom) (setf (slot-value folder 'recent) number) (when on-recent (funcall on-recent number))) ((eq :unseen atom) (setf (slot-value folder 'unseen) number) (when on-unseen (funcall on-unseen number))) ((eq :expunge atom) (expunge-sequence-number folder number) (when on-expunge (funcall on-expunge number))) ((eq :fetch atom) (let ((form (second arguments))) (when *imap-debug* (assert (and form (consp form)) (form) "Is not a form")) (process-fetch number form)))))) (process-fetch (n form) ;; Message (when-let (message (getf form :BODYSTRUCTURE)) (when on-bodystructure (funcall on-bodystructure message)) (setf part message)) (when-let (message (getf form :BODY[HEADER])) (with-input-from-sequence (s message) (setf (weird-mail.mime:header-fields (sequence-number-message folder n)) (mel.mime:read-rfc2822-header s))) (when on-header (funcall on-header message)) (setf part message)) (when-let (message (getf form :|BODY[TEXT]|)) (when on-body (funcall on-body message)) (setf part message)) (when-let (message (getf form :|BODY[]|)) (when on-body (funcall on-body message)) (setf part message)) ;; Attributes (let (message) (when-let (uid (getf form :uid)) ;; We got a FETCH response with ;; an UID. We use this for creation ;; of the message objects ;; Create or find cached message object associated ;; with given UID (setf message (find-message folder uid :if-does-not-exist :create)) ;; Register sequence number with message (setf (sequence-number message) n) (when on-uid ;; Call hook (funcall on-uid message))) (let ((flags (getf form :flags :n/a))) (unless (eq flags :n/a) (if message (setf (flags message) flags) (setf (flags (sequence-number-message folder n)) flags)))) (when-let (size (getf form :RFC822.SIZE)) (when on-size (let ((message (or message (sequence-number-message folder n)))) (setf (gethash (uid message) (size-table folder)) size)) (funcall on-size message))) (push form attributes)))) ;; Process next IMAP response (loop (destructuring-bind (tag type &rest arguments) (read-response stream) (force-output t) (cond ((eq tag :+) (when on-continuation (funcall on-continuation type arguments))) ((keywordp tag) (case type (:ok (return (values part attributes))) ((:no :bad) (error "Error on response: ~A (cmd: ~A)" arguments (if *imap-debug* (last-command folder) "N/A"))))) ((eql tag #\*) (cond ((numberp type) (process-untagged-number type arguments)) ((eq :list type) (when on-list (funcall on-list (first arguments) (rest arguments)))) ((eq :search type) (when on-list (funcall on-list arguments))) ((eq :capability type) (setf (slot-value folder 'capabilities) (rest arguments))) ((eql type :ok) (case (first arguments) (:uidvalidity (if (uidvalidity folder) (unless (= (first (second arguments)) (uidvalidity folder)) (setf (slot-value folder 'uidvalidity) (first (second arguments))) (clrhash (size-table folder)) (clrhash (uid-table folder))) (setf (slot-value folder 'uidvalidity) (first (second arguments))))) (:capabilities (setf (slot-value folder 'capabilities) (second arguments)))))))))))))) (defun authenticate-cram-md5 (sink-folder) (format (connection sink-folder) "CRAM AUTHENTICATE CRAM-MD5") (write-char #\return (connection sink-folder)) (write-char #\linefeed (connection sink-folder)) (force-output (connection sink-folder)) (process-response sink-folder :on-continuation (lambda (arg1 arguments) (declare (ignore arguments)) (let ((timestamp (map 'string #'code-char (mel.mime::decode-base64 arg1)))) (format t "(Challenge) ~A~%" timestamp) (let ((username (mel.cipher:string-to-octets (format nil "~A " (username sink-folder)))) (digest (mel.cipher:hmac-md5 timestamp (password sink-folder)))) (let ((response (concatenate 'vector username digest))) (format t "(Response) ~A~%" (map 'string #'code-char response)) (write-string (mel.mime::encode-base64 response) (connection sink-folder)) (write-char #\return (connection sink-folder)) (write-char #\linefeed (connection sink-folder)) (force-output (connection sink-folder)))))))) (defmethod login ((folder imap-folder)) (let ((connection (connection folder))) (format connection "c01 LOGIN ~A \"~A\"~A~A" (username folder) (password folder) #\return #\linefeed) ;; Not really tested yet ; (authenticate-cram-md5 folder) (force-output connection) (process-response folder) connection)) (defmethod make-imap-connection ((folder imap-folder)) (let ((connection (mel.network:make-connection :remote-host (host folder) :remote-port (imap-port folder) :element-type '(unsigned-byte 8)))) (setf (connection folder) connection) (setf (state folder) :connected) (read-response connection) (login folder))) (defmethod make-imaps-connection ((folder imaps-folder)) (let ((connection (mel.network:make-connection :remote-host (host folder) :remote-port (imap-port folder) :ssl t :element-type '(unsigned-byte 8)))) (setf (connection folder) connection) (setf (state folder) :connected) (read-response connection) (login folder))) (defun send-command (folder string &rest args) (handler-case (let ((stream (ensure-connection folder))) (when *imap-debug* (setf (last-command folder) (apply #'format nil string args))) (apply #'format stream string args) (write-char #\return stream) (write-char #\linefeed stream) (force-output stream)) (end-of-file () (setf (state folder) :disconnected)))) (defmethod ensure-connection ((folder imap-folder)) (when (eq (state folder) :disconnected) (setf (connection folder) (make-imap-connection folder)) (setf (state folder) :connected) (select-mailbox folder)) (handler-case (connection folder) (cl:end-of-file () (setf (state folder) :disconnected) (ensure-connection folder)))) ;; Required untagged responses: FLAGS EXISTS RECENT ;; Optional untagged responses: UNSEEN, PERMANENTFLAGS (defun select-mailbox (folder) (unless (connection folder) (ensure-connection folder)) (let ((stream (connection folder))) (format stream "~A select ~A~A~A" "t01" (mailbox folder) #\return #\linefeed) (force-output stream) (let (recent exists) (process-response folder :on-recent (lambda (n) (setf recent n)) :on-exists (lambda (n) (setf exists n))) (values exists recent)))) (defun capability (folder) (send-command folder "~A capability" "t01") (process-response folder)) (defun start-idle (folder) (send-command folder "~A idle" "t01") (process-response folder)) (defun end-idle (folder) (send-command folder "done") (process-response folder)) (defun noop (folder) (send-command folder "~A noop" "t01") (process-response folder)) (defun create-mailbox (folder mailbox) (send-command folder "~A create ~A" "create" mailbox) (process-response folder)) (defun list-mailboxes (folder pattern) (send-command folder "~A list \"\" ~S" "create" pattern) (let (result) (process-response folder :on-list (lambda (flags args) (push (list* flags args) result))) result)) (defun close-mailbox (folder) (when (eq (state folder) :connected) (send-command folder "c1 close") (process-response folder) (setf (state folder) :disconnected) ;; Added by KTR on 07/17/2008 to close the network connection (close (connection folder)))) (defun examine-mailbox (folder) (send-command folder "~A select ~A" "t01" (mailbox folder)) (process-response folder)) (defun expunge-mailbox (folder) (send-command folder "~A expunge" "t01") (process-response folder)) (defmethod update-mailbox ((folder imap-folder) callback) (let ((non-recent (hash-table-count (message-cache folder))) (exists (count-messages folder))) (cond ((/= exists non-recent) (clrhash (size-table folder)) (ensure-connection folder) (send-command folder "~A fetch 1:~A (UID FLAGS)" ; (UID RFC822.SIZE FLAGS)" "UPDATE" (slot-value folder 'exists)) (let (messages) (process-response folder :on-uid (lambda (message) (push message messages) (funcall callback message))) (setf (slot-value folder 'messages) messages))) (t (slot-value folder 'messages))))) (defmethod update-new-mailbox ((folder imap-folder) callback) (let ((non-recent (hash-table-count (message-cache folder))) (exists (count-messages folder))) (cond ((> exists non-recent) (clrhash (size-table folder)) (ensure-connection folder) (send-command folder "~A fetch 1:~A (UID FLAGS)" ; (UID RFC822.SIZE FLAGS)" "UPDATE" (slot-value folder 'exists)) (let (messages) (process-response folder :on-uid (lambda (message) (push message messages) (funcall callback message))) (setf (slot-value folder 'messages) messages))) (t (slot-value folder 'messages))))) (defun append-message (sink-folder message-string) (let ((message-size (length message-string))) (send-command sink-folder "~A APPEND ~A () {~D}" "APPEND" (mailbox sink-folder) message-size) (process-response sink-folder :on-continuation (lambda (type arguments) (declare (ignore type arguments)) (write-sequence message-string (connection sink-folder)) (write-char #\return (connection sink-folder)) (write-char #\linefeed (connection sink-folder)) (force-output (connection sink-folder)))))) (defmethod fetch-message ((folder imap-folder) uid) (send-command folder "~A uid fetch ~A (UID BODY[])" "MESSAGE" uid) (let (result) (process-response folder :on-body (lambda (body) (setf result body))) result)) (defmethod fetch-message-body ((folder imap-folder) uid) (send-command folder "~A uid fetch ~A (UID BODY[TEXT])" "BODY" uid) (let (result) (process-response folder :on-body (lambda (body) (setf result body))) result)) (defmethod fetch-message-header ((folder imap-folder) uid) (send-command folder "~A uid fetch ~A (UID BODY[HEADER])" "HEADER" uid #\return #\linefeed) (let (result) (process-response folder :on-header (lambda (header) (setf result header))) result)) (defmethod fetch-all-message-headers ((folder imap-folder)) (send-command folder "~A fetch 1:* (UID BODY[HEADER])" "HEADER" #\return #\linefeed) (process-response folder :on-header (lambda (header) (declare (ignore header))))) (defmethod fetch-message-bodystructure ((folder imap-folder) uid) (send-command folder "~A uid fetch ~A (UID BODYSTRUCTURE)" "BODYSTRUCTURE" uid) (let (result) (process-response folder :on-bodystructure (lambda (b) (setf result b))) result)) (defun canonicalize-bodystructure (bodystructure) (labels ((keyword (string) (typecase string (symbol string) (string (intern (string-upcase string) #.(find-package :keyword))))) (canonicalize-parameters (params) (loop for (name value) on params by #'cddr nconc (list (keyword name) value))) (canonicalize-simple-part (bs) `(,(keyword (first bs)) ,(keyword (second bs)) ,(canonicalize-parameters (third bs)) nil nil ,(keyword (sixth bs)) ,(seventh bs) ,(eighth bs) nil nil nil)) (canonicalize-multipart (bs) (loop for tail on bs while (consp (first tail)) collect (canonicalize-bodystructure (first tail)) into parts finally (return `(,@parts ,(keyword (first tail)) ,(canonicalize-parameters (second tail)) nil nil))))) (etypecase (car bodystructure) (cons (canonicalize-multipart bodystructure)) (string (canonicalize-simple-part bodystructure)) (symbol (canonicalize-simple-part bodystructure))))) (defmethod mel.mime::compute-bodystructure-using-folder ((folder imap-folder) (message mel.mime::bodystructure-mixin)) (let ((bodystructure (fetch-message-bodystructure folder (uid message)))) (canonicalize-bodystructure bodystructure))) (defmethod search-mailbox ((folder imap-folder) query) (send-command folder "~A uid search ~A" "t01" query) (let (messages) (labels ((return-messages (list) (setf messages (mapcar (lambda (uid) (find-message folder uid)) list)))) (process-response folder :on-list #'return-messages) messages))) (defmethod mark-deleted ((folder imap-folder) uid) (send-command folder "~A uid store ~A +flags (\\Deleted)" "t01" uid) (process-response folder)) ;;;;;;;;;;;;;;;;;;;;; ;; Folder Protocol ;; ;;;;;;;;;;;;;;;;;;;;; (defmethod close-folder ((folder imap-folder)) (unless (eq (state folder) :disconnected) (ignore-errors (close-mailbox folder)) (setf (connection folder) nil (state folder) :disconnected) (clrhash (uid-table folder)) (clrhash (size-table folder)) (setf (slot-value folder 'messages) nil (slot-value folder 'exists) 0 (slot-value folder 'recent) 0) )) (defmethod open-message-input-stream-using-folder ((folder imap-folder) message start) (let ((stream (make-sequence-input-stream (fetch-message folder (uid message))))) (file-position stream (+ (file-position stream) start)) stream)) (defmethod message-body-stream-using-folder ((folder imap-folder) message) (make-sequence-input-stream (fetch-message-body folder (uid message)))) (defmethod message-header-stream-using-folder ((folder imap-folder) message) (let ((stream (make-sequence-input-stream (fetch-message-header folder (uid message))))) stream)) ;;; Folder Protocol Support (defmethod copy-message-using-folders :around ((message message) (message-folder imap-folder) (sink-folder imap-folder)) "Copy a message between two imap folders. We can optimize this case if the folders are on the same server." (if (and (equal (host message-folder) (host sink-folder)) (equal (username message-folder) (username sink-folder)) (equal (password message-folder) (password sink-folder)) (equal (imap-port message-folder) (imap-port sink-folder))) (progn (send-command message-folder "~A uid copy ~A ~A" "UID" (uid message) (mailbox sink-folder)) (process-response message-folder :on-uid (lambda (m) m))) ;; if we're not using the same server, play it safe (call-next-method))) (defmethod map-messages (fn (folder imap-folder)) (update-mailbox folder fn)) (defmethod message-size-using-folder ((folder imap-folder) (message message)) "A message's size is cached in the folder object. If there is a cache fault a FETCH for the RFC822.SIZE of the message is sent. Doing this for many messages at once may be slow because of the roundtrip delay. I deliberately left out RFC822.SIZE from the message-list FETCH (see UPDATE-MAILBOX) because it slowed it down to much." (multiple-value-bind (size existsp) (gethash (uid message) (size-table folder)) (if existsp size (let ((seq (sequence-number message))) (unless seq (error "No sequence number for message ~A (UID: ~A)" message (uid message))) (send-command folder "~A fetch ~A:~A (UID RFC822.SIZE)" "SIZE" seq seq) (process-response folder :on-size (lambda (m) m)) (gethash (uid message) (size-table folder)))))) (defmethod copy-folder ((source-folder imap-folder) (sink-folder folder)) "Overload for more efficient message transfer. Up to now messages are always fetched completely as a string buffer. This may lead to large memory consumption for big mails (And to problems with Lispsystems which have relatively small array-dimension-limits" (dolist (message (messages source-folder)) (with-open-stream (sink (open-message-storing-stream sink-folder message)) (let ((buffer (fetch-message source-folder (uid message)))) (write-sequence buffer sink))))) (defmethod copy-folder ((source-folder folder) (sink-folder imap-folder)) (cerror "Cancel copying of folder ~A to the imap folder ~A" "imap folders are not yet supported as message sinks" source-folder sink-folder)) (defmethod delete-message-using-folder ((folder imap-folder) message) (mark-deleted folder (uid message)) (expunge-mailbox folder)) (defmethod count-messages ((folder imap-folder)) "Count messages by sending an EXAMINE command. EXAMINE triggers an EXISTS response which contains the number of available messages in the imap folder." (noop folder) (slot-value folder 'exists)) (defmethod short-name ((folder imap-folder)) (format nil "imap://~A@~A" (username folder) (host folder))) #+nil (defmethod find-message ((folder imap-folder) uid) "Return cached message or create and cache a new one." (or (gethash uid (uid-table folder)) (setf (gethash uid (uid-table folder)) (call-next-method)))) (defun collect-ranges (predicate folder &key (key #'identity)) "A utility function that loops over all messages from the lowest sequence id to the highest. For each coherent subsequence of messages for which the predicate is true a pair containing the start and end position is collected." (with-slots (seq-table) folder (let ((start 1) (count (length seq-table)) ranges) (loop while (and start (< start count)) do (setf start (position-if predicate seq-table :key key :start start)) (unless start (return-from collect-ranges ranges)) (let ((end (position-if-not predicate seq-table :key key :start start))) (if end (push (cons start (1- end)) ranges) (push (cons start "*") ranges)) (setf start (if end (1+ end))))) ranges))) (defmethod ensure-all-headers ((folder imap-folder) &key hook) "Read all yet unread headers. First we construct a list of sequence id range pairs for those messages that do not have any cached header-fields yet. After that we send a FETCH command for each range in that list." (let ((ranges (collect-ranges #'null folder :key #'mel.mime:header-fields))) (loop for (start . end) in ranges do (send-command folder "~A fetch ~a:~a (BODY[HEADER])" "HEADER" start end #\return #\linefeed) (process-response folder :on-header (lambda (header) (funcall hook header)))))) #+nil (defmethod flagp-using-folder ((folder imap-folder) message (flag (eql :recent))) (multiple-value-bind (cell existsp) (gethash (uid message) (uid-cache folder)) (unless existsp (error "Message does not exist in uid cache")) (ecase (car cell) (:new t) (:cur nil)))) (defmethod mark-message-using-folder ((folder imap-folder) message (flag (eql :recent))) (declare (ignore message)) (cerror "Continue without setting the RECENT flag" "It is not possible to modify the RECENT flag manually")) (defmethod unmark-message-using-folder ((folder imap-folder) message (flag (eql :recent))) (declare (ignore message)) #+nil (cerror "Continue without unsetting the RECENT flag" "It is not possible to modify the RECENT flag manually")) ;; Sender Protocol (defclass imap-message-storing-stream (encapsulating-output-stream) ((message :accessor message :initarg :message) (folder :accessor stream-folder :initarg :folder))) (defmethod close ((stream imap-message-storing-stream) &key abort) (let ((message (get-output-stream-string (encapsulated-output-stream stream)))) (format t "Close message storing stream~%") (format t "Storing message of size ~D~%" (length message)) (force-output t) (unless abort (append-message (stream-folder stream) message)))) (defmethod open-message-storing-stream ((folder imap-folder) message) (format t "Open message storing stream~%") (force-output t) (let ((stream (make-instance 'imap-message-storing-stream :output-stream (make-string-output-stream) :message message :folder folder))) stream))
33153
;;; -*- Mode: LISP; Syntax: COMMON-LISP; Package: CL-USER; Base: 10 -*- ;;; Copyright (c) 2004, <NAME> <<EMAIL>>. ;;; 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 :mel.folders.imap) ;;;;;;;;;;;;;;;;; ;; IMAP folder ;; ;;;;;;;;;;;;;;;;; ;; Dependencies ;; MAKE-CONNECTION (defvar *imap-debug* nil) ;;; We want to assign sequence numbers to messages of a folder. ;;; (defclass sequence-table-mixin () ((seq-table :initform (make-array 5000 :adjustable t :fill-pointer 1 :initial-element nil)))) (defmethod (setf sequence-number) (n (message message)) "Set the sequence number of a message" (with-slots (seq-table) (folder message) (unless (> (array-dimension seq-table 0) n) (adjust-array seq-table (* 2 n) :fill-pointer n)) (unless (> (length seq-table) n) (setf (fill-pointer seq-table) (1+ n))) (setf (aref seq-table n) message))) (defmethod sequence-number ((message message)) "Return the sequence number of a message. This is an O(N) operation!" (with-slots (seq-table) (folder message) (position message seq-table :test #'eq))) (defmethod sequence-number-message ((folder sequence-table-mixin) n) (with-slots (seq-table) folder (let ((message (aref seq-table n))) (unless message (error "Sequence number ~d does not reference a message" n)) message))) (defmethod expunge-sequence-number ((folder sequence-table-mixin) n) (with-slots (seq-table) folder (let ((exists (length seq-table))) (rotatef (aref seq-table n) (aref seq-table exists)) (loop for i from n below exists do (rotatef (aref seq-table i) (aref seq-table (1+ i)))) (setf (aref seq-table exists) nil) (decf (fill-pointer seq-table))))) (defmethod close-folder :after((folder sequence-table-mixin)) (with-slots (seq-table) folder (fill seq-table nil) (setf (fill-pointer seq-table) 1))) (defclass network-folder-mixin () ((connection :accessor connection) (host :accessor host :initarg :host) (port :accessor imap-port :initarg :port) (username :accessor username :initarg :username) (password :accessor password :initarg :password))) (defclass imap-folder (sequence-table-mixin network-folder-mixin eql-message-cache-mixin basic-receiver basic-sender) ((mailbox :accessor mailbox :initarg :mailbox :initform "INBOX") (capabilities :reader capabilities :initform nil) (uidvalidity :reader uidvalidity) (uid-table :accessor uid-table :initform (make-hash-table :test 'eql)) (size-table :accessor size-table :initform (make-hash-table :test 'eql)) (exists :initform 0) (recent :initform 0) (unseen :initform nil) (messages :initform nil) (last-command :initform nil :accessor last-command) (state :accessor state :initarg :state :initform :disconnected))) (defclass imaps-folder (imap-folder) ()) (defun make-imap-folder (&key (host "imap.web.de")(port 143) username password (mailbox "INBOX")) (make-instance 'imap-folder :name (format nil "imap://~A!~A@~A:~A" username password host port) :host host :port port :username username :password <PASSWORD> :mailbox mailbox :state :disconnected)) (defun make-imaps-folder (&key (host "imap.web.de")(port 993) username password (mailbox "INBOX")) (make-instance 'imaps-folder :name (format nil "imaps://~A!~A@~A:~A" username password host port) :host host :port port :username username :password <PASSWORD> :mailbox mailbox :state :disconnected)) (defmethod serialize-folder ((folder imap-folder) stream) (with-standard-io-syntax (write `(make-imap-folder :host ,(host folder) :port ,(imap-port folder) :username ,(username folder) :password ,(password folder)) :stream stream))) ;;;;;;;;;;;;;;;;;;; ;; IMAP Protocol ;; ; ;; ; LOGIN ;; ; SELECT ;; ; SEARCH ;; ; FETCH ;; ; CLOSE ;; ;;;;;;;;;;;;;;;;;;; ;; Atom ; atom-specials: "(){" SPACE CTL list_wildcards quoted_specials ; quoted-specials: '"\' ; list-wildcards: "%*" ; 1*(non-special) (defvar *atom-specials* '(#\( #\) #\{ #\space #\% #\* #\" #\\)) (declaim (inline atom-char-p)) (defun atom-char-p (char) (declare (optimize (speed 3) (safety 1))) (and (characterp char) (not (or (let ((code (char-code char))) (or (<= #x00 code #x1f) (= code #x7f))) (member char *atom-specials*))))) (declaim (inline atom-char-p)) (defun read-atom (stream) (declare (optimize (speed 3) (safety 1))) (let ((string (with-output-to-string (s) (loop for c = (peek-char nil stream nil nil) while (atom-char-p c) do (read-char stream)(write-char c s))))) string)) ;; Number unsigned 32 bit ; 1*(digit) (declaim (inline read-number)) (defun read-number (stream) (declare (optimize (speed 3) (safety 1))) (let ((string (with-output-to-string (s) (loop for c = (peek-char nil stream nil nil) while (and c (digit-char-p c)) do (read-char stream)(write-char c s))))) (declare (optimize (speed 3) (safety 1)) (dynamic-extent string)) (parse-integer string))) ;; String ; quoted ; '"' *(7-bit ASCII without CR LF) '"' (declaim (inline read-quoted-string)) (defun read-quoted-string (stream) (declare (optimize (speed 3) (safety 1))) (let ((char (read-char stream))) (with-output-to-string (out) (ecase char (#\" (loop for c = (read-char stream) while (case c (#\\ (write-char (read-char stream) out) t) (#\" nil) (otherwise (write-char c out) t)))))))) (define-condition imap-paren-closed () ()) (define-condition imap-bracket-closed () ()) (define-condition end-of-imap-response () ()) ; * OK [PERMANENTFLAGS (\* \Draft \Answered \Flagged \Deleted \Seen)] Limited (declaim (inline accept-char)) (defun accept-char (c stream) (declare (optimize (speed 3) (safety 1))) (let ((char (peek-char nil stream nil nil))) (if (and char (char= c char)) (read-char stream) nil))) ;; Fix keywords ;; OK NO BAD ;; (defvar *imap-read-case* :keyword) (defun convert-atom (string) (ecase *imap-read-case* (:keyword (intern (string-upcase string) :keyword)) (:upcase (string-upcase string)) (:downcase (string-downcase string) :keyword) (:preserve string))) (defun imap-read (stream &optional (eof-errorp t) eof-value) (loop for c = (peek-char nil stream eof-errorp eof-value) while (case c ((#\space #\tab) (read-char stream) t) (otherwise nil))) (let ((char (peek-char nil stream eof-errorp eof-value))) (cond #+faithful-input((accept-char #\linefeed stream) (if eof-errorp (error 'end-of-imap-response) (return-from imap-read eof-value))) #-faithful-input((char= #\return char) (read-char stream) (accept-char #\linefeed stream) (if eof-errorp (error 'end-of-imap-response) (return-from imap-read eof-value))) ((char= #\" char) (read-quoted-string stream)) ((char= #\( char) (read-char stream) (imap-read-delimited-list stream)) ((char= #\[ char) (read-char stream) (imap-read-bracket-list stream)) ((char= #\) char) (read-char stream) (signal 'imap-paren-closed)) ((char= #\] char) (read-char stream) (signal 'imap-bracket-closed)) ;; Read chunk ((char= #\{ char) (read-char stream) (let ((number (read-number stream))) (unless (accept-char #\} stream) (error "Syntax error")) #-faithful-input(unless (accept-char #\return stream) (error "Syntax error")) (unless (accept-char #\linefeed stream) (error "Syntax error")) #-faithful-input (let ((buffer (make-array number :element-type '(unsigned-byte 8)))) (read-sequence buffer stream) buffer) #+faithful-input (let ((buffer (make-array number :element-type '(unsigned-byte 8)))) (setf (stream-element-type stream) '(unsigned-byte 8)) (read-sequence buffer stream) (setf (stream-element-type stream) 'character) (map 'string (lambda (b) (code-char b)) buffer)))) ((char= #\\ char) (read-char stream) (let ((char (peek-char nil stream))) (if (eql #\* char) :* (let ((atom (read-atom stream))) (cond ((zerop (length atom)) (error "Zero length \\atom")) ((string-equal atom "NIL") nil) ((every #'digit-char-p atom) (parse-integer atom)) (t (convert-atom atom))))))) ((atom-char-p char) (let ((atom (read-atom stream))) (cond ((zerop (length atom)) (error "Zero length atom")) ((string-equal atom "NIL") nil) ((every #'digit-char-p atom) (parse-integer atom)) (t (convert-atom atom))))) (t (read-char stream))))) (declaim (inline imap-read-delimited-list)) (defun imap-read-delimited-list (stream) (declare (optimize (speed 3) (safety 1))) (let (forms) (handler-case (loop for form = (imap-read stream) do (push form forms)) (imap-paren-closed () (nreverse forms))))) (declaim (inline imap-read-bracket-list)) (defun imap-read-bracket-list (stream) (declare (optimize (speed 3) (safety 1))) (let (forms) (handler-case (loop for form = (imap-read stream) do (push form forms)) (imap-bracket-closed () (nreverse forms))))) ;; Response (declaim (inline read-response)) (defun read-response (stream) (let (result) (handler-case (let ((tag (imap-read stream))) (push tag result) (let ((*imap-read-case* (if (eq :+ tag) :preserve :keyword))) (loop for form = (imap-read stream) do (push form result)))) (end-of-imap-response () (let ((result (nreverse result))) (if *imap-debug* (print result) result)))))) (defun skip-responses (stream) (loop for response = (read-response stream) do (print response *standard-output*) (case (second response) (:ok (return nil)) ((:no :bad (error "Error on response")))))) (defmethod process-response ((folder imap-folder) &key on-recent on-unseen on-exists on-expunge on-size on-uid on-body on-list on-header on-bodystructure on-continuation) (let ((stream (ensure-connection folder))) (let (attributes part) (labels ((process-untagged-number (type arguments) (let ((number type) (atom (first arguments))) (when *imap-debug* (assert (numberp number) (number) "Is not a number") (assert (keywordp atom) (atom) "Is not an atom")) (cond ((eq :exists atom) (setf (slot-value folder 'exists) number) (when on-exists (funcall on-exists number))) ((eq :recent atom) (setf (slot-value folder 'recent) number) (when on-recent (funcall on-recent number))) ((eq :unseen atom) (setf (slot-value folder 'unseen) number) (when on-unseen (funcall on-unseen number))) ((eq :expunge atom) (expunge-sequence-number folder number) (when on-expunge (funcall on-expunge number))) ((eq :fetch atom) (let ((form (second arguments))) (when *imap-debug* (assert (and form (consp form)) (form) "Is not a form")) (process-fetch number form)))))) (process-fetch (n form) ;; Message (when-let (message (getf form :BODYSTRUCTURE)) (when on-bodystructure (funcall on-bodystructure message)) (setf part message)) (when-let (message (getf form :BODY[HEADER])) (with-input-from-sequence (s message) (setf (weird-mail.mime:header-fields (sequence-number-message folder n)) (mel.mime:read-rfc2822-header s))) (when on-header (funcall on-header message)) (setf part message)) (when-let (message (getf form :|BODY[TEXT]|)) (when on-body (funcall on-body message)) (setf part message)) (when-let (message (getf form :|BODY[]|)) (when on-body (funcall on-body message)) (setf part message)) ;; Attributes (let (message) (when-let (uid (getf form :uid)) ;; We got a FETCH response with ;; an UID. We use this for creation ;; of the message objects ;; Create or find cached message object associated ;; with given UID (setf message (find-message folder uid :if-does-not-exist :create)) ;; Register sequence number with message (setf (sequence-number message) n) (when on-uid ;; Call hook (funcall on-uid message))) (let ((flags (getf form :flags :n/a))) (unless (eq flags :n/a) (if message (setf (flags message) flags) (setf (flags (sequence-number-message folder n)) flags)))) (when-let (size (getf form :RFC822.SIZE)) (when on-size (let ((message (or message (sequence-number-message folder n)))) (setf (gethash (uid message) (size-table folder)) size)) (funcall on-size message))) (push form attributes)))) ;; Process next IMAP response (loop (destructuring-bind (tag type &rest arguments) (read-response stream) (force-output t) (cond ((eq tag :+) (when on-continuation (funcall on-continuation type arguments))) ((keywordp tag) (case type (:ok (return (values part attributes))) ((:no :bad) (error "Error on response: ~A (cmd: ~A)" arguments (if *imap-debug* (last-command folder) "N/A"))))) ((eql tag #\*) (cond ((numberp type) (process-untagged-number type arguments)) ((eq :list type) (when on-list (funcall on-list (first arguments) (rest arguments)))) ((eq :search type) (when on-list (funcall on-list arguments))) ((eq :capability type) (setf (slot-value folder 'capabilities) (rest arguments))) ((eql type :ok) (case (first arguments) (:uidvalidity (if (uidvalidity folder) (unless (= (first (second arguments)) (uidvalidity folder)) (setf (slot-value folder 'uidvalidity) (first (second arguments))) (clrhash (size-table folder)) (clrhash (uid-table folder))) (setf (slot-value folder 'uidvalidity) (first (second arguments))))) (:capabilities (setf (slot-value folder 'capabilities) (second arguments)))))))))))))) (defun authenticate-cram-md5 (sink-folder) (format (connection sink-folder) "CRAM AUTHENTICATE CRAM-MD5") (write-char #\return (connection sink-folder)) (write-char #\linefeed (connection sink-folder)) (force-output (connection sink-folder)) (process-response sink-folder :on-continuation (lambda (arg1 arguments) (declare (ignore arguments)) (let ((timestamp (map 'string #'code-char (mel.mime::decode-base64 arg1)))) (format t "(Challenge) ~A~%" timestamp) (let ((username (mel.cipher:string-to-octets (format nil "~A " (username sink-folder)))) (digest (mel.cipher:hmac-md5 timestamp (password sink-folder)))) (let ((response (concatenate 'vector username digest))) (format t "(Response) ~A~%" (map 'string #'code-char response)) (write-string (mel.mime::encode-base64 response) (connection sink-folder)) (write-char #\return (connection sink-folder)) (write-char #\linefeed (connection sink-folder)) (force-output (connection sink-folder)))))))) (defmethod login ((folder imap-folder)) (let ((connection (connection folder))) (format connection "c01 LOGIN ~A \"~A\"~A~A" (username folder) (password folder) #\return #\linefeed) ;; Not really tested yet ; (authenticate-cram-md5 folder) (force-output connection) (process-response folder) connection)) (defmethod make-imap-connection ((folder imap-folder)) (let ((connection (mel.network:make-connection :remote-host (host folder) :remote-port (imap-port folder) :element-type '(unsigned-byte 8)))) (setf (connection folder) connection) (setf (state folder) :connected) (read-response connection) (login folder))) (defmethod make-imaps-connection ((folder imaps-folder)) (let ((connection (mel.network:make-connection :remote-host (host folder) :remote-port (imap-port folder) :ssl t :element-type '(unsigned-byte 8)))) (setf (connection folder) connection) (setf (state folder) :connected) (read-response connection) (login folder))) (defun send-command (folder string &rest args) (handler-case (let ((stream (ensure-connection folder))) (when *imap-debug* (setf (last-command folder) (apply #'format nil string args))) (apply #'format stream string args) (write-char #\return stream) (write-char #\linefeed stream) (force-output stream)) (end-of-file () (setf (state folder) :disconnected)))) (defmethod ensure-connection ((folder imap-folder)) (when (eq (state folder) :disconnected) (setf (connection folder) (make-imap-connection folder)) (setf (state folder) :connected) (select-mailbox folder)) (handler-case (connection folder) (cl:end-of-file () (setf (state folder) :disconnected) (ensure-connection folder)))) ;; Required untagged responses: FLAGS EXISTS RECENT ;; Optional untagged responses: UNSEEN, PERMANENTFLAGS (defun select-mailbox (folder) (unless (connection folder) (ensure-connection folder)) (let ((stream (connection folder))) (format stream "~A select ~A~A~A" "t01" (mailbox folder) #\return #\linefeed) (force-output stream) (let (recent exists) (process-response folder :on-recent (lambda (n) (setf recent n)) :on-exists (lambda (n) (setf exists n))) (values exists recent)))) (defun capability (folder) (send-command folder "~A capability" "t01") (process-response folder)) (defun start-idle (folder) (send-command folder "~A idle" "t01") (process-response folder)) (defun end-idle (folder) (send-command folder "done") (process-response folder)) (defun noop (folder) (send-command folder "~A noop" "t01") (process-response folder)) (defun create-mailbox (folder mailbox) (send-command folder "~A create ~A" "create" mailbox) (process-response folder)) (defun list-mailboxes (folder pattern) (send-command folder "~A list \"\" ~S" "create" pattern) (let (result) (process-response folder :on-list (lambda (flags args) (push (list* flags args) result))) result)) (defun close-mailbox (folder) (when (eq (state folder) :connected) (send-command folder "c1 close") (process-response folder) (setf (state folder) :disconnected) ;; Added by KTR on 07/17/2008 to close the network connection (close (connection folder)))) (defun examine-mailbox (folder) (send-command folder "~A select ~A" "t01" (mailbox folder)) (process-response folder)) (defun expunge-mailbox (folder) (send-command folder "~A expunge" "t01") (process-response folder)) (defmethod update-mailbox ((folder imap-folder) callback) (let ((non-recent (hash-table-count (message-cache folder))) (exists (count-messages folder))) (cond ((/= exists non-recent) (clrhash (size-table folder)) (ensure-connection folder) (send-command folder "~A fetch 1:~A (UID FLAGS)" ; (UID RFC822.SIZE FLAGS)" "UPDATE" (slot-value folder 'exists)) (let (messages) (process-response folder :on-uid (lambda (message) (push message messages) (funcall callback message))) (setf (slot-value folder 'messages) messages))) (t (slot-value folder 'messages))))) (defmethod update-new-mailbox ((folder imap-folder) callback) (let ((non-recent (hash-table-count (message-cache folder))) (exists (count-messages folder))) (cond ((> exists non-recent) (clrhash (size-table folder)) (ensure-connection folder) (send-command folder "~A fetch 1:~A (UID FLAGS)" ; (UID RFC822.SIZE FLAGS)" "UPDATE" (slot-value folder 'exists)) (let (messages) (process-response folder :on-uid (lambda (message) (push message messages) (funcall callback message))) (setf (slot-value folder 'messages) messages))) (t (slot-value folder 'messages))))) (defun append-message (sink-folder message-string) (let ((message-size (length message-string))) (send-command sink-folder "~A APPEND ~A () {~D}" "APPEND" (mailbox sink-folder) message-size) (process-response sink-folder :on-continuation (lambda (type arguments) (declare (ignore type arguments)) (write-sequence message-string (connection sink-folder)) (write-char #\return (connection sink-folder)) (write-char #\linefeed (connection sink-folder)) (force-output (connection sink-folder)))))) (defmethod fetch-message ((folder imap-folder) uid) (send-command folder "~A uid fetch ~A (UID BODY[])" "MESSAGE" uid) (let (result) (process-response folder :on-body (lambda (body) (setf result body))) result)) (defmethod fetch-message-body ((folder imap-folder) uid) (send-command folder "~A uid fetch ~A (UID BODY[TEXT])" "BODY" uid) (let (result) (process-response folder :on-body (lambda (body) (setf result body))) result)) (defmethod fetch-message-header ((folder imap-folder) uid) (send-command folder "~A uid fetch ~A (UID BODY[HEADER])" "HEADER" uid #\return #\linefeed) (let (result) (process-response folder :on-header (lambda (header) (setf result header))) result)) (defmethod fetch-all-message-headers ((folder imap-folder)) (send-command folder "~A fetch 1:* (UID BODY[HEADER])" "HEADER" #\return #\linefeed) (process-response folder :on-header (lambda (header) (declare (ignore header))))) (defmethod fetch-message-bodystructure ((folder imap-folder) uid) (send-command folder "~A uid fetch ~A (UID BODYSTRUCTURE)" "BODYSTRUCTURE" uid) (let (result) (process-response folder :on-bodystructure (lambda (b) (setf result b))) result)) (defun canonicalize-bodystructure (bodystructure) (labels ((keyword (string) (typecase string (symbol string) (string (intern (string-upcase string) #.(find-package :keyword))))) (canonicalize-parameters (params) (loop for (name value) on params by #'cddr nconc (list (keyword name) value))) (canonicalize-simple-part (bs) `(,(keyword (first bs)) ,(keyword (second bs)) ,(canonicalize-parameters (third bs)) nil nil ,(keyword (sixth bs)) ,(seventh bs) ,(eighth bs) nil nil nil)) (canonicalize-multipart (bs) (loop for tail on bs while (consp (first tail)) collect (canonicalize-bodystructure (first tail)) into parts finally (return `(,@parts ,(keyword (first tail)) ,(canonicalize-parameters (second tail)) nil nil))))) (etypecase (car bodystructure) (cons (canonicalize-multipart bodystructure)) (string (canonicalize-simple-part bodystructure)) (symbol (canonicalize-simple-part bodystructure))))) (defmethod mel.mime::compute-bodystructure-using-folder ((folder imap-folder) (message mel.mime::bodystructure-mixin)) (let ((bodystructure (fetch-message-bodystructure folder (uid message)))) (canonicalize-bodystructure bodystructure))) (defmethod search-mailbox ((folder imap-folder) query) (send-command folder "~A uid search ~A" "t01" query) (let (messages) (labels ((return-messages (list) (setf messages (mapcar (lambda (uid) (find-message folder uid)) list)))) (process-response folder :on-list #'return-messages) messages))) (defmethod mark-deleted ((folder imap-folder) uid) (send-command folder "~A uid store ~A +flags (\\Deleted)" "t01" uid) (process-response folder)) ;;;;;;;;;;;;;;;;;;;;; ;; Folder Protocol ;; ;;;;;;;;;;;;;;;;;;;;; (defmethod close-folder ((folder imap-folder)) (unless (eq (state folder) :disconnected) (ignore-errors (close-mailbox folder)) (setf (connection folder) nil (state folder) :disconnected) (clrhash (uid-table folder)) (clrhash (size-table folder)) (setf (slot-value folder 'messages) nil (slot-value folder 'exists) 0 (slot-value folder 'recent) 0) )) (defmethod open-message-input-stream-using-folder ((folder imap-folder) message start) (let ((stream (make-sequence-input-stream (fetch-message folder (uid message))))) (file-position stream (+ (file-position stream) start)) stream)) (defmethod message-body-stream-using-folder ((folder imap-folder) message) (make-sequence-input-stream (fetch-message-body folder (uid message)))) (defmethod message-header-stream-using-folder ((folder imap-folder) message) (let ((stream (make-sequence-input-stream (fetch-message-header folder (uid message))))) stream)) ;;; Folder Protocol Support (defmethod copy-message-using-folders :around ((message message) (message-folder imap-folder) (sink-folder imap-folder)) "Copy a message between two imap folders. We can optimize this case if the folders are on the same server." (if (and (equal (host message-folder) (host sink-folder)) (equal (username message-folder) (username sink-folder)) (equal (password message-folder) (password sink-folder)) (equal (imap-port message-folder) (imap-port sink-folder))) (progn (send-command message-folder "~A uid copy ~A ~A" "UID" (uid message) (mailbox sink-folder)) (process-response message-folder :on-uid (lambda (m) m))) ;; if we're not using the same server, play it safe (call-next-method))) (defmethod map-messages (fn (folder imap-folder)) (update-mailbox folder fn)) (defmethod message-size-using-folder ((folder imap-folder) (message message)) "A message's size is cached in the folder object. If there is a cache fault a FETCH for the RFC822.SIZE of the message is sent. Doing this for many messages at once may be slow because of the roundtrip delay. I deliberately left out RFC822.SIZE from the message-list FETCH (see UPDATE-MAILBOX) because it slowed it down to much." (multiple-value-bind (size existsp) (gethash (uid message) (size-table folder)) (if existsp size (let ((seq (sequence-number message))) (unless seq (error "No sequence number for message ~A (UID: ~A)" message (uid message))) (send-command folder "~A fetch ~A:~A (UID RFC822.SIZE)" "SIZE" seq seq) (process-response folder :on-size (lambda (m) m)) (gethash (uid message) (size-table folder)))))) (defmethod copy-folder ((source-folder imap-folder) (sink-folder folder)) "Overload for more efficient message transfer. Up to now messages are always fetched completely as a string buffer. This may lead to large memory consumption for big mails (And to problems with Lispsystems which have relatively small array-dimension-limits" (dolist (message (messages source-folder)) (with-open-stream (sink (open-message-storing-stream sink-folder message)) (let ((buffer (fetch-message source-folder (uid message)))) (write-sequence buffer sink))))) (defmethod copy-folder ((source-folder folder) (sink-folder imap-folder)) (cerror "Cancel copying of folder ~A to the imap folder ~A" "imap folders are not yet supported as message sinks" source-folder sink-folder)) (defmethod delete-message-using-folder ((folder imap-folder) message) (mark-deleted folder (uid message)) (expunge-mailbox folder)) (defmethod count-messages ((folder imap-folder)) "Count messages by sending an EXAMINE command. EXAMINE triggers an EXISTS response which contains the number of available messages in the imap folder." (noop folder) (slot-value folder 'exists)) (defmethod short-name ((folder imap-folder)) (format nil "imap://~A@~A" (username folder) (host folder))) #+nil (defmethod find-message ((folder imap-folder) uid) "Return cached message or create and cache a new one." (or (gethash uid (uid-table folder)) (setf (gethash uid (uid-table folder)) (call-next-method)))) (defun collect-ranges (predicate folder &key (key #'identity)) "A utility function that loops over all messages from the lowest sequence id to the highest. For each coherent subsequence of messages for which the predicate is true a pair containing the start and end position is collected." (with-slots (seq-table) folder (let ((start 1) (count (length seq-table)) ranges) (loop while (and start (< start count)) do (setf start (position-if predicate seq-table :key key :start start)) (unless start (return-from collect-ranges ranges)) (let ((end (position-if-not predicate seq-table :key key :start start))) (if end (push (cons start (1- end)) ranges) (push (cons start "*") ranges)) (setf start (if end (1+ end))))) ranges))) (defmethod ensure-all-headers ((folder imap-folder) &key hook) "Read all yet unread headers. First we construct a list of sequence id range pairs for those messages that do not have any cached header-fields yet. After that we send a FETCH command for each range in that list." (let ((ranges (collect-ranges #'null folder :key #'mel.mime:header-fields))) (loop for (start . end) in ranges do (send-command folder "~A fetch ~a:~a (BODY[HEADER])" "HEADER" start end #\return #\linefeed) (process-response folder :on-header (lambda (header) (funcall hook header)))))) #+nil (defmethod flagp-using-folder ((folder imap-folder) message (flag (eql :recent))) (multiple-value-bind (cell existsp) (gethash (uid message) (uid-cache folder)) (unless existsp (error "Message does not exist in uid cache")) (ecase (car cell) (:new t) (:cur nil)))) (defmethod mark-message-using-folder ((folder imap-folder) message (flag (eql :recent))) (declare (ignore message)) (cerror "Continue without setting the RECENT flag" "It is not possible to modify the RECENT flag manually")) (defmethod unmark-message-using-folder ((folder imap-folder) message (flag (eql :recent))) (declare (ignore message)) #+nil (cerror "Continue without unsetting the RECENT flag" "It is not possible to modify the RECENT flag manually")) ;; Sender Protocol (defclass imap-message-storing-stream (encapsulating-output-stream) ((message :accessor message :initarg :message) (folder :accessor stream-folder :initarg :folder))) (defmethod close ((stream imap-message-storing-stream) &key abort) (let ((message (get-output-stream-string (encapsulated-output-stream stream)))) (format t "Close message storing stream~%") (format t "Storing message of size ~D~%" (length message)) (force-output t) (unless abort (append-message (stream-folder stream) message)))) (defmethod open-message-storing-stream ((folder imap-folder) message) (format t "Open message storing stream~%") (force-output t) (let ((stream (make-instance 'imap-message-storing-stream :output-stream (make-string-output-stream) :message message :folder folder))) stream))
true
;;; -*- Mode: LISP; Syntax: COMMON-LISP; Package: CL-USER; Base: 10 -*- ;;; Copyright (c) 2004, PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>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 :mel.folders.imap) ;;;;;;;;;;;;;;;;; ;; IMAP folder ;; ;;;;;;;;;;;;;;;;; ;; Dependencies ;; MAKE-CONNECTION (defvar *imap-debug* nil) ;;; We want to assign sequence numbers to messages of a folder. ;;; (defclass sequence-table-mixin () ((seq-table :initform (make-array 5000 :adjustable t :fill-pointer 1 :initial-element nil)))) (defmethod (setf sequence-number) (n (message message)) "Set the sequence number of a message" (with-slots (seq-table) (folder message) (unless (> (array-dimension seq-table 0) n) (adjust-array seq-table (* 2 n) :fill-pointer n)) (unless (> (length seq-table) n) (setf (fill-pointer seq-table) (1+ n))) (setf (aref seq-table n) message))) (defmethod sequence-number ((message message)) "Return the sequence number of a message. This is an O(N) operation!" (with-slots (seq-table) (folder message) (position message seq-table :test #'eq))) (defmethod sequence-number-message ((folder sequence-table-mixin) n) (with-slots (seq-table) folder (let ((message (aref seq-table n))) (unless message (error "Sequence number ~d does not reference a message" n)) message))) (defmethod expunge-sequence-number ((folder sequence-table-mixin) n) (with-slots (seq-table) folder (let ((exists (length seq-table))) (rotatef (aref seq-table n) (aref seq-table exists)) (loop for i from n below exists do (rotatef (aref seq-table i) (aref seq-table (1+ i)))) (setf (aref seq-table exists) nil) (decf (fill-pointer seq-table))))) (defmethod close-folder :after((folder sequence-table-mixin)) (with-slots (seq-table) folder (fill seq-table nil) (setf (fill-pointer seq-table) 1))) (defclass network-folder-mixin () ((connection :accessor connection) (host :accessor host :initarg :host) (port :accessor imap-port :initarg :port) (username :accessor username :initarg :username) (password :accessor password :initarg :password))) (defclass imap-folder (sequence-table-mixin network-folder-mixin eql-message-cache-mixin basic-receiver basic-sender) ((mailbox :accessor mailbox :initarg :mailbox :initform "INBOX") (capabilities :reader capabilities :initform nil) (uidvalidity :reader uidvalidity) (uid-table :accessor uid-table :initform (make-hash-table :test 'eql)) (size-table :accessor size-table :initform (make-hash-table :test 'eql)) (exists :initform 0) (recent :initform 0) (unseen :initform nil) (messages :initform nil) (last-command :initform nil :accessor last-command) (state :accessor state :initarg :state :initform :disconnected))) (defclass imaps-folder (imap-folder) ()) (defun make-imap-folder (&key (host "imap.web.de")(port 143) username password (mailbox "INBOX")) (make-instance 'imap-folder :name (format nil "imap://~A!~A@~A:~A" username password host port) :host host :port port :username username :password PI:PASSWORD:<PASSWORD>END_PI :mailbox mailbox :state :disconnected)) (defun make-imaps-folder (&key (host "imap.web.de")(port 993) username password (mailbox "INBOX")) (make-instance 'imaps-folder :name (format nil "imaps://~A!~A@~A:~A" username password host port) :host host :port port :username username :password PI:PASSWORD:<PASSWORD>END_PI :mailbox mailbox :state :disconnected)) (defmethod serialize-folder ((folder imap-folder) stream) (with-standard-io-syntax (write `(make-imap-folder :host ,(host folder) :port ,(imap-port folder) :username ,(username folder) :password ,(password folder)) :stream stream))) ;;;;;;;;;;;;;;;;;;; ;; IMAP Protocol ;; ; ;; ; LOGIN ;; ; SELECT ;; ; SEARCH ;; ; FETCH ;; ; CLOSE ;; ;;;;;;;;;;;;;;;;;;; ;; Atom ; atom-specials: "(){" SPACE CTL list_wildcards quoted_specials ; quoted-specials: '"\' ; list-wildcards: "%*" ; 1*(non-special) (defvar *atom-specials* '(#\( #\) #\{ #\space #\% #\* #\" #\\)) (declaim (inline atom-char-p)) (defun atom-char-p (char) (declare (optimize (speed 3) (safety 1))) (and (characterp char) (not (or (let ((code (char-code char))) (or (<= #x00 code #x1f) (= code #x7f))) (member char *atom-specials*))))) (declaim (inline atom-char-p)) (defun read-atom (stream) (declare (optimize (speed 3) (safety 1))) (let ((string (with-output-to-string (s) (loop for c = (peek-char nil stream nil nil) while (atom-char-p c) do (read-char stream)(write-char c s))))) string)) ;; Number unsigned 32 bit ; 1*(digit) (declaim (inline read-number)) (defun read-number (stream) (declare (optimize (speed 3) (safety 1))) (let ((string (with-output-to-string (s) (loop for c = (peek-char nil stream nil nil) while (and c (digit-char-p c)) do (read-char stream)(write-char c s))))) (declare (optimize (speed 3) (safety 1)) (dynamic-extent string)) (parse-integer string))) ;; String ; quoted ; '"' *(7-bit ASCII without CR LF) '"' (declaim (inline read-quoted-string)) (defun read-quoted-string (stream) (declare (optimize (speed 3) (safety 1))) (let ((char (read-char stream))) (with-output-to-string (out) (ecase char (#\" (loop for c = (read-char stream) while (case c (#\\ (write-char (read-char stream) out) t) (#\" nil) (otherwise (write-char c out) t)))))))) (define-condition imap-paren-closed () ()) (define-condition imap-bracket-closed () ()) (define-condition end-of-imap-response () ()) ; * OK [PERMANENTFLAGS (\* \Draft \Answered \Flagged \Deleted \Seen)] Limited (declaim (inline accept-char)) (defun accept-char (c stream) (declare (optimize (speed 3) (safety 1))) (let ((char (peek-char nil stream nil nil))) (if (and char (char= c char)) (read-char stream) nil))) ;; Fix keywords ;; OK NO BAD ;; (defvar *imap-read-case* :keyword) (defun convert-atom (string) (ecase *imap-read-case* (:keyword (intern (string-upcase string) :keyword)) (:upcase (string-upcase string)) (:downcase (string-downcase string) :keyword) (:preserve string))) (defun imap-read (stream &optional (eof-errorp t) eof-value) (loop for c = (peek-char nil stream eof-errorp eof-value) while (case c ((#\space #\tab) (read-char stream) t) (otherwise nil))) (let ((char (peek-char nil stream eof-errorp eof-value))) (cond #+faithful-input((accept-char #\linefeed stream) (if eof-errorp (error 'end-of-imap-response) (return-from imap-read eof-value))) #-faithful-input((char= #\return char) (read-char stream) (accept-char #\linefeed stream) (if eof-errorp (error 'end-of-imap-response) (return-from imap-read eof-value))) ((char= #\" char) (read-quoted-string stream)) ((char= #\( char) (read-char stream) (imap-read-delimited-list stream)) ((char= #\[ char) (read-char stream) (imap-read-bracket-list stream)) ((char= #\) char) (read-char stream) (signal 'imap-paren-closed)) ((char= #\] char) (read-char stream) (signal 'imap-bracket-closed)) ;; Read chunk ((char= #\{ char) (read-char stream) (let ((number (read-number stream))) (unless (accept-char #\} stream) (error "Syntax error")) #-faithful-input(unless (accept-char #\return stream) (error "Syntax error")) (unless (accept-char #\linefeed stream) (error "Syntax error")) #-faithful-input (let ((buffer (make-array number :element-type '(unsigned-byte 8)))) (read-sequence buffer stream) buffer) #+faithful-input (let ((buffer (make-array number :element-type '(unsigned-byte 8)))) (setf (stream-element-type stream) '(unsigned-byte 8)) (read-sequence buffer stream) (setf (stream-element-type stream) 'character) (map 'string (lambda (b) (code-char b)) buffer)))) ((char= #\\ char) (read-char stream) (let ((char (peek-char nil stream))) (if (eql #\* char) :* (let ((atom (read-atom stream))) (cond ((zerop (length atom)) (error "Zero length \\atom")) ((string-equal atom "NIL") nil) ((every #'digit-char-p atom) (parse-integer atom)) (t (convert-atom atom))))))) ((atom-char-p char) (let ((atom (read-atom stream))) (cond ((zerop (length atom)) (error "Zero length atom")) ((string-equal atom "NIL") nil) ((every #'digit-char-p atom) (parse-integer atom)) (t (convert-atom atom))))) (t (read-char stream))))) (declaim (inline imap-read-delimited-list)) (defun imap-read-delimited-list (stream) (declare (optimize (speed 3) (safety 1))) (let (forms) (handler-case (loop for form = (imap-read stream) do (push form forms)) (imap-paren-closed () (nreverse forms))))) (declaim (inline imap-read-bracket-list)) (defun imap-read-bracket-list (stream) (declare (optimize (speed 3) (safety 1))) (let (forms) (handler-case (loop for form = (imap-read stream) do (push form forms)) (imap-bracket-closed () (nreverse forms))))) ;; Response (declaim (inline read-response)) (defun read-response (stream) (let (result) (handler-case (let ((tag (imap-read stream))) (push tag result) (let ((*imap-read-case* (if (eq :+ tag) :preserve :keyword))) (loop for form = (imap-read stream) do (push form result)))) (end-of-imap-response () (let ((result (nreverse result))) (if *imap-debug* (print result) result)))))) (defun skip-responses (stream) (loop for response = (read-response stream) do (print response *standard-output*) (case (second response) (:ok (return nil)) ((:no :bad (error "Error on response")))))) (defmethod process-response ((folder imap-folder) &key on-recent on-unseen on-exists on-expunge on-size on-uid on-body on-list on-header on-bodystructure on-continuation) (let ((stream (ensure-connection folder))) (let (attributes part) (labels ((process-untagged-number (type arguments) (let ((number type) (atom (first arguments))) (when *imap-debug* (assert (numberp number) (number) "Is not a number") (assert (keywordp atom) (atom) "Is not an atom")) (cond ((eq :exists atom) (setf (slot-value folder 'exists) number) (when on-exists (funcall on-exists number))) ((eq :recent atom) (setf (slot-value folder 'recent) number) (when on-recent (funcall on-recent number))) ((eq :unseen atom) (setf (slot-value folder 'unseen) number) (when on-unseen (funcall on-unseen number))) ((eq :expunge atom) (expunge-sequence-number folder number) (when on-expunge (funcall on-expunge number))) ((eq :fetch atom) (let ((form (second arguments))) (when *imap-debug* (assert (and form (consp form)) (form) "Is not a form")) (process-fetch number form)))))) (process-fetch (n form) ;; Message (when-let (message (getf form :BODYSTRUCTURE)) (when on-bodystructure (funcall on-bodystructure message)) (setf part message)) (when-let (message (getf form :BODY[HEADER])) (with-input-from-sequence (s message) (setf (weird-mail.mime:header-fields (sequence-number-message folder n)) (mel.mime:read-rfc2822-header s))) (when on-header (funcall on-header message)) (setf part message)) (when-let (message (getf form :|BODY[TEXT]|)) (when on-body (funcall on-body message)) (setf part message)) (when-let (message (getf form :|BODY[]|)) (when on-body (funcall on-body message)) (setf part message)) ;; Attributes (let (message) (when-let (uid (getf form :uid)) ;; We got a FETCH response with ;; an UID. We use this for creation ;; of the message objects ;; Create or find cached message object associated ;; with given UID (setf message (find-message folder uid :if-does-not-exist :create)) ;; Register sequence number with message (setf (sequence-number message) n) (when on-uid ;; Call hook (funcall on-uid message))) (let ((flags (getf form :flags :n/a))) (unless (eq flags :n/a) (if message (setf (flags message) flags) (setf (flags (sequence-number-message folder n)) flags)))) (when-let (size (getf form :RFC822.SIZE)) (when on-size (let ((message (or message (sequence-number-message folder n)))) (setf (gethash (uid message) (size-table folder)) size)) (funcall on-size message))) (push form attributes)))) ;; Process next IMAP response (loop (destructuring-bind (tag type &rest arguments) (read-response stream) (force-output t) (cond ((eq tag :+) (when on-continuation (funcall on-continuation type arguments))) ((keywordp tag) (case type (:ok (return (values part attributes))) ((:no :bad) (error "Error on response: ~A (cmd: ~A)" arguments (if *imap-debug* (last-command folder) "N/A"))))) ((eql tag #\*) (cond ((numberp type) (process-untagged-number type arguments)) ((eq :list type) (when on-list (funcall on-list (first arguments) (rest arguments)))) ((eq :search type) (when on-list (funcall on-list arguments))) ((eq :capability type) (setf (slot-value folder 'capabilities) (rest arguments))) ((eql type :ok) (case (first arguments) (:uidvalidity (if (uidvalidity folder) (unless (= (first (second arguments)) (uidvalidity folder)) (setf (slot-value folder 'uidvalidity) (first (second arguments))) (clrhash (size-table folder)) (clrhash (uid-table folder))) (setf (slot-value folder 'uidvalidity) (first (second arguments))))) (:capabilities (setf (slot-value folder 'capabilities) (second arguments)))))))))))))) (defun authenticate-cram-md5 (sink-folder) (format (connection sink-folder) "CRAM AUTHENTICATE CRAM-MD5") (write-char #\return (connection sink-folder)) (write-char #\linefeed (connection sink-folder)) (force-output (connection sink-folder)) (process-response sink-folder :on-continuation (lambda (arg1 arguments) (declare (ignore arguments)) (let ((timestamp (map 'string #'code-char (mel.mime::decode-base64 arg1)))) (format t "(Challenge) ~A~%" timestamp) (let ((username (mel.cipher:string-to-octets (format nil "~A " (username sink-folder)))) (digest (mel.cipher:hmac-md5 timestamp (password sink-folder)))) (let ((response (concatenate 'vector username digest))) (format t "(Response) ~A~%" (map 'string #'code-char response)) (write-string (mel.mime::encode-base64 response) (connection sink-folder)) (write-char #\return (connection sink-folder)) (write-char #\linefeed (connection sink-folder)) (force-output (connection sink-folder)))))))) (defmethod login ((folder imap-folder)) (let ((connection (connection folder))) (format connection "c01 LOGIN ~A \"~A\"~A~A" (username folder) (password folder) #\return #\linefeed) ;; Not really tested yet ; (authenticate-cram-md5 folder) (force-output connection) (process-response folder) connection)) (defmethod make-imap-connection ((folder imap-folder)) (let ((connection (mel.network:make-connection :remote-host (host folder) :remote-port (imap-port folder) :element-type '(unsigned-byte 8)))) (setf (connection folder) connection) (setf (state folder) :connected) (read-response connection) (login folder))) (defmethod make-imaps-connection ((folder imaps-folder)) (let ((connection (mel.network:make-connection :remote-host (host folder) :remote-port (imap-port folder) :ssl t :element-type '(unsigned-byte 8)))) (setf (connection folder) connection) (setf (state folder) :connected) (read-response connection) (login folder))) (defun send-command (folder string &rest args) (handler-case (let ((stream (ensure-connection folder))) (when *imap-debug* (setf (last-command folder) (apply #'format nil string args))) (apply #'format stream string args) (write-char #\return stream) (write-char #\linefeed stream) (force-output stream)) (end-of-file () (setf (state folder) :disconnected)))) (defmethod ensure-connection ((folder imap-folder)) (when (eq (state folder) :disconnected) (setf (connection folder) (make-imap-connection folder)) (setf (state folder) :connected) (select-mailbox folder)) (handler-case (connection folder) (cl:end-of-file () (setf (state folder) :disconnected) (ensure-connection folder)))) ;; Required untagged responses: FLAGS EXISTS RECENT ;; Optional untagged responses: UNSEEN, PERMANENTFLAGS (defun select-mailbox (folder) (unless (connection folder) (ensure-connection folder)) (let ((stream (connection folder))) (format stream "~A select ~A~A~A" "t01" (mailbox folder) #\return #\linefeed) (force-output stream) (let (recent exists) (process-response folder :on-recent (lambda (n) (setf recent n)) :on-exists (lambda (n) (setf exists n))) (values exists recent)))) (defun capability (folder) (send-command folder "~A capability" "t01") (process-response folder)) (defun start-idle (folder) (send-command folder "~A idle" "t01") (process-response folder)) (defun end-idle (folder) (send-command folder "done") (process-response folder)) (defun noop (folder) (send-command folder "~A noop" "t01") (process-response folder)) (defun create-mailbox (folder mailbox) (send-command folder "~A create ~A" "create" mailbox) (process-response folder)) (defun list-mailboxes (folder pattern) (send-command folder "~A list \"\" ~S" "create" pattern) (let (result) (process-response folder :on-list (lambda (flags args) (push (list* flags args) result))) result)) (defun close-mailbox (folder) (when (eq (state folder) :connected) (send-command folder "c1 close") (process-response folder) (setf (state folder) :disconnected) ;; Added by KTR on 07/17/2008 to close the network connection (close (connection folder)))) (defun examine-mailbox (folder) (send-command folder "~A select ~A" "t01" (mailbox folder)) (process-response folder)) (defun expunge-mailbox (folder) (send-command folder "~A expunge" "t01") (process-response folder)) (defmethod update-mailbox ((folder imap-folder) callback) (let ((non-recent (hash-table-count (message-cache folder))) (exists (count-messages folder))) (cond ((/= exists non-recent) (clrhash (size-table folder)) (ensure-connection folder) (send-command folder "~A fetch 1:~A (UID FLAGS)" ; (UID RFC822.SIZE FLAGS)" "UPDATE" (slot-value folder 'exists)) (let (messages) (process-response folder :on-uid (lambda (message) (push message messages) (funcall callback message))) (setf (slot-value folder 'messages) messages))) (t (slot-value folder 'messages))))) (defmethod update-new-mailbox ((folder imap-folder) callback) (let ((non-recent (hash-table-count (message-cache folder))) (exists (count-messages folder))) (cond ((> exists non-recent) (clrhash (size-table folder)) (ensure-connection folder) (send-command folder "~A fetch 1:~A (UID FLAGS)" ; (UID RFC822.SIZE FLAGS)" "UPDATE" (slot-value folder 'exists)) (let (messages) (process-response folder :on-uid (lambda (message) (push message messages) (funcall callback message))) (setf (slot-value folder 'messages) messages))) (t (slot-value folder 'messages))))) (defun append-message (sink-folder message-string) (let ((message-size (length message-string))) (send-command sink-folder "~A APPEND ~A () {~D}" "APPEND" (mailbox sink-folder) message-size) (process-response sink-folder :on-continuation (lambda (type arguments) (declare (ignore type arguments)) (write-sequence message-string (connection sink-folder)) (write-char #\return (connection sink-folder)) (write-char #\linefeed (connection sink-folder)) (force-output (connection sink-folder)))))) (defmethod fetch-message ((folder imap-folder) uid) (send-command folder "~A uid fetch ~A (UID BODY[])" "MESSAGE" uid) (let (result) (process-response folder :on-body (lambda (body) (setf result body))) result)) (defmethod fetch-message-body ((folder imap-folder) uid) (send-command folder "~A uid fetch ~A (UID BODY[TEXT])" "BODY" uid) (let (result) (process-response folder :on-body (lambda (body) (setf result body))) result)) (defmethod fetch-message-header ((folder imap-folder) uid) (send-command folder "~A uid fetch ~A (UID BODY[HEADER])" "HEADER" uid #\return #\linefeed) (let (result) (process-response folder :on-header (lambda (header) (setf result header))) result)) (defmethod fetch-all-message-headers ((folder imap-folder)) (send-command folder "~A fetch 1:* (UID BODY[HEADER])" "HEADER" #\return #\linefeed) (process-response folder :on-header (lambda (header) (declare (ignore header))))) (defmethod fetch-message-bodystructure ((folder imap-folder) uid) (send-command folder "~A uid fetch ~A (UID BODYSTRUCTURE)" "BODYSTRUCTURE" uid) (let (result) (process-response folder :on-bodystructure (lambda (b) (setf result b))) result)) (defun canonicalize-bodystructure (bodystructure) (labels ((keyword (string) (typecase string (symbol string) (string (intern (string-upcase string) #.(find-package :keyword))))) (canonicalize-parameters (params) (loop for (name value) on params by #'cddr nconc (list (keyword name) value))) (canonicalize-simple-part (bs) `(,(keyword (first bs)) ,(keyword (second bs)) ,(canonicalize-parameters (third bs)) nil nil ,(keyword (sixth bs)) ,(seventh bs) ,(eighth bs) nil nil nil)) (canonicalize-multipart (bs) (loop for tail on bs while (consp (first tail)) collect (canonicalize-bodystructure (first tail)) into parts finally (return `(,@parts ,(keyword (first tail)) ,(canonicalize-parameters (second tail)) nil nil))))) (etypecase (car bodystructure) (cons (canonicalize-multipart bodystructure)) (string (canonicalize-simple-part bodystructure)) (symbol (canonicalize-simple-part bodystructure))))) (defmethod mel.mime::compute-bodystructure-using-folder ((folder imap-folder) (message mel.mime::bodystructure-mixin)) (let ((bodystructure (fetch-message-bodystructure folder (uid message)))) (canonicalize-bodystructure bodystructure))) (defmethod search-mailbox ((folder imap-folder) query) (send-command folder "~A uid search ~A" "t01" query) (let (messages) (labels ((return-messages (list) (setf messages (mapcar (lambda (uid) (find-message folder uid)) list)))) (process-response folder :on-list #'return-messages) messages))) (defmethod mark-deleted ((folder imap-folder) uid) (send-command folder "~A uid store ~A +flags (\\Deleted)" "t01" uid) (process-response folder)) ;;;;;;;;;;;;;;;;;;;;; ;; Folder Protocol ;; ;;;;;;;;;;;;;;;;;;;;; (defmethod close-folder ((folder imap-folder)) (unless (eq (state folder) :disconnected) (ignore-errors (close-mailbox folder)) (setf (connection folder) nil (state folder) :disconnected) (clrhash (uid-table folder)) (clrhash (size-table folder)) (setf (slot-value folder 'messages) nil (slot-value folder 'exists) 0 (slot-value folder 'recent) 0) )) (defmethod open-message-input-stream-using-folder ((folder imap-folder) message start) (let ((stream (make-sequence-input-stream (fetch-message folder (uid message))))) (file-position stream (+ (file-position stream) start)) stream)) (defmethod message-body-stream-using-folder ((folder imap-folder) message) (make-sequence-input-stream (fetch-message-body folder (uid message)))) (defmethod message-header-stream-using-folder ((folder imap-folder) message) (let ((stream (make-sequence-input-stream (fetch-message-header folder (uid message))))) stream)) ;;; Folder Protocol Support (defmethod copy-message-using-folders :around ((message message) (message-folder imap-folder) (sink-folder imap-folder)) "Copy a message between two imap folders. We can optimize this case if the folders are on the same server." (if (and (equal (host message-folder) (host sink-folder)) (equal (username message-folder) (username sink-folder)) (equal (password message-folder) (password sink-folder)) (equal (imap-port message-folder) (imap-port sink-folder))) (progn (send-command message-folder "~A uid copy ~A ~A" "UID" (uid message) (mailbox sink-folder)) (process-response message-folder :on-uid (lambda (m) m))) ;; if we're not using the same server, play it safe (call-next-method))) (defmethod map-messages (fn (folder imap-folder)) (update-mailbox folder fn)) (defmethod message-size-using-folder ((folder imap-folder) (message message)) "A message's size is cached in the folder object. If there is a cache fault a FETCH for the RFC822.SIZE of the message is sent. Doing this for many messages at once may be slow because of the roundtrip delay. I deliberately left out RFC822.SIZE from the message-list FETCH (see UPDATE-MAILBOX) because it slowed it down to much." (multiple-value-bind (size existsp) (gethash (uid message) (size-table folder)) (if existsp size (let ((seq (sequence-number message))) (unless seq (error "No sequence number for message ~A (UID: ~A)" message (uid message))) (send-command folder "~A fetch ~A:~A (UID RFC822.SIZE)" "SIZE" seq seq) (process-response folder :on-size (lambda (m) m)) (gethash (uid message) (size-table folder)))))) (defmethod copy-folder ((source-folder imap-folder) (sink-folder folder)) "Overload for more efficient message transfer. Up to now messages are always fetched completely as a string buffer. This may lead to large memory consumption for big mails (And to problems with Lispsystems which have relatively small array-dimension-limits" (dolist (message (messages source-folder)) (with-open-stream (sink (open-message-storing-stream sink-folder message)) (let ((buffer (fetch-message source-folder (uid message)))) (write-sequence buffer sink))))) (defmethod copy-folder ((source-folder folder) (sink-folder imap-folder)) (cerror "Cancel copying of folder ~A to the imap folder ~A" "imap folders are not yet supported as message sinks" source-folder sink-folder)) (defmethod delete-message-using-folder ((folder imap-folder) message) (mark-deleted folder (uid message)) (expunge-mailbox folder)) (defmethod count-messages ((folder imap-folder)) "Count messages by sending an EXAMINE command. EXAMINE triggers an EXISTS response which contains the number of available messages in the imap folder." (noop folder) (slot-value folder 'exists)) (defmethod short-name ((folder imap-folder)) (format nil "imap://~A@~A" (username folder) (host folder))) #+nil (defmethod find-message ((folder imap-folder) uid) "Return cached message or create and cache a new one." (or (gethash uid (uid-table folder)) (setf (gethash uid (uid-table folder)) (call-next-method)))) (defun collect-ranges (predicate folder &key (key #'identity)) "A utility function that loops over all messages from the lowest sequence id to the highest. For each coherent subsequence of messages for which the predicate is true a pair containing the start and end position is collected." (with-slots (seq-table) folder (let ((start 1) (count (length seq-table)) ranges) (loop while (and start (< start count)) do (setf start (position-if predicate seq-table :key key :start start)) (unless start (return-from collect-ranges ranges)) (let ((end (position-if-not predicate seq-table :key key :start start))) (if end (push (cons start (1- end)) ranges) (push (cons start "*") ranges)) (setf start (if end (1+ end))))) ranges))) (defmethod ensure-all-headers ((folder imap-folder) &key hook) "Read all yet unread headers. First we construct a list of sequence id range pairs for those messages that do not have any cached header-fields yet. After that we send a FETCH command for each range in that list." (let ((ranges (collect-ranges #'null folder :key #'mel.mime:header-fields))) (loop for (start . end) in ranges do (send-command folder "~A fetch ~a:~a (BODY[HEADER])" "HEADER" start end #\return #\linefeed) (process-response folder :on-header (lambda (header) (funcall hook header)))))) #+nil (defmethod flagp-using-folder ((folder imap-folder) message (flag (eql :recent))) (multiple-value-bind (cell existsp) (gethash (uid message) (uid-cache folder)) (unless existsp (error "Message does not exist in uid cache")) (ecase (car cell) (:new t) (:cur nil)))) (defmethod mark-message-using-folder ((folder imap-folder) message (flag (eql :recent))) (declare (ignore message)) (cerror "Continue without setting the RECENT flag" "It is not possible to modify the RECENT flag manually")) (defmethod unmark-message-using-folder ((folder imap-folder) message (flag (eql :recent))) (declare (ignore message)) #+nil (cerror "Continue without unsetting the RECENT flag" "It is not possible to modify the RECENT flag manually")) ;; Sender Protocol (defclass imap-message-storing-stream (encapsulating-output-stream) ((message :accessor message :initarg :message) (folder :accessor stream-folder :initarg :folder))) (defmethod close ((stream imap-message-storing-stream) &key abort) (let ((message (get-output-stream-string (encapsulated-output-stream stream)))) (format t "Close message storing stream~%") (format t "Storing message of size ~D~%" (length message)) (force-output t) (unless abort (append-message (stream-folder stream) message)))) (defmethod open-message-storing-stream ((folder imap-folder) message) (format t "Open message storing stream~%") (force-output t) (let ((stream (make-instance 'imap-message-storing-stream :output-stream (make-string-output-stream) :message message :folder folder))) stream))
[ { "context": "(cl:in-package \"https://github.com/g000001/srfi-25#internals\")\n\n(def-suite* srfi-25)\n\n;;; ar", "end": 42, "score": 0.9934242963790894, "start": 35, "tag": "USERNAME", "value": "g000001" }, { "context": "s\")\n\n(def-suite* srfi-25)\n\n;;; array test\n;;; 2001 Jussi Piitulainen\n\n(define-function past\n (let ((stones '()))\n ", "end": 127, "score": 0.9998571872711182, "start": 110, "tag": "NAME", "value": "Jussi Piitulainen" } ]
test.lisp
g000001/srfi-25
0
(cl:in-package "https://github.com/g000001/srfi-25#internals") (def-suite* srfi-25) ;;; array test ;;; 2001 Jussi Piitulainen (define-function past (let ((stones '())) (lambda stone (if (null? stone) (reverse stones) (set! stones (cons (apply (lambda (stone) stone) stone) stones)))))) (define-function (tail n) (if (< n (length (past))) (list-tail (past) (- (length (past)) n)) (past))) (test |Simple tests| (is-true (and (shape) (shape -1 -1) (shape -1 0) (shape -1 1) (shape 1 2 3 4 5 6 7 8 1 2 3 4 5 6 7 8 1 2 3 4 5 6 7 8) )) (past "shape") (is-true (and (make-array (shape)) (make-array (shape) *) (make-array (shape -1 -1)) (make-array (shape -1 -1) *) (make-array (shape -1 1)) (make-array (shape 1 2 3 4 5 6 7 8 1 2 3 4 5 6 7 8 1 2 3 4) *) )) (past "make-array") (is-true (and (array (shape) *) (array (shape -1 -1)) (array (shape -1 1) * *) (array (shape 1 2 3 4 5 6 7 8 1 2 3 4 5 6 7 8) *) )) (past "array") (is-true (and (= (array-rank (shape)) 2) (= (array-rank (shape -1 -1)) 2) (= (array-rank (shape -1 1)) 2) (= (array-rank (shape 1 2 3 4 5 6 7 8)) 2) )) (past "array-rank of shape") (is-true (and (= (array-rank (make-array (shape))) 0) (= (array-rank (make-array (shape -1 -1))) 1) (= (array-rank (make-array (shape -1 1))) 1) (= (array-rank (make-array (shape 1 2 3 4 5 6 7 8))) 4) )) (past "array-rank of make-array") (is-true (and (= (array-rank (array (shape) *)) 0) (= (array-rank (array (shape -1 -1))) 1) (= (array-rank (array (shape -1 1) * *)) 1) (= (array-rank (array (shape 1 2 3 4 5 6 7 8) *)) 4) )) (past "array-rank of array") (is-true (and (= (array-start (shape -1 -1) 0) 0) (= (array-start (shape -1 -1) 1) 0) (= (array-start (shape -1 1) 0) 0) (= (array-start (shape -1 1) 1) 0) (= (array-start (shape 1 2 3 4 5 6 7 8) 0) 0) (= (array-start (shape 1 2 3 4 5 6 7 8) 1) 0) )) (past "array-start of shape") (is-true (and (= (array-end (shape -1 -1) 0) 1) (= (array-end (shape -1 -1) 1) 2) (= (array-end (shape -1 1) 0) 1) (= (array-end (shape -1 1) 1) 2) (= (array-end (shape 1 2 3 4 5 6 7 8) 0) 4) (= (array-end (shape 1 2 3 4 5 6 7 8) 1) 2) )) (past "array-end of shape") (is-true (and (= (array-start (make-array (shape -1 -1)) 0) -1) (= (array-start (make-array (shape -1 1)) 0) -1) (= (array-start (make-array (shape 1 2 3 4 5 6 7 8)) 0) 1) (= (array-start (make-array (shape 1 2 3 4 5 6 7 8)) 1) 3) (= (array-start (make-array (shape 1 2 3 4 5 6 7 8)) 2) 5) (= (array-start (make-array (shape 1 2 3 4 5 6 7 8)) 3) 7) )) (past "array-start of make-array") (is-true (and (= (array-end (make-array (shape -1 -1)) 0) -1) (= (array-end (make-array (shape -1 1)) 0) 1) (= (array-end (make-array (shape 1 2 3 4 5 6 7 8)) 0) 2) (= (array-end (make-array (shape 1 2 3 4 5 6 7 8)) 1) 4) (= (array-end (make-array (shape 1 2 3 4 5 6 7 8)) 2) 6) (= (array-end (make-array (shape 1 2 3 4 5 6 7 8)) 3) 8) )) (past "array-end of make-array") (is-true (and (= (array-start (array (shape -1 -1)) 0) -1) (= (array-start (array (shape -1 1) * *) 0) -1) (= (array-start (array (shape 1 2 3 4 5 6 7 8) *) 0) 1) (= (array-start (array (shape 1 2 3 4 5 6 7 8) *) 1) 3) (= (array-start (array (shape 1 2 3 4 5 6 7 8) *) 2) 5) (= (array-start (array (shape 1 2 3 4 5 6 7 8) *) 3) 7) )) (past "array-start of array") (is-true (and (= (array-end (array (shape -1 -1)) 0) -1) (= (array-end (array (shape -1 1) * *) 0) 1) (= (array-end (array (shape 1 2 3 4 5 6 7 8) *) 0) 2) (= (array-end (array (shape 1 2 3 4 5 6 7 8) *) 1) 4) (= (array-end (array (shape 1 2 3 4 5 6 7 8) *) 2) 6) (= (array-end (array (shape 1 2 3 4 5 6 7 8) *) 3) 8) )) (past "array-end of array") (is-true (and (eq? (array-ref (make-array (shape) 'a)) 'a) (eq? (array-ref (make-array (shape -1 1) 'b) -1) 'b) (eq? (array-ref (make-array (shape -1 1) 'c) 0) 'c) (eq? (array-ref (make-array (shape 1 2 3 4 5 6 7 8) 'd) 1 3 5 7) 'd) )) (past "array-ref of make-array with arguments") (is-true (and (eq? (array-ref (make-array (shape) 'a) '#()) 'a) (eq? (array-ref (make-array (shape -1 1) 'b) '#(-1)) 'b) (eq? (array-ref (make-array (shape -1 1) 'c) '#(0)) 'c) (eq? (array-ref (make-array (shape 1 2 3 4 5 6 7 8) 'd) '#(1 3 5 7) ) 'd ))) (past "array-ref of make-array with vector") (is-true (and (eq? (array-ref (make-array (shape) 'a) (array (shape 0 0)) ) 'a ) (eq? (array-ref (make-array (shape -1 1) 'b) (array (shape 0 1) -1) ) 'b ) (eq? (array-ref (make-array (shape -1 1) 'c) (array (shape 0 1) 0) ) 'c ) (eq? (array-ref (make-array (shape 1 2 3 4 5 6 7 8) 'd) (array (shape 0 4) 1 3 5 7) ) 'd ))) (past "array-ref of make-array with array") (is-true (and (let ((arr (make-array (shape) 'o))) (array-set! arr 'a) (eq? (array-ref arr) 'a) ) (let ((arr (make-array (shape -1 1) 'o))) (array-set! arr -1 'b) (array-set! arr 0 'c) (and (eq? (array-ref arr -1) 'b) (eq? (array-ref arr 0) 'c) )) (let ((arr (make-array (shape 1 2 3 4 5 6 7 8) 'o))) (array-set! arr 1 3 5 7 'd) (eq? (array-ref arr 1 3 5 7) 'd) ))) (past "array-set! of make-array with arguments") (is-true (and (let ((arr (make-array (shape) 'o))) (array-set! arr '#() 'a) (eq? (array-ref arr) 'a) ) (let ((arr (make-array (shape -1 1) 'o))) (array-set! arr '#(-1) 'b) (array-set! arr '#(0) 'c) (and (eq? (array-ref arr -1) 'b) (eq? (array-ref arr 0) 'c) )) (let ((arr (make-array (shape 1 2 3 4 5 6 7 8) 'o))) (array-set! arr '#(1 3 5 7) 'd) (eq? (array-ref arr 1 3 5 7) 'd) ))) (past "array-set! of make-array with vector") (is-true (and (let ((arr (make-array (shape) 'o))) (array-set! arr 'a) (eq? (array-ref arr) 'a) ) (let ((arr (make-array (shape -1 1) 'o))) (array-set! arr (array (shape 0 1) -1) 'b) (array-set! arr (array (shape 0 1) 0) 'c) (and (eq? (array-ref arr -1) 'b) (eq? (array-ref arr 0) 'c) )) (let ((arr (make-array (shape 1 2 3 4 5 6 7 8) 'o))) (array-set! arr (array (shape 0 4) 1 3 5 7) 'd) (eq? (array-ref arr 1 3 5 7) 'd) ))) (past "array-set! of make-array with array") ) (test |Share and change:| ;; ;; ;; org brk swp box ;; ;; 0 1 1 2 5 6 ;; 6 a b 2 a b 3 d c 0 2 4 6 8: e ;; 7 c d 3 e f 4 f e ;; 8 e f (is-true (let* ((org (array (shape 6 9 0 2) 'a 'b 'c 'd 'e 'f)) (brk (share-array org (shape 2 4 1 3) (lambda (r k) (values (+ 6 (* 2 (- r 2))) (- k 1) )))) (swp (share-array org (shape 3 5 5 7) (lambda (r k) (values (+ 7 (- r 3)) (- 1 (- k 5)) )))) (box (share-array swp (shape 0 1 2 3 4 5 6 7 8 9) (lambda _ (declare (ignore _)) (values 4 6)) )) (org-contents (lambda () (list (array-ref org 6 0) (array-ref org 6 1) (array-ref org 7 0) (array-ref org 7 1) (array-ref org 8 0) (array-ref org 8 1)))) (brk-contents (lambda () (list (array-ref brk 2 1) (array-ref brk 2 2) (array-ref brk 3 1) (array-ref brk 3 2)))) (swp-contents (lambda () (list (array-ref swp 3 5) (array-ref swp 3 6) (array-ref swp 4 5) (array-ref swp 4 6)))) (box-contents (lambda () (list (array-ref box 0 2 4 6 8)) ))) (and (equal? (funcall org-contents) '(a b c d e f)) (equal? (funcall brk-contents) '(a b e f)) (equal? (funcall swp-contents) '(d c f e)) (equal? (funcall box-contents) '(e)) (begin (array-set! org 6 0 'x) t) (equal? (funcall org-contents) '(x b c d e f)) (equal? (funcall brk-contents) '(x b e f)) (equal? (funcall swp-contents) '(d c f e)) (equal? (funcall box-contents) '(e)) (begin (array-set! brk 3 1 'y) t) (equal? (funcall org-contents) '(x b c d y f)) (equal? (funcall brk-contents) '(x b y f)) (equal? (funcall swp-contents) '(d c f y)) (equal? (funcall box-contents) '(y)) (begin (array-set! swp 4 5 'z) t) (equal? (funcall org-contents) '(x b c d y z)) (equal? (funcall brk-contents) '(x b y z)) (equal? (funcall swp-contents) '(d c z y)) (equal? (funcall box-contents) '(y)) (begin (array-set! box 0 2 4 6 8 'e) t) (equal? (funcall org-contents) '(x b c d e z)) (equal? (funcall brk-contents) '(x b e z)) (equal? (funcall swp-contents) '(d c z e)) (equal? (funcall box-contents) '(e))))) (past "shared change")) ;;; (test |Check that arrays copy the shape specification| (is-true (let ((shp (shape 10 12))) (let ((arr (make-array shp)) (ars (array shp * *)) (art (share-array (make-array shp) shp (lambda (k) k))) ) (array-set! shp 0 0 '?) (array-set! shp 0 1 '!) (and (= (array-rank shp) 2) (= (array-start shp 0) 0) (= (array-end shp 0) 1) (= (array-start shp 1) 0) (= (array-end shp 1) 2) (eq? (array-ref shp 0 0) '?) (eq? (array-ref shp 0 1) '!) (= (array-rank arr) 1) (= (array-start arr 0) 10) (= (array-end arr 0) 12) (= (array-rank ars) 1) (= (array-start ars 0) 10) (= (array-end ars 0) 12) (= (array-rank art) 1) (= (array-start art 0) 10) (= (array-end art 0) 12) )))) (past "array-set! of shape") ) (test |Check that index arrays work even when they share| ;; arr ixn ;; 5 6 0 1 ;; 4 nw ne 0 4 6 ;; 5 sw se 1 5 4 (let ((arr (array (shape 4 6 5 7) 'nw 'ne 'sw 'se)) (ixn (array (shape 0 2 0 2) 4 6 5 4)) ) (let ((col0 (share-array ixn (shape 0 2) (lambda (k) (values k 0) ))) (row0 (share-array ixn (shape 0 2) (lambda (k) (values 0 k) ))) (wor1 (share-array ixn (shape 0 2) (lambda (k) (values 1 (- 1 k)) ))) (cod (share-array ixn (shape 0 2) (lambda (k) (case k ((0) (values 1 0)) ((1) (values 0 1)) )))) (box (share-array ixn (shape 0 2) (lambda (k) (declare (ignore k)) (values 1 0) )))) (and (eq? (array-ref arr col0) 'nw) (eq? (array-ref arr row0) 'ne) (eq? (array-ref arr wor1) 'nw) (eq? (array-ref arr cod) 'se) (eq? (array-ref arr box) 'sw) (begin (array-set! arr col0 'ul) (array-set! arr row0 'ur) (array-set! arr cod 'lr) (array-set! arr box 'll) t ) (eq? (array-ref arr 4 5) 'ul) (eq? (array-ref arr 4 6) 'ur) (eq? (array-ref arr 5 5) 'll) (eq? (array-ref arr 5 6) 'lr) (begin (array-set! arr wor1 'xx) (eq? (array-ref arr 4 5) 'xx) )))) (past "array access with sharing index array") ) ;; ;; ;; arr shp shq shr shs ;; 1 2 3 4 0 1 0 1 0 1 0 1 ;; 1 10 12 16 20 0 10 12 0 12 20 0 10 10 0 12 12 ;; 2 10 11 12 13 1 10 11 1 11 13 1 11 12 1 12 12 ;; 2 12 16 ;; 3 13 20 (test |Check that shape arrays work even when they share| (is-true (let ((arr (array (shape 1 3 1 5) 10 12 16 20 10 11 12 13))) (let ((shp (share-array arr (shape 0 2 0 2) (lambda (r k) (values (+ r 1) (+ k 1))))) (shq (share-array arr (shape 0 2 0 2) (lambda (r k) (values (+ r 1) (* 2 (+ 1 k)))))) (shr (share-array arr (shape 0 4 0 2) (lambda (r k) (values (- 2 k) (+ r 1))))) (shs (share-array arr (shape 0 2 0 2) (lambda (r k) (declare (ignore r k)) (values 2 3))))) (and (let ((arr-p (make-array shp))) (and (= (array-rank arr-p) 2) (= (array-start arr-p 0) 10) (= (array-end arr-p 0) 12) (= (array-start arr-p 1) 10) (= (array-end arr-p 1) 11))) (let ((arr-q (array shq * * * * * * * * * * * * * * * *))) (and (= (array-rank arr-q) 2) (= (array-start arr-q 0) 12) (= (array-end arr-q 0) 20) (= (array-start arr-q 1) 11) (= (array-end arr-q 1) 13))) (let ((arr-r (share-array (array (shape) *) shr (lambda _ (declare (ignore _)) (values))))) (and (= (array-rank arr-r) 4) (= (array-start arr-r 0) 10) (= (array-end arr-r 0) 10) (= (array-start arr-r 1) 11) (= (array-end arr-r 1) 12) (= (array-start arr-r 2) 12) (= (array-end arr-r 2) 16) (= (array-start arr-r 3) 13) (= (array-end arr-r 3) 20))) (let ((arr-s (make-array shs))) (and (= (array-rank arr-s) 2) (= (array-start arr-s 0) 12) (= (array-end arr-s 0) 12) (= (array-start arr-s 1) 12) (= (array-end arr-s 1) 12))))))) (past "sharing shape array")) (test |Sharing with sharing subshape| (let ((super (array (shape 4 7 4 7) 1 * * * 2 * * * 3)) (subshape (share-array (array (shape 0 2 0 3) * 4 * * 7 *) (shape 0 1 0 2) (lambda (r k) (declare (ignore r)) (values k 1))))) (let ((sub (share-array super subshape (lambda (k) (values k k))))) ;(array-equal? subshape (shape 4 7)) (is-true (and (= (array-rank subshape) 2) (= (array-start subshape 0) 0) (= (array-end subshape 0) 1) (= (array-start subshape 1) 0) (= (array-end subshape 1) 2) (= (array-ref subshape 0 0) 4) (= (array-ref subshape 0 1) 7))) ;(array-equal? sub (array (shape 4 7) 1 2 3)) (is-true (and (= (array-rank sub) 1) (= (array-start sub 0) 4) (= (array-end sub 0) 7) (= (array-ref sub 4) 1) (= (array-ref sub 5) 2) (= (array-ref sub 6) 3))))) (past "sharing with sharing subshape")) ;;; eof
84402
(cl:in-package "https://github.com/g000001/srfi-25#internals") (def-suite* srfi-25) ;;; array test ;;; 2001 <NAME> (define-function past (let ((stones '())) (lambda stone (if (null? stone) (reverse stones) (set! stones (cons (apply (lambda (stone) stone) stone) stones)))))) (define-function (tail n) (if (< n (length (past))) (list-tail (past) (- (length (past)) n)) (past))) (test |Simple tests| (is-true (and (shape) (shape -1 -1) (shape -1 0) (shape -1 1) (shape 1 2 3 4 5 6 7 8 1 2 3 4 5 6 7 8 1 2 3 4 5 6 7 8) )) (past "shape") (is-true (and (make-array (shape)) (make-array (shape) *) (make-array (shape -1 -1)) (make-array (shape -1 -1) *) (make-array (shape -1 1)) (make-array (shape 1 2 3 4 5 6 7 8 1 2 3 4 5 6 7 8 1 2 3 4) *) )) (past "make-array") (is-true (and (array (shape) *) (array (shape -1 -1)) (array (shape -1 1) * *) (array (shape 1 2 3 4 5 6 7 8 1 2 3 4 5 6 7 8) *) )) (past "array") (is-true (and (= (array-rank (shape)) 2) (= (array-rank (shape -1 -1)) 2) (= (array-rank (shape -1 1)) 2) (= (array-rank (shape 1 2 3 4 5 6 7 8)) 2) )) (past "array-rank of shape") (is-true (and (= (array-rank (make-array (shape))) 0) (= (array-rank (make-array (shape -1 -1))) 1) (= (array-rank (make-array (shape -1 1))) 1) (= (array-rank (make-array (shape 1 2 3 4 5 6 7 8))) 4) )) (past "array-rank of make-array") (is-true (and (= (array-rank (array (shape) *)) 0) (= (array-rank (array (shape -1 -1))) 1) (= (array-rank (array (shape -1 1) * *)) 1) (= (array-rank (array (shape 1 2 3 4 5 6 7 8) *)) 4) )) (past "array-rank of array") (is-true (and (= (array-start (shape -1 -1) 0) 0) (= (array-start (shape -1 -1) 1) 0) (= (array-start (shape -1 1) 0) 0) (= (array-start (shape -1 1) 1) 0) (= (array-start (shape 1 2 3 4 5 6 7 8) 0) 0) (= (array-start (shape 1 2 3 4 5 6 7 8) 1) 0) )) (past "array-start of shape") (is-true (and (= (array-end (shape -1 -1) 0) 1) (= (array-end (shape -1 -1) 1) 2) (= (array-end (shape -1 1) 0) 1) (= (array-end (shape -1 1) 1) 2) (= (array-end (shape 1 2 3 4 5 6 7 8) 0) 4) (= (array-end (shape 1 2 3 4 5 6 7 8) 1) 2) )) (past "array-end of shape") (is-true (and (= (array-start (make-array (shape -1 -1)) 0) -1) (= (array-start (make-array (shape -1 1)) 0) -1) (= (array-start (make-array (shape 1 2 3 4 5 6 7 8)) 0) 1) (= (array-start (make-array (shape 1 2 3 4 5 6 7 8)) 1) 3) (= (array-start (make-array (shape 1 2 3 4 5 6 7 8)) 2) 5) (= (array-start (make-array (shape 1 2 3 4 5 6 7 8)) 3) 7) )) (past "array-start of make-array") (is-true (and (= (array-end (make-array (shape -1 -1)) 0) -1) (= (array-end (make-array (shape -1 1)) 0) 1) (= (array-end (make-array (shape 1 2 3 4 5 6 7 8)) 0) 2) (= (array-end (make-array (shape 1 2 3 4 5 6 7 8)) 1) 4) (= (array-end (make-array (shape 1 2 3 4 5 6 7 8)) 2) 6) (= (array-end (make-array (shape 1 2 3 4 5 6 7 8)) 3) 8) )) (past "array-end of make-array") (is-true (and (= (array-start (array (shape -1 -1)) 0) -1) (= (array-start (array (shape -1 1) * *) 0) -1) (= (array-start (array (shape 1 2 3 4 5 6 7 8) *) 0) 1) (= (array-start (array (shape 1 2 3 4 5 6 7 8) *) 1) 3) (= (array-start (array (shape 1 2 3 4 5 6 7 8) *) 2) 5) (= (array-start (array (shape 1 2 3 4 5 6 7 8) *) 3) 7) )) (past "array-start of array") (is-true (and (= (array-end (array (shape -1 -1)) 0) -1) (= (array-end (array (shape -1 1) * *) 0) 1) (= (array-end (array (shape 1 2 3 4 5 6 7 8) *) 0) 2) (= (array-end (array (shape 1 2 3 4 5 6 7 8) *) 1) 4) (= (array-end (array (shape 1 2 3 4 5 6 7 8) *) 2) 6) (= (array-end (array (shape 1 2 3 4 5 6 7 8) *) 3) 8) )) (past "array-end of array") (is-true (and (eq? (array-ref (make-array (shape) 'a)) 'a) (eq? (array-ref (make-array (shape -1 1) 'b) -1) 'b) (eq? (array-ref (make-array (shape -1 1) 'c) 0) 'c) (eq? (array-ref (make-array (shape 1 2 3 4 5 6 7 8) 'd) 1 3 5 7) 'd) )) (past "array-ref of make-array with arguments") (is-true (and (eq? (array-ref (make-array (shape) 'a) '#()) 'a) (eq? (array-ref (make-array (shape -1 1) 'b) '#(-1)) 'b) (eq? (array-ref (make-array (shape -1 1) 'c) '#(0)) 'c) (eq? (array-ref (make-array (shape 1 2 3 4 5 6 7 8) 'd) '#(1 3 5 7) ) 'd ))) (past "array-ref of make-array with vector") (is-true (and (eq? (array-ref (make-array (shape) 'a) (array (shape 0 0)) ) 'a ) (eq? (array-ref (make-array (shape -1 1) 'b) (array (shape 0 1) -1) ) 'b ) (eq? (array-ref (make-array (shape -1 1) 'c) (array (shape 0 1) 0) ) 'c ) (eq? (array-ref (make-array (shape 1 2 3 4 5 6 7 8) 'd) (array (shape 0 4) 1 3 5 7) ) 'd ))) (past "array-ref of make-array with array") (is-true (and (let ((arr (make-array (shape) 'o))) (array-set! arr 'a) (eq? (array-ref arr) 'a) ) (let ((arr (make-array (shape -1 1) 'o))) (array-set! arr -1 'b) (array-set! arr 0 'c) (and (eq? (array-ref arr -1) 'b) (eq? (array-ref arr 0) 'c) )) (let ((arr (make-array (shape 1 2 3 4 5 6 7 8) 'o))) (array-set! arr 1 3 5 7 'd) (eq? (array-ref arr 1 3 5 7) 'd) ))) (past "array-set! of make-array with arguments") (is-true (and (let ((arr (make-array (shape) 'o))) (array-set! arr '#() 'a) (eq? (array-ref arr) 'a) ) (let ((arr (make-array (shape -1 1) 'o))) (array-set! arr '#(-1) 'b) (array-set! arr '#(0) 'c) (and (eq? (array-ref arr -1) 'b) (eq? (array-ref arr 0) 'c) )) (let ((arr (make-array (shape 1 2 3 4 5 6 7 8) 'o))) (array-set! arr '#(1 3 5 7) 'd) (eq? (array-ref arr 1 3 5 7) 'd) ))) (past "array-set! of make-array with vector") (is-true (and (let ((arr (make-array (shape) 'o))) (array-set! arr 'a) (eq? (array-ref arr) 'a) ) (let ((arr (make-array (shape -1 1) 'o))) (array-set! arr (array (shape 0 1) -1) 'b) (array-set! arr (array (shape 0 1) 0) 'c) (and (eq? (array-ref arr -1) 'b) (eq? (array-ref arr 0) 'c) )) (let ((arr (make-array (shape 1 2 3 4 5 6 7 8) 'o))) (array-set! arr (array (shape 0 4) 1 3 5 7) 'd) (eq? (array-ref arr 1 3 5 7) 'd) ))) (past "array-set! of make-array with array") ) (test |Share and change:| ;; ;; ;; org brk swp box ;; ;; 0 1 1 2 5 6 ;; 6 a b 2 a b 3 d c 0 2 4 6 8: e ;; 7 c d 3 e f 4 f e ;; 8 e f (is-true (let* ((org (array (shape 6 9 0 2) 'a 'b 'c 'd 'e 'f)) (brk (share-array org (shape 2 4 1 3) (lambda (r k) (values (+ 6 (* 2 (- r 2))) (- k 1) )))) (swp (share-array org (shape 3 5 5 7) (lambda (r k) (values (+ 7 (- r 3)) (- 1 (- k 5)) )))) (box (share-array swp (shape 0 1 2 3 4 5 6 7 8 9) (lambda _ (declare (ignore _)) (values 4 6)) )) (org-contents (lambda () (list (array-ref org 6 0) (array-ref org 6 1) (array-ref org 7 0) (array-ref org 7 1) (array-ref org 8 0) (array-ref org 8 1)))) (brk-contents (lambda () (list (array-ref brk 2 1) (array-ref brk 2 2) (array-ref brk 3 1) (array-ref brk 3 2)))) (swp-contents (lambda () (list (array-ref swp 3 5) (array-ref swp 3 6) (array-ref swp 4 5) (array-ref swp 4 6)))) (box-contents (lambda () (list (array-ref box 0 2 4 6 8)) ))) (and (equal? (funcall org-contents) '(a b c d e f)) (equal? (funcall brk-contents) '(a b e f)) (equal? (funcall swp-contents) '(d c f e)) (equal? (funcall box-contents) '(e)) (begin (array-set! org 6 0 'x) t) (equal? (funcall org-contents) '(x b c d e f)) (equal? (funcall brk-contents) '(x b e f)) (equal? (funcall swp-contents) '(d c f e)) (equal? (funcall box-contents) '(e)) (begin (array-set! brk 3 1 'y) t) (equal? (funcall org-contents) '(x b c d y f)) (equal? (funcall brk-contents) '(x b y f)) (equal? (funcall swp-contents) '(d c f y)) (equal? (funcall box-contents) '(y)) (begin (array-set! swp 4 5 'z) t) (equal? (funcall org-contents) '(x b c d y z)) (equal? (funcall brk-contents) '(x b y z)) (equal? (funcall swp-contents) '(d c z y)) (equal? (funcall box-contents) '(y)) (begin (array-set! box 0 2 4 6 8 'e) t) (equal? (funcall org-contents) '(x b c d e z)) (equal? (funcall brk-contents) '(x b e z)) (equal? (funcall swp-contents) '(d c z e)) (equal? (funcall box-contents) '(e))))) (past "shared change")) ;;; (test |Check that arrays copy the shape specification| (is-true (let ((shp (shape 10 12))) (let ((arr (make-array shp)) (ars (array shp * *)) (art (share-array (make-array shp) shp (lambda (k) k))) ) (array-set! shp 0 0 '?) (array-set! shp 0 1 '!) (and (= (array-rank shp) 2) (= (array-start shp 0) 0) (= (array-end shp 0) 1) (= (array-start shp 1) 0) (= (array-end shp 1) 2) (eq? (array-ref shp 0 0) '?) (eq? (array-ref shp 0 1) '!) (= (array-rank arr) 1) (= (array-start arr 0) 10) (= (array-end arr 0) 12) (= (array-rank ars) 1) (= (array-start ars 0) 10) (= (array-end ars 0) 12) (= (array-rank art) 1) (= (array-start art 0) 10) (= (array-end art 0) 12) )))) (past "array-set! of shape") ) (test |Check that index arrays work even when they share| ;; arr ixn ;; 5 6 0 1 ;; 4 nw ne 0 4 6 ;; 5 sw se 1 5 4 (let ((arr (array (shape 4 6 5 7) 'nw 'ne 'sw 'se)) (ixn (array (shape 0 2 0 2) 4 6 5 4)) ) (let ((col0 (share-array ixn (shape 0 2) (lambda (k) (values k 0) ))) (row0 (share-array ixn (shape 0 2) (lambda (k) (values 0 k) ))) (wor1 (share-array ixn (shape 0 2) (lambda (k) (values 1 (- 1 k)) ))) (cod (share-array ixn (shape 0 2) (lambda (k) (case k ((0) (values 1 0)) ((1) (values 0 1)) )))) (box (share-array ixn (shape 0 2) (lambda (k) (declare (ignore k)) (values 1 0) )))) (and (eq? (array-ref arr col0) 'nw) (eq? (array-ref arr row0) 'ne) (eq? (array-ref arr wor1) 'nw) (eq? (array-ref arr cod) 'se) (eq? (array-ref arr box) 'sw) (begin (array-set! arr col0 'ul) (array-set! arr row0 'ur) (array-set! arr cod 'lr) (array-set! arr box 'll) t ) (eq? (array-ref arr 4 5) 'ul) (eq? (array-ref arr 4 6) 'ur) (eq? (array-ref arr 5 5) 'll) (eq? (array-ref arr 5 6) 'lr) (begin (array-set! arr wor1 'xx) (eq? (array-ref arr 4 5) 'xx) )))) (past "array access with sharing index array") ) ;; ;; ;; arr shp shq shr shs ;; 1 2 3 4 0 1 0 1 0 1 0 1 ;; 1 10 12 16 20 0 10 12 0 12 20 0 10 10 0 12 12 ;; 2 10 11 12 13 1 10 11 1 11 13 1 11 12 1 12 12 ;; 2 12 16 ;; 3 13 20 (test |Check that shape arrays work even when they share| (is-true (let ((arr (array (shape 1 3 1 5) 10 12 16 20 10 11 12 13))) (let ((shp (share-array arr (shape 0 2 0 2) (lambda (r k) (values (+ r 1) (+ k 1))))) (shq (share-array arr (shape 0 2 0 2) (lambda (r k) (values (+ r 1) (* 2 (+ 1 k)))))) (shr (share-array arr (shape 0 4 0 2) (lambda (r k) (values (- 2 k) (+ r 1))))) (shs (share-array arr (shape 0 2 0 2) (lambda (r k) (declare (ignore r k)) (values 2 3))))) (and (let ((arr-p (make-array shp))) (and (= (array-rank arr-p) 2) (= (array-start arr-p 0) 10) (= (array-end arr-p 0) 12) (= (array-start arr-p 1) 10) (= (array-end arr-p 1) 11))) (let ((arr-q (array shq * * * * * * * * * * * * * * * *))) (and (= (array-rank arr-q) 2) (= (array-start arr-q 0) 12) (= (array-end arr-q 0) 20) (= (array-start arr-q 1) 11) (= (array-end arr-q 1) 13))) (let ((arr-r (share-array (array (shape) *) shr (lambda _ (declare (ignore _)) (values))))) (and (= (array-rank arr-r) 4) (= (array-start arr-r 0) 10) (= (array-end arr-r 0) 10) (= (array-start arr-r 1) 11) (= (array-end arr-r 1) 12) (= (array-start arr-r 2) 12) (= (array-end arr-r 2) 16) (= (array-start arr-r 3) 13) (= (array-end arr-r 3) 20))) (let ((arr-s (make-array shs))) (and (= (array-rank arr-s) 2) (= (array-start arr-s 0) 12) (= (array-end arr-s 0) 12) (= (array-start arr-s 1) 12) (= (array-end arr-s 1) 12))))))) (past "sharing shape array")) (test |Sharing with sharing subshape| (let ((super (array (shape 4 7 4 7) 1 * * * 2 * * * 3)) (subshape (share-array (array (shape 0 2 0 3) * 4 * * 7 *) (shape 0 1 0 2) (lambda (r k) (declare (ignore r)) (values k 1))))) (let ((sub (share-array super subshape (lambda (k) (values k k))))) ;(array-equal? subshape (shape 4 7)) (is-true (and (= (array-rank subshape) 2) (= (array-start subshape 0) 0) (= (array-end subshape 0) 1) (= (array-start subshape 1) 0) (= (array-end subshape 1) 2) (= (array-ref subshape 0 0) 4) (= (array-ref subshape 0 1) 7))) ;(array-equal? sub (array (shape 4 7) 1 2 3)) (is-true (and (= (array-rank sub) 1) (= (array-start sub 0) 4) (= (array-end sub 0) 7) (= (array-ref sub 4) 1) (= (array-ref sub 5) 2) (= (array-ref sub 6) 3))))) (past "sharing with sharing subshape")) ;;; eof
true
(cl:in-package "https://github.com/g000001/srfi-25#internals") (def-suite* srfi-25) ;;; array test ;;; 2001 PI:NAME:<NAME>END_PI (define-function past (let ((stones '())) (lambda stone (if (null? stone) (reverse stones) (set! stones (cons (apply (lambda (stone) stone) stone) stones)))))) (define-function (tail n) (if (< n (length (past))) (list-tail (past) (- (length (past)) n)) (past))) (test |Simple tests| (is-true (and (shape) (shape -1 -1) (shape -1 0) (shape -1 1) (shape 1 2 3 4 5 6 7 8 1 2 3 4 5 6 7 8 1 2 3 4 5 6 7 8) )) (past "shape") (is-true (and (make-array (shape)) (make-array (shape) *) (make-array (shape -1 -1)) (make-array (shape -1 -1) *) (make-array (shape -1 1)) (make-array (shape 1 2 3 4 5 6 7 8 1 2 3 4 5 6 7 8 1 2 3 4) *) )) (past "make-array") (is-true (and (array (shape) *) (array (shape -1 -1)) (array (shape -1 1) * *) (array (shape 1 2 3 4 5 6 7 8 1 2 3 4 5 6 7 8) *) )) (past "array") (is-true (and (= (array-rank (shape)) 2) (= (array-rank (shape -1 -1)) 2) (= (array-rank (shape -1 1)) 2) (= (array-rank (shape 1 2 3 4 5 6 7 8)) 2) )) (past "array-rank of shape") (is-true (and (= (array-rank (make-array (shape))) 0) (= (array-rank (make-array (shape -1 -1))) 1) (= (array-rank (make-array (shape -1 1))) 1) (= (array-rank (make-array (shape 1 2 3 4 5 6 7 8))) 4) )) (past "array-rank of make-array") (is-true (and (= (array-rank (array (shape) *)) 0) (= (array-rank (array (shape -1 -1))) 1) (= (array-rank (array (shape -1 1) * *)) 1) (= (array-rank (array (shape 1 2 3 4 5 6 7 8) *)) 4) )) (past "array-rank of array") (is-true (and (= (array-start (shape -1 -1) 0) 0) (= (array-start (shape -1 -1) 1) 0) (= (array-start (shape -1 1) 0) 0) (= (array-start (shape -1 1) 1) 0) (= (array-start (shape 1 2 3 4 5 6 7 8) 0) 0) (= (array-start (shape 1 2 3 4 5 6 7 8) 1) 0) )) (past "array-start of shape") (is-true (and (= (array-end (shape -1 -1) 0) 1) (= (array-end (shape -1 -1) 1) 2) (= (array-end (shape -1 1) 0) 1) (= (array-end (shape -1 1) 1) 2) (= (array-end (shape 1 2 3 4 5 6 7 8) 0) 4) (= (array-end (shape 1 2 3 4 5 6 7 8) 1) 2) )) (past "array-end of shape") (is-true (and (= (array-start (make-array (shape -1 -1)) 0) -1) (= (array-start (make-array (shape -1 1)) 0) -1) (= (array-start (make-array (shape 1 2 3 4 5 6 7 8)) 0) 1) (= (array-start (make-array (shape 1 2 3 4 5 6 7 8)) 1) 3) (= (array-start (make-array (shape 1 2 3 4 5 6 7 8)) 2) 5) (= (array-start (make-array (shape 1 2 3 4 5 6 7 8)) 3) 7) )) (past "array-start of make-array") (is-true (and (= (array-end (make-array (shape -1 -1)) 0) -1) (= (array-end (make-array (shape -1 1)) 0) 1) (= (array-end (make-array (shape 1 2 3 4 5 6 7 8)) 0) 2) (= (array-end (make-array (shape 1 2 3 4 5 6 7 8)) 1) 4) (= (array-end (make-array (shape 1 2 3 4 5 6 7 8)) 2) 6) (= (array-end (make-array (shape 1 2 3 4 5 6 7 8)) 3) 8) )) (past "array-end of make-array") (is-true (and (= (array-start (array (shape -1 -1)) 0) -1) (= (array-start (array (shape -1 1) * *) 0) -1) (= (array-start (array (shape 1 2 3 4 5 6 7 8) *) 0) 1) (= (array-start (array (shape 1 2 3 4 5 6 7 8) *) 1) 3) (= (array-start (array (shape 1 2 3 4 5 6 7 8) *) 2) 5) (= (array-start (array (shape 1 2 3 4 5 6 7 8) *) 3) 7) )) (past "array-start of array") (is-true (and (= (array-end (array (shape -1 -1)) 0) -1) (= (array-end (array (shape -1 1) * *) 0) 1) (= (array-end (array (shape 1 2 3 4 5 6 7 8) *) 0) 2) (= (array-end (array (shape 1 2 3 4 5 6 7 8) *) 1) 4) (= (array-end (array (shape 1 2 3 4 5 6 7 8) *) 2) 6) (= (array-end (array (shape 1 2 3 4 5 6 7 8) *) 3) 8) )) (past "array-end of array") (is-true (and (eq? (array-ref (make-array (shape) 'a)) 'a) (eq? (array-ref (make-array (shape -1 1) 'b) -1) 'b) (eq? (array-ref (make-array (shape -1 1) 'c) 0) 'c) (eq? (array-ref (make-array (shape 1 2 3 4 5 6 7 8) 'd) 1 3 5 7) 'd) )) (past "array-ref of make-array with arguments") (is-true (and (eq? (array-ref (make-array (shape) 'a) '#()) 'a) (eq? (array-ref (make-array (shape -1 1) 'b) '#(-1)) 'b) (eq? (array-ref (make-array (shape -1 1) 'c) '#(0)) 'c) (eq? (array-ref (make-array (shape 1 2 3 4 5 6 7 8) 'd) '#(1 3 5 7) ) 'd ))) (past "array-ref of make-array with vector") (is-true (and (eq? (array-ref (make-array (shape) 'a) (array (shape 0 0)) ) 'a ) (eq? (array-ref (make-array (shape -1 1) 'b) (array (shape 0 1) -1) ) 'b ) (eq? (array-ref (make-array (shape -1 1) 'c) (array (shape 0 1) 0) ) 'c ) (eq? (array-ref (make-array (shape 1 2 3 4 5 6 7 8) 'd) (array (shape 0 4) 1 3 5 7) ) 'd ))) (past "array-ref of make-array with array") (is-true (and (let ((arr (make-array (shape) 'o))) (array-set! arr 'a) (eq? (array-ref arr) 'a) ) (let ((arr (make-array (shape -1 1) 'o))) (array-set! arr -1 'b) (array-set! arr 0 'c) (and (eq? (array-ref arr -1) 'b) (eq? (array-ref arr 0) 'c) )) (let ((arr (make-array (shape 1 2 3 4 5 6 7 8) 'o))) (array-set! arr 1 3 5 7 'd) (eq? (array-ref arr 1 3 5 7) 'd) ))) (past "array-set! of make-array with arguments") (is-true (and (let ((arr (make-array (shape) 'o))) (array-set! arr '#() 'a) (eq? (array-ref arr) 'a) ) (let ((arr (make-array (shape -1 1) 'o))) (array-set! arr '#(-1) 'b) (array-set! arr '#(0) 'c) (and (eq? (array-ref arr -1) 'b) (eq? (array-ref arr 0) 'c) )) (let ((arr (make-array (shape 1 2 3 4 5 6 7 8) 'o))) (array-set! arr '#(1 3 5 7) 'd) (eq? (array-ref arr 1 3 5 7) 'd) ))) (past "array-set! of make-array with vector") (is-true (and (let ((arr (make-array (shape) 'o))) (array-set! arr 'a) (eq? (array-ref arr) 'a) ) (let ((arr (make-array (shape -1 1) 'o))) (array-set! arr (array (shape 0 1) -1) 'b) (array-set! arr (array (shape 0 1) 0) 'c) (and (eq? (array-ref arr -1) 'b) (eq? (array-ref arr 0) 'c) )) (let ((arr (make-array (shape 1 2 3 4 5 6 7 8) 'o))) (array-set! arr (array (shape 0 4) 1 3 5 7) 'd) (eq? (array-ref arr 1 3 5 7) 'd) ))) (past "array-set! of make-array with array") ) (test |Share and change:| ;; ;; ;; org brk swp box ;; ;; 0 1 1 2 5 6 ;; 6 a b 2 a b 3 d c 0 2 4 6 8: e ;; 7 c d 3 e f 4 f e ;; 8 e f (is-true (let* ((org (array (shape 6 9 0 2) 'a 'b 'c 'd 'e 'f)) (brk (share-array org (shape 2 4 1 3) (lambda (r k) (values (+ 6 (* 2 (- r 2))) (- k 1) )))) (swp (share-array org (shape 3 5 5 7) (lambda (r k) (values (+ 7 (- r 3)) (- 1 (- k 5)) )))) (box (share-array swp (shape 0 1 2 3 4 5 6 7 8 9) (lambda _ (declare (ignore _)) (values 4 6)) )) (org-contents (lambda () (list (array-ref org 6 0) (array-ref org 6 1) (array-ref org 7 0) (array-ref org 7 1) (array-ref org 8 0) (array-ref org 8 1)))) (brk-contents (lambda () (list (array-ref brk 2 1) (array-ref brk 2 2) (array-ref brk 3 1) (array-ref brk 3 2)))) (swp-contents (lambda () (list (array-ref swp 3 5) (array-ref swp 3 6) (array-ref swp 4 5) (array-ref swp 4 6)))) (box-contents (lambda () (list (array-ref box 0 2 4 6 8)) ))) (and (equal? (funcall org-contents) '(a b c d e f)) (equal? (funcall brk-contents) '(a b e f)) (equal? (funcall swp-contents) '(d c f e)) (equal? (funcall box-contents) '(e)) (begin (array-set! org 6 0 'x) t) (equal? (funcall org-contents) '(x b c d e f)) (equal? (funcall brk-contents) '(x b e f)) (equal? (funcall swp-contents) '(d c f e)) (equal? (funcall box-contents) '(e)) (begin (array-set! brk 3 1 'y) t) (equal? (funcall org-contents) '(x b c d y f)) (equal? (funcall brk-contents) '(x b y f)) (equal? (funcall swp-contents) '(d c f y)) (equal? (funcall box-contents) '(y)) (begin (array-set! swp 4 5 'z) t) (equal? (funcall org-contents) '(x b c d y z)) (equal? (funcall brk-contents) '(x b y z)) (equal? (funcall swp-contents) '(d c z y)) (equal? (funcall box-contents) '(y)) (begin (array-set! box 0 2 4 6 8 'e) t) (equal? (funcall org-contents) '(x b c d e z)) (equal? (funcall brk-contents) '(x b e z)) (equal? (funcall swp-contents) '(d c z e)) (equal? (funcall box-contents) '(e))))) (past "shared change")) ;;; (test |Check that arrays copy the shape specification| (is-true (let ((shp (shape 10 12))) (let ((arr (make-array shp)) (ars (array shp * *)) (art (share-array (make-array shp) shp (lambda (k) k))) ) (array-set! shp 0 0 '?) (array-set! shp 0 1 '!) (and (= (array-rank shp) 2) (= (array-start shp 0) 0) (= (array-end shp 0) 1) (= (array-start shp 1) 0) (= (array-end shp 1) 2) (eq? (array-ref shp 0 0) '?) (eq? (array-ref shp 0 1) '!) (= (array-rank arr) 1) (= (array-start arr 0) 10) (= (array-end arr 0) 12) (= (array-rank ars) 1) (= (array-start ars 0) 10) (= (array-end ars 0) 12) (= (array-rank art) 1) (= (array-start art 0) 10) (= (array-end art 0) 12) )))) (past "array-set! of shape") ) (test |Check that index arrays work even when they share| ;; arr ixn ;; 5 6 0 1 ;; 4 nw ne 0 4 6 ;; 5 sw se 1 5 4 (let ((arr (array (shape 4 6 5 7) 'nw 'ne 'sw 'se)) (ixn (array (shape 0 2 0 2) 4 6 5 4)) ) (let ((col0 (share-array ixn (shape 0 2) (lambda (k) (values k 0) ))) (row0 (share-array ixn (shape 0 2) (lambda (k) (values 0 k) ))) (wor1 (share-array ixn (shape 0 2) (lambda (k) (values 1 (- 1 k)) ))) (cod (share-array ixn (shape 0 2) (lambda (k) (case k ((0) (values 1 0)) ((1) (values 0 1)) )))) (box (share-array ixn (shape 0 2) (lambda (k) (declare (ignore k)) (values 1 0) )))) (and (eq? (array-ref arr col0) 'nw) (eq? (array-ref arr row0) 'ne) (eq? (array-ref arr wor1) 'nw) (eq? (array-ref arr cod) 'se) (eq? (array-ref arr box) 'sw) (begin (array-set! arr col0 'ul) (array-set! arr row0 'ur) (array-set! arr cod 'lr) (array-set! arr box 'll) t ) (eq? (array-ref arr 4 5) 'ul) (eq? (array-ref arr 4 6) 'ur) (eq? (array-ref arr 5 5) 'll) (eq? (array-ref arr 5 6) 'lr) (begin (array-set! arr wor1 'xx) (eq? (array-ref arr 4 5) 'xx) )))) (past "array access with sharing index array") ) ;; ;; ;; arr shp shq shr shs ;; 1 2 3 4 0 1 0 1 0 1 0 1 ;; 1 10 12 16 20 0 10 12 0 12 20 0 10 10 0 12 12 ;; 2 10 11 12 13 1 10 11 1 11 13 1 11 12 1 12 12 ;; 2 12 16 ;; 3 13 20 (test |Check that shape arrays work even when they share| (is-true (let ((arr (array (shape 1 3 1 5) 10 12 16 20 10 11 12 13))) (let ((shp (share-array arr (shape 0 2 0 2) (lambda (r k) (values (+ r 1) (+ k 1))))) (shq (share-array arr (shape 0 2 0 2) (lambda (r k) (values (+ r 1) (* 2 (+ 1 k)))))) (shr (share-array arr (shape 0 4 0 2) (lambda (r k) (values (- 2 k) (+ r 1))))) (shs (share-array arr (shape 0 2 0 2) (lambda (r k) (declare (ignore r k)) (values 2 3))))) (and (let ((arr-p (make-array shp))) (and (= (array-rank arr-p) 2) (= (array-start arr-p 0) 10) (= (array-end arr-p 0) 12) (= (array-start arr-p 1) 10) (= (array-end arr-p 1) 11))) (let ((arr-q (array shq * * * * * * * * * * * * * * * *))) (and (= (array-rank arr-q) 2) (= (array-start arr-q 0) 12) (= (array-end arr-q 0) 20) (= (array-start arr-q 1) 11) (= (array-end arr-q 1) 13))) (let ((arr-r (share-array (array (shape) *) shr (lambda _ (declare (ignore _)) (values))))) (and (= (array-rank arr-r) 4) (= (array-start arr-r 0) 10) (= (array-end arr-r 0) 10) (= (array-start arr-r 1) 11) (= (array-end arr-r 1) 12) (= (array-start arr-r 2) 12) (= (array-end arr-r 2) 16) (= (array-start arr-r 3) 13) (= (array-end arr-r 3) 20))) (let ((arr-s (make-array shs))) (and (= (array-rank arr-s) 2) (= (array-start arr-s 0) 12) (= (array-end arr-s 0) 12) (= (array-start arr-s 1) 12) (= (array-end arr-s 1) 12))))))) (past "sharing shape array")) (test |Sharing with sharing subshape| (let ((super (array (shape 4 7 4 7) 1 * * * 2 * * * 3)) (subshape (share-array (array (shape 0 2 0 3) * 4 * * 7 *) (shape 0 1 0 2) (lambda (r k) (declare (ignore r)) (values k 1))))) (let ((sub (share-array super subshape (lambda (k) (values k k))))) ;(array-equal? subshape (shape 4 7)) (is-true (and (= (array-rank subshape) 2) (= (array-start subshape 0) 0) (= (array-end subshape 0) 1) (= (array-start subshape 1) 0) (= (array-end subshape 1) 2) (= (array-ref subshape 0 0) 4) (= (array-ref subshape 0 1) 7))) ;(array-equal? sub (array (shape 4 7) 1 2 3)) (is-true (and (= (array-rank sub) 1) (= (array-start sub 0) 4) (= (array-end sub 0) 7) (= (array-ref sub 4) 1) (= (array-ref sub 5) 2) (= (array-ref sub 6) 3))))) (past "sharing with sharing subshape")) ;;; eof
[ { "context": ";;;; $Id: usocket.lisp 331 2008-04-11 21:48:26Z ehuelsmann $\n;;;; $URL: svn+ssh://[email protected]", "end": 58, "score": 0.996469259262085, "start": 48, "tag": "USERNAME", "value": "ehuelsmann" }, { "context": "04-11 21:48:26Z ehuelsmann $\n;;;; $URL: svn+ssh://[email protected]/project/usocket/svn/usock", "end": 84, "score": 0.5087477564811707, "start": 82, "tag": "EMAIL", "value": "eh" }, { "context": "er ((string string))\n \"Convert a string, such as 192.168.1.1, to host-byte-order,\nsuch as 3232235777.\"\n (let ", "end": 6908, "score": 0.9997245669364929, "start": 6897, "tag": "IP_ADDRESS", "value": "192.168.1.1" } ]
cusp/jasko.tim.lisp.libs/libs/usocket-0.3.7/usocket.lisp
TeamSPoon/CYC_JRTL_with_CommonLisp_OLD
10
;;;; $Id: usocket.lisp 331 2008-04-11 21:48:26Z ehuelsmann $ ;;;; $URL: svn+ssh://[email protected]/project/usocket/svn/usocket/tags/0.3.7/usocket.lisp $ ;;;; See LICENSE for licensing information. (in-package :usocket) (defparameter *wildcard-host* #(0 0 0 0) "Hostname to pass when all interfaces in the current system are to be bound.") (defparameter *auto-port* 0 "Port number to pass when an auto-assigned port number is wanted.") (defclass usocket () ((socket :initarg :socket :accessor socket :documentation "Implementation specific socket object instance.")) (:documentation "The main socket class. Sockets should be closed using the `socket-close' method.")) (defclass stream-usocket (usocket) ((stream :initarg :stream :accessor socket-stream :documentation "Stream instance associated with the socket." ;; ;;Iff an external-format was passed to `socket-connect' or `socket-listen' ;;the stream is a flexi-stream. Otherwise the stream is implementation ;;specific." )) (:documentation "Stream socket class. Contrary to other sockets, these sockets may be closed either with the `socket-close' method or by closing the associated stream (which can be retrieved with the `socket-stream' accessor).")) (defclass stream-server-usocket (usocket) ((element-type :initarg :element-type :initform #-lispworks 'character #+lispworks 'base-char :reader element-type :documentation "Default element type for streams created by `socket-accept'.")) (:documentation "Socket which listens for stream connections to be initiated from remote sockets.")) ;;Not in use yet: ;;(defclass datagram-usocket (usocket) ;; () ;; (:documentation "")) (defun make-socket (&key socket) "Create a usocket socket type from implementation specific socket." (unless socket (error 'invalid-socket)) (make-stream-socket :socket socket)) (defun make-stream-socket (&key socket stream) "Create a usocket socket type from implementation specific socket and stream objects. Sockets returned should be closed using the `socket-close' method or by closing the stream associated with the socket. " (unless socket (error 'invalid-socket-error)) (unless stream (error 'invalid-socket-stream-error)) (make-instance 'stream-usocket :socket socket :stream stream)) (defun make-stream-server-socket (socket &key (element-type #-lispworks 'character #+lispworks 'base-char)) "Create a usocket-server socket type from an implementation-specific socket object. The returned value is a subtype of `stream-server-usocket'. " (unless socket (error 'invalid-socket-error)) (make-instance 'stream-server-usocket :socket socket :element-type element-type)) (defgeneric socket-close (usocket) (:documentation "Close a previously opened `usocket'.")) (defgeneric get-local-address (socket) (:documentation "Returns the IP address of the socket.")) (defgeneric get-peer-address (socket) (:documentation "Returns the IP address of the peer the socket is connected to.")) (defgeneric get-local-port (socket) (:documentation "Returns the IP port of the socket. This function applies to both `stream-usocket' and `server-stream-usocket' type objects.")) (defgeneric get-peer-port (socket) (:documentation "Returns the IP port of the peer the socket to.")) (defgeneric get-local-name (socket) (:documentation "Returns the IP address and port of the socket as values. This function applies to both `stream-usocket' and `server-stream-usocket' type objects.")) (defgeneric get-peer-name (socket) (:documentation "Returns the IP address and port of the peer the socket is connected to as values.")) (defmacro with-connected-socket ((var socket) &body body) "Bind `socket' to `var', ensuring socket destruction on exit. `body' is only evaluated when `var' is bound to a non-null value. The `body' is an implied progn form." `(let ((,var ,socket)) (unwind-protect (when ,var (with-mapped-conditions (,var) ,@body)) (when ,var (socket-close ,var))))) (defmacro with-client-socket ((socket-var stream-var &rest socket-connect-args) &body body) "Bind the socket resulting from a call to `socket-connect' with the arguments `socket-connect-args' to `socket-var' and if `stream-var' is non-nil, bind the associated socket stream to it." `(with-connected-socket (,socket-var (socket-connect ,@socket-connect-args)) ,(if (null stream-var) `(progn ,@body) `(let ((,stream-var (socket-stream ,socket-var))) ,@body)))) (defmacro with-server-socket ((var server-socket) &body body) "Bind `server-socket' to `var', ensuring socket destruction on exit. `body' is only evaluated when `var' is bound to a non-null value. The `body' is an implied progn form." `(with-connected-socket (,var ,server-socket) ,@body)) (defmacro with-socket-listener ((socket-var &rest socket-listen-args) &body body) "Bind the socket resulting from a call to `socket-listen' with arguments `socket-listen-args' to `socket-var'." `(with-server-socket (,socket-var (socket-listen ,@socket-listen-args)) ,@body)) ;; ;; IP(v4) utility functions ;; (defun list-of-strings-to-integers (list) "Take a list of strings and return a new list of integers (from parse-integer) on each of the string elements." (let ((new-list nil)) (dolist (element (reverse list)) (push (parse-integer element) new-list)) new-list)) (defun hbo-to-dotted-quad (integer) "Host-byte-order integer to dotted-quad string conversion utility." (let ((first (ldb (byte 8 24) integer)) (second (ldb (byte 8 16) integer)) (third (ldb (byte 8 8) integer)) (fourth (ldb (byte 8 0) integer))) (format nil "~A.~A.~A.~A" first second third fourth))) (defun hbo-to-vector-quad (integer) "Host-byte-order integer to dotted-quad string conversion utility." (let ((first (ldb (byte 8 24) integer)) (second (ldb (byte 8 16) integer)) (third (ldb (byte 8 8) integer)) (fourth (ldb (byte 8 0) integer))) (vector first second third fourth))) (defun vector-quad-to-dotted-quad (vector) (format nil "~A.~A.~A.~A" (aref vector 0) (aref vector 1) (aref vector 2) (aref vector 3))) (defun dotted-quad-to-vector-quad (string) (let ((list (list-of-strings-to-integers (split-sequence:split-sequence #\. string)))) (vector (first list) (second list) (third list) (fourth list)))) (defgeneric host-byte-order (address)) (defmethod host-byte-order ((string string)) "Convert a string, such as 192.168.1.1, to host-byte-order, such as 3232235777." (let ((list (list-of-strings-to-integers (split-sequence:split-sequence #\. string)))) (+ (* (first list) 256 256 256) (* (second list) 256 256) (* (third list) 256) (fourth list)))) (defmethod host-byte-order ((vector vector)) "Convert a vector, such as #(192 168 1 1), to host-byte-order, such as 3232235777." (+ (* (aref vector 0) 256 256 256) (* (aref vector 1) 256 256) (* (aref vector 2) 256) (aref vector 3))) (defmethod host-byte-order ((int integer)) int) (defun host-to-hostname (host) "Translate a string or vector quad to a stringified hostname." (etypecase host (string host) ((vector t 4) (vector-quad-to-dotted-quad host)) (integer (hbo-to-dotted-quad host)))) (defun ip= (ip1 ip2) (etypecase ip1 (string (string= ip1 (host-to-hostname ip2))) ((vector t 4) (or (eq ip1 ip2) (and (= (aref ip1 0) (aref ip2 0)) (= (aref ip1 1) (aref ip2 1)) (= (aref ip1 2) (aref ip2 2)) (= (aref ip1 3) (aref ip2 3))))) (integer (= ip1 (host-byte-order ip2))))) (defun ip/= (ip1 ip2) (not (ip= ip1 ip2))) ;; ;; DNS helper functions ;; #-(or clisp armedbear) (progn (defun get-host-by-name (name) (let ((hosts (get-hosts-by-name name))) (car hosts))) (defun get-random-host-by-name (name) (let ((hosts (get-hosts-by-name name))) (when hosts (elt hosts (random (length hosts)))))) (defun host-to-vector-quad (host) "Translate a host specification (vector quad, dotted quad or domain name) to a vector quad." (etypecase host (string (let* ((ip (ignore-errors (dotted-quad-to-vector-quad host)))) (if (and ip (= 4 (length ip))) ;; valid IP dotted quad? ip (get-random-host-by-name host)))) ((vector t 4) host) (integer (hbo-to-vector-quad host)))) (defun host-to-hbo (host) (etypecase host (string (let ((ip (ignore-errors (dotted-quad-to-vector-quad host)))) (if (and ip (= 4 (length ip))) (host-byte-order ip) (host-to-hbo (get-host-by-name host))))) ((vector t 4) (host-byte-order host)) (integer host)))) ;; ;; Setting of documentation for backend defined functions ;; ;; Documentation for the function ;; ;; (defun SOCKET-CONNECT (host port) ..) ;; (setf (documentation 'socket-connect 'function) "Connect to `host' on `port'. `host' is assumed to be a string or an IP address represented in vector notation, such as #(192 168 1 1). `port' is assumed to be an integer. Returns a usocket object.") ;; Documentation for the function ;; ;; (defun SOCKET-LISTEN (host port &key reuseaddress backlog element-type) ..) ;;###FIXME: extend with default-element-type (setf (documentation 'socket-listen 'function) "Bind to interface `host' on `port'. `host' should be the representation of an interface address. The implementation is not required to do an address lookup, making no guarantees that hostnames will be correctly resolved. If `*wildcard-host*' is passed for `host', the socket will be bound to all available interfaces for the IPv4 protocol in the system. `port' can be selected by the IP stack by passing `*auto-port*'. Returns an object of type `stream-server-usocket'. `reuse-address' and `backlog' are advisory parameters for setting socket options at creation time. `element-type' is the element type of the streams to be created by `socket-accept'. `reuseaddress' is supported for backward compatibility (but deprecated); when both `reuseaddress' and `reuse-address' have been specified, the latter takes precedence. ") ;; Documentation for the function ;; ;; (defun SOCKET-ACCEPT (socket &key element-type) (setf (documentation 'socket-accept 'function) "Accepts a connection from `socket', returning a `stream-socket'. The stream associated with the socket returned has `element-type' when explicitly specified, or the element-type passed to `socket-listen' otherwise.")
19006
;;;; $Id: usocket.lisp 331 2008-04-11 21:48:26Z ehuelsmann $ ;;;; $URL: svn+ssh://<EMAIL>[email protected]/project/usocket/svn/usocket/tags/0.3.7/usocket.lisp $ ;;;; See LICENSE for licensing information. (in-package :usocket) (defparameter *wildcard-host* #(0 0 0 0) "Hostname to pass when all interfaces in the current system are to be bound.") (defparameter *auto-port* 0 "Port number to pass when an auto-assigned port number is wanted.") (defclass usocket () ((socket :initarg :socket :accessor socket :documentation "Implementation specific socket object instance.")) (:documentation "The main socket class. Sockets should be closed using the `socket-close' method.")) (defclass stream-usocket (usocket) ((stream :initarg :stream :accessor socket-stream :documentation "Stream instance associated with the socket." ;; ;;Iff an external-format was passed to `socket-connect' or `socket-listen' ;;the stream is a flexi-stream. Otherwise the stream is implementation ;;specific." )) (:documentation "Stream socket class. Contrary to other sockets, these sockets may be closed either with the `socket-close' method or by closing the associated stream (which can be retrieved with the `socket-stream' accessor).")) (defclass stream-server-usocket (usocket) ((element-type :initarg :element-type :initform #-lispworks 'character #+lispworks 'base-char :reader element-type :documentation "Default element type for streams created by `socket-accept'.")) (:documentation "Socket which listens for stream connections to be initiated from remote sockets.")) ;;Not in use yet: ;;(defclass datagram-usocket (usocket) ;; () ;; (:documentation "")) (defun make-socket (&key socket) "Create a usocket socket type from implementation specific socket." (unless socket (error 'invalid-socket)) (make-stream-socket :socket socket)) (defun make-stream-socket (&key socket stream) "Create a usocket socket type from implementation specific socket and stream objects. Sockets returned should be closed using the `socket-close' method or by closing the stream associated with the socket. " (unless socket (error 'invalid-socket-error)) (unless stream (error 'invalid-socket-stream-error)) (make-instance 'stream-usocket :socket socket :stream stream)) (defun make-stream-server-socket (socket &key (element-type #-lispworks 'character #+lispworks 'base-char)) "Create a usocket-server socket type from an implementation-specific socket object. The returned value is a subtype of `stream-server-usocket'. " (unless socket (error 'invalid-socket-error)) (make-instance 'stream-server-usocket :socket socket :element-type element-type)) (defgeneric socket-close (usocket) (:documentation "Close a previously opened `usocket'.")) (defgeneric get-local-address (socket) (:documentation "Returns the IP address of the socket.")) (defgeneric get-peer-address (socket) (:documentation "Returns the IP address of the peer the socket is connected to.")) (defgeneric get-local-port (socket) (:documentation "Returns the IP port of the socket. This function applies to both `stream-usocket' and `server-stream-usocket' type objects.")) (defgeneric get-peer-port (socket) (:documentation "Returns the IP port of the peer the socket to.")) (defgeneric get-local-name (socket) (:documentation "Returns the IP address and port of the socket as values. This function applies to both `stream-usocket' and `server-stream-usocket' type objects.")) (defgeneric get-peer-name (socket) (:documentation "Returns the IP address and port of the peer the socket is connected to as values.")) (defmacro with-connected-socket ((var socket) &body body) "Bind `socket' to `var', ensuring socket destruction on exit. `body' is only evaluated when `var' is bound to a non-null value. The `body' is an implied progn form." `(let ((,var ,socket)) (unwind-protect (when ,var (with-mapped-conditions (,var) ,@body)) (when ,var (socket-close ,var))))) (defmacro with-client-socket ((socket-var stream-var &rest socket-connect-args) &body body) "Bind the socket resulting from a call to `socket-connect' with the arguments `socket-connect-args' to `socket-var' and if `stream-var' is non-nil, bind the associated socket stream to it." `(with-connected-socket (,socket-var (socket-connect ,@socket-connect-args)) ,(if (null stream-var) `(progn ,@body) `(let ((,stream-var (socket-stream ,socket-var))) ,@body)))) (defmacro with-server-socket ((var server-socket) &body body) "Bind `server-socket' to `var', ensuring socket destruction on exit. `body' is only evaluated when `var' is bound to a non-null value. The `body' is an implied progn form." `(with-connected-socket (,var ,server-socket) ,@body)) (defmacro with-socket-listener ((socket-var &rest socket-listen-args) &body body) "Bind the socket resulting from a call to `socket-listen' with arguments `socket-listen-args' to `socket-var'." `(with-server-socket (,socket-var (socket-listen ,@socket-listen-args)) ,@body)) ;; ;; IP(v4) utility functions ;; (defun list-of-strings-to-integers (list) "Take a list of strings and return a new list of integers (from parse-integer) on each of the string elements." (let ((new-list nil)) (dolist (element (reverse list)) (push (parse-integer element) new-list)) new-list)) (defun hbo-to-dotted-quad (integer) "Host-byte-order integer to dotted-quad string conversion utility." (let ((first (ldb (byte 8 24) integer)) (second (ldb (byte 8 16) integer)) (third (ldb (byte 8 8) integer)) (fourth (ldb (byte 8 0) integer))) (format nil "~A.~A.~A.~A" first second third fourth))) (defun hbo-to-vector-quad (integer) "Host-byte-order integer to dotted-quad string conversion utility." (let ((first (ldb (byte 8 24) integer)) (second (ldb (byte 8 16) integer)) (third (ldb (byte 8 8) integer)) (fourth (ldb (byte 8 0) integer))) (vector first second third fourth))) (defun vector-quad-to-dotted-quad (vector) (format nil "~A.~A.~A.~A" (aref vector 0) (aref vector 1) (aref vector 2) (aref vector 3))) (defun dotted-quad-to-vector-quad (string) (let ((list (list-of-strings-to-integers (split-sequence:split-sequence #\. string)))) (vector (first list) (second list) (third list) (fourth list)))) (defgeneric host-byte-order (address)) (defmethod host-byte-order ((string string)) "Convert a string, such as 192.168.1.1, to host-byte-order, such as 3232235777." (let ((list (list-of-strings-to-integers (split-sequence:split-sequence #\. string)))) (+ (* (first list) 256 256 256) (* (second list) 256 256) (* (third list) 256) (fourth list)))) (defmethod host-byte-order ((vector vector)) "Convert a vector, such as #(192 168 1 1), to host-byte-order, such as 3232235777." (+ (* (aref vector 0) 256 256 256) (* (aref vector 1) 256 256) (* (aref vector 2) 256) (aref vector 3))) (defmethod host-byte-order ((int integer)) int) (defun host-to-hostname (host) "Translate a string or vector quad to a stringified hostname." (etypecase host (string host) ((vector t 4) (vector-quad-to-dotted-quad host)) (integer (hbo-to-dotted-quad host)))) (defun ip= (ip1 ip2) (etypecase ip1 (string (string= ip1 (host-to-hostname ip2))) ((vector t 4) (or (eq ip1 ip2) (and (= (aref ip1 0) (aref ip2 0)) (= (aref ip1 1) (aref ip2 1)) (= (aref ip1 2) (aref ip2 2)) (= (aref ip1 3) (aref ip2 3))))) (integer (= ip1 (host-byte-order ip2))))) (defun ip/= (ip1 ip2) (not (ip= ip1 ip2))) ;; ;; DNS helper functions ;; #-(or clisp armedbear) (progn (defun get-host-by-name (name) (let ((hosts (get-hosts-by-name name))) (car hosts))) (defun get-random-host-by-name (name) (let ((hosts (get-hosts-by-name name))) (when hosts (elt hosts (random (length hosts)))))) (defun host-to-vector-quad (host) "Translate a host specification (vector quad, dotted quad or domain name) to a vector quad." (etypecase host (string (let* ((ip (ignore-errors (dotted-quad-to-vector-quad host)))) (if (and ip (= 4 (length ip))) ;; valid IP dotted quad? ip (get-random-host-by-name host)))) ((vector t 4) host) (integer (hbo-to-vector-quad host)))) (defun host-to-hbo (host) (etypecase host (string (let ((ip (ignore-errors (dotted-quad-to-vector-quad host)))) (if (and ip (= 4 (length ip))) (host-byte-order ip) (host-to-hbo (get-host-by-name host))))) ((vector t 4) (host-byte-order host)) (integer host)))) ;; ;; Setting of documentation for backend defined functions ;; ;; Documentation for the function ;; ;; (defun SOCKET-CONNECT (host port) ..) ;; (setf (documentation 'socket-connect 'function) "Connect to `host' on `port'. `host' is assumed to be a string or an IP address represented in vector notation, such as #(192 168 1 1). `port' is assumed to be an integer. Returns a usocket object.") ;; Documentation for the function ;; ;; (defun SOCKET-LISTEN (host port &key reuseaddress backlog element-type) ..) ;;###FIXME: extend with default-element-type (setf (documentation 'socket-listen 'function) "Bind to interface `host' on `port'. `host' should be the representation of an interface address. The implementation is not required to do an address lookup, making no guarantees that hostnames will be correctly resolved. If `*wildcard-host*' is passed for `host', the socket will be bound to all available interfaces for the IPv4 protocol in the system. `port' can be selected by the IP stack by passing `*auto-port*'. Returns an object of type `stream-server-usocket'. `reuse-address' and `backlog' are advisory parameters for setting socket options at creation time. `element-type' is the element type of the streams to be created by `socket-accept'. `reuseaddress' is supported for backward compatibility (but deprecated); when both `reuseaddress' and `reuse-address' have been specified, the latter takes precedence. ") ;; Documentation for the function ;; ;; (defun SOCKET-ACCEPT (socket &key element-type) (setf (documentation 'socket-accept 'function) "Accepts a connection from `socket', returning a `stream-socket'. The stream associated with the socket returned has `element-type' when explicitly specified, or the element-type passed to `socket-listen' otherwise.")
true
;;;; $Id: usocket.lisp 331 2008-04-11 21:48:26Z ehuelsmann $ ;;;; $URL: svn+ssh://PI:EMAIL:<EMAIL>[email protected]/project/usocket/svn/usocket/tags/0.3.7/usocket.lisp $ ;;;; See LICENSE for licensing information. (in-package :usocket) (defparameter *wildcard-host* #(0 0 0 0) "Hostname to pass when all interfaces in the current system are to be bound.") (defparameter *auto-port* 0 "Port number to pass when an auto-assigned port number is wanted.") (defclass usocket () ((socket :initarg :socket :accessor socket :documentation "Implementation specific socket object instance.")) (:documentation "The main socket class. Sockets should be closed using the `socket-close' method.")) (defclass stream-usocket (usocket) ((stream :initarg :stream :accessor socket-stream :documentation "Stream instance associated with the socket." ;; ;;Iff an external-format was passed to `socket-connect' or `socket-listen' ;;the stream is a flexi-stream. Otherwise the stream is implementation ;;specific." )) (:documentation "Stream socket class. Contrary to other sockets, these sockets may be closed either with the `socket-close' method or by closing the associated stream (which can be retrieved with the `socket-stream' accessor).")) (defclass stream-server-usocket (usocket) ((element-type :initarg :element-type :initform #-lispworks 'character #+lispworks 'base-char :reader element-type :documentation "Default element type for streams created by `socket-accept'.")) (:documentation "Socket which listens for stream connections to be initiated from remote sockets.")) ;;Not in use yet: ;;(defclass datagram-usocket (usocket) ;; () ;; (:documentation "")) (defun make-socket (&key socket) "Create a usocket socket type from implementation specific socket." (unless socket (error 'invalid-socket)) (make-stream-socket :socket socket)) (defun make-stream-socket (&key socket stream) "Create a usocket socket type from implementation specific socket and stream objects. Sockets returned should be closed using the `socket-close' method or by closing the stream associated with the socket. " (unless socket (error 'invalid-socket-error)) (unless stream (error 'invalid-socket-stream-error)) (make-instance 'stream-usocket :socket socket :stream stream)) (defun make-stream-server-socket (socket &key (element-type #-lispworks 'character #+lispworks 'base-char)) "Create a usocket-server socket type from an implementation-specific socket object. The returned value is a subtype of `stream-server-usocket'. " (unless socket (error 'invalid-socket-error)) (make-instance 'stream-server-usocket :socket socket :element-type element-type)) (defgeneric socket-close (usocket) (:documentation "Close a previously opened `usocket'.")) (defgeneric get-local-address (socket) (:documentation "Returns the IP address of the socket.")) (defgeneric get-peer-address (socket) (:documentation "Returns the IP address of the peer the socket is connected to.")) (defgeneric get-local-port (socket) (:documentation "Returns the IP port of the socket. This function applies to both `stream-usocket' and `server-stream-usocket' type objects.")) (defgeneric get-peer-port (socket) (:documentation "Returns the IP port of the peer the socket to.")) (defgeneric get-local-name (socket) (:documentation "Returns the IP address and port of the socket as values. This function applies to both `stream-usocket' and `server-stream-usocket' type objects.")) (defgeneric get-peer-name (socket) (:documentation "Returns the IP address and port of the peer the socket is connected to as values.")) (defmacro with-connected-socket ((var socket) &body body) "Bind `socket' to `var', ensuring socket destruction on exit. `body' is only evaluated when `var' is bound to a non-null value. The `body' is an implied progn form." `(let ((,var ,socket)) (unwind-protect (when ,var (with-mapped-conditions (,var) ,@body)) (when ,var (socket-close ,var))))) (defmacro with-client-socket ((socket-var stream-var &rest socket-connect-args) &body body) "Bind the socket resulting from a call to `socket-connect' with the arguments `socket-connect-args' to `socket-var' and if `stream-var' is non-nil, bind the associated socket stream to it." `(with-connected-socket (,socket-var (socket-connect ,@socket-connect-args)) ,(if (null stream-var) `(progn ,@body) `(let ((,stream-var (socket-stream ,socket-var))) ,@body)))) (defmacro with-server-socket ((var server-socket) &body body) "Bind `server-socket' to `var', ensuring socket destruction on exit. `body' is only evaluated when `var' is bound to a non-null value. The `body' is an implied progn form." `(with-connected-socket (,var ,server-socket) ,@body)) (defmacro with-socket-listener ((socket-var &rest socket-listen-args) &body body) "Bind the socket resulting from a call to `socket-listen' with arguments `socket-listen-args' to `socket-var'." `(with-server-socket (,socket-var (socket-listen ,@socket-listen-args)) ,@body)) ;; ;; IP(v4) utility functions ;; (defun list-of-strings-to-integers (list) "Take a list of strings and return a new list of integers (from parse-integer) on each of the string elements." (let ((new-list nil)) (dolist (element (reverse list)) (push (parse-integer element) new-list)) new-list)) (defun hbo-to-dotted-quad (integer) "Host-byte-order integer to dotted-quad string conversion utility." (let ((first (ldb (byte 8 24) integer)) (second (ldb (byte 8 16) integer)) (third (ldb (byte 8 8) integer)) (fourth (ldb (byte 8 0) integer))) (format nil "~A.~A.~A.~A" first second third fourth))) (defun hbo-to-vector-quad (integer) "Host-byte-order integer to dotted-quad string conversion utility." (let ((first (ldb (byte 8 24) integer)) (second (ldb (byte 8 16) integer)) (third (ldb (byte 8 8) integer)) (fourth (ldb (byte 8 0) integer))) (vector first second third fourth))) (defun vector-quad-to-dotted-quad (vector) (format nil "~A.~A.~A.~A" (aref vector 0) (aref vector 1) (aref vector 2) (aref vector 3))) (defun dotted-quad-to-vector-quad (string) (let ((list (list-of-strings-to-integers (split-sequence:split-sequence #\. string)))) (vector (first list) (second list) (third list) (fourth list)))) (defgeneric host-byte-order (address)) (defmethod host-byte-order ((string string)) "Convert a string, such as 192.168.1.1, to host-byte-order, such as 3232235777." (let ((list (list-of-strings-to-integers (split-sequence:split-sequence #\. string)))) (+ (* (first list) 256 256 256) (* (second list) 256 256) (* (third list) 256) (fourth list)))) (defmethod host-byte-order ((vector vector)) "Convert a vector, such as #(192 168 1 1), to host-byte-order, such as 3232235777." (+ (* (aref vector 0) 256 256 256) (* (aref vector 1) 256 256) (* (aref vector 2) 256) (aref vector 3))) (defmethod host-byte-order ((int integer)) int) (defun host-to-hostname (host) "Translate a string or vector quad to a stringified hostname." (etypecase host (string host) ((vector t 4) (vector-quad-to-dotted-quad host)) (integer (hbo-to-dotted-quad host)))) (defun ip= (ip1 ip2) (etypecase ip1 (string (string= ip1 (host-to-hostname ip2))) ((vector t 4) (or (eq ip1 ip2) (and (= (aref ip1 0) (aref ip2 0)) (= (aref ip1 1) (aref ip2 1)) (= (aref ip1 2) (aref ip2 2)) (= (aref ip1 3) (aref ip2 3))))) (integer (= ip1 (host-byte-order ip2))))) (defun ip/= (ip1 ip2) (not (ip= ip1 ip2))) ;; ;; DNS helper functions ;; #-(or clisp armedbear) (progn (defun get-host-by-name (name) (let ((hosts (get-hosts-by-name name))) (car hosts))) (defun get-random-host-by-name (name) (let ((hosts (get-hosts-by-name name))) (when hosts (elt hosts (random (length hosts)))))) (defun host-to-vector-quad (host) "Translate a host specification (vector quad, dotted quad or domain name) to a vector quad." (etypecase host (string (let* ((ip (ignore-errors (dotted-quad-to-vector-quad host)))) (if (and ip (= 4 (length ip))) ;; valid IP dotted quad? ip (get-random-host-by-name host)))) ((vector t 4) host) (integer (hbo-to-vector-quad host)))) (defun host-to-hbo (host) (etypecase host (string (let ((ip (ignore-errors (dotted-quad-to-vector-quad host)))) (if (and ip (= 4 (length ip))) (host-byte-order ip) (host-to-hbo (get-host-by-name host))))) ((vector t 4) (host-byte-order host)) (integer host)))) ;; ;; Setting of documentation for backend defined functions ;; ;; Documentation for the function ;; ;; (defun SOCKET-CONNECT (host port) ..) ;; (setf (documentation 'socket-connect 'function) "Connect to `host' on `port'. `host' is assumed to be a string or an IP address represented in vector notation, such as #(192 168 1 1). `port' is assumed to be an integer. Returns a usocket object.") ;; Documentation for the function ;; ;; (defun SOCKET-LISTEN (host port &key reuseaddress backlog element-type) ..) ;;###FIXME: extend with default-element-type (setf (documentation 'socket-listen 'function) "Bind to interface `host' on `port'. `host' should be the representation of an interface address. The implementation is not required to do an address lookup, making no guarantees that hostnames will be correctly resolved. If `*wildcard-host*' is passed for `host', the socket will be bound to all available interfaces for the IPv4 protocol in the system. `port' can be selected by the IP stack by passing `*auto-port*'. Returns an object of type `stream-server-usocket'. `reuse-address' and `backlog' are advisory parameters for setting socket options at creation time. `element-type' is the element type of the streams to be created by `socket-accept'. `reuseaddress' is supported for backward compatibility (but deprecated); when both `reuseaddress' and `reuse-address' have been specified, the latter takes precedence. ") ;; Documentation for the function ;; ;; (defun SOCKET-ACCEPT (socket &key element-type) (setf (documentation 'socket-accept 'function) "Accepts a connection from `socket', returning a `stream-socket'. The stream associated with the socket returned has `element-type' when explicitly specified, or the element-type passed to `socket-listen' otherwise.")
[ { "context": "An ACL2 Tarai Function book.\n; Copyright (C) 2000 John R. Cowles, University of Wyoming\n\n; This book is free softw", "end": 67, "score": 0.9998640418052673, "start": 53, "tag": "NAME", "value": "John R. Cowles" }, { "context": "ss Ave, Cambridge, MA 02139, USA.\n\n; Written by:\n; John Cowles\n; Department of Computer Science\n; University of ", "end": 793, "score": 0.9998612403869629, "start": 782, "tag": "NAME", "value": "John Cowles" } ]
books/workshops/2000/cowles/books/tarai10.lisp
ragerdl/acl2-defthm-rc2
1
; An ACL2 Tarai Function book. ; Copyright (C) 2000 John R. Cowles, University of Wyoming ; This book 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 book 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 book; if not, write to the Free Software ; Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. ; Written by: ; John Cowles ; Department of Computer Science ; University of Wyoming ; Laramie, WY 82071-3682 U.S.A. ;; These implementations of Knuth's and Bailey's versions of the f function ;; for Knuth's theorem 4 compute the same results for all true lists of ;; lengths 0-4 and for all lists of integers of length 5. An example is ;; provided showing there are lists of integers of length 6 for which the ;; two functions compute different results. ;; (certify-book "C:/acl2/tak/tarai10") (in-package "ACL2") (defmacro last-el (lst) "Return the last element in the list lst." (list 'car (list 'last lst))) (defun Gb (lst) "Bailey's g function for Knuth's Theorem 4. The input lst is intended to be a nonempty list of integers." (declare (xargs :guard (and (integer-listp lst) (consp lst)))) (cond ((consp (nthcdr 3 lst)) ;; (len lst) > 3 (if (or (equal (first lst) (+ (second lst) 1)) (> (second lst) (+ (third lst) 1))) (Gb (rest lst)) (max (third lst) (last-el lst)))) (t (last-el lst)))) ;; (len lst) <= 3 (defun Gk (lst) "Knuth's g function for Knuth's Theorem 4. The input lst is intended to be a nonempty list of integers." (declare (xargs :guard (and (integer-listp lst) (consp lst)))) (cond ((consp (nthcdr 2 lst)) ;; (len lst) > 2 (cond ((equal (first lst) (+ (second lst) 1)) (Gk (rest lst))) ((equal (second lst) (+ (third lst) 1)) (max (third lst) (last-el lst))) (t (last-el lst)))) (t (last-el lst)))) ;; (len lst) <= 2 (defun decreasing-p (lst) "Determine if the elements in lst are strictly decreasing." (declare (xargs :guard (rational-listp lst))) (if (consp (rest lst)) ;; (len lst) > 1 (and (> (first lst)(second lst)) (decreasing-p (rest lst))) t)) (defun first-non-decrease (lst) "Return the front of lst up to and including the first element that does not strictly decrease." (declare (xargs :guard (and (rational-listp lst) (not (decreasing-p lst))))) (if (consp (rest lst)) ;; (len lst) > 1 (if (<= (first lst)(second lst)) (list (first lst)(second lst)) (cons (first lst) (first-non-decrease (rest lst)))) lst)) (defun Fb (lst) "Bailey's f function for Knuth's theorem 4. The input lst is intended to be a nonempty list of integers." (declare (xargs :guard (and (integer-listp lst) (consp lst)))) (if (decreasing-p lst) (first lst) (Gb (first-non-decrease lst)))) (defun Fk (lst) "Knuth's f function for Knuth's theorem 4. The input lst is intended to be a nonempty list of integers." (declare (xargs :guard (and (integer-listp lst) (consp lst)))) (if (decreasing-p lst) (first lst) (Gk (first-non-decrease lst)))) (defthm Fk=Fb-1 (let ((lst (list first))) (equal (Fk lst)(Fb lst)))) (defthm Fk=Fb-2 (let ((lst (list first second))) (equal (Fk lst)(Fb lst)))) (defthm Fk=Fb-3 (let ((lst (list first second third))) (equal (Fk lst)(Fb lst)))) (defthm Fk=Fb-4 (let ((lst (list first second third fourth))) (equal (Fk lst)(Fb lst)))) (defthm Fk=Fb-0-4 (implies (and (true-listp lst) (not (consp (nthcdr 4 lst)))) ;; (len lst) <= 4 (equal (Fk lst)(Fb lst))) :hints (("Goal" :in-theory (disable Fk Fb)))) (defthm Fk=Fb-5 (let ((lst (list first second third fourth fifth))) (implies (integer-listp lst) (equal (Fk lst)(Fb lst))))) (defthm Fk=Fb-0-5 (implies (and (integer-listp lst) (not (consp (nthcdr 5 lst)))) ;; (len lst) <= 5 (equal (Fk lst)(Fb lst))) :hints (("Goal" :in-theory (disable Fk Fb)))) (defthm Fk<>Fb-6-example (let ((lst '(8 6 4 3 1 2))) (and (equal (Fk lst) 2) (equal (Fb lst) 3) (not (equal (Fk lst)(Fb lst))))))
84451
; An ACL2 Tarai Function book. ; Copyright (C) 2000 <NAME>, University of Wyoming ; This book 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 book 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 book; if not, write to the Free Software ; Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. ; Written by: ; <NAME> ; Department of Computer Science ; University of Wyoming ; Laramie, WY 82071-3682 U.S.A. ;; These implementations of Knuth's and Bailey's versions of the f function ;; for Knuth's theorem 4 compute the same results for all true lists of ;; lengths 0-4 and for all lists of integers of length 5. An example is ;; provided showing there are lists of integers of length 6 for which the ;; two functions compute different results. ;; (certify-book "C:/acl2/tak/tarai10") (in-package "ACL2") (defmacro last-el (lst) "Return the last element in the list lst." (list 'car (list 'last lst))) (defun Gb (lst) "Bailey's g function for Knuth's Theorem 4. The input lst is intended to be a nonempty list of integers." (declare (xargs :guard (and (integer-listp lst) (consp lst)))) (cond ((consp (nthcdr 3 lst)) ;; (len lst) > 3 (if (or (equal (first lst) (+ (second lst) 1)) (> (second lst) (+ (third lst) 1))) (Gb (rest lst)) (max (third lst) (last-el lst)))) (t (last-el lst)))) ;; (len lst) <= 3 (defun Gk (lst) "Knuth's g function for Knuth's Theorem 4. The input lst is intended to be a nonempty list of integers." (declare (xargs :guard (and (integer-listp lst) (consp lst)))) (cond ((consp (nthcdr 2 lst)) ;; (len lst) > 2 (cond ((equal (first lst) (+ (second lst) 1)) (Gk (rest lst))) ((equal (second lst) (+ (third lst) 1)) (max (third lst) (last-el lst))) (t (last-el lst)))) (t (last-el lst)))) ;; (len lst) <= 2 (defun decreasing-p (lst) "Determine if the elements in lst are strictly decreasing." (declare (xargs :guard (rational-listp lst))) (if (consp (rest lst)) ;; (len lst) > 1 (and (> (first lst)(second lst)) (decreasing-p (rest lst))) t)) (defun first-non-decrease (lst) "Return the front of lst up to and including the first element that does not strictly decrease." (declare (xargs :guard (and (rational-listp lst) (not (decreasing-p lst))))) (if (consp (rest lst)) ;; (len lst) > 1 (if (<= (first lst)(second lst)) (list (first lst)(second lst)) (cons (first lst) (first-non-decrease (rest lst)))) lst)) (defun Fb (lst) "Bailey's f function for Knuth's theorem 4. The input lst is intended to be a nonempty list of integers." (declare (xargs :guard (and (integer-listp lst) (consp lst)))) (if (decreasing-p lst) (first lst) (Gb (first-non-decrease lst)))) (defun Fk (lst) "Knuth's f function for Knuth's theorem 4. The input lst is intended to be a nonempty list of integers." (declare (xargs :guard (and (integer-listp lst) (consp lst)))) (if (decreasing-p lst) (first lst) (Gk (first-non-decrease lst)))) (defthm Fk=Fb-1 (let ((lst (list first))) (equal (Fk lst)(Fb lst)))) (defthm Fk=Fb-2 (let ((lst (list first second))) (equal (Fk lst)(Fb lst)))) (defthm Fk=Fb-3 (let ((lst (list first second third))) (equal (Fk lst)(Fb lst)))) (defthm Fk=Fb-4 (let ((lst (list first second third fourth))) (equal (Fk lst)(Fb lst)))) (defthm Fk=Fb-0-4 (implies (and (true-listp lst) (not (consp (nthcdr 4 lst)))) ;; (len lst) <= 4 (equal (Fk lst)(Fb lst))) :hints (("Goal" :in-theory (disable Fk Fb)))) (defthm Fk=Fb-5 (let ((lst (list first second third fourth fifth))) (implies (integer-listp lst) (equal (Fk lst)(Fb lst))))) (defthm Fk=Fb-0-5 (implies (and (integer-listp lst) (not (consp (nthcdr 5 lst)))) ;; (len lst) <= 5 (equal (Fk lst)(Fb lst))) :hints (("Goal" :in-theory (disable Fk Fb)))) (defthm Fk<>Fb-6-example (let ((lst '(8 6 4 3 1 2))) (and (equal (Fk lst) 2) (equal (Fb lst) 3) (not (equal (Fk lst)(Fb lst))))))
true
; An ACL2 Tarai Function book. ; Copyright (C) 2000 PI:NAME:<NAME>END_PI, University of Wyoming ; This book 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 book 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 book; if not, write to the Free Software ; Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. ; Written by: ; PI:NAME:<NAME>END_PI ; Department of Computer Science ; University of Wyoming ; Laramie, WY 82071-3682 U.S.A. ;; These implementations of Knuth's and Bailey's versions of the f function ;; for Knuth's theorem 4 compute the same results for all true lists of ;; lengths 0-4 and for all lists of integers of length 5. An example is ;; provided showing there are lists of integers of length 6 for which the ;; two functions compute different results. ;; (certify-book "C:/acl2/tak/tarai10") (in-package "ACL2") (defmacro last-el (lst) "Return the last element in the list lst." (list 'car (list 'last lst))) (defun Gb (lst) "Bailey's g function for Knuth's Theorem 4. The input lst is intended to be a nonempty list of integers." (declare (xargs :guard (and (integer-listp lst) (consp lst)))) (cond ((consp (nthcdr 3 lst)) ;; (len lst) > 3 (if (or (equal (first lst) (+ (second lst) 1)) (> (second lst) (+ (third lst) 1))) (Gb (rest lst)) (max (third lst) (last-el lst)))) (t (last-el lst)))) ;; (len lst) <= 3 (defun Gk (lst) "Knuth's g function for Knuth's Theorem 4. The input lst is intended to be a nonempty list of integers." (declare (xargs :guard (and (integer-listp lst) (consp lst)))) (cond ((consp (nthcdr 2 lst)) ;; (len lst) > 2 (cond ((equal (first lst) (+ (second lst) 1)) (Gk (rest lst))) ((equal (second lst) (+ (third lst) 1)) (max (third lst) (last-el lst))) (t (last-el lst)))) (t (last-el lst)))) ;; (len lst) <= 2 (defun decreasing-p (lst) "Determine if the elements in lst are strictly decreasing." (declare (xargs :guard (rational-listp lst))) (if (consp (rest lst)) ;; (len lst) > 1 (and (> (first lst)(second lst)) (decreasing-p (rest lst))) t)) (defun first-non-decrease (lst) "Return the front of lst up to and including the first element that does not strictly decrease." (declare (xargs :guard (and (rational-listp lst) (not (decreasing-p lst))))) (if (consp (rest lst)) ;; (len lst) > 1 (if (<= (first lst)(second lst)) (list (first lst)(second lst)) (cons (first lst) (first-non-decrease (rest lst)))) lst)) (defun Fb (lst) "Bailey's f function for Knuth's theorem 4. The input lst is intended to be a nonempty list of integers." (declare (xargs :guard (and (integer-listp lst) (consp lst)))) (if (decreasing-p lst) (first lst) (Gb (first-non-decrease lst)))) (defun Fk (lst) "Knuth's f function for Knuth's theorem 4. The input lst is intended to be a nonempty list of integers." (declare (xargs :guard (and (integer-listp lst) (consp lst)))) (if (decreasing-p lst) (first lst) (Gk (first-non-decrease lst)))) (defthm Fk=Fb-1 (let ((lst (list first))) (equal (Fk lst)(Fb lst)))) (defthm Fk=Fb-2 (let ((lst (list first second))) (equal (Fk lst)(Fb lst)))) (defthm Fk=Fb-3 (let ((lst (list first second third))) (equal (Fk lst)(Fb lst)))) (defthm Fk=Fb-4 (let ((lst (list first second third fourth))) (equal (Fk lst)(Fb lst)))) (defthm Fk=Fb-0-4 (implies (and (true-listp lst) (not (consp (nthcdr 4 lst)))) ;; (len lst) <= 4 (equal (Fk lst)(Fb lst))) :hints (("Goal" :in-theory (disable Fk Fb)))) (defthm Fk=Fb-5 (let ((lst (list first second third fourth fifth))) (implies (integer-listp lst) (equal (Fk lst)(Fb lst))))) (defthm Fk=Fb-0-5 (implies (and (integer-listp lst) (not (consp (nthcdr 5 lst)))) ;; (len lst) <= 5 (equal (Fk lst)(Fb lst))) :hints (("Goal" :in-theory (disable Fk Fb)))) (defthm Fk<>Fb-6-example (let ((lst '(8 6 4 3 1 2))) (and (equal (Fk lst) 2) (equal (Fb lst) 3) (not (equal (Fk lst)(Fb lst))))))
[ { "context": "he LICENSE file distributed with ACL2.\n;\n; Author: Alessandro Coglio ([email protected])\n\n;;;;;;;;;;;;;;;;;;;;;;;;;;;", "end": 192, "score": 0.9998748302459717, "start": 175, "tag": "NAME", "value": "Alessandro Coglio" }, { "context": "ributed with ACL2.\n;\n; Author: Alessandro Coglio ([email protected])\n\n;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;", "end": 212, "score": 0.9999299049377441, "start": 194, "tag": "EMAIL", "value": "[email protected]" } ]
books/kestrel/zcash/gadgets/a-3-3-4-spec.lisp
mayankmanj/acl2
305
; Zcash 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]) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ; Specification of the gadget in [ZPS:A.3.3.4]. (in-package "ZCASH") (include-book "kestrel/zcash/jubjub-montgomery" :dir :system) (define montgomery-add-precond (x1 y1 x2 y2) :guard (and (fep x1 (jubjub-q)) (fep y1 (jubjub-q)) (fep x2 (jubjub-q)) (fep y2 (jubjub-q))) (and (ecurve::point-on-montgomery-p (ecurve::point-finite x1 y1) (jubjub-montgomery-curve)) (ecurve::point-on-montgomery-p (ecurve::point-finite x2 y2) (jubjub-montgomery-curve)) (not (equal x1 x2)))) (define montgomery-add-spec (x1 y1 x2 y2 x3 y3) :guard (and (fep x1 (jubjub-q)) (fep y1 (jubjub-q)) (fep x2 (jubjub-q)) (fep y2 (jubjub-q)) (fep x3 (jubjub-q)) (fep y3 (jubjub-q)) (montgomery-add-precond x1 y1 x2 y2)) (equal (ecurve::montgomery-add (ecurve::point-finite x1 y1) (ecurve::point-finite x2 y2) (jubjub-montgomery-curve)) (ecurve::point-finite x3 y3)) :guard-hints (("Goal" :in-theory (enable montgomery-add-precond))))
58980
; Zcash 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>) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ; Specification of the gadget in [ZPS:A.3.3.4]. (in-package "ZCASH") (include-book "kestrel/zcash/jubjub-montgomery" :dir :system) (define montgomery-add-precond (x1 y1 x2 y2) :guard (and (fep x1 (jubjub-q)) (fep y1 (jubjub-q)) (fep x2 (jubjub-q)) (fep y2 (jubjub-q))) (and (ecurve::point-on-montgomery-p (ecurve::point-finite x1 y1) (jubjub-montgomery-curve)) (ecurve::point-on-montgomery-p (ecurve::point-finite x2 y2) (jubjub-montgomery-curve)) (not (equal x1 x2)))) (define montgomery-add-spec (x1 y1 x2 y2 x3 y3) :guard (and (fep x1 (jubjub-q)) (fep y1 (jubjub-q)) (fep x2 (jubjub-q)) (fep y2 (jubjub-q)) (fep x3 (jubjub-q)) (fep y3 (jubjub-q)) (montgomery-add-precond x1 y1 x2 y2)) (equal (ecurve::montgomery-add (ecurve::point-finite x1 y1) (ecurve::point-finite x2 y2) (jubjub-montgomery-curve)) (ecurve::point-finite x3 y3)) :guard-hints (("Goal" :in-theory (enable montgomery-add-precond))))
true
; Zcash 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) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ; Specification of the gadget in [ZPS:A.3.3.4]. (in-package "ZCASH") (include-book "kestrel/zcash/jubjub-montgomery" :dir :system) (define montgomery-add-precond (x1 y1 x2 y2) :guard (and (fep x1 (jubjub-q)) (fep y1 (jubjub-q)) (fep x2 (jubjub-q)) (fep y2 (jubjub-q))) (and (ecurve::point-on-montgomery-p (ecurve::point-finite x1 y1) (jubjub-montgomery-curve)) (ecurve::point-on-montgomery-p (ecurve::point-finite x2 y2) (jubjub-montgomery-curve)) (not (equal x1 x2)))) (define montgomery-add-spec (x1 y1 x2 y2 x3 y3) :guard (and (fep x1 (jubjub-q)) (fep y1 (jubjub-q)) (fep x2 (jubjub-q)) (fep y2 (jubjub-q)) (fep x3 (jubjub-q)) (fep y3 (jubjub-q)) (montgomery-add-precond x1 y1 x2 y2)) (equal (ecurve::montgomery-add (ecurve::point-finite x1 y1) (ecurve::point-finite x2 y2) (jubjub-montgomery-curve)) (ecurve::point-finite x3 y3)) :guard-hints (("Goal" :in-theory (enable montgomery-add-precond))))
[ { "context": "; DEALINGS IN THE SOFTWARE.\n;\n; Original author: Jared Davis <[email protected]>\n\n(in-package \"VL\")\n(include-", "end": 1390, "score": 0.9996533989906311, "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 \"../utils\")\n(in", "end": 1410, "score": 0.9999337196350098, "start": 1392, "tag": "EMAIL", "value": "[email protected]" } ]
books/centaur/vl/loader/parser/tests/base.lisp
jaredcdavis/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 "../utils") (include-book "../../lexer/lexer") ;; for make-test-tokens, etc. (include-book "../../../parsetree") (include-book "../../../mlib/expr-tools") ; We now introduce a function to convert expressions into a "pretty" format ; which makes it a bit easier to see if an expression is what you expect for ; writing unit tests. ;; (define vl-pretty-atom ((x vl-expr-p)) ;; :guard (vl-atom-p x) ;; (let ((guts (vl-atom->guts x))) ;; (cond ((vl-constint-p guts) (vl-constint->value guts)) ;; ((vl-weirdint-p guts) ;; (list 'weird ;; (vl-bitlist->string (vl-weirdint->bits guts)))) ;; ((vl-string-p guts) (list 'str (vl-string->value guts))) ;; ((vl-real-p guts) (list 'real (vl-real->value guts))) ;; ((vl-id-p guts) (list 'id (vl-id->name guts))) ;; ((vl-hidpiece-p guts) (list 'hid (vl-hidpiece->name guts))) ;; ((vl-funname-p guts) (list 'fun (vl-funname->name guts))) ;; ((vl-typename-p guts) (list 'type (vl-typename->name guts))) ;; ((vl-sysfunname-p guts) (list 'sys (vl-sysfunname->name guts))) ;; ((vl-keyguts-p guts) (list 'key (vl-keyguts->type guts))) ;; ((vl-basictype-p guts) (list 'basic (vl-basictype->kind guts))) ;; ((vl-tagname-p guts) (list 'tag (vl-tagname->name guts))) ;; ((vl-time-p guts) ;; (list 'time ;; (concatenate 'string ;; (vl-time->quantity guts) ;; (vl-timeunit->string ;; (vl-time->units guts))))) ;; ((vl-extint-p guts) ;; (list 'ext (vl-extint->value guts))) ;; (t ;; (raise "Unsupported kind of atom: ~x0." x))))) (define vl-pretty-value ((x vl-value-p)) (vl-value-case x :vl-constint x.value :vl-weirdint (list 'weird x.bits) :vl-extint (list 'ext x.value) :vl-real (list 'real x.value) :vl-time (list 'time (str::cat x.quantity (vl-timeunit->string x.units))) :vl-string (list 'str x.value))) (define vl-pretty-scopename ((x vl-scopename-p)) (let ((x (vl-scopename-fix x))) (case x (:vl-local '(key :vl-local)) (:vl-$unit '(key :vl-$unit)) (t x)))) (define vl-pretty-hidname ((x vl-hidname-p)) (let ((x (vl-hidname-fix x))) (case x (:vl-$root '(key :vl-$root)) (otherwise x)))) (define vl-pretty-specialkey ((x vl-specialkey-p)) (let ((x (vl-specialkey-fix x))) (case x (:vl-null '(key :vl-null)) (:vl-$ '(key :vl-$)) (:vl-emptyqueue '(key :vl-emptyqueue))))) (defines vl-pretty-exprs :flag nil (define vl-pretty-hidindex ((x vl-hidindex-p)) :measure (vl-hidindex-count x) (b* (((vl-hidindex x)) ((unless x.indices) x.name)) (list :vl-hid-index (vl-pretty-hidname x.name) (vl-pretty-exprlist x.indices)))) (define vl-pretty-hidexpr ((x vl-hidexpr-p)) :measure (vl-hidexpr-count x) (vl-hidexpr-case x (:end x.name) (:dot (list :dot (vl-pretty-hidindex x.first) (vl-pretty-hidexpr x.rest))))) (define vl-pretty-scopeexpr ((x vl-scopeexpr-p)) :measure (vl-scopeexpr-count x) (vl-scopeexpr-case x (:end (vl-pretty-hidexpr x.hid)) (:colon (list :scope (vl-pretty-scopename x.first) (vl-pretty-scopeexpr x.rest))))) (define vl-pretty-plusminus ((x vl-plusminus-p)) :measure (vl-plusminus-count x) (b* (((vl-plusminus x))) (list (if x.minusp :minuscolon :pluscolon) (vl-pretty-expr x.base) (vl-pretty-expr x.width)))) (define vl-pretty-partselect ((x vl-partselect-p)) :measure (vl-partselect-count x) (vl-partselect-case x (:none nil) (:range (list :colon (vl-pretty-expr x.msb) (vl-pretty-expr x.lsb))) (:plusminus (vl-pretty-plusminus x.plusminus)))) (define vl-pretty-arrayrange ((x vl-arrayrange-p)) :measure (vl-arrayrange-count x) (vl-arrayrange-case x (:none nil) (:range (vl-pretty-range x.range)) (:plusminus (vl-pretty-plusminus x.plusminus)) (:index (list :arrindex (vl-pretty-expr x.expr))))) (define vl-pretty-streamexpr ((x vl-streamexpr-p)) :measure (vl-streamexpr-count x) (b* (((vl-streamexpr x)) ((when (vl-arrayrange-case x.part :none)) (vl-pretty-expr x.expr))) (list (vl-pretty-expr x.expr) :with (vl-pretty-arrayrange x.part)))) (define vl-pretty-streamexprlist ((x vl-streamexprlist-p)) :measure (vl-streamexprlist-count x) (if (atom x) nil (cons (vl-pretty-streamexpr (car x)) (vl-pretty-streamexprlist (cdr x))))) (define vl-pretty-valuerange ((x vl-valuerange-p)) :measure (vl-valuerange-count x) (vl-valuerange-case x (:range (vl-pretty-range x.range)) (:single (vl-pretty-expr x.expr)))) (define vl-pretty-valuerangelist ((x vl-valuerangelist-p)) :measure (vl-valuerangelist-count x) (if (atom x) nil (cons (vl-pretty-valuerange (car x)) (vl-pretty-valuerangelist (cdr x))))) (define vl-pretty-patternkey ((x vl-patternkey-p)) :measure (vl-patternkey-count x) (vl-patternkey-case x (:expr (vl-pretty-expr x.key)) (:type (vl-pretty-datatype x.type)) (:default :vl-default))) (define vl-pretty-slicesize ((x vl-slicesize-p)) :measure (vl-slicesize-count x) (vl-slicesize-case x (:expr (vl-pretty-expr x.expr)) (:type (vl-pretty-datatype x.type)) (:none nil))) (define vl-pretty-keyvallist ((x vl-keyvallist-p)) :measure (vl-keyvallist-count x) (b* ((x (vl-keyvallist-fix x)) ((when (atom x)) nil) ((cons key val) (car x))) (cons (list key '<- val) (vl-pretty-keyvallist (cdr x))))) (define vl-pretty-assignpat ((x vl-assignpat-p)) :measure (vl-assignpat-count x) (vl-assignpat-case x (:positional (vl-pretty-exprlist x.vals)) (:keyval (vl-pretty-keyvallist x.pairs)) (:repeat (list :vl-repeat (vl-pretty-expr x.reps) (vl-pretty-exprlist x.vals))))) (define vl-pretty-casttype ((x vl-casttype-p)) :measure (vl-casttype-count x) (vl-casttype-case x :type (vl-pretty-datatype x.type) :size (vl-pretty-expr x.size) :signedness (if x.signedp :signed :unsigned) :const :const)) (define vl-pretty-expr ((x vl-expr-p)) :measure (vl-expr-count x) (vl-expr-case x :vl-special (vl-pretty-specialkey x.key) :vl-literal (vl-pretty-value x.val) :vl-index (b* (((when (vl-idexpr-p x)) (list 'id (vl-idexpr->name x)))) (list :index (vl-pretty-atts x.atts) (vl-pretty-scopeexpr x.scope) (vl-pretty-exprlist x.indices) (vl-pretty-partselect x.part))) :vl-unary (list x.op (vl-pretty-atts x.atts) (vl-pretty-expr x.arg)) :vl-binary (list x.op (vl-pretty-atts x.atts) (vl-pretty-expr x.left) (vl-pretty-expr x.right)) :vl-qmark (list :vl-qmark (vl-pretty-atts x.atts) (vl-pretty-expr x.test) (vl-pretty-expr x.then) (vl-pretty-expr x.else)) :vl-mintypmax (list :vl-mintypmax (vl-pretty-atts x.atts) (vl-pretty-expr x.min) (vl-pretty-expr x.typ) (vl-pretty-expr x.max)) :vl-concat (list* :vl-concat (vl-pretty-atts x.atts) (vl-pretty-exprlist x.parts)) :vl-multiconcat (list* :vl-multiconcat (vl-pretty-atts x.atts) (vl-pretty-expr x.reps) (vl-pretty-exprlist x.parts)) :vl-stream (list* (if (eq x.dir :left) :vl-stream-left :vl-stream-right) (vl-pretty-atts x.atts) (if (vl-slicesize-case x.size :none) (vl-pretty-streamexprlist x.parts) (cons (vl-pretty-slicesize x.size) (vl-pretty-streamexprlist x.parts)))) :vl-call (list* (if x.systemp :vl-syscall :vl-funcall) (vl-pretty-atts x.atts) (vl-pretty-scopeexpr x.name) (if x.typearg (cons (vl-pretty-maybe-datatype x.typearg) (vl-pretty-exprlist x.args)) (vl-pretty-exprlist x.args))) :vl-cast (list :cast (vl-pretty-atts x.atts) (vl-pretty-casttype x.to) (vl-pretty-expr x.expr)) :vl-inside (list* :inside (vl-pretty-atts x.atts) (vl-pretty-expr x.elem) (vl-pretty-valuerangelist x.set)) :vl-tagged (list* :vl-tagged (vl-pretty-atts x.atts) x.tag (if x.expr (list (vl-pretty-maybe-expr x.expr)) nil)) :vl-pattern (list* :pattern (vl-pretty-atts x.atts) (vl-pretty-maybe-datatype x.pattype) (vl-pretty-assignpat x.pat)))) (define vl-pretty-atts ((x vl-atts-p)) :measure (vl-atts-count x) (b* ((x (vl-atts-fix x)) ((when (atom x)) nil) ((cons key val) (car x))) (cons (if val (list key '<- (vl-pretty-maybe-expr val)) key) (vl-pretty-atts (cdr x))))) (define vl-pretty-exprlist ((x vl-exprlist-p)) :measure (vl-exprlist-count x) (if (atom x) nil (cons (vl-pretty-expr (car x)) (vl-pretty-exprlist (cdr x))))) (define vl-pretty-maybe-expr ((x vl-maybe-expr-p)) :measure (vl-maybe-expr-count x) (if x (vl-pretty-expr x) nil)) (define vl-pretty-enumitem ((x vl-enumitem-p)) :measure (vl-enumitem-count x) (b* (((vl-enumitem x) x)) (append (list x.name) (and x.range (list (vl-pretty-maybe-range x.range))) (and x.value (list '= (vl-pretty-maybe-expr x.value)))))) (define vl-pretty-enumitemlist ((x vl-enumitemlist-p)) :measure (vl-enumitemlist-count x) (if (atom x) nil (cons (vl-pretty-enumitem (car x)) (vl-pretty-enumitemlist (cdr x))))) (define vl-pretty-range ((x vl-range-p)) :measure (vl-range-count x) (b* (((vl-range x))) (list :range (vl-pretty-expr x.msb) (vl-pretty-expr x.lsb)))) (define vl-pretty-maybe-range ((x vl-maybe-range-p)) :measure (vl-maybe-range-count x) (if x (vl-pretty-range x) '(no-range))) (define vl-pretty-packeddimension ((x vl-packeddimension-p)) :measure (vl-packeddimension-count x) (vl-packeddimension-case x :unsized :vl-unsized-dimension :range (vl-pretty-range x.range))) (define vl-pretty-packeddimensionlist ((x vl-packeddimensionlist-p)) :measure (vl-packeddimensionlist-count x) (if (atom x) nil (cons (vl-pretty-packeddimension (car x)) (vl-pretty-packeddimensionlist (cdr x))))) (define vl-pretty-maybe-packeddimension ((x vl-maybe-packeddimension-p)) :measure (vl-maybe-packeddimension-count x) (if x (vl-pretty-packeddimension x) nil)) (define vl-pretty-datatype ((x vl-datatype-p)) :measure (vl-datatype-count x) (vl-datatype-case x ;; this is messy but we're trying to be compatible without rewriting all the tests (:vl-coretype (append (list x.name (if x.signedp 'signed 'unsigned)) (and x.pdims (vl-pretty-packeddimensionlist x.pdims)) (and x.udims (cons :udims (vl-pretty-packeddimensionlist x.udims))))) (:vl-struct (append '(:vl-struct) (if x.packedp '(packed) nil) (if x.signedp '(signed) nil) (vl-pretty-structmemberlist x.members) (and x.pdims (cons :dims (vl-pretty-packeddimensionlist x.pdims))) (and x.udims (cons :udims (vl-pretty-packeddimensionlist x.udims))))) (:vl-union (append '(:vl-union) (if x.taggedp '(tagged) nil) (if x.packedp '(packed) nil) (if x.signedp '(signed) nil) (vl-pretty-structmemberlist x.members) (and x.pdims (cons :dims (vl-pretty-packeddimensionlist x.pdims))) (and x.udims (cons :udims (vl-pretty-packeddimensionlist x.udims))))) (:vl-enum (append '(:vl-enum) (vl-pretty-datatype x.basetype) (vl-pretty-enumitemlist x.items) (and x.pdims (cons :dims (vl-pretty-packeddimensionlist x.pdims))) (and x.udims (cons :udims (vl-pretty-packeddimensionlist x.udims))))) (:vl-usertype (append '(:vl-usertype) (list (vl-pretty-scopeexpr x.name)) (and x.pdims (cons :dims (vl-pretty-packeddimensionlist x.pdims))) (and x.udims (cons :udims (vl-pretty-packeddimensionlist x.udims))))))) (define vl-pretty-structmemberlist ((x vl-structmemberlist-p)) :measure (vl-structmemberlist-count x) (if (atom x) nil (cons (vl-pretty-structmember (car x)) (vl-pretty-structmemberlist (cdr x))))) (define vl-pretty-structmember ((x vl-structmember-p)) :measure (vl-structmember-count x) (b* (((vl-structmember x) x)) (append (list x.name) (and x.rand (list x.rand)) (vl-pretty-datatype x.type) (and x.rhs (list '= (vl-pretty-maybe-expr x.rhs)))))) (define vl-pretty-maybe-datatype ((x vl-maybe-datatype-p)) :measure (vl-maybe-datatype-count x) (if x (vl-pretty-datatype x) nil))) (define vl-pretty-range-list ((x vl-rangelist-p)) (if (atom x) nil (cons (vl-pretty-range (car x)) (vl-pretty-range-list (cdr x))))) (define vl-pretty-plainarg ((x vl-plainarg-p)) (let ((expr (vl-plainarg->expr x))) (if (not expr) :blank (vl-pretty-expr expr)))) (define vl-pretty-plainarg-list ((x vl-plainarglist-p)) (if (atom x) nil (cons (vl-pretty-plainarg (car x)) (vl-pretty-plainarg-list (cdr x))))) (define vl-pretty-namedarg ((x vl-namedarg-p)) (let ((name (vl-namedarg->name x)) (expr (vl-namedarg->expr x))) (list name '<-- (if expr (vl-pretty-expr expr) :blank)))) (define vl-pretty-namedarg-list ((x vl-namedarglist-p)) (if (atom x) nil (cons (vl-pretty-namedarg (car x)) (vl-pretty-namedarg-list (cdr x))))) (define vl-pretty-arguments ((x vl-arguments-p)) (vl-arguments-case x :vl-arguments-named (list :namedargs (vl-pretty-namedarg-list x.args)) :vl-arguments-plain (list :plainargs (vl-pretty-plainarg-list x.args)))) (define vl-pretty-fwdtypedef ((x vl-fwdtypedef-p)) (b* (((vl-fwdtypedef x) x)) (list 'fwdtypedef x.kind x.name))) (define vl-pretty-typedef ((x vl-typedef-p)) (b* (((vl-typedef x) x)) (list :vl-typedef x.name (vl-pretty-datatype x.type)))) (define vl-pretty-type-declaration ((x (or (vl-typedef-p x) (vl-fwdtypedef-p x)))) (if (eq (tag x) :vl-fwdtypedef) (vl-pretty-fwdtypedef x) (vl-pretty-typedef x))) (define vl-pretty-evatom ((x vl-evatom-p)) (b* (((vl-evatom x))) (list x.type (vl-pretty-expr x.expr)))) (define vl-pretty-evatomlist ((x vl-evatomlist-p)) (if (atom x) nil (cons (vl-pretty-evatom (car x)) (vl-pretty-evatomlist (cdr x))))) (define vl-pretty-eventcontrol ((x vl-eventcontrol-p)) (b* (((vl-eventcontrol x))) (if x.starp (cons '* (vl-pretty-evatomlist x.atoms)) (vl-pretty-evatomlist x.atoms)))) (define vl-pretty-delaycontrol ((x vl-delaycontrol-p)) (vl-pretty-expr (vl-delaycontrol->value x))) (define vl-pretty-repeateventcontrol ((x vl-repeateventcontrol-p)) (b* (((vl-repeateventcontrol x))) (list :repeat (vl-pretty-expr x.expr) (vl-pretty-eventcontrol x.ctrl)))) (define vl-pretty-delayoreventcontrol ((x vl-delayoreventcontrol-p)) (case (tag x) (:vl-delaycontrol (vl-pretty-delaycontrol x)) (:vl-eventcontrol (vl-pretty-eventcontrol x)) (:vl-repeateventcontrol (vl-pretty-repeateventcontrol x)))) ;; A very useful tracing mechanism for debugging: (defun vl-debug-tokstream (tokstream) (declare (xargs :stobjs tokstream :guard-debug t)) (let* ((tokens (redundant-list-fix (vl-tokstream->tokens))) (n (min 5 (len tokens)))) (vl-tokenlist->string-with-spaces (take n tokens)))) (defmacro trace-parser (fn &key printer) `(trace! (,fn :entry (list ',fn :tokens (vl-debug-tokstream tokstream)) :exit (list ',fn :errmsg (with-local-ps (vl-print-warning (first values))) :val ,(if printer `(with-local-ps (,printer (second values))) `(second values)) :remainder (vl-debug-tokstream (third values))))))
9973
; 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 "../utils") (include-book "../../lexer/lexer") ;; for make-test-tokens, etc. (include-book "../../../parsetree") (include-book "../../../mlib/expr-tools") ; We now introduce a function to convert expressions into a "pretty" format ; which makes it a bit easier to see if an expression is what you expect for ; writing unit tests. ;; (define vl-pretty-atom ((x vl-expr-p)) ;; :guard (vl-atom-p x) ;; (let ((guts (vl-atom->guts x))) ;; (cond ((vl-constint-p guts) (vl-constint->value guts)) ;; ((vl-weirdint-p guts) ;; (list 'weird ;; (vl-bitlist->string (vl-weirdint->bits guts)))) ;; ((vl-string-p guts) (list 'str (vl-string->value guts))) ;; ((vl-real-p guts) (list 'real (vl-real->value guts))) ;; ((vl-id-p guts) (list 'id (vl-id->name guts))) ;; ((vl-hidpiece-p guts) (list 'hid (vl-hidpiece->name guts))) ;; ((vl-funname-p guts) (list 'fun (vl-funname->name guts))) ;; ((vl-typename-p guts) (list 'type (vl-typename->name guts))) ;; ((vl-sysfunname-p guts) (list 'sys (vl-sysfunname->name guts))) ;; ((vl-keyguts-p guts) (list 'key (vl-keyguts->type guts))) ;; ((vl-basictype-p guts) (list 'basic (vl-basictype->kind guts))) ;; ((vl-tagname-p guts) (list 'tag (vl-tagname->name guts))) ;; ((vl-time-p guts) ;; (list 'time ;; (concatenate 'string ;; (vl-time->quantity guts) ;; (vl-timeunit->string ;; (vl-time->units guts))))) ;; ((vl-extint-p guts) ;; (list 'ext (vl-extint->value guts))) ;; (t ;; (raise "Unsupported kind of atom: ~x0." x))))) (define vl-pretty-value ((x vl-value-p)) (vl-value-case x :vl-constint x.value :vl-weirdint (list 'weird x.bits) :vl-extint (list 'ext x.value) :vl-real (list 'real x.value) :vl-time (list 'time (str::cat x.quantity (vl-timeunit->string x.units))) :vl-string (list 'str x.value))) (define vl-pretty-scopename ((x vl-scopename-p)) (let ((x (vl-scopename-fix x))) (case x (:vl-local '(key :vl-local)) (:vl-$unit '(key :vl-$unit)) (t x)))) (define vl-pretty-hidname ((x vl-hidname-p)) (let ((x (vl-hidname-fix x))) (case x (:vl-$root '(key :vl-$root)) (otherwise x)))) (define vl-pretty-specialkey ((x vl-specialkey-p)) (let ((x (vl-specialkey-fix x))) (case x (:vl-null '(key :vl-null)) (:vl-$ '(key :vl-$)) (:vl-emptyqueue '(key :vl-emptyqueue))))) (defines vl-pretty-exprs :flag nil (define vl-pretty-hidindex ((x vl-hidindex-p)) :measure (vl-hidindex-count x) (b* (((vl-hidindex x)) ((unless x.indices) x.name)) (list :vl-hid-index (vl-pretty-hidname x.name) (vl-pretty-exprlist x.indices)))) (define vl-pretty-hidexpr ((x vl-hidexpr-p)) :measure (vl-hidexpr-count x) (vl-hidexpr-case x (:end x.name) (:dot (list :dot (vl-pretty-hidindex x.first) (vl-pretty-hidexpr x.rest))))) (define vl-pretty-scopeexpr ((x vl-scopeexpr-p)) :measure (vl-scopeexpr-count x) (vl-scopeexpr-case x (:end (vl-pretty-hidexpr x.hid)) (:colon (list :scope (vl-pretty-scopename x.first) (vl-pretty-scopeexpr x.rest))))) (define vl-pretty-plusminus ((x vl-plusminus-p)) :measure (vl-plusminus-count x) (b* (((vl-plusminus x))) (list (if x.minusp :minuscolon :pluscolon) (vl-pretty-expr x.base) (vl-pretty-expr x.width)))) (define vl-pretty-partselect ((x vl-partselect-p)) :measure (vl-partselect-count x) (vl-partselect-case x (:none nil) (:range (list :colon (vl-pretty-expr x.msb) (vl-pretty-expr x.lsb))) (:plusminus (vl-pretty-plusminus x.plusminus)))) (define vl-pretty-arrayrange ((x vl-arrayrange-p)) :measure (vl-arrayrange-count x) (vl-arrayrange-case x (:none nil) (:range (vl-pretty-range x.range)) (:plusminus (vl-pretty-plusminus x.plusminus)) (:index (list :arrindex (vl-pretty-expr x.expr))))) (define vl-pretty-streamexpr ((x vl-streamexpr-p)) :measure (vl-streamexpr-count x) (b* (((vl-streamexpr x)) ((when (vl-arrayrange-case x.part :none)) (vl-pretty-expr x.expr))) (list (vl-pretty-expr x.expr) :with (vl-pretty-arrayrange x.part)))) (define vl-pretty-streamexprlist ((x vl-streamexprlist-p)) :measure (vl-streamexprlist-count x) (if (atom x) nil (cons (vl-pretty-streamexpr (car x)) (vl-pretty-streamexprlist (cdr x))))) (define vl-pretty-valuerange ((x vl-valuerange-p)) :measure (vl-valuerange-count x) (vl-valuerange-case x (:range (vl-pretty-range x.range)) (:single (vl-pretty-expr x.expr)))) (define vl-pretty-valuerangelist ((x vl-valuerangelist-p)) :measure (vl-valuerangelist-count x) (if (atom x) nil (cons (vl-pretty-valuerange (car x)) (vl-pretty-valuerangelist (cdr x))))) (define vl-pretty-patternkey ((x vl-patternkey-p)) :measure (vl-patternkey-count x) (vl-patternkey-case x (:expr (vl-pretty-expr x.key)) (:type (vl-pretty-datatype x.type)) (:default :vl-default))) (define vl-pretty-slicesize ((x vl-slicesize-p)) :measure (vl-slicesize-count x) (vl-slicesize-case x (:expr (vl-pretty-expr x.expr)) (:type (vl-pretty-datatype x.type)) (:none nil))) (define vl-pretty-keyvallist ((x vl-keyvallist-p)) :measure (vl-keyvallist-count x) (b* ((x (vl-keyvallist-fix x)) ((when (atom x)) nil) ((cons key val) (car x))) (cons (list key '<- val) (vl-pretty-keyvallist (cdr x))))) (define vl-pretty-assignpat ((x vl-assignpat-p)) :measure (vl-assignpat-count x) (vl-assignpat-case x (:positional (vl-pretty-exprlist x.vals)) (:keyval (vl-pretty-keyvallist x.pairs)) (:repeat (list :vl-repeat (vl-pretty-expr x.reps) (vl-pretty-exprlist x.vals))))) (define vl-pretty-casttype ((x vl-casttype-p)) :measure (vl-casttype-count x) (vl-casttype-case x :type (vl-pretty-datatype x.type) :size (vl-pretty-expr x.size) :signedness (if x.signedp :signed :unsigned) :const :const)) (define vl-pretty-expr ((x vl-expr-p)) :measure (vl-expr-count x) (vl-expr-case x :vl-special (vl-pretty-specialkey x.key) :vl-literal (vl-pretty-value x.val) :vl-index (b* (((when (vl-idexpr-p x)) (list 'id (vl-idexpr->name x)))) (list :index (vl-pretty-atts x.atts) (vl-pretty-scopeexpr x.scope) (vl-pretty-exprlist x.indices) (vl-pretty-partselect x.part))) :vl-unary (list x.op (vl-pretty-atts x.atts) (vl-pretty-expr x.arg)) :vl-binary (list x.op (vl-pretty-atts x.atts) (vl-pretty-expr x.left) (vl-pretty-expr x.right)) :vl-qmark (list :vl-qmark (vl-pretty-atts x.atts) (vl-pretty-expr x.test) (vl-pretty-expr x.then) (vl-pretty-expr x.else)) :vl-mintypmax (list :vl-mintypmax (vl-pretty-atts x.atts) (vl-pretty-expr x.min) (vl-pretty-expr x.typ) (vl-pretty-expr x.max)) :vl-concat (list* :vl-concat (vl-pretty-atts x.atts) (vl-pretty-exprlist x.parts)) :vl-multiconcat (list* :vl-multiconcat (vl-pretty-atts x.atts) (vl-pretty-expr x.reps) (vl-pretty-exprlist x.parts)) :vl-stream (list* (if (eq x.dir :left) :vl-stream-left :vl-stream-right) (vl-pretty-atts x.atts) (if (vl-slicesize-case x.size :none) (vl-pretty-streamexprlist x.parts) (cons (vl-pretty-slicesize x.size) (vl-pretty-streamexprlist x.parts)))) :vl-call (list* (if x.systemp :vl-syscall :vl-funcall) (vl-pretty-atts x.atts) (vl-pretty-scopeexpr x.name) (if x.typearg (cons (vl-pretty-maybe-datatype x.typearg) (vl-pretty-exprlist x.args)) (vl-pretty-exprlist x.args))) :vl-cast (list :cast (vl-pretty-atts x.atts) (vl-pretty-casttype x.to) (vl-pretty-expr x.expr)) :vl-inside (list* :inside (vl-pretty-atts x.atts) (vl-pretty-expr x.elem) (vl-pretty-valuerangelist x.set)) :vl-tagged (list* :vl-tagged (vl-pretty-atts x.atts) x.tag (if x.expr (list (vl-pretty-maybe-expr x.expr)) nil)) :vl-pattern (list* :pattern (vl-pretty-atts x.atts) (vl-pretty-maybe-datatype x.pattype) (vl-pretty-assignpat x.pat)))) (define vl-pretty-atts ((x vl-atts-p)) :measure (vl-atts-count x) (b* ((x (vl-atts-fix x)) ((when (atom x)) nil) ((cons key val) (car x))) (cons (if val (list key '<- (vl-pretty-maybe-expr val)) key) (vl-pretty-atts (cdr x))))) (define vl-pretty-exprlist ((x vl-exprlist-p)) :measure (vl-exprlist-count x) (if (atom x) nil (cons (vl-pretty-expr (car x)) (vl-pretty-exprlist (cdr x))))) (define vl-pretty-maybe-expr ((x vl-maybe-expr-p)) :measure (vl-maybe-expr-count x) (if x (vl-pretty-expr x) nil)) (define vl-pretty-enumitem ((x vl-enumitem-p)) :measure (vl-enumitem-count x) (b* (((vl-enumitem x) x)) (append (list x.name) (and x.range (list (vl-pretty-maybe-range x.range))) (and x.value (list '= (vl-pretty-maybe-expr x.value)))))) (define vl-pretty-enumitemlist ((x vl-enumitemlist-p)) :measure (vl-enumitemlist-count x) (if (atom x) nil (cons (vl-pretty-enumitem (car x)) (vl-pretty-enumitemlist (cdr x))))) (define vl-pretty-range ((x vl-range-p)) :measure (vl-range-count x) (b* (((vl-range x))) (list :range (vl-pretty-expr x.msb) (vl-pretty-expr x.lsb)))) (define vl-pretty-maybe-range ((x vl-maybe-range-p)) :measure (vl-maybe-range-count x) (if x (vl-pretty-range x) '(no-range))) (define vl-pretty-packeddimension ((x vl-packeddimension-p)) :measure (vl-packeddimension-count x) (vl-packeddimension-case x :unsized :vl-unsized-dimension :range (vl-pretty-range x.range))) (define vl-pretty-packeddimensionlist ((x vl-packeddimensionlist-p)) :measure (vl-packeddimensionlist-count x) (if (atom x) nil (cons (vl-pretty-packeddimension (car x)) (vl-pretty-packeddimensionlist (cdr x))))) (define vl-pretty-maybe-packeddimension ((x vl-maybe-packeddimension-p)) :measure (vl-maybe-packeddimension-count x) (if x (vl-pretty-packeddimension x) nil)) (define vl-pretty-datatype ((x vl-datatype-p)) :measure (vl-datatype-count x) (vl-datatype-case x ;; this is messy but we're trying to be compatible without rewriting all the tests (:vl-coretype (append (list x.name (if x.signedp 'signed 'unsigned)) (and x.pdims (vl-pretty-packeddimensionlist x.pdims)) (and x.udims (cons :udims (vl-pretty-packeddimensionlist x.udims))))) (:vl-struct (append '(:vl-struct) (if x.packedp '(packed) nil) (if x.signedp '(signed) nil) (vl-pretty-structmemberlist x.members) (and x.pdims (cons :dims (vl-pretty-packeddimensionlist x.pdims))) (and x.udims (cons :udims (vl-pretty-packeddimensionlist x.udims))))) (:vl-union (append '(:vl-union) (if x.taggedp '(tagged) nil) (if x.packedp '(packed) nil) (if x.signedp '(signed) nil) (vl-pretty-structmemberlist x.members) (and x.pdims (cons :dims (vl-pretty-packeddimensionlist x.pdims))) (and x.udims (cons :udims (vl-pretty-packeddimensionlist x.udims))))) (:vl-enum (append '(:vl-enum) (vl-pretty-datatype x.basetype) (vl-pretty-enumitemlist x.items) (and x.pdims (cons :dims (vl-pretty-packeddimensionlist x.pdims))) (and x.udims (cons :udims (vl-pretty-packeddimensionlist x.udims))))) (:vl-usertype (append '(:vl-usertype) (list (vl-pretty-scopeexpr x.name)) (and x.pdims (cons :dims (vl-pretty-packeddimensionlist x.pdims))) (and x.udims (cons :udims (vl-pretty-packeddimensionlist x.udims))))))) (define vl-pretty-structmemberlist ((x vl-structmemberlist-p)) :measure (vl-structmemberlist-count x) (if (atom x) nil (cons (vl-pretty-structmember (car x)) (vl-pretty-structmemberlist (cdr x))))) (define vl-pretty-structmember ((x vl-structmember-p)) :measure (vl-structmember-count x) (b* (((vl-structmember x) x)) (append (list x.name) (and x.rand (list x.rand)) (vl-pretty-datatype x.type) (and x.rhs (list '= (vl-pretty-maybe-expr x.rhs)))))) (define vl-pretty-maybe-datatype ((x vl-maybe-datatype-p)) :measure (vl-maybe-datatype-count x) (if x (vl-pretty-datatype x) nil))) (define vl-pretty-range-list ((x vl-rangelist-p)) (if (atom x) nil (cons (vl-pretty-range (car x)) (vl-pretty-range-list (cdr x))))) (define vl-pretty-plainarg ((x vl-plainarg-p)) (let ((expr (vl-plainarg->expr x))) (if (not expr) :blank (vl-pretty-expr expr)))) (define vl-pretty-plainarg-list ((x vl-plainarglist-p)) (if (atom x) nil (cons (vl-pretty-plainarg (car x)) (vl-pretty-plainarg-list (cdr x))))) (define vl-pretty-namedarg ((x vl-namedarg-p)) (let ((name (vl-namedarg->name x)) (expr (vl-namedarg->expr x))) (list name '<-- (if expr (vl-pretty-expr expr) :blank)))) (define vl-pretty-namedarg-list ((x vl-namedarglist-p)) (if (atom x) nil (cons (vl-pretty-namedarg (car x)) (vl-pretty-namedarg-list (cdr x))))) (define vl-pretty-arguments ((x vl-arguments-p)) (vl-arguments-case x :vl-arguments-named (list :namedargs (vl-pretty-namedarg-list x.args)) :vl-arguments-plain (list :plainargs (vl-pretty-plainarg-list x.args)))) (define vl-pretty-fwdtypedef ((x vl-fwdtypedef-p)) (b* (((vl-fwdtypedef x) x)) (list 'fwdtypedef x.kind x.name))) (define vl-pretty-typedef ((x vl-typedef-p)) (b* (((vl-typedef x) x)) (list :vl-typedef x.name (vl-pretty-datatype x.type)))) (define vl-pretty-type-declaration ((x (or (vl-typedef-p x) (vl-fwdtypedef-p x)))) (if (eq (tag x) :vl-fwdtypedef) (vl-pretty-fwdtypedef x) (vl-pretty-typedef x))) (define vl-pretty-evatom ((x vl-evatom-p)) (b* (((vl-evatom x))) (list x.type (vl-pretty-expr x.expr)))) (define vl-pretty-evatomlist ((x vl-evatomlist-p)) (if (atom x) nil (cons (vl-pretty-evatom (car x)) (vl-pretty-evatomlist (cdr x))))) (define vl-pretty-eventcontrol ((x vl-eventcontrol-p)) (b* (((vl-eventcontrol x))) (if x.starp (cons '* (vl-pretty-evatomlist x.atoms)) (vl-pretty-evatomlist x.atoms)))) (define vl-pretty-delaycontrol ((x vl-delaycontrol-p)) (vl-pretty-expr (vl-delaycontrol->value x))) (define vl-pretty-repeateventcontrol ((x vl-repeateventcontrol-p)) (b* (((vl-repeateventcontrol x))) (list :repeat (vl-pretty-expr x.expr) (vl-pretty-eventcontrol x.ctrl)))) (define vl-pretty-delayoreventcontrol ((x vl-delayoreventcontrol-p)) (case (tag x) (:vl-delaycontrol (vl-pretty-delaycontrol x)) (:vl-eventcontrol (vl-pretty-eventcontrol x)) (:vl-repeateventcontrol (vl-pretty-repeateventcontrol x)))) ;; A very useful tracing mechanism for debugging: (defun vl-debug-tokstream (tokstream) (declare (xargs :stobjs tokstream :guard-debug t)) (let* ((tokens (redundant-list-fix (vl-tokstream->tokens))) (n (min 5 (len tokens)))) (vl-tokenlist->string-with-spaces (take n tokens)))) (defmacro trace-parser (fn &key printer) `(trace! (,fn :entry (list ',fn :tokens (vl-debug-tokstream tokstream)) :exit (list ',fn :errmsg (with-local-ps (vl-print-warning (first values))) :val ,(if printer `(with-local-ps (,printer (second values))) `(second values)) :remainder (vl-debug-tokstream (third values))))))
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 "../utils") (include-book "../../lexer/lexer") ;; for make-test-tokens, etc. (include-book "../../../parsetree") (include-book "../../../mlib/expr-tools") ; We now introduce a function to convert expressions into a "pretty" format ; which makes it a bit easier to see if an expression is what you expect for ; writing unit tests. ;; (define vl-pretty-atom ((x vl-expr-p)) ;; :guard (vl-atom-p x) ;; (let ((guts (vl-atom->guts x))) ;; (cond ((vl-constint-p guts) (vl-constint->value guts)) ;; ((vl-weirdint-p guts) ;; (list 'weird ;; (vl-bitlist->string (vl-weirdint->bits guts)))) ;; ((vl-string-p guts) (list 'str (vl-string->value guts))) ;; ((vl-real-p guts) (list 'real (vl-real->value guts))) ;; ((vl-id-p guts) (list 'id (vl-id->name guts))) ;; ((vl-hidpiece-p guts) (list 'hid (vl-hidpiece->name guts))) ;; ((vl-funname-p guts) (list 'fun (vl-funname->name guts))) ;; ((vl-typename-p guts) (list 'type (vl-typename->name guts))) ;; ((vl-sysfunname-p guts) (list 'sys (vl-sysfunname->name guts))) ;; ((vl-keyguts-p guts) (list 'key (vl-keyguts->type guts))) ;; ((vl-basictype-p guts) (list 'basic (vl-basictype->kind guts))) ;; ((vl-tagname-p guts) (list 'tag (vl-tagname->name guts))) ;; ((vl-time-p guts) ;; (list 'time ;; (concatenate 'string ;; (vl-time->quantity guts) ;; (vl-timeunit->string ;; (vl-time->units guts))))) ;; ((vl-extint-p guts) ;; (list 'ext (vl-extint->value guts))) ;; (t ;; (raise "Unsupported kind of atom: ~x0." x))))) (define vl-pretty-value ((x vl-value-p)) (vl-value-case x :vl-constint x.value :vl-weirdint (list 'weird x.bits) :vl-extint (list 'ext x.value) :vl-real (list 'real x.value) :vl-time (list 'time (str::cat x.quantity (vl-timeunit->string x.units))) :vl-string (list 'str x.value))) (define vl-pretty-scopename ((x vl-scopename-p)) (let ((x (vl-scopename-fix x))) (case x (:vl-local '(key :vl-local)) (:vl-$unit '(key :vl-$unit)) (t x)))) (define vl-pretty-hidname ((x vl-hidname-p)) (let ((x (vl-hidname-fix x))) (case x (:vl-$root '(key :vl-$root)) (otherwise x)))) (define vl-pretty-specialkey ((x vl-specialkey-p)) (let ((x (vl-specialkey-fix x))) (case x (:vl-null '(key :vl-null)) (:vl-$ '(key :vl-$)) (:vl-emptyqueue '(key :vl-emptyqueue))))) (defines vl-pretty-exprs :flag nil (define vl-pretty-hidindex ((x vl-hidindex-p)) :measure (vl-hidindex-count x) (b* (((vl-hidindex x)) ((unless x.indices) x.name)) (list :vl-hid-index (vl-pretty-hidname x.name) (vl-pretty-exprlist x.indices)))) (define vl-pretty-hidexpr ((x vl-hidexpr-p)) :measure (vl-hidexpr-count x) (vl-hidexpr-case x (:end x.name) (:dot (list :dot (vl-pretty-hidindex x.first) (vl-pretty-hidexpr x.rest))))) (define vl-pretty-scopeexpr ((x vl-scopeexpr-p)) :measure (vl-scopeexpr-count x) (vl-scopeexpr-case x (:end (vl-pretty-hidexpr x.hid)) (:colon (list :scope (vl-pretty-scopename x.first) (vl-pretty-scopeexpr x.rest))))) (define vl-pretty-plusminus ((x vl-plusminus-p)) :measure (vl-plusminus-count x) (b* (((vl-plusminus x))) (list (if x.minusp :minuscolon :pluscolon) (vl-pretty-expr x.base) (vl-pretty-expr x.width)))) (define vl-pretty-partselect ((x vl-partselect-p)) :measure (vl-partselect-count x) (vl-partselect-case x (:none nil) (:range (list :colon (vl-pretty-expr x.msb) (vl-pretty-expr x.lsb))) (:plusminus (vl-pretty-plusminus x.plusminus)))) (define vl-pretty-arrayrange ((x vl-arrayrange-p)) :measure (vl-arrayrange-count x) (vl-arrayrange-case x (:none nil) (:range (vl-pretty-range x.range)) (:plusminus (vl-pretty-plusminus x.plusminus)) (:index (list :arrindex (vl-pretty-expr x.expr))))) (define vl-pretty-streamexpr ((x vl-streamexpr-p)) :measure (vl-streamexpr-count x) (b* (((vl-streamexpr x)) ((when (vl-arrayrange-case x.part :none)) (vl-pretty-expr x.expr))) (list (vl-pretty-expr x.expr) :with (vl-pretty-arrayrange x.part)))) (define vl-pretty-streamexprlist ((x vl-streamexprlist-p)) :measure (vl-streamexprlist-count x) (if (atom x) nil (cons (vl-pretty-streamexpr (car x)) (vl-pretty-streamexprlist (cdr x))))) (define vl-pretty-valuerange ((x vl-valuerange-p)) :measure (vl-valuerange-count x) (vl-valuerange-case x (:range (vl-pretty-range x.range)) (:single (vl-pretty-expr x.expr)))) (define vl-pretty-valuerangelist ((x vl-valuerangelist-p)) :measure (vl-valuerangelist-count x) (if (atom x) nil (cons (vl-pretty-valuerange (car x)) (vl-pretty-valuerangelist (cdr x))))) (define vl-pretty-patternkey ((x vl-patternkey-p)) :measure (vl-patternkey-count x) (vl-patternkey-case x (:expr (vl-pretty-expr x.key)) (:type (vl-pretty-datatype x.type)) (:default :vl-default))) (define vl-pretty-slicesize ((x vl-slicesize-p)) :measure (vl-slicesize-count x) (vl-slicesize-case x (:expr (vl-pretty-expr x.expr)) (:type (vl-pretty-datatype x.type)) (:none nil))) (define vl-pretty-keyvallist ((x vl-keyvallist-p)) :measure (vl-keyvallist-count x) (b* ((x (vl-keyvallist-fix x)) ((when (atom x)) nil) ((cons key val) (car x))) (cons (list key '<- val) (vl-pretty-keyvallist (cdr x))))) (define vl-pretty-assignpat ((x vl-assignpat-p)) :measure (vl-assignpat-count x) (vl-assignpat-case x (:positional (vl-pretty-exprlist x.vals)) (:keyval (vl-pretty-keyvallist x.pairs)) (:repeat (list :vl-repeat (vl-pretty-expr x.reps) (vl-pretty-exprlist x.vals))))) (define vl-pretty-casttype ((x vl-casttype-p)) :measure (vl-casttype-count x) (vl-casttype-case x :type (vl-pretty-datatype x.type) :size (vl-pretty-expr x.size) :signedness (if x.signedp :signed :unsigned) :const :const)) (define vl-pretty-expr ((x vl-expr-p)) :measure (vl-expr-count x) (vl-expr-case x :vl-special (vl-pretty-specialkey x.key) :vl-literal (vl-pretty-value x.val) :vl-index (b* (((when (vl-idexpr-p x)) (list 'id (vl-idexpr->name x)))) (list :index (vl-pretty-atts x.atts) (vl-pretty-scopeexpr x.scope) (vl-pretty-exprlist x.indices) (vl-pretty-partselect x.part))) :vl-unary (list x.op (vl-pretty-atts x.atts) (vl-pretty-expr x.arg)) :vl-binary (list x.op (vl-pretty-atts x.atts) (vl-pretty-expr x.left) (vl-pretty-expr x.right)) :vl-qmark (list :vl-qmark (vl-pretty-atts x.atts) (vl-pretty-expr x.test) (vl-pretty-expr x.then) (vl-pretty-expr x.else)) :vl-mintypmax (list :vl-mintypmax (vl-pretty-atts x.atts) (vl-pretty-expr x.min) (vl-pretty-expr x.typ) (vl-pretty-expr x.max)) :vl-concat (list* :vl-concat (vl-pretty-atts x.atts) (vl-pretty-exprlist x.parts)) :vl-multiconcat (list* :vl-multiconcat (vl-pretty-atts x.atts) (vl-pretty-expr x.reps) (vl-pretty-exprlist x.parts)) :vl-stream (list* (if (eq x.dir :left) :vl-stream-left :vl-stream-right) (vl-pretty-atts x.atts) (if (vl-slicesize-case x.size :none) (vl-pretty-streamexprlist x.parts) (cons (vl-pretty-slicesize x.size) (vl-pretty-streamexprlist x.parts)))) :vl-call (list* (if x.systemp :vl-syscall :vl-funcall) (vl-pretty-atts x.atts) (vl-pretty-scopeexpr x.name) (if x.typearg (cons (vl-pretty-maybe-datatype x.typearg) (vl-pretty-exprlist x.args)) (vl-pretty-exprlist x.args))) :vl-cast (list :cast (vl-pretty-atts x.atts) (vl-pretty-casttype x.to) (vl-pretty-expr x.expr)) :vl-inside (list* :inside (vl-pretty-atts x.atts) (vl-pretty-expr x.elem) (vl-pretty-valuerangelist x.set)) :vl-tagged (list* :vl-tagged (vl-pretty-atts x.atts) x.tag (if x.expr (list (vl-pretty-maybe-expr x.expr)) nil)) :vl-pattern (list* :pattern (vl-pretty-atts x.atts) (vl-pretty-maybe-datatype x.pattype) (vl-pretty-assignpat x.pat)))) (define vl-pretty-atts ((x vl-atts-p)) :measure (vl-atts-count x) (b* ((x (vl-atts-fix x)) ((when (atom x)) nil) ((cons key val) (car x))) (cons (if val (list key '<- (vl-pretty-maybe-expr val)) key) (vl-pretty-atts (cdr x))))) (define vl-pretty-exprlist ((x vl-exprlist-p)) :measure (vl-exprlist-count x) (if (atom x) nil (cons (vl-pretty-expr (car x)) (vl-pretty-exprlist (cdr x))))) (define vl-pretty-maybe-expr ((x vl-maybe-expr-p)) :measure (vl-maybe-expr-count x) (if x (vl-pretty-expr x) nil)) (define vl-pretty-enumitem ((x vl-enumitem-p)) :measure (vl-enumitem-count x) (b* (((vl-enumitem x) x)) (append (list x.name) (and x.range (list (vl-pretty-maybe-range x.range))) (and x.value (list '= (vl-pretty-maybe-expr x.value)))))) (define vl-pretty-enumitemlist ((x vl-enumitemlist-p)) :measure (vl-enumitemlist-count x) (if (atom x) nil (cons (vl-pretty-enumitem (car x)) (vl-pretty-enumitemlist (cdr x))))) (define vl-pretty-range ((x vl-range-p)) :measure (vl-range-count x) (b* (((vl-range x))) (list :range (vl-pretty-expr x.msb) (vl-pretty-expr x.lsb)))) (define vl-pretty-maybe-range ((x vl-maybe-range-p)) :measure (vl-maybe-range-count x) (if x (vl-pretty-range x) '(no-range))) (define vl-pretty-packeddimension ((x vl-packeddimension-p)) :measure (vl-packeddimension-count x) (vl-packeddimension-case x :unsized :vl-unsized-dimension :range (vl-pretty-range x.range))) (define vl-pretty-packeddimensionlist ((x vl-packeddimensionlist-p)) :measure (vl-packeddimensionlist-count x) (if (atom x) nil (cons (vl-pretty-packeddimension (car x)) (vl-pretty-packeddimensionlist (cdr x))))) (define vl-pretty-maybe-packeddimension ((x vl-maybe-packeddimension-p)) :measure (vl-maybe-packeddimension-count x) (if x (vl-pretty-packeddimension x) nil)) (define vl-pretty-datatype ((x vl-datatype-p)) :measure (vl-datatype-count x) (vl-datatype-case x ;; this is messy but we're trying to be compatible without rewriting all the tests (:vl-coretype (append (list x.name (if x.signedp 'signed 'unsigned)) (and x.pdims (vl-pretty-packeddimensionlist x.pdims)) (and x.udims (cons :udims (vl-pretty-packeddimensionlist x.udims))))) (:vl-struct (append '(:vl-struct) (if x.packedp '(packed) nil) (if x.signedp '(signed) nil) (vl-pretty-structmemberlist x.members) (and x.pdims (cons :dims (vl-pretty-packeddimensionlist x.pdims))) (and x.udims (cons :udims (vl-pretty-packeddimensionlist x.udims))))) (:vl-union (append '(:vl-union) (if x.taggedp '(tagged) nil) (if x.packedp '(packed) nil) (if x.signedp '(signed) nil) (vl-pretty-structmemberlist x.members) (and x.pdims (cons :dims (vl-pretty-packeddimensionlist x.pdims))) (and x.udims (cons :udims (vl-pretty-packeddimensionlist x.udims))))) (:vl-enum (append '(:vl-enum) (vl-pretty-datatype x.basetype) (vl-pretty-enumitemlist x.items) (and x.pdims (cons :dims (vl-pretty-packeddimensionlist x.pdims))) (and x.udims (cons :udims (vl-pretty-packeddimensionlist x.udims))))) (:vl-usertype (append '(:vl-usertype) (list (vl-pretty-scopeexpr x.name)) (and x.pdims (cons :dims (vl-pretty-packeddimensionlist x.pdims))) (and x.udims (cons :udims (vl-pretty-packeddimensionlist x.udims))))))) (define vl-pretty-structmemberlist ((x vl-structmemberlist-p)) :measure (vl-structmemberlist-count x) (if (atom x) nil (cons (vl-pretty-structmember (car x)) (vl-pretty-structmemberlist (cdr x))))) (define vl-pretty-structmember ((x vl-structmember-p)) :measure (vl-structmember-count x) (b* (((vl-structmember x) x)) (append (list x.name) (and x.rand (list x.rand)) (vl-pretty-datatype x.type) (and x.rhs (list '= (vl-pretty-maybe-expr x.rhs)))))) (define vl-pretty-maybe-datatype ((x vl-maybe-datatype-p)) :measure (vl-maybe-datatype-count x) (if x (vl-pretty-datatype x) nil))) (define vl-pretty-range-list ((x vl-rangelist-p)) (if (atom x) nil (cons (vl-pretty-range (car x)) (vl-pretty-range-list (cdr x))))) (define vl-pretty-plainarg ((x vl-plainarg-p)) (let ((expr (vl-plainarg->expr x))) (if (not expr) :blank (vl-pretty-expr expr)))) (define vl-pretty-plainarg-list ((x vl-plainarglist-p)) (if (atom x) nil (cons (vl-pretty-plainarg (car x)) (vl-pretty-plainarg-list (cdr x))))) (define vl-pretty-namedarg ((x vl-namedarg-p)) (let ((name (vl-namedarg->name x)) (expr (vl-namedarg->expr x))) (list name '<-- (if expr (vl-pretty-expr expr) :blank)))) (define vl-pretty-namedarg-list ((x vl-namedarglist-p)) (if (atom x) nil (cons (vl-pretty-namedarg (car x)) (vl-pretty-namedarg-list (cdr x))))) (define vl-pretty-arguments ((x vl-arguments-p)) (vl-arguments-case x :vl-arguments-named (list :namedargs (vl-pretty-namedarg-list x.args)) :vl-arguments-plain (list :plainargs (vl-pretty-plainarg-list x.args)))) (define vl-pretty-fwdtypedef ((x vl-fwdtypedef-p)) (b* (((vl-fwdtypedef x) x)) (list 'fwdtypedef x.kind x.name))) (define vl-pretty-typedef ((x vl-typedef-p)) (b* (((vl-typedef x) x)) (list :vl-typedef x.name (vl-pretty-datatype x.type)))) (define vl-pretty-type-declaration ((x (or (vl-typedef-p x) (vl-fwdtypedef-p x)))) (if (eq (tag x) :vl-fwdtypedef) (vl-pretty-fwdtypedef x) (vl-pretty-typedef x))) (define vl-pretty-evatom ((x vl-evatom-p)) (b* (((vl-evatom x))) (list x.type (vl-pretty-expr x.expr)))) (define vl-pretty-evatomlist ((x vl-evatomlist-p)) (if (atom x) nil (cons (vl-pretty-evatom (car x)) (vl-pretty-evatomlist (cdr x))))) (define vl-pretty-eventcontrol ((x vl-eventcontrol-p)) (b* (((vl-eventcontrol x))) (if x.starp (cons '* (vl-pretty-evatomlist x.atoms)) (vl-pretty-evatomlist x.atoms)))) (define vl-pretty-delaycontrol ((x vl-delaycontrol-p)) (vl-pretty-expr (vl-delaycontrol->value x))) (define vl-pretty-repeateventcontrol ((x vl-repeateventcontrol-p)) (b* (((vl-repeateventcontrol x))) (list :repeat (vl-pretty-expr x.expr) (vl-pretty-eventcontrol x.ctrl)))) (define vl-pretty-delayoreventcontrol ((x vl-delayoreventcontrol-p)) (case (tag x) (:vl-delaycontrol (vl-pretty-delaycontrol x)) (:vl-eventcontrol (vl-pretty-eventcontrol x)) (:vl-repeateventcontrol (vl-pretty-repeateventcontrol x)))) ;; A very useful tracing mechanism for debugging: (defun vl-debug-tokstream (tokstream) (declare (xargs :stobjs tokstream :guard-debug t)) (let* ((tokens (redundant-list-fix (vl-tokstream->tokens))) (n (min 5 (len tokens)))) (vl-tokenlist->string-with-spaces (take n tokens)))) (defmacro trace-parser (fn &key printer) `(trace! (,fn :entry (list ',fn :tokens (vl-debug-tokstream tokstream)) :exit (list ',fn :errmsg (with-local-ps (vl-print-warning (first values))) :val ,(if printer `(with-local-ps (,printer (second values))) `(second values)) :remainder (vl-debug-tokstream (third values))))))
[ { "context": "ense. See the file books/3BSD-mod.txt.\n;\n; Author: Eric Smith ([email protected])\n\n;;;;;;;;;;;;;;;;;;;;;;;", "end": 159, "score": 0.9988794326782227, "start": 149, "tag": "NAME", "value": "Eric Smith" }, { "context": " file books/3BSD-mod.txt.\n;\n; Author: Eric Smith ([email protected])\n\n;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;", "end": 183, "score": 0.9999289512634277, "start": 161, "tag": "EMAIL", "value": "[email protected]" } ]
books/kestrel/axe/get-disjuncts-tests.lisp
mayankmanj/acl2
305
; Tests for get-disjuncts ; ; Copyright (C) 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 "get-disjuncts") (include-book "make-term-into-dag-array-basic") (include-book "dag-to-term") (include-book "dag-array-printing") (defund get-disjuncts-tester (term state) (declare (xargs :stobjs state :mode :program)) (b* ((term (translate-term term 'get-disjuncts-tester (w state))) ((mv erp nodenum-or-quotep dag-array dag-len dag-parent-array dag-constant-alist dag-variable-alist) (make-term-into-dag-array-basic term 'dag-array 'dag-parent-array nil)) ((when erp) (er hard? 'get-disjuncts-tester "Error making term.")) ((mv erp provedp disjuncts dag-array & ; dag-len & & & ;dag-parent-array dag-constant-alist dag-variable-alist ) (get-darg-disjuncts nodenum-or-quotep dag-array dag-len dag-parent-array dag-constant-alist dag-variable-alist nil ;acc nil ;negated-flg t ;print )) ((when erp) (er hard? 'get-disjuncts-tester "Error getting disjuncts."))) (if provedp :proved ;; todo: return these, as terms, instead of printing them: (print-dag-only-supporters-lst disjuncts 'dag-array dag-array)))) ;; TODO: Get these into the build: ;; (get-disjuncts-tester 'x state) ;; (get-disjuncts-tester '(boolor x y) state) ;; (get-disjuncts-tester '(boolor x t) state) ;; (get-disjuncts-tester '(boolor t y) state) ;; (get-disjuncts-tester '(boolor x nil) state) ;; (get-disjuncts-tester '(boolor nil y) state) ;; (get-disjuncts-tester '(not x) state) ;; (get-disjuncts-tester '(not (not x)) state) ;; (get-disjuncts-tester '(not (booland x y)) state) ;; (get-disjuncts-tester '(not (booland nil y)) state) ;; (get-disjuncts-tester '(not (booland x nil)) state) ;; (get-disjuncts-tester '(not (booland t y)) state) ;; (get-disjuncts-tester '(not (booland x t)) state) ;; (get-disjuncts-tester '(not (boolor x y)) state) ;nothing to do ;; (get-disjuncts-tester '(not (booland (not x) (not y))) state) ;; (get-disjuncts-tester '(not (not t)) state) ;; (get-disjuncts-tester '(not (not nil)) state)
44573
; Tests for get-disjuncts ; ; Copyright (C) 2020 Kestrel Institute ; ; License: A 3-clause BSD license. See the file books/3BSD-mod.txt. ; ; Author: <NAME> (<EMAIL>) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (in-package "ACL2") (include-book "get-disjuncts") (include-book "make-term-into-dag-array-basic") (include-book "dag-to-term") (include-book "dag-array-printing") (defund get-disjuncts-tester (term state) (declare (xargs :stobjs state :mode :program)) (b* ((term (translate-term term 'get-disjuncts-tester (w state))) ((mv erp nodenum-or-quotep dag-array dag-len dag-parent-array dag-constant-alist dag-variable-alist) (make-term-into-dag-array-basic term 'dag-array 'dag-parent-array nil)) ((when erp) (er hard? 'get-disjuncts-tester "Error making term.")) ((mv erp provedp disjuncts dag-array & ; dag-len & & & ;dag-parent-array dag-constant-alist dag-variable-alist ) (get-darg-disjuncts nodenum-or-quotep dag-array dag-len dag-parent-array dag-constant-alist dag-variable-alist nil ;acc nil ;negated-flg t ;print )) ((when erp) (er hard? 'get-disjuncts-tester "Error getting disjuncts."))) (if provedp :proved ;; todo: return these, as terms, instead of printing them: (print-dag-only-supporters-lst disjuncts 'dag-array dag-array)))) ;; TODO: Get these into the build: ;; (get-disjuncts-tester 'x state) ;; (get-disjuncts-tester '(boolor x y) state) ;; (get-disjuncts-tester '(boolor x t) state) ;; (get-disjuncts-tester '(boolor t y) state) ;; (get-disjuncts-tester '(boolor x nil) state) ;; (get-disjuncts-tester '(boolor nil y) state) ;; (get-disjuncts-tester '(not x) state) ;; (get-disjuncts-tester '(not (not x)) state) ;; (get-disjuncts-tester '(not (booland x y)) state) ;; (get-disjuncts-tester '(not (booland nil y)) state) ;; (get-disjuncts-tester '(not (booland x nil)) state) ;; (get-disjuncts-tester '(not (booland t y)) state) ;; (get-disjuncts-tester '(not (booland x t)) state) ;; (get-disjuncts-tester '(not (boolor x y)) state) ;nothing to do ;; (get-disjuncts-tester '(not (booland (not x) (not y))) state) ;; (get-disjuncts-tester '(not (not t)) state) ;; (get-disjuncts-tester '(not (not nil)) state)
true
; Tests for get-disjuncts ; ; Copyright (C) 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 "get-disjuncts") (include-book "make-term-into-dag-array-basic") (include-book "dag-to-term") (include-book "dag-array-printing") (defund get-disjuncts-tester (term state) (declare (xargs :stobjs state :mode :program)) (b* ((term (translate-term term 'get-disjuncts-tester (w state))) ((mv erp nodenum-or-quotep dag-array dag-len dag-parent-array dag-constant-alist dag-variable-alist) (make-term-into-dag-array-basic term 'dag-array 'dag-parent-array nil)) ((when erp) (er hard? 'get-disjuncts-tester "Error making term.")) ((mv erp provedp disjuncts dag-array & ; dag-len & & & ;dag-parent-array dag-constant-alist dag-variable-alist ) (get-darg-disjuncts nodenum-or-quotep dag-array dag-len dag-parent-array dag-constant-alist dag-variable-alist nil ;acc nil ;negated-flg t ;print )) ((when erp) (er hard? 'get-disjuncts-tester "Error getting disjuncts."))) (if provedp :proved ;; todo: return these, as terms, instead of printing them: (print-dag-only-supporters-lst disjuncts 'dag-array dag-array)))) ;; TODO: Get these into the build: ;; (get-disjuncts-tester 'x state) ;; (get-disjuncts-tester '(boolor x y) state) ;; (get-disjuncts-tester '(boolor x t) state) ;; (get-disjuncts-tester '(boolor t y) state) ;; (get-disjuncts-tester '(boolor x nil) state) ;; (get-disjuncts-tester '(boolor nil y) state) ;; (get-disjuncts-tester '(not x) state) ;; (get-disjuncts-tester '(not (not x)) state) ;; (get-disjuncts-tester '(not (booland x y)) state) ;; (get-disjuncts-tester '(not (booland nil y)) state) ;; (get-disjuncts-tester '(not (booland x nil)) state) ;; (get-disjuncts-tester '(not (booland t y)) state) ;; (get-disjuncts-tester '(not (booland x t)) state) ;; (get-disjuncts-tester '(not (boolor x y)) state) ;nothing to do ;; (get-disjuncts-tester '(not (booland (not x) (not y))) state) ;; (get-disjuncts-tester '(not (not t)) state) ;; (get-disjuncts-tester '(not (not nil)) state)
[ { "context": "pecific is using abstractions.\n(defvar *names* '((Robbert E. Lee) ...))\nthen you should also define functions to g", "end": 322, "score": 0.9998151063919067, "start": 308, "tag": "NAME", "value": "Robbert E. Lee" } ]
paip/3.1-a-guide-to-lisp-style.lisp
junjiemars/l
1
;;;; -*- Mode: Lisp; Syntax: Common-Lisp -*- #| Using the most specific form possible makes it easier for your reader to understand your intent. (1) For example, the conditional special form when is more specific than if. (2) One important way of being specific is using abstractions. (defvar *names* '((Robbert E. Lee) ...)) then you should also define functions to get at the components of each name. To get at Lee, use (last-name (first *names*)), not (caddar *names*). (3) Often the maxims are in concord. For example, if your code is trying to find an element in a list, you should use find (or maybe find-if), not loop or do. (4) Sometimes, however, the maxims are in conflict, and experience will tell you which one to prefer. Consider the following two ways of placing a new key/value pair on an association list: (push (cons key val) a-list) (setf a-list (acons key val a-list)) The first is more concise. But the second is more specific, as it uses the acons function, which is designed specifically for association lists. (5) Feeling that it is more consistent to use a single form, setf, for all updating. (6) Be consistent. |#
63511
;;;; -*- Mode: Lisp; Syntax: Common-Lisp -*- #| Using the most specific form possible makes it easier for your reader to understand your intent. (1) For example, the conditional special form when is more specific than if. (2) One important way of being specific is using abstractions. (defvar *names* '((<NAME>) ...)) then you should also define functions to get at the components of each name. To get at Lee, use (last-name (first *names*)), not (caddar *names*). (3) Often the maxims are in concord. For example, if your code is trying to find an element in a list, you should use find (or maybe find-if), not loop or do. (4) Sometimes, however, the maxims are in conflict, and experience will tell you which one to prefer. Consider the following two ways of placing a new key/value pair on an association list: (push (cons key val) a-list) (setf a-list (acons key val a-list)) The first is more concise. But the second is more specific, as it uses the acons function, which is designed specifically for association lists. (5) Feeling that it is more consistent to use a single form, setf, for all updating. (6) Be consistent. |#
true
;;;; -*- Mode: Lisp; Syntax: Common-Lisp -*- #| Using the most specific form possible makes it easier for your reader to understand your intent. (1) For example, the conditional special form when is more specific than if. (2) One important way of being specific is using abstractions. (defvar *names* '((PI:NAME:<NAME>END_PI) ...)) then you should also define functions to get at the components of each name. To get at Lee, use (last-name (first *names*)), not (caddar *names*). (3) Often the maxims are in concord. For example, if your code is trying to find an element in a list, you should use find (or maybe find-if), not loop or do. (4) Sometimes, however, the maxims are in conflict, and experience will tell you which one to prefer. Consider the following two ways of placing a new key/value pair on an association list: (push (cons key val) a-list) (setf a-list (acons key val a-list)) The first is more concise. But the second is more specific, as it uses the acons function, which is designed specifically for association lists. (5) Feeling that it is more consistent to use a single form, setf, for all updating. (6) Be consistent. |#
[ { "context": "ad\n (:title (str (conc (getf data :title) \" | James Ball\")))\n (:link :rel \"stylesheet\" :href \"/css/te", "end": 135, "score": 0.9983633160591125, "start": 125, "tag": "NAME", "value": "James Ball" }, { "context": " (:li (:a :href \"https://github.com/84115/84115\" \"Github\"))\n ))))\n (s", "end": 880, "score": 0.9991462826728821, "start": 875, "tag": "USERNAME", "value": "84115" }, { "context": "\n (:li (:a :href \"https://github.com/84115\" \"Github\")))\n (:p \"MIT Licensed | &cop", "end": 1146, "score": 0.9991902112960815, "start": 1141, "tag": "USERNAME", "value": "84115" }, { "context": "\"Github\")))\n (:p \"MIT Licensed | &copy; James Ball | \" (:a :href \"https://github.com/84115/84115\" \"S", "end": 1209, "score": 0.9982274770736694, "start": 1199, "tag": "NAME", "value": "James Ball" }, { "context": "opy; James Ball | \" (:a :href \"https://github.com/84115/84115\" \"Source Code\")))))\n\n (:script :src \"/", "end": 1249, "score": 0.9992631077766418, "start": 1244, "tag": "USERNAME", "value": "84115" } ]
views/layouts/base.lisp
84115/84115
0
(in-package :eight) (deflayout base (data :top-level t) (:html (:head (:title (str (conc (getf data :title) " | James Ball"))) (:link :rel "stylesheet" :href "/css/template.css") (:link :rel "shortcut icon" :href "/favicon.png" :type "image/png") (:link :rel "stylesheet" :href "/css/highlight-lisp-theme.css" :id "hl-style")) (:body :class (getf data :body-class) (:div :id "container" (:header (:div :class "inner" (:h1 (:a :href "/" "james-ball.co.uk")) (:nav (:ul (:li (:a :href "/portfolio" "Portfolio")) (:li (:a :href "/docs" "Docs")) (:li (:a :href "/blog" "Blog")) (:li (:a :href "/about" "About")) (:li (:a :href "/contact" "Contact")) (:li (:a :href "https://github.com/84115/84115" "Github")) )))) (str (getf data :content)) (:footer (:div :class "footer-container" (:ul (:li (:a :href "/sitemap" "Sitemap")) (:li (:a :href "https://github.com/84115" "Github"))) (:p "MIT Licensed | &copy; James Ball | " (:a :href "https://github.com/84115/84115" "Source Code"))))) (:script :src "/js/main.js") (:script :src "/js/highlight-lisp.min.js"))))
15787
(in-package :eight) (deflayout base (data :top-level t) (:html (:head (:title (str (conc (getf data :title) " | <NAME>"))) (:link :rel "stylesheet" :href "/css/template.css") (:link :rel "shortcut icon" :href "/favicon.png" :type "image/png") (:link :rel "stylesheet" :href "/css/highlight-lisp-theme.css" :id "hl-style")) (:body :class (getf data :body-class) (:div :id "container" (:header (:div :class "inner" (:h1 (:a :href "/" "james-ball.co.uk")) (:nav (:ul (:li (:a :href "/portfolio" "Portfolio")) (:li (:a :href "/docs" "Docs")) (:li (:a :href "/blog" "Blog")) (:li (:a :href "/about" "About")) (:li (:a :href "/contact" "Contact")) (:li (:a :href "https://github.com/84115/84115" "Github")) )))) (str (getf data :content)) (:footer (:div :class "footer-container" (:ul (:li (:a :href "/sitemap" "Sitemap")) (:li (:a :href "https://github.com/84115" "Github"))) (:p "MIT Licensed | &copy; <NAME> | " (:a :href "https://github.com/84115/84115" "Source Code"))))) (:script :src "/js/main.js") (:script :src "/js/highlight-lisp.min.js"))))
true
(in-package :eight) (deflayout base (data :top-level t) (:html (:head (:title (str (conc (getf data :title) " | PI:NAME:<NAME>END_PI"))) (:link :rel "stylesheet" :href "/css/template.css") (:link :rel "shortcut icon" :href "/favicon.png" :type "image/png") (:link :rel "stylesheet" :href "/css/highlight-lisp-theme.css" :id "hl-style")) (:body :class (getf data :body-class) (:div :id "container" (:header (:div :class "inner" (:h1 (:a :href "/" "james-ball.co.uk")) (:nav (:ul (:li (:a :href "/portfolio" "Portfolio")) (:li (:a :href "/docs" "Docs")) (:li (:a :href "/blog" "Blog")) (:li (:a :href "/about" "About")) (:li (:a :href "/contact" "Contact")) (:li (:a :href "https://github.com/84115/84115" "Github")) )))) (str (getf data :content)) (:footer (:div :class "footer-container" (:ul (:li (:a :href "/sitemap" "Sitemap")) (:li (:a :href "https://github.com/84115" "Github"))) (:p "MIT Licensed | &copy; PI:NAME:<NAME>END_PI | " (:a :href "https://github.com/84115/84115" "Source Code"))))) (:script :src "/js/main.js") (:script :src "/js/highlight-lisp.min.js"))))
[ { "context": "/01/15 03:42:53 dalal Exp $\n\n;; Modified 3aug02 by Mike Matessa and Bonnie John We changed the\n;; hold-resourc", "end": 254, "score": 0.9998905062675476, "start": 242, "tag": "NAME", "value": "Mike Matessa" }, { "context": "alal Exp $\n\n;; Modified 3aug02 by Mike Matessa and Bonnie John We changed the\n;; hold-resource to be inside a", "end": 270, "score": 0.9998838901519775, "start": 259, "tag": "NAME", "value": "Bonnie John" }, { "context": "the PDL template to type the string str\n;; author: eyk\n(defun build-pdl (str func-name)\n (let* ((chunk", "end": 7309, "score": 0.9994322061538696, "start": 7306, "tag": "USERNAME", "value": "eyk" }, { "context": "g each a single initiate-keystroke step\n;; author: eyk\n(defun create-initiate-keystroke-pdl (str-list\n ", "end": 14467, "score": 0.9996585249900818, "start": 14464, "tag": "USERNAME", "value": "eyk" }, { "context": "create-initiate-keystroke-type-string-body author: eyk\n\n(defun create-type-key-pdl (str-total-numchar\n ", "end": 23143, "score": 0.9946337938308716, "start": 23140, "tag": "USERNAME", "value": "eyk" }, { "context": " step-index1 step-index2))) ; bonnie told me to!\n )\n ", "end": 25733, "score": 0.9274439811706543, "start": 25727, "tag": "NAME", "value": "bonnie" }, { "context": ".g. (str2lis \"elaine\") => (E L A I N E)\n;; author: Mike Matessa\n(defun str2lis (x)\n (let ((ans nil)\n (s", "end": 52119, "score": 0.9998303651809692, "start": 52107, "tag": "NAME", "value": "Mike Matessa" }, { "context": "> (H-KEY L-KEY A-KEY I-KEY N-KEY E-KEY)\n;; author: eyk\n(defun string-to-list (x)\n (append-all (mapcar ", "end": 52539, "score": 0.9850928783416748, "start": 52536, "tag": "USERNAME", "value": "eyk" }, { "context": "ate-initiate-keystroke-type-string-body\n;; author: eyk\n(defun inc-left-numchar-cnt (cur-hand)\n (if (", "end": 55801, "score": 0.9994325637817383, "start": 55798, "tag": "USERNAME", "value": "eyk" }, { "context": "ate-initiate-keystroke-type-string-body\n;; author: eyk\n(defun inc-right-numchar-cnt (cur-hand)\n (if ", "end": 56150, "score": 0.9996381998062134, "start": 56147, "tag": "USERNAME", "value": "eyk" }, { "context": "key l-key o-key) for the string \"hello\"\n;; author: eyk\n\n(defun create-left-numchar (lis)\n (cond ((equa", "end": 56610, "score": 0.9995722770690918, "start": 56607, "tag": "USERNAME", "value": "eyk" }, { "context": "key l-key o-key) for the string \"hello\"\n;; author: eyk\n(defun create-right-numchar (lis)\n (cond ((equa", "end": 57108, "score": 0.9996302127838135, "start": 57105, "tag": "USERNAME", "value": "eyk" }, { "context": "laine\") => (index (type-string-elaine))\n;; author: eyk\n(defun create-type-string-index-clause (func-name", "end": 57696, "score": 0.9990534782409668, "start": 57693, "tag": "USERNAME", "value": "eyk" }, { "context": "tep c2 (initiate-keystroke) (waitfor ?c1)) author: eyk notes: NEED\n;; TO CHECK FOR NIL WAITFOR LISTS (ta", "end": 58144, "score": 0.9984782338142395, "start": 58141, "tag": "USERNAME", "value": "eyk" }, { "context": "x x\n;; return value: termination clause\n;; author: eyk\n(defun create-terminate-clause ()\n (list 'step ", "end": 58671, "score": 0.9970822334289551, "start": 58668, "tag": "USERNAME", "value": "eyk" } ]
examples/apexlib/primitive-templates/typist.lisp
willf/apex
1
;;;-*- Mode: Lisp; Package: :cl-user -*- ;;; ;;; apex/examples/apexlib/primitive-templates/typist.lisp ;;; ;;; Copyright: See apex/LICENSE ;;; Version: $Id: typist.lisp,v 1.7 2006/01/15 03:42:53 dalal Exp $ ;; Modified 3aug02 by Mike Matessa and Bonnie John We changed the ;; hold-resource to be inside a hold-resource-step That step uses the ;; resource that it holds. This solved a problem that we had with the ;; CAD model, where contention for the left-hand-block caused the ;; template to lose ownership of all resources, which released the ;; typing-cognition-block, which allowed activities from later ;; templates to sneak in. Our solution removed the contention, and ;; hence made the CAD model run, but we still need to think about ;; whether the asa should remove resources as it is doing or if it ;; should do it some other way that does not cause the problem if ;; other unanticipated contentions arise. ;; The hold-resource-steps are at the top of this file. It is likely ;; that all templates should use them but we will decide about that ;; after the Cognitive Science 2002 Tutorial. ;; ;; modified 5/10/02 (eyk) ;;; -- wf. 12 January 2005. ;;; Version 2.4.x of Apex incorrectly converted these sequential ;;; procedures to put in a 'waitfor' on the 'hold-resource' step ;;; of these procedures. That is to say, it was not defined what it ;;; would mean to have a PROFILE step in :sequential procedures ;;; and Apex didn't signal an error. Rewriting these to have the ;;; a 'waitfor' that can't complete seems to solve the problems with ;;; the applications, but it might not be what is wanted. ;;; ;;;(procedure :sequential ;;; (index (hold-resource-step right-hand-block)) ;;; (profile right-hand-block) ;;; (hold-resource right-hand-block :ancestor 2)) ;;; ;;;(procedure :sequential ;;; (index (hold-resource-step left-hand-block)) ;;; (profile left-hand-block) ;;; (hold-resource left-hand-block :ancestor 2)) ;;; ;;;(procedure :sequential ;;; (index (hold-resource-step type-string-block)) ;;; (profile type-string-block) ;;; (hold-resource type-string-block :ancestor 2)) ;;; ;;;(procedure :sequential ;;; (index (hold-resource-step typing-cognition-block)) ;;; (profile typing-cognition-block) ;;; (hold-resource typing-cognition-block :ancestor 2)) (procedure ;; :sequential (index (hold-resource-step right-hand-block)) (profile right-hand-block) (step s1 (hold-resource right-hand-block :ancestor 2)) ;; (waitfor ?ever)) (step term (terminate) (waitfor ?s1))) (procedure ;; :sequential (index (hold-resource-step left-hand-block)) (profile left-hand-block) (step s1 (hold-resource left-hand-block :ancestor 2)) ;; (waitfor ?ever)) (step term (terminate) (waitfor ?s1))) (procedure ;; :sequential (index (hold-resource-step type-string-block)) (profile type-string-block) (step s1 (hold-resource type-string-block :ancestor 2)) ;; (waitfor ?ever)) (step term (terminate) (waitfor ?s1))) (procedure ;;:sequential (index (hold-resource-step typing-cognition-block)) (profile typing-cognition-block) (step s1 (hold-resource typing-cognition-block :ancestor 2)) ;; (waitfor ?ever)) (step term (terminate) (waitfor ?s1))) ;;;;;;;;;;; GLOBAL CONSTANTS ;;;;;;;; ;; COGNITION PRIMITIVES (setf *get-chunk* (list 'get-chunk)) (setf *initiate-keystroke* (list 'initiate-keystroke)) ;; LEFT-HAND PRIMITIVES (setf *type-key-left* (list 'type-key-left)) ;; RIGHT-HAND PRIMITIVES (setf *type-key-right* (list 'type-key-right)) ;; WORLD PRIMITIVE (setf *world* (list 'world)) ;;;;;;;;;;; GLOBAL VARIABLES ;;;;;;;; (setf *LAST-CHAR-HAND-GENSYM* nil) ;; Unique symbol of previous type-string template created ;; (if it exists). This is to keep track of a world event that ;; is generated at the end of every type-string template created. ;; If the current type-string template has a same-hand constraint ;; it needs to wait for the last motor activity of the previous ;; type-string template to begin the first initiate-keystroke ;; activity of the current template being generated. (setf *LAST-CHAR-HAND* nil) ;; Holds the hand that typed the last character of the ;; previous template. ;;;;;;;;;; TYPIST CODE ;;;;;;;;;;;;;; ;; TYPE-STRING ;; args: ?str ;; description: constructs one pdl template for a given string. ;; the pdl template is given a unique identifier. ;; after the pdl template is constructed, the pdl template is called. ;; return value: nothing ;(procedure :sequential ; (index (type-string ?str)) ; (construct-typing-pdl ?str => ?pdl-name) ; (TYPE-STRING-CREATED ?pdl-name) ;) (procedure (index (type-string ?str)) (step s1 (?this-step) (select ?this-step (depends-on '*R-hand-on* '((mouse home-to-keyboard) (keyboard no-op)))) (rank 1)) (step s2 (type-string-R-hand-on-keyboard ?str) (rank 2)) (step t (terminate) (waitfor ?s1 ?s2)) ) (procedure :sequential (index (type-string-R-hand-on-keyboard ?str)) (construct-typing-pdl ?str => ?pdl-name) (TYPE-STRING-CREATED ?pdl-name) ) (procedure :sequential (index (home-to-keyboard-before-typing)) (hold-resource-step right-hand-block) (initiate-home-to keyboard) (right-hand-home-to keyboard) (WORLD 0 *R-hand-on* keyboard)) ;; CONSTRUCT-TYPING-PDL ;; args: ?str ;; description: generates a new pdl template to type the string ?str. ;; a unique id is given to the template. ;; sets the hand of the last chararacter typed in ?str and unique id. ;; return value: the unique id for the template ;;;(procedure :special ;;; (index (construct-typing-pdl ?str)) ;;; (let ;;; ((func-name (gensym))) ;;create the new procedure name ;;; (eval (build-pdl ?str func-name)) ;;; (add-newest-proc) ;;; (setf *LAST-CHAR-HAND-GENSYM* (read-from-string (string func-name))) ;;; (setf *LAST-CHAR-HAND* (choose-hand (car (last (string-to-list ?str))))) ;;; func-name ;;; ) ;;;) (primitive (index (construct-typing-pdl ?str)) (return (let ((func-name (gensym))) ;;create the new procedure name (eval (build-pdl ?str func-name)) (add-newest-proc) (setf *LAST-CHAR-HAND-GENSYM* (read-from-string (string func-name))) (setf *LAST-CHAR-HAND* (choose-hand (car (last (string-to-list ?str))))) func-name ) )) ;; ADD-NEWEST-PROC (mfreed) ;; args: none ;; description: Call this after (eval (build-pdl ?str func-name)) in the procedure type-string. ;; return value: don't know ;; notes: This function is a hack, to be obsoleted after revising proc management mechanisms. (defun add-newest-proc () (add-procedure (first *proclib*) *agent*)) ;; BUILD-PDL ;; args: str func-name ;; description: returns a list representing the PDL procedure to type str ;; return value: a list representing the PDL template to type the string str ;; author: eyk (defun build-pdl (str func-name) (let* ((chunks (chop-up str))) (cons 'procedure (cons (create-type-string-index-clause func-name) (append (build-iter chunks 1 nil chunks) (append (list (create-step-clause 'w (append *world* (list 0) (list 'LAST-CHAR-HAND-GENSYM) (list (read-from-string (string func-name)))) (create-waitfor-clause (list (create-motor-step-index-var (length chunks) (+ (length (string-to-list (car (last chunks)))) 1))) ) )) (list (create-terminate-clause)) ) ) ) ) ) ) ;; BUILD-ITER ;; args: lis ;; ind ;; wait-for ;; orig-chunks ;; description: iterates through each chunk and calls build-pdl-chunk to create the pdl for each chunk ;; return value: the initiate-keystroke and type-key pdl for all the chunks of the type-string template (defun build-iter (lis ind wait-for orig-chunks) (if (null lis) nil (append (build-pdl-chunk (car lis) ind wait-for orig-chunks) (build-iter (cdr lis) (+ ind 1) (create-waitfor-clause (list (create-cog-step-index-var ind (+ (length (string-to-list (car lis))) 1) ) ) ) orig-chunks) ) ) ) ;; BUILD-PDL-CHUNK ;; args: str ;; ind ;; wait-for ;; orig-str-chunks-lis ;; description: creates the pdl for one particular chunk ;; return value: the initiate-keystroke and type-key pdl for ONE chunk of the type-string template (defun build-pdl-chunk (str ind wait-for orig-str-chunks-lis) (cons (create-step-clause (create-COG-STEP-INDEX ind 1) (cons 'get-chunk (list (read-from-string str))) wait-for) (cons ;; hold virtual resource - typing-cognition-block (create-step-clause (create-hold-virtual-resource-step-index ind 1 0) (list 'hold-resource-step 'typing-cognition-block) (create-waitfor-clause (list (create-cog-step-index-var ind 1))) ) (create-initiate-keystroke-type-string-body (string-to-list str) ind orig-str-chunks-lis) ) ) ) ;; create-INITIATE-KEYSTROKE-TYPE-STRING-BODY ;; args: orig-str-lis ;; description: takes a list of keys representing the string and returns the a list representing ;; the initiate-keystroke-type-string pdl for the entire string ;; return value: a list representing the PDL code for initiate-keystroke and type-key steps ;; for typing a chunk (defun create-initiate-keystroke-type-string-body (orig-str-lis step-index1 orig-str-chunks-lis) (do* ( ;; var1 init1 update ;; variables with no update on each iteration (str-total-numchar (length orig-str-lis)) (str-left-numchar (create-left-numchar orig-str-lis)) (str-right-numchar (create-right-numchar orig-str-lis)) (step-index2 2 (+ step-index2 1)) (prev-hand nil (choose-hand cur-key)) ;; variables with updates on each iteration (str-list orig-str-lis (rest str-list)) (cur-key (first orig-str-lis) (first str-list)) (cur-hand (choose-hand cur-key) (choose-hand cur-key)) (str-left-numchar-cnt (+ 0 (inc-left-numchar-cnt cur-hand)) (+ str-left-numchar-cnt (inc-left-numchar-cnt cur-hand))) (str-right-numchar-cnt (+ 0 (inc-right-numchar-cnt cur-hand)) (+ str-right-numchar-cnt (inc-right-numchar-cnt cur-hand))) (result-pdl-list (append (create-type-key-pdl str-total-numchar str-left-numchar str-right-numchar step-index1 step-index2 cur-hand str-left-numchar-cnt str-right-numchar-cnt str-list orig-str-chunks-lis) (append (create-initiate-keystroke-pdl str-list cur-hand prev-hand step-index1 step-index2 orig-str-chunks-lis) nil)) (append (create-type-key-pdl str-total-numchar str-left-numchar str-right-numchar step-index1 step-index2 cur-hand str-left-numchar-cnt str-right-numchar-cnt str-list orig-str-chunks-lis) (append (create-initiate-keystroke-pdl str-list cur-hand prev-hand step-index1 step-index2 orig-str-chunks-lis) result-pdl-list))) ) ;; test action1 .. action-n ((equal 1 (length str-list)) (reverse result-pdl-list) ) ) ;;end do* ) ;; create-INITIATE-KEYSTROKE-PDL ;; args: str-list cur-hand prev-hand step-index ;; description: takes 4 arguments. str-list represents the list of keys that yet to have ;; PDL generated. cur-hand is the hand needed to type the current key. ;; prev-hand is the hand needed to type the previous key (nil if first key). ;; step index is the current step. ;; return value: a list representing each a single initiate-keystroke step ;; author: eyk (defun create-initiate-keystroke-pdl (str-list cur-hand prev-hand step-index1 step-index2 orig-str-chunks-lis) (cond ((and (= step-index1 1) (= step-index2 2) (equal cur-hand *LAST-CHAR-HAND*)) ;; same-hand constraint across chunks BETWEEN templates for first initiate-keystroke cognitive operator (cond ((equal 1 (length str-list)) (list (create-step-clause (create-cog-step-index step-index1 step-index2) (reverse (cons (first str-list) *initiate-keystroke*)) (append (create-waitfor-clause (cons (create-cog-step-index-var step-index1 (- step-index2 1)) nil)) (list (list 'variable 'LAST-CHAR-HAND-GENSYM *LAST-CHAR-HAND-GENSYM*)) ) ) ;; release virtual resource - typing-cognition-block (create-step-clause (create-release-virtual-resource-step-index step-index1 step-index2 0) (list 'release-resource 'typing-cognition-block ':ancestor 1) (create-waitfor-clause (list (create-cog-step-index-var step-index1 step-index2))) ) ) ) (t (list (create-step-clause (create-cog-step-index step-index1 step-index2) (reverse (cons (first str-list) *initiate-keystroke*)) (append (create-waitfor-clause (cons (create-cog-step-index-var step-index1 (- step-index2 1)) nil)) (list (list 'variable 'LAST-CHAR-HAND-GENSYM *LAST-CHAR-HAND-GENSYM*)) ) ) ) ) ) ) ((and (> step-index1 1) (= step-index2 2) (equal cur-hand (choose-hand (nth (- (length (string-to-list (nth (- step-index1 2) orig-str-chunks-lis))) 1) (string-to-list (nth (- step-index1 2) orig-str-chunks-lis))) )) ) ;; same-hand constraint across chunks WITHIN templates ;; for first initiate-keystroke cognitive operator (list (create-step-clause (create-cog-step-index step-index1 step-index2) (reverse (cons (first str-list) *initiate-keystroke*)) (create-waitfor-clause (cons (create-cog-step-index-var step-index1 (- step-index2 1)) (cons (create-motor-step-index-var (- step-index1 1) (+ (length (string-to-list (nth (- step-index1 2) orig-str-chunks-lis))) 1)) nil)))) ) ) ((equal 1 (length str-list)) ;; last character (cond ((equal cur-hand prev-hand) (list (create-step-clause (create-cog-step-index step-index1 step-index2) (reverse (cons (first str-list) *initiate-keystroke*)) (create-waitfor-clause (cons (create-cog-step-index-var step-index1 (- step-index2 1)) (cons (create-motor-step-index-var step-index1 (- step-index2 1)) nil)))) ;; release virtual resource - typing-cognition-block (create-step-clause (create-release-virtual-resource-step-index step-index1 step-index2 0) (list 'release-resource 'typing-cognition-block ':ancestor 1) (create-waitfor-clause (list (create-cog-step-index-var step-index1 step-index2))) ) ) ) (t (list (create-step-clause (create-cog-step-index step-index1 step-index2) (reverse (cons (first str-list) *initiate-keystroke*)) (create-waitfor-clause (cons (create-cog-step-index-var step-index1 (- step-index2 1)) nil))) ;; release virtual resource - typing-cognition-block (create-step-clause (create-release-virtual-resource-step-index step-index1 step-index2 0) (list 'release-resource 'typing-cognition-block ':ancestor 1) (create-waitfor-clause (list (create-cog-step-index-var step-index1 step-index2))) ) ) ) ) ) (t ;; not last character (cond ((equal cur-hand prev-hand) (list (create-step-clause (create-cog-step-index step-index1 step-index2) (reverse (cons (first str-list) *initiate-keystroke*)) (create-waitfor-clause (cons (create-cog-step-index-var step-index1 (- step-index2 1)) (cons (create-motor-step-index-var step-index1 (- step-index2 1)) nil)))) ) ) (t (list (create-step-clause (create-cog-step-index step-index1 step-index2) (reverse (cons (first str-list) *initiate-keystroke*)) (create-waitfor-clause (cons (create-cog-step-index-var step-index1 (- step-index2 1)) nil))) ) ) ) ) ) ) ;; create-TYPE-KEY-PDL ;; args: str-total-numchar ;; str-left-numchar ;; str-right-numchar ;; step-index ;; cur-hand ;; str-left-numchar-cnt ;; str-right-numchar-cnt ;; str-list ;; description: takes 8 arguments. str-total-numchar is the total ;; number of characters in the string. str-left-numchar is ;; the total number of characters typed with the left-hand. ;; str-right-numchar is the total number of characters ;; typed with the right-hand. step-index is the number for ;; the current step to be generated. cur-hand is the hand ;; (left or right) used to type the current character. ;; str-left-numchar-cnt is a counter to determine how many ;; characters have been typed with the left hand. ;; str-right-numchar-cnt is a coutner to determine how many ;; characters have been typed with the right hand. ;; str-list is the list representation of the string to be ;; typed. ;; notes: this is a helper function called by ;; create-initiate-keystroke-type-string-body author: eyk (defun create-type-key-pdl (str-total-numchar str-left-numchar str-right-numchar step-index1 step-index2 cur-hand str-left-numchar-cnt str-right-numchar-cnt str-list orig-str-chunks-lis) (let* ((vr-index 0)) (cond ((equal str-total-numchar (length str-list)) ;first motor operator (cond ((> step-index1 1) ;; the current chunk is 2..n chunk (cond ((equal 'right cur-hand) (cond ((equal str-right-numchar str-right-numchar-cnt) (list (create-step-clause (create-motor-step-index step-index1 step-index2) (reverse (cons (first str-list) *type-key-right*)) (create-waitfor-clause (cons (create-cog-step-index-var step-index1 step-index2) (cons (create-motor-step-index-var (- step-index1 1) (+ (length (string-to-list (nth (- step-index1 2) orig-str-chunks-lis))) 1)) nil)))) (create-step-clause (create-hold-virtual-resource-step-index step-index1 step-index2 (+ vr-index 1)) (list 'hold-resource-step 'right-hand-block) (create-waitfor-clause (list (create-cog-step-index-var step-index1 step-index2))) ; bonnie told me to! ) (create-step-clause (create-hold-virtual-resource-step-index step-index1 step-index2 (+ vr-index 2)) (list 'hold-resource-step 'type-string-block) (create-waitfor-clause (list (create-cog-step-index-var step-index1 step-index2))) ) (create-step-clause (create-release-virtual-resource-step-index step-index1 step-index2 (+ vr-index 3)) (list 'release-resource 'right-hand-block ':ancestor 1) (create-waitfor-clause (list (create-motor-step-index-var step-index1 step-index2))) ) ) ) (t (list (create-step-clause (create-motor-step-index step-index1 step-index2) (reverse (cons (first str-list) *type-key-right*)) (create-waitfor-clause (cons (create-cog-step-index-var step-index1 step-index2) (cons (create-motor-step-index-var (- step-index1 1) (+ (length (string-to-list (nth (- step-index1 2) orig-str-chunks-lis))) 1)) nil)))) (create-step-clause (create-hold-virtual-resource-step-index step-index1 step-index2 (+ vr-index 1)) (list 'hold-resource-step 'right-hand-block) (create-waitfor-clause (list (create-motor-step-index-var step-index1 step-index2))) ) (create-step-clause (create-hold-virtual-resource-step-index step-index1 step-index2 (+ vr-index 2)) (list 'hold-resource-step 'type-string-block) (create-waitfor-clause (list (create-cog-step-index-var step-index1 step-index2))) ) ) ))) ((equal 'left cur-hand) (cond ((equal str-left-numchar str-left-numchar-cnt) (list (create-step-clause (create-motor-step-index step-index1 step-index2) (reverse (cons (first str-list) *type-key-left*)) (create-waitfor-clause (cons (create-cog-step-index-var step-index1 step-index2) (cons (create-motor-step-index-var (- step-index1 1) (+ (length (string-to-list (nth (- step-index1 2) orig-str-chunks-lis))) 1)) nil)))) (create-step-clause (create-hold-virtual-resource-step-index step-index1 step-index2 (+ vr-index 1)) (list 'hold-resource-step 'left-hand-block) (create-waitfor-clause (list (create-cog-step-index-var step-index1 step-index2))) ) (create-step-clause (create-hold-virtual-resource-step-index step-index1 step-index2 (+ vr-index 2)) (list 'hold-resource-step 'type-string-block) (create-waitfor-clause (list (create-cog-step-index-var step-index1 step-index2))) ) (create-step-clause (create-release-virtual-resource-step-index step-index1 step-index2 (+ vr-index 3)) (list 'release-resource 'left-hand-block ':ancestor 1) (create-waitfor-clause (list (create-motor-step-index-var step-index1 step-index2))) ) ) ) (t (list (create-step-clause (create-motor-step-index step-index1 step-index2) (reverse (cons (first str-list) *type-key-left*)) (create-waitfor-clause (cons (create-cog-step-index-var step-index1 step-index2) (cons (create-motor-step-index-var (- step-index1 1) (+ (length (string-to-list (nth (- step-index1 2) orig-str-chunks-lis))) 1)) nil)))) (create-step-clause (create-hold-virtual-resource-step-index step-index1 step-index2 (+ vr-index 1)) (list 'hold-resource-step 'left-hand-block) (create-waitfor-clause (list (create-cog-step-index-var step-index1 step-index2))) ) (create-step-clause (create-hold-virtual-resource-step-index step-index1 step-index2 (+ vr-index 2)) (list 'hold-resource-step 'type-string-block) (create-waitfor-clause (list (create-cog-step-index-var step-index1 step-index2))) ) ) ) )) ) ) (t ;; the current chunk is the first chunk (cond ((equal 'right cur-hand) (cond ((equal str-right-numchar str-right-numchar-cnt) (list (create-step-clause (create-motor-step-index step-index1 step-index2) (reverse (cons (first str-list) *type-key-right*)) (create-waitfor-clause (cons (create-cog-step-index-var step-index1 step-index2) nil))) (create-step-clause (create-hold-virtual-resource-step-index step-index1 step-index2 (+ vr-index 1)) (list 'hold-resource-step 'right-hand-block) (create-waitfor-clause (list (create-cog-step-index-var step-index1 step-index2))) ) (create-step-clause (create-hold-virtual-resource-step-index step-index1 step-index2 (+ vr-index 2)) (list 'hold-resource-step 'type-string-block) (create-waitfor-clause (list (create-cog-step-index-var step-index1 step-index2))) ) (create-step-clause (create-release-virtual-resource-step-index step-index1 step-index2 (+ vr-index 3)) (list 'release-resource 'right-hand-block ':ancestor 1) (create-waitfor-clause (list (create-motor-step-index-var step-index1 step-index2))) ) ) ) (t (list (create-step-clause (create-motor-step-index step-index1 step-index2) (reverse (cons (first str-list) *type-key-right*)) (create-waitfor-clause (cons (create-cog-step-index-var step-index1 step-index2) nil))) (create-step-clause (create-hold-virtual-resource-step-index step-index1 step-index2 (+ vr-index 1)) (list 'hold-resource-step 'right-hand-block) (create-waitfor-clause (list (create-cog-step-index-var step-index1 step-index2))) ) (create-step-clause (create-hold-virtual-resource-step-index step-index1 step-index2 (+ vr-index 2)) (list 'hold-resource-step 'type-string-block) (create-waitfor-clause (list (create-cog-step-index-var step-index1 step-index2))) ) ) ))) ((equal 'left cur-hand) (cond ((equal str-left-numchar str-left-numchar-cnt) (list (create-step-clause (create-motor-step-index step-index1 step-index2) (reverse (cons (first str-list) *type-key-left*)) (create-waitfor-clause (cons (create-cog-step-index-var step-index1 step-index2) nil))) (create-step-clause (create-hold-virtual-resource-step-index step-index1 step-index2 (+ vr-index 1)) (list 'hold-resource-step 'left-hand-block) (create-waitfor-clause (list (create-cog-step-index-var step-index1 step-index2))) ) (create-step-clause (create-hold-virtual-resource-step-index step-index1 step-index2 (+ vr-index 2)) (list 'hold-resource-step 'type-string-block) (create-waitfor-clause (list (create-cog-step-index-var step-index1 step-index2))) ) (create-step-clause (create-release-virtual-resource-step-index step-index1 step-index2 (+ vr-index 3)) (list 'release-resource 'left-hand-block ':ancestor 1) (create-waitfor-clause (list (create-motor-step-index-var step-index1 step-index2))) ) ) ) (t (list (create-step-clause (create-motor-step-index step-index1 step-index2) (reverse (cons (first str-list) *type-key-left*)) (create-waitfor-clause (cons (create-cog-step-index-var step-index1 step-index2) nil))) (create-step-clause (create-hold-virtual-resource-step-index step-index1 step-index2 (+ vr-index 1)) (list 'hold-resource-step 'left-hand-block) (create-waitfor-clause (list (create-cog-step-index-var step-index1 step-index2))) ) (create-step-clause (create-hold-virtual-resource-step-index step-index1 step-index2 (+ vr-index 2)) (list 'hold-resource-step 'type-string-block) (create-waitfor-clause (list (create-cog-step-index-var step-index1 step-index2))) ) ) ))) ) ) ) ) ((equal 'right cur-hand) ;right motor operator (cond ((equal 1 str-right-numchar-cnt) ;;type-key-right-first (list (create-step-clause (create-motor-step-index step-index1 step-index2) (reverse (cons (first str-list) *type-key-right*)) (create-waitfor-clause (cons (create-cog-step-index-var step-index1 step-index2) (cons (create-motor-step-index-var step-index1 (- step-index2 1)) nil)))) (create-step-clause (create-hold-virtual-resource-step-index step-index1 step-index2 (+ vr-index 1)) (list 'hold-resource-step 'right-hand-block) (create-waitfor-clause (list (create-cog-step-index-var step-index1 step-index2))) ) ) ) ((equal str-total-numchar (+ str-right-numchar-cnt str-left-numchar-cnt)) (list (create-step-clause (create-motor-step-index step-index1 step-index2) (reverse (cons (first str-list) *type-key-right*)) (create-waitfor-clause (cons (create-cog-step-index-var step-index1 step-index2) (cons (create-motor-step-index-var step-index1 (- step-index2 1)) nil)))) (create-step-clause (create-release-virtual-resource-step-index step-index1 step-index2 (+ vr-index 1)) (list 'release-resource 'right-hand-block ':ancestor 1) (create-waitfor-clause (list (create-motor-step-index-var step-index1 step-index2))) ) (create-step-clause (create-release-virtual-resource-step-index step-index1 step-index2 (+ vr-index 2)) (list 'release-resource 'type-string-block ':ancestor 1) (create-waitfor-clause (list (create-cog-step-index-var step-index1 step-index2))) ) ) ) ((equal str-right-numchar str-right-numchar-cnt) (list (create-step-clause (create-motor-step-index step-index1 step-index2) (reverse (cons (first str-list) *type-key-right*)) (create-waitfor-clause (cons (create-cog-step-index-var step-index1 step-index2) (cons (create-motor-step-index-var step-index1 (- step-index2 1)) nil)))) (create-step-clause (create-release-virtual-resource-step-index step-index1 step-index2 (+ vr-index 1)) (list 'release-resource 'right-hand-block ':ancestor 1) (create-waitfor-clause (list (create-motor-step-index-var step-index1 step-index2))) ) ) ) (t (list (create-step-clause (create-motor-step-index step-index1 step-index2) (reverse (cons (first str-list) *type-key-right*)) (create-waitfor-clause (cons (create-cog-step-index-var step-index1 step-index2) (cons (create-motor-step-index-var step-index1 (- step-index2 1)) nil)))) ) ) ) ) ((equal 'left cur-hand) (cond ((equal 1 str-left-numchar-cnt) ;;type-key-right-first (list (create-step-clause (create-motor-step-index step-index1 step-index2) (reverse (cons (first str-list) *type-key-left*)) (create-waitfor-clause (cons (create-cog-step-index-var step-index1 step-index2) (cons (create-motor-step-index-var step-index1 (- step-index2 1)) nil)))) (create-step-clause (create-hold-virtual-resource-step-index step-index1 step-index2 (+ vr-index 1)) (list 'hold-resource-step 'left-hand-block) (create-waitfor-clause (list (create-cog-step-index-var step-index1 step-index2))) ) ) ) ((equal str-total-numchar (+ str-right-numchar-cnt str-left-numchar-cnt)) (list (create-step-clause (create-motor-step-index step-index1 step-index2) (reverse (cons (first str-list) *type-key-left*)) (create-waitfor-clause (cons (create-cog-step-index-var step-index1 step-index2) (cons (create-motor-step-index-var step-index1 (- step-index2 1)) nil)))) (create-step-clause (create-release-virtual-resource-step-index step-index1 step-index2 (+ vr-index 1)) (list 'release-resource 'left-hand-block ':ancestor 1) (create-waitfor-clause (list (create-motor-step-index-var step-index1 step-index2))) ) (create-step-clause (create-release-virtual-resource-step-index step-index1 step-index2 (+ vr-index 2)) (list 'release-resource 'type-string-block ':ancestor 1) (create-waitfor-clause (list (create-cog-step-index-var step-index1 step-index2))) ) ) ) ((equal str-left-numchar str-left-numchar-cnt) (list (create-step-clause (create-motor-step-index step-index1 step-index2) (reverse (cons (first str-list) *type-key-left*)) (create-waitfor-clause (cons (create-cog-step-index-var step-index1 step-index2) (cons (create-motor-step-index-var step-index1 (- step-index2 1)) nil)))) (create-step-clause (create-release-virtual-resource-step-index step-index1 step-index2 (+ vr-index 1)) (list 'release-resource 'left-hand-block ':ancestor 1) (create-waitfor-clause (list (create-motor-step-index-var step-index1 step-index2))) ) ) ) (t (list (create-step-clause (create-motor-step-index step-index1 step-index2) (reverse (cons (first str-list) *type-key-left*)) (create-waitfor-clause (cons (create-cog-step-index-var step-index1 step-index2) (cons (create-motor-step-index-var step-index1 (- step-index2 1)) nil)))) ) ) ) ) (nil (print "error! key not found!")) ;;error! key not found! ) ) ) ;; kmd added this; it might be wrong ;;;;;;;;;;;;;;;;; helper functions ;;;;;;;;;;;;;;;;;; ;; CHOOSE-HAND ;; args: key ;; description: Accepts a key in the form <key>-key and returns the hand that types it ;; return value: Hand that typed the key ;; notes: This is the knowledge of which hand types which key ;; that a touch-typist has "at her fingertips" ;; This means we are not actually using the keyboard at all ;; that may not be stupid for a touch typist (bej) (defun choose-hand (key) (cond ((equal key nil) nil) ((member key '(esc-key f1-key f2-key f3-key f4-key f5-key tilda-key excl-key at-key hash-key quest-key perc-key carrot-key bquote-key 1-key 2-key 3-key 4-key 5-key 6-key tab-key q-key w-key e-key r-key t-key caps-key a-key s-key d-key f-key g-key shft-key z-key x-key c-key v-key b-key ctrl-key win-key alt-key)) 'left) ((member key '(f6-key f7-key f8-key f9-key f10-key f11-key f12-key and-key aster-key left-paren-key right-paren-key dash-key equal-key plus-key 7-key 8-key 9-key 0-key hyphen-key equal-key bslash-key y-key u-key i-key o-key p-key [-key ]-key h-key j-key k-key l-key semi-key quote-key enter-key n-key m-key comma-key period-key slash-key shift-key space-key alt-key win-key select-key ctrl-key colon-key double-quote-key left-bracket-key right-bracket-key less-key greater-key question-key backslash-key)) 'right) (t "not a key we know") ) ) ;; CHOP-UP (mmatessa) ;; args: str ;; description: parses str into separate strings in a list, each string represents a "chunk" ;; return value: a list representing the string parsed into chunks (defun chop-up (str) (let* ((pos (or (position #\space str) (position #\return str))) (end (if pos (position-if-not #'(lambda (x) (or (equal x #\space) (equal x #\return))) str :start pos)))) (cond ((or (null pos) (null end)) (list str)) (t (cons (subseq str 0 end) (chop-up (subseq str end (length str)))))))) ;; STR2LIS ;; args: x ;; description: accepts a string and returns a list representing that string ;; e.g. (str2lis "elaine") => (E L A I N E) ;; author: Mike Matessa (defun str2lis (x) (let ((ans nil) (sub nil)) (dotimes (i (length x)) (setf sub (subseq x i (1+ i))) (push sub ans)) (reverse ans))) ;; STRING-TO-LIST ;; args: x ;; description: This converts a string to a list of characters with "-key" appended to each ;; character. ;; e.g. (string-to-list "hello") => (H-KEY L-KEY A-KEY I-KEY N-KEY E-KEY) ;; author: eyk (defun string-to-list (x) (append-all (mapcar 'char2key (str2lis x))) ) (defun append-all (lis) (if (null lis) nil (append (car lis) (append-all (cdr lis))))) ;; CHAR2KEY ;; args: x ;; description: This adds "-key" to each charcter in the list ;; author: (defun char2key (x) (if (or (and (char>= (char x 0) #\A) (char<= (char x 0) #\Z)) (char= (char x 0) #\~) (char= (char x 0) #\!) (char= (char x 0) #\@) (char= (char x 0) #\#) (char= (char x 0) #\$) (char= (char x 0) #\%) (char= (char x 0) #\^) (char= (char x 0) #\&) (char= (char x 0) #\*) (char= (char x 0) #\() (char= (char x 0) #\)) (char= (char x 0) #\_) (char= (char x 0) #\+) (char= (char x 0) #\{) (char= (char x 0) #\}) ;;(char= (char x 0) #\|) ;;errors occur on "|" (char= (char x 0) #\:) (char= (char x 0) #\") (char= (char x 0) #\<) (char= (char x 0) #\>) (char= (char x 0) #\?) (char= (char x 0) #\\)) (cons 'shft-key (list (to-dash-key x))) (list (to-dash-key x)) ) ) ;; TO-DASH-KEY ;; args: x ;; description: accepts a character and returns the equivalent id for the key (defun to-dash-key (x) (cond ((equal x " ") 'space-key) ((equal x " ") 'enter-key) ((equal x "`") 'bquote-key) ((equal x ",") 'comma-key) ((equal x ".") 'period-key) ((equal x "=") 'equal-key) ((equal x "-") 'hyphen-key) ((equal x "/") 'slash-key) ((equal x ";") 'semi-key) ((equal x "'") 'quote-key) ;;shifted characters ((equal x "~") 'tilda-key) ((equal x "!") 'excl-key) ((equal x "@") 'at-key) ((equal x "#") 'hash-key) ((equal x "$") 'quest-key) ((equal x "%") 'perc-key) ((equal x "^") 'carrot-key) ((equal x "&") 'and-key) ((equal x "*") 'aster-key) ((equal x "(") 'left-paren-key) ((equal x ")") 'right-paren-key) ((equal x "_") 'dash-key) ((equal x "+") 'plus-key) ((equal x "}") 'right-bracket-key) ((equal x "{") 'left-bracket-key) ((equal x ":") 'colon-key) ((equal x "<") 'less-key) ((equal x ">") 'greater-key) ((equal x "?") 'question-key) ((equal x "\"") 'double-quote-key) ((equal x "\\") 'backslash-key) ((string< x "0") 'char-key) (t (read-from-string (format nil "~a-key" x))))) ;; INC-LEFT-NUMCHAR-CNT ;; args: cur-hand ;; description: accepts one argument cur-hand (left or right) to determine whether to increment ;; returns: updated value ;; notes: this is a helper function called by create-initiate-keystroke-type-string-body ;; author: eyk (defun inc-left-numchar-cnt (cur-hand) (if (equal cur-hand 'left) 1 0) ) ;; INC-RIGHT-NUMCHAR-CNT ;; args: cur-hand ;; description: accepts one argument cur-hand (left or right) to determine whether to increment ;; returns: updated value ;; notes: this is a helper function called by create-initiate-keystroke-type-string-body ;; author: eyk (defun inc-right-numchar-cnt (cur-hand) (if (equal cur-hand 'right) 1 0) ) ;; INTEGER-TO-STRING ;; args: x ;; description: converts a digit x to a string ;; return value: "x" (defun integer-to-string (x) (prin1-to-string x)) ;; create-LEFT-NUMCHAR args: lis description: returns the number of ;; characters typed with the left hand in a string the argument lis is ;; in the form (h-key e-key l-key l-key o-key) for the string "hello" ;; author: eyk (defun create-left-numchar (lis) (cond ((equal nil lis) 0) ((equal 'left (choose-hand (first lis))) (+ 1 (create-left-numchar (rest lis)))) (t (+ 0 (create-left-numchar (rest lis))))) ) ;; create-RIGHT-NUMCHAR ;; args: lis ;; description: returns the number of characters typed with the right ;; hand in a string, the argument lis is in the form (h-key ;; e-key l-key l-key o-key) for the string "hello" ;; author: eyk (defun create-right-numchar (lis) (cond ((equal nil lis) 0) ((equal 'right (choose-hand (first lis))) (+ 1 (create-right-numchar (rest lis)))) (t (+ 0 (create-right-numchar (rest lis))))) ) ;;;;;;;;;;;;;;;;; functions to return step clauses for a given step, primitive, and waitfor condition ;;;;;;;;;;;; ;; create-TYPE-STRING-INDEX-CLAUSE args: string description: returns the ;; index clause for a given string to type return value: index clause ;; e.g. (create-type-string "elaine") => (index (type-string-elaine)) ;; author: eyk (defun create-type-string-index-clause (func-name) (list 'index (list 'TYPE-STRING-CREATED func-name))) ;; create-STEP-CLAUSE args: step-index atom, primitive list, waitfor ;; list description: returns the step clause for a given step-index ;; string, primitive list, and waitfor list return value: step clause ;; e.g. (create-step-clause 'c2 '(initiate-keystroke) '(waitfor ?c1)) => ;; (step c2 (initiate-keystroke) (waitfor ?c1)) author: eyk notes: NEED ;; TO CHECK FOR NIL WAITFOR LISTS (taken care of) (defun create-step-clause (step-index primitive-list waitfor-list) (cond ((equal waitfor-list nil) ;; no waitfors (append (list 'step step-index) (list primitive-list))) (t (append (append (list 'step step-index) (list primitive-list)) (list waitfor-list))))) ;; create-TERMINATE-CLAUSE ;; args: x ;; description: returns the termination clause for a given waitfor step index x ;; return value: termination clause ;; author: eyk (defun create-terminate-clause () (list 'step 't '(terminate) '(waitfor ?w)) ) ;;;;;;;;;;;;;;;;;;; functions to return waitfor clauses for step indexes ;;;;;;;;;;;;;;;;; ;; create-WAITFOR-CLAUSE args: list of step indexes description: returns ;; the waitfor clause for a list of waitfor for conditions (conjunctive) ;; return value: waitfor clause e.g (create-waitfor-clause '(?c3 ?m2)) ;; => (waitfor ?c3 ?m2) (defun create-waitfor-clause (lis) (cons 'waitfor lis) ) ;;;;;;;;;;;;;;;;;;; functions to return a step index (motor, cog, world) ;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;; ;; create-MOTOR-STEP-INDEX-VAR ;; args: step index ;; description: returns the string value of a motor step for a given index ;; return value: motor step e.g. (create-motor-step-index '5) => ?m5) (defun create-motor-step-index-var (num-char1 num-char2) (read-from-string (concatenate 'string "?m" (integer-to-string num-char1) "-" (integer-to-string num-char2)))) ;; create-COG-STEP-INDEX-VAR ;; args: step index ;; description: returns the string value of a cognitive step for a given index ;; return value: cognitive step e.g. (create-cog-step-index-str '5) => ?c5) (defun create-cog-step-index-var (num-char1 num-char2) (read-from-string (concatenate 'string "?c" (integer-to-string num-char1) "-" (integer-to-string num-char2)))) ;; create-WORLD-STEP-INDEX-VAR ;; args: step index ;; description: returns the string value of a world step for a given index ;; return value: world step e.g. (create-world-step-index-str '5) => ?w5) (defun create-world-step-index-var (num-char1 num-char2) (read-from-string (concatenate 'string "?w" (integer-to-string num-char1) "-" (integer-to-string num-char2)))) ;; create-MOTOR-STEP-INDEX ;; args: step index ;; description: returns the string value of a motor step for a given index ;; return value: motor step e.g. (create-motor-step-index '5) => m5) (defun create-motor-step-index (num-char1 num-char2) (read-from-string (concatenate 'string "m" (integer-to-string num-char1) "-" (integer-to-string num-char2)))) ;; create-COG-STEP-INDEX ;; args: step index ;; description: returns the string value of a cognitive step for a given index ;; return value: cognitive step e.g. (create-cog-step-index '5) => c5) (defun create-cog-step-index (num-char1 num-char2) (read-from-string (concatenate 'string "c" (integer-to-string num-char1) "-" (integer-to-string num-char2)))) ;; create-WORLD-STEP-INDEX ;; args: step index ;; description: returns the string value of a world step for a given index ;; return value: world step e.g. (create-world-step-index-str '5) => w5) (defun create-world-step-index (num-char1 num-char2) (read-from-string (concatenate 'string "w" (integer-to-string num-char1) "-" (integer-to-string num-char2)) ) ) ;; create-HOLD-VIRTUAL-RESOURCE-STEP-INDEX ;; args: step index ;; description: returns the string value of a cognitive step for a given index ;; return value: cognitive step e.g. (create-cog-step-index '5) => c5) (defun create-hold-virtual-resource-step-index (num-char1 num-char2 num-char3) (read-from-string (concatenate 'string "hvr" (integer-to-string num-char1) "-" (integer-to-string num-char2) "-" (integer-to-string num-char3)))) ;; create-RELEASE-VIRTUAL-RESOURCE-STEP-INDEX ;; args: step index ;; description: returns the string value of a cognitive step for a given index ;; return value: cognitive step e.g. (create-cog-step-index '5) => c5) (defun create-release-virtual-resource-step-index (num-char1 num-char2 num-char3) (read-from-string (concatenate 'string "rvr" (integer-to-string num-char1) "-" (integer-to-string num-char2) "-" (integer-to-string num-char3))))
74844
;;;-*- Mode: Lisp; Package: :cl-user -*- ;;; ;;; apex/examples/apexlib/primitive-templates/typist.lisp ;;; ;;; Copyright: See apex/LICENSE ;;; Version: $Id: typist.lisp,v 1.7 2006/01/15 03:42:53 dalal Exp $ ;; Modified 3aug02 by <NAME> and <NAME> We changed the ;; hold-resource to be inside a hold-resource-step That step uses the ;; resource that it holds. This solved a problem that we had with the ;; CAD model, where contention for the left-hand-block caused the ;; template to lose ownership of all resources, which released the ;; typing-cognition-block, which allowed activities from later ;; templates to sneak in. Our solution removed the contention, and ;; hence made the CAD model run, but we still need to think about ;; whether the asa should remove resources as it is doing or if it ;; should do it some other way that does not cause the problem if ;; other unanticipated contentions arise. ;; The hold-resource-steps are at the top of this file. It is likely ;; that all templates should use them but we will decide about that ;; after the Cognitive Science 2002 Tutorial. ;; ;; modified 5/10/02 (eyk) ;;; -- wf. 12 January 2005. ;;; Version 2.4.x of Apex incorrectly converted these sequential ;;; procedures to put in a 'waitfor' on the 'hold-resource' step ;;; of these procedures. That is to say, it was not defined what it ;;; would mean to have a PROFILE step in :sequential procedures ;;; and Apex didn't signal an error. Rewriting these to have the ;;; a 'waitfor' that can't complete seems to solve the problems with ;;; the applications, but it might not be what is wanted. ;;; ;;;(procedure :sequential ;;; (index (hold-resource-step right-hand-block)) ;;; (profile right-hand-block) ;;; (hold-resource right-hand-block :ancestor 2)) ;;; ;;;(procedure :sequential ;;; (index (hold-resource-step left-hand-block)) ;;; (profile left-hand-block) ;;; (hold-resource left-hand-block :ancestor 2)) ;;; ;;;(procedure :sequential ;;; (index (hold-resource-step type-string-block)) ;;; (profile type-string-block) ;;; (hold-resource type-string-block :ancestor 2)) ;;; ;;;(procedure :sequential ;;; (index (hold-resource-step typing-cognition-block)) ;;; (profile typing-cognition-block) ;;; (hold-resource typing-cognition-block :ancestor 2)) (procedure ;; :sequential (index (hold-resource-step right-hand-block)) (profile right-hand-block) (step s1 (hold-resource right-hand-block :ancestor 2)) ;; (waitfor ?ever)) (step term (terminate) (waitfor ?s1))) (procedure ;; :sequential (index (hold-resource-step left-hand-block)) (profile left-hand-block) (step s1 (hold-resource left-hand-block :ancestor 2)) ;; (waitfor ?ever)) (step term (terminate) (waitfor ?s1))) (procedure ;; :sequential (index (hold-resource-step type-string-block)) (profile type-string-block) (step s1 (hold-resource type-string-block :ancestor 2)) ;; (waitfor ?ever)) (step term (terminate) (waitfor ?s1))) (procedure ;;:sequential (index (hold-resource-step typing-cognition-block)) (profile typing-cognition-block) (step s1 (hold-resource typing-cognition-block :ancestor 2)) ;; (waitfor ?ever)) (step term (terminate) (waitfor ?s1))) ;;;;;;;;;;; GLOBAL CONSTANTS ;;;;;;;; ;; COGNITION PRIMITIVES (setf *get-chunk* (list 'get-chunk)) (setf *initiate-keystroke* (list 'initiate-keystroke)) ;; LEFT-HAND PRIMITIVES (setf *type-key-left* (list 'type-key-left)) ;; RIGHT-HAND PRIMITIVES (setf *type-key-right* (list 'type-key-right)) ;; WORLD PRIMITIVE (setf *world* (list 'world)) ;;;;;;;;;;; GLOBAL VARIABLES ;;;;;;;; (setf *LAST-CHAR-HAND-GENSYM* nil) ;; Unique symbol of previous type-string template created ;; (if it exists). This is to keep track of a world event that ;; is generated at the end of every type-string template created. ;; If the current type-string template has a same-hand constraint ;; it needs to wait for the last motor activity of the previous ;; type-string template to begin the first initiate-keystroke ;; activity of the current template being generated. (setf *LAST-CHAR-HAND* nil) ;; Holds the hand that typed the last character of the ;; previous template. ;;;;;;;;;; TYPIST CODE ;;;;;;;;;;;;;; ;; TYPE-STRING ;; args: ?str ;; description: constructs one pdl template for a given string. ;; the pdl template is given a unique identifier. ;; after the pdl template is constructed, the pdl template is called. ;; return value: nothing ;(procedure :sequential ; (index (type-string ?str)) ; (construct-typing-pdl ?str => ?pdl-name) ; (TYPE-STRING-CREATED ?pdl-name) ;) (procedure (index (type-string ?str)) (step s1 (?this-step) (select ?this-step (depends-on '*R-hand-on* '((mouse home-to-keyboard) (keyboard no-op)))) (rank 1)) (step s2 (type-string-R-hand-on-keyboard ?str) (rank 2)) (step t (terminate) (waitfor ?s1 ?s2)) ) (procedure :sequential (index (type-string-R-hand-on-keyboard ?str)) (construct-typing-pdl ?str => ?pdl-name) (TYPE-STRING-CREATED ?pdl-name) ) (procedure :sequential (index (home-to-keyboard-before-typing)) (hold-resource-step right-hand-block) (initiate-home-to keyboard) (right-hand-home-to keyboard) (WORLD 0 *R-hand-on* keyboard)) ;; CONSTRUCT-TYPING-PDL ;; args: ?str ;; description: generates a new pdl template to type the string ?str. ;; a unique id is given to the template. ;; sets the hand of the last chararacter typed in ?str and unique id. ;; return value: the unique id for the template ;;;(procedure :special ;;; (index (construct-typing-pdl ?str)) ;;; (let ;;; ((func-name (gensym))) ;;create the new procedure name ;;; (eval (build-pdl ?str func-name)) ;;; (add-newest-proc) ;;; (setf *LAST-CHAR-HAND-GENSYM* (read-from-string (string func-name))) ;;; (setf *LAST-CHAR-HAND* (choose-hand (car (last (string-to-list ?str))))) ;;; func-name ;;; ) ;;;) (primitive (index (construct-typing-pdl ?str)) (return (let ((func-name (gensym))) ;;create the new procedure name (eval (build-pdl ?str func-name)) (add-newest-proc) (setf *LAST-CHAR-HAND-GENSYM* (read-from-string (string func-name))) (setf *LAST-CHAR-HAND* (choose-hand (car (last (string-to-list ?str))))) func-name ) )) ;; ADD-NEWEST-PROC (mfreed) ;; args: none ;; description: Call this after (eval (build-pdl ?str func-name)) in the procedure type-string. ;; return value: don't know ;; notes: This function is a hack, to be obsoleted after revising proc management mechanisms. (defun add-newest-proc () (add-procedure (first *proclib*) *agent*)) ;; BUILD-PDL ;; args: str func-name ;; description: returns a list representing the PDL procedure to type str ;; return value: a list representing the PDL template to type the string str ;; author: eyk (defun build-pdl (str func-name) (let* ((chunks (chop-up str))) (cons 'procedure (cons (create-type-string-index-clause func-name) (append (build-iter chunks 1 nil chunks) (append (list (create-step-clause 'w (append *world* (list 0) (list 'LAST-CHAR-HAND-GENSYM) (list (read-from-string (string func-name)))) (create-waitfor-clause (list (create-motor-step-index-var (length chunks) (+ (length (string-to-list (car (last chunks)))) 1))) ) )) (list (create-terminate-clause)) ) ) ) ) ) ) ;; BUILD-ITER ;; args: lis ;; ind ;; wait-for ;; orig-chunks ;; description: iterates through each chunk and calls build-pdl-chunk to create the pdl for each chunk ;; return value: the initiate-keystroke and type-key pdl for all the chunks of the type-string template (defun build-iter (lis ind wait-for orig-chunks) (if (null lis) nil (append (build-pdl-chunk (car lis) ind wait-for orig-chunks) (build-iter (cdr lis) (+ ind 1) (create-waitfor-clause (list (create-cog-step-index-var ind (+ (length (string-to-list (car lis))) 1) ) ) ) orig-chunks) ) ) ) ;; BUILD-PDL-CHUNK ;; args: str ;; ind ;; wait-for ;; orig-str-chunks-lis ;; description: creates the pdl for one particular chunk ;; return value: the initiate-keystroke and type-key pdl for ONE chunk of the type-string template (defun build-pdl-chunk (str ind wait-for orig-str-chunks-lis) (cons (create-step-clause (create-COG-STEP-INDEX ind 1) (cons 'get-chunk (list (read-from-string str))) wait-for) (cons ;; hold virtual resource - typing-cognition-block (create-step-clause (create-hold-virtual-resource-step-index ind 1 0) (list 'hold-resource-step 'typing-cognition-block) (create-waitfor-clause (list (create-cog-step-index-var ind 1))) ) (create-initiate-keystroke-type-string-body (string-to-list str) ind orig-str-chunks-lis) ) ) ) ;; create-INITIATE-KEYSTROKE-TYPE-STRING-BODY ;; args: orig-str-lis ;; description: takes a list of keys representing the string and returns the a list representing ;; the initiate-keystroke-type-string pdl for the entire string ;; return value: a list representing the PDL code for initiate-keystroke and type-key steps ;; for typing a chunk (defun create-initiate-keystroke-type-string-body (orig-str-lis step-index1 orig-str-chunks-lis) (do* ( ;; var1 init1 update ;; variables with no update on each iteration (str-total-numchar (length orig-str-lis)) (str-left-numchar (create-left-numchar orig-str-lis)) (str-right-numchar (create-right-numchar orig-str-lis)) (step-index2 2 (+ step-index2 1)) (prev-hand nil (choose-hand cur-key)) ;; variables with updates on each iteration (str-list orig-str-lis (rest str-list)) (cur-key (first orig-str-lis) (first str-list)) (cur-hand (choose-hand cur-key) (choose-hand cur-key)) (str-left-numchar-cnt (+ 0 (inc-left-numchar-cnt cur-hand)) (+ str-left-numchar-cnt (inc-left-numchar-cnt cur-hand))) (str-right-numchar-cnt (+ 0 (inc-right-numchar-cnt cur-hand)) (+ str-right-numchar-cnt (inc-right-numchar-cnt cur-hand))) (result-pdl-list (append (create-type-key-pdl str-total-numchar str-left-numchar str-right-numchar step-index1 step-index2 cur-hand str-left-numchar-cnt str-right-numchar-cnt str-list orig-str-chunks-lis) (append (create-initiate-keystroke-pdl str-list cur-hand prev-hand step-index1 step-index2 orig-str-chunks-lis) nil)) (append (create-type-key-pdl str-total-numchar str-left-numchar str-right-numchar step-index1 step-index2 cur-hand str-left-numchar-cnt str-right-numchar-cnt str-list orig-str-chunks-lis) (append (create-initiate-keystroke-pdl str-list cur-hand prev-hand step-index1 step-index2 orig-str-chunks-lis) result-pdl-list))) ) ;; test action1 .. action-n ((equal 1 (length str-list)) (reverse result-pdl-list) ) ) ;;end do* ) ;; create-INITIATE-KEYSTROKE-PDL ;; args: str-list cur-hand prev-hand step-index ;; description: takes 4 arguments. str-list represents the list of keys that yet to have ;; PDL generated. cur-hand is the hand needed to type the current key. ;; prev-hand is the hand needed to type the previous key (nil if first key). ;; step index is the current step. ;; return value: a list representing each a single initiate-keystroke step ;; author: eyk (defun create-initiate-keystroke-pdl (str-list cur-hand prev-hand step-index1 step-index2 orig-str-chunks-lis) (cond ((and (= step-index1 1) (= step-index2 2) (equal cur-hand *LAST-CHAR-HAND*)) ;; same-hand constraint across chunks BETWEEN templates for first initiate-keystroke cognitive operator (cond ((equal 1 (length str-list)) (list (create-step-clause (create-cog-step-index step-index1 step-index2) (reverse (cons (first str-list) *initiate-keystroke*)) (append (create-waitfor-clause (cons (create-cog-step-index-var step-index1 (- step-index2 1)) nil)) (list (list 'variable 'LAST-CHAR-HAND-GENSYM *LAST-CHAR-HAND-GENSYM*)) ) ) ;; release virtual resource - typing-cognition-block (create-step-clause (create-release-virtual-resource-step-index step-index1 step-index2 0) (list 'release-resource 'typing-cognition-block ':ancestor 1) (create-waitfor-clause (list (create-cog-step-index-var step-index1 step-index2))) ) ) ) (t (list (create-step-clause (create-cog-step-index step-index1 step-index2) (reverse (cons (first str-list) *initiate-keystroke*)) (append (create-waitfor-clause (cons (create-cog-step-index-var step-index1 (- step-index2 1)) nil)) (list (list 'variable 'LAST-CHAR-HAND-GENSYM *LAST-CHAR-HAND-GENSYM*)) ) ) ) ) ) ) ((and (> step-index1 1) (= step-index2 2) (equal cur-hand (choose-hand (nth (- (length (string-to-list (nth (- step-index1 2) orig-str-chunks-lis))) 1) (string-to-list (nth (- step-index1 2) orig-str-chunks-lis))) )) ) ;; same-hand constraint across chunks WITHIN templates ;; for first initiate-keystroke cognitive operator (list (create-step-clause (create-cog-step-index step-index1 step-index2) (reverse (cons (first str-list) *initiate-keystroke*)) (create-waitfor-clause (cons (create-cog-step-index-var step-index1 (- step-index2 1)) (cons (create-motor-step-index-var (- step-index1 1) (+ (length (string-to-list (nth (- step-index1 2) orig-str-chunks-lis))) 1)) nil)))) ) ) ((equal 1 (length str-list)) ;; last character (cond ((equal cur-hand prev-hand) (list (create-step-clause (create-cog-step-index step-index1 step-index2) (reverse (cons (first str-list) *initiate-keystroke*)) (create-waitfor-clause (cons (create-cog-step-index-var step-index1 (- step-index2 1)) (cons (create-motor-step-index-var step-index1 (- step-index2 1)) nil)))) ;; release virtual resource - typing-cognition-block (create-step-clause (create-release-virtual-resource-step-index step-index1 step-index2 0) (list 'release-resource 'typing-cognition-block ':ancestor 1) (create-waitfor-clause (list (create-cog-step-index-var step-index1 step-index2))) ) ) ) (t (list (create-step-clause (create-cog-step-index step-index1 step-index2) (reverse (cons (first str-list) *initiate-keystroke*)) (create-waitfor-clause (cons (create-cog-step-index-var step-index1 (- step-index2 1)) nil))) ;; release virtual resource - typing-cognition-block (create-step-clause (create-release-virtual-resource-step-index step-index1 step-index2 0) (list 'release-resource 'typing-cognition-block ':ancestor 1) (create-waitfor-clause (list (create-cog-step-index-var step-index1 step-index2))) ) ) ) ) ) (t ;; not last character (cond ((equal cur-hand prev-hand) (list (create-step-clause (create-cog-step-index step-index1 step-index2) (reverse (cons (first str-list) *initiate-keystroke*)) (create-waitfor-clause (cons (create-cog-step-index-var step-index1 (- step-index2 1)) (cons (create-motor-step-index-var step-index1 (- step-index2 1)) nil)))) ) ) (t (list (create-step-clause (create-cog-step-index step-index1 step-index2) (reverse (cons (first str-list) *initiate-keystroke*)) (create-waitfor-clause (cons (create-cog-step-index-var step-index1 (- step-index2 1)) nil))) ) ) ) ) ) ) ;; create-TYPE-KEY-PDL ;; args: str-total-numchar ;; str-left-numchar ;; str-right-numchar ;; step-index ;; cur-hand ;; str-left-numchar-cnt ;; str-right-numchar-cnt ;; str-list ;; description: takes 8 arguments. str-total-numchar is the total ;; number of characters in the string. str-left-numchar is ;; the total number of characters typed with the left-hand. ;; str-right-numchar is the total number of characters ;; typed with the right-hand. step-index is the number for ;; the current step to be generated. cur-hand is the hand ;; (left or right) used to type the current character. ;; str-left-numchar-cnt is a counter to determine how many ;; characters have been typed with the left hand. ;; str-right-numchar-cnt is a coutner to determine how many ;; characters have been typed with the right hand. ;; str-list is the list representation of the string to be ;; typed. ;; notes: this is a helper function called by ;; create-initiate-keystroke-type-string-body author: eyk (defun create-type-key-pdl (str-total-numchar str-left-numchar str-right-numchar step-index1 step-index2 cur-hand str-left-numchar-cnt str-right-numchar-cnt str-list orig-str-chunks-lis) (let* ((vr-index 0)) (cond ((equal str-total-numchar (length str-list)) ;first motor operator (cond ((> step-index1 1) ;; the current chunk is 2..n chunk (cond ((equal 'right cur-hand) (cond ((equal str-right-numchar str-right-numchar-cnt) (list (create-step-clause (create-motor-step-index step-index1 step-index2) (reverse (cons (first str-list) *type-key-right*)) (create-waitfor-clause (cons (create-cog-step-index-var step-index1 step-index2) (cons (create-motor-step-index-var (- step-index1 1) (+ (length (string-to-list (nth (- step-index1 2) orig-str-chunks-lis))) 1)) nil)))) (create-step-clause (create-hold-virtual-resource-step-index step-index1 step-index2 (+ vr-index 1)) (list 'hold-resource-step 'right-hand-block) (create-waitfor-clause (list (create-cog-step-index-var step-index1 step-index2))) ; <NAME> told me to! ) (create-step-clause (create-hold-virtual-resource-step-index step-index1 step-index2 (+ vr-index 2)) (list 'hold-resource-step 'type-string-block) (create-waitfor-clause (list (create-cog-step-index-var step-index1 step-index2))) ) (create-step-clause (create-release-virtual-resource-step-index step-index1 step-index2 (+ vr-index 3)) (list 'release-resource 'right-hand-block ':ancestor 1) (create-waitfor-clause (list (create-motor-step-index-var step-index1 step-index2))) ) ) ) (t (list (create-step-clause (create-motor-step-index step-index1 step-index2) (reverse (cons (first str-list) *type-key-right*)) (create-waitfor-clause (cons (create-cog-step-index-var step-index1 step-index2) (cons (create-motor-step-index-var (- step-index1 1) (+ (length (string-to-list (nth (- step-index1 2) orig-str-chunks-lis))) 1)) nil)))) (create-step-clause (create-hold-virtual-resource-step-index step-index1 step-index2 (+ vr-index 1)) (list 'hold-resource-step 'right-hand-block) (create-waitfor-clause (list (create-motor-step-index-var step-index1 step-index2))) ) (create-step-clause (create-hold-virtual-resource-step-index step-index1 step-index2 (+ vr-index 2)) (list 'hold-resource-step 'type-string-block) (create-waitfor-clause (list (create-cog-step-index-var step-index1 step-index2))) ) ) ))) ((equal 'left cur-hand) (cond ((equal str-left-numchar str-left-numchar-cnt) (list (create-step-clause (create-motor-step-index step-index1 step-index2) (reverse (cons (first str-list) *type-key-left*)) (create-waitfor-clause (cons (create-cog-step-index-var step-index1 step-index2) (cons (create-motor-step-index-var (- step-index1 1) (+ (length (string-to-list (nth (- step-index1 2) orig-str-chunks-lis))) 1)) nil)))) (create-step-clause (create-hold-virtual-resource-step-index step-index1 step-index2 (+ vr-index 1)) (list 'hold-resource-step 'left-hand-block) (create-waitfor-clause (list (create-cog-step-index-var step-index1 step-index2))) ) (create-step-clause (create-hold-virtual-resource-step-index step-index1 step-index2 (+ vr-index 2)) (list 'hold-resource-step 'type-string-block) (create-waitfor-clause (list (create-cog-step-index-var step-index1 step-index2))) ) (create-step-clause (create-release-virtual-resource-step-index step-index1 step-index2 (+ vr-index 3)) (list 'release-resource 'left-hand-block ':ancestor 1) (create-waitfor-clause (list (create-motor-step-index-var step-index1 step-index2))) ) ) ) (t (list (create-step-clause (create-motor-step-index step-index1 step-index2) (reverse (cons (first str-list) *type-key-left*)) (create-waitfor-clause (cons (create-cog-step-index-var step-index1 step-index2) (cons (create-motor-step-index-var (- step-index1 1) (+ (length (string-to-list (nth (- step-index1 2) orig-str-chunks-lis))) 1)) nil)))) (create-step-clause (create-hold-virtual-resource-step-index step-index1 step-index2 (+ vr-index 1)) (list 'hold-resource-step 'left-hand-block) (create-waitfor-clause (list (create-cog-step-index-var step-index1 step-index2))) ) (create-step-clause (create-hold-virtual-resource-step-index step-index1 step-index2 (+ vr-index 2)) (list 'hold-resource-step 'type-string-block) (create-waitfor-clause (list (create-cog-step-index-var step-index1 step-index2))) ) ) ) )) ) ) (t ;; the current chunk is the first chunk (cond ((equal 'right cur-hand) (cond ((equal str-right-numchar str-right-numchar-cnt) (list (create-step-clause (create-motor-step-index step-index1 step-index2) (reverse (cons (first str-list) *type-key-right*)) (create-waitfor-clause (cons (create-cog-step-index-var step-index1 step-index2) nil))) (create-step-clause (create-hold-virtual-resource-step-index step-index1 step-index2 (+ vr-index 1)) (list 'hold-resource-step 'right-hand-block) (create-waitfor-clause (list (create-cog-step-index-var step-index1 step-index2))) ) (create-step-clause (create-hold-virtual-resource-step-index step-index1 step-index2 (+ vr-index 2)) (list 'hold-resource-step 'type-string-block) (create-waitfor-clause (list (create-cog-step-index-var step-index1 step-index2))) ) (create-step-clause (create-release-virtual-resource-step-index step-index1 step-index2 (+ vr-index 3)) (list 'release-resource 'right-hand-block ':ancestor 1) (create-waitfor-clause (list (create-motor-step-index-var step-index1 step-index2))) ) ) ) (t (list (create-step-clause (create-motor-step-index step-index1 step-index2) (reverse (cons (first str-list) *type-key-right*)) (create-waitfor-clause (cons (create-cog-step-index-var step-index1 step-index2) nil))) (create-step-clause (create-hold-virtual-resource-step-index step-index1 step-index2 (+ vr-index 1)) (list 'hold-resource-step 'right-hand-block) (create-waitfor-clause (list (create-cog-step-index-var step-index1 step-index2))) ) (create-step-clause (create-hold-virtual-resource-step-index step-index1 step-index2 (+ vr-index 2)) (list 'hold-resource-step 'type-string-block) (create-waitfor-clause (list (create-cog-step-index-var step-index1 step-index2))) ) ) ))) ((equal 'left cur-hand) (cond ((equal str-left-numchar str-left-numchar-cnt) (list (create-step-clause (create-motor-step-index step-index1 step-index2) (reverse (cons (first str-list) *type-key-left*)) (create-waitfor-clause (cons (create-cog-step-index-var step-index1 step-index2) nil))) (create-step-clause (create-hold-virtual-resource-step-index step-index1 step-index2 (+ vr-index 1)) (list 'hold-resource-step 'left-hand-block) (create-waitfor-clause (list (create-cog-step-index-var step-index1 step-index2))) ) (create-step-clause (create-hold-virtual-resource-step-index step-index1 step-index2 (+ vr-index 2)) (list 'hold-resource-step 'type-string-block) (create-waitfor-clause (list (create-cog-step-index-var step-index1 step-index2))) ) (create-step-clause (create-release-virtual-resource-step-index step-index1 step-index2 (+ vr-index 3)) (list 'release-resource 'left-hand-block ':ancestor 1) (create-waitfor-clause (list (create-motor-step-index-var step-index1 step-index2))) ) ) ) (t (list (create-step-clause (create-motor-step-index step-index1 step-index2) (reverse (cons (first str-list) *type-key-left*)) (create-waitfor-clause (cons (create-cog-step-index-var step-index1 step-index2) nil))) (create-step-clause (create-hold-virtual-resource-step-index step-index1 step-index2 (+ vr-index 1)) (list 'hold-resource-step 'left-hand-block) (create-waitfor-clause (list (create-cog-step-index-var step-index1 step-index2))) ) (create-step-clause (create-hold-virtual-resource-step-index step-index1 step-index2 (+ vr-index 2)) (list 'hold-resource-step 'type-string-block) (create-waitfor-clause (list (create-cog-step-index-var step-index1 step-index2))) ) ) ))) ) ) ) ) ((equal 'right cur-hand) ;right motor operator (cond ((equal 1 str-right-numchar-cnt) ;;type-key-right-first (list (create-step-clause (create-motor-step-index step-index1 step-index2) (reverse (cons (first str-list) *type-key-right*)) (create-waitfor-clause (cons (create-cog-step-index-var step-index1 step-index2) (cons (create-motor-step-index-var step-index1 (- step-index2 1)) nil)))) (create-step-clause (create-hold-virtual-resource-step-index step-index1 step-index2 (+ vr-index 1)) (list 'hold-resource-step 'right-hand-block) (create-waitfor-clause (list (create-cog-step-index-var step-index1 step-index2))) ) ) ) ((equal str-total-numchar (+ str-right-numchar-cnt str-left-numchar-cnt)) (list (create-step-clause (create-motor-step-index step-index1 step-index2) (reverse (cons (first str-list) *type-key-right*)) (create-waitfor-clause (cons (create-cog-step-index-var step-index1 step-index2) (cons (create-motor-step-index-var step-index1 (- step-index2 1)) nil)))) (create-step-clause (create-release-virtual-resource-step-index step-index1 step-index2 (+ vr-index 1)) (list 'release-resource 'right-hand-block ':ancestor 1) (create-waitfor-clause (list (create-motor-step-index-var step-index1 step-index2))) ) (create-step-clause (create-release-virtual-resource-step-index step-index1 step-index2 (+ vr-index 2)) (list 'release-resource 'type-string-block ':ancestor 1) (create-waitfor-clause (list (create-cog-step-index-var step-index1 step-index2))) ) ) ) ((equal str-right-numchar str-right-numchar-cnt) (list (create-step-clause (create-motor-step-index step-index1 step-index2) (reverse (cons (first str-list) *type-key-right*)) (create-waitfor-clause (cons (create-cog-step-index-var step-index1 step-index2) (cons (create-motor-step-index-var step-index1 (- step-index2 1)) nil)))) (create-step-clause (create-release-virtual-resource-step-index step-index1 step-index2 (+ vr-index 1)) (list 'release-resource 'right-hand-block ':ancestor 1) (create-waitfor-clause (list (create-motor-step-index-var step-index1 step-index2))) ) ) ) (t (list (create-step-clause (create-motor-step-index step-index1 step-index2) (reverse (cons (first str-list) *type-key-right*)) (create-waitfor-clause (cons (create-cog-step-index-var step-index1 step-index2) (cons (create-motor-step-index-var step-index1 (- step-index2 1)) nil)))) ) ) ) ) ((equal 'left cur-hand) (cond ((equal 1 str-left-numchar-cnt) ;;type-key-right-first (list (create-step-clause (create-motor-step-index step-index1 step-index2) (reverse (cons (first str-list) *type-key-left*)) (create-waitfor-clause (cons (create-cog-step-index-var step-index1 step-index2) (cons (create-motor-step-index-var step-index1 (- step-index2 1)) nil)))) (create-step-clause (create-hold-virtual-resource-step-index step-index1 step-index2 (+ vr-index 1)) (list 'hold-resource-step 'left-hand-block) (create-waitfor-clause (list (create-cog-step-index-var step-index1 step-index2))) ) ) ) ((equal str-total-numchar (+ str-right-numchar-cnt str-left-numchar-cnt)) (list (create-step-clause (create-motor-step-index step-index1 step-index2) (reverse (cons (first str-list) *type-key-left*)) (create-waitfor-clause (cons (create-cog-step-index-var step-index1 step-index2) (cons (create-motor-step-index-var step-index1 (- step-index2 1)) nil)))) (create-step-clause (create-release-virtual-resource-step-index step-index1 step-index2 (+ vr-index 1)) (list 'release-resource 'left-hand-block ':ancestor 1) (create-waitfor-clause (list (create-motor-step-index-var step-index1 step-index2))) ) (create-step-clause (create-release-virtual-resource-step-index step-index1 step-index2 (+ vr-index 2)) (list 'release-resource 'type-string-block ':ancestor 1) (create-waitfor-clause (list (create-cog-step-index-var step-index1 step-index2))) ) ) ) ((equal str-left-numchar str-left-numchar-cnt) (list (create-step-clause (create-motor-step-index step-index1 step-index2) (reverse (cons (first str-list) *type-key-left*)) (create-waitfor-clause (cons (create-cog-step-index-var step-index1 step-index2) (cons (create-motor-step-index-var step-index1 (- step-index2 1)) nil)))) (create-step-clause (create-release-virtual-resource-step-index step-index1 step-index2 (+ vr-index 1)) (list 'release-resource 'left-hand-block ':ancestor 1) (create-waitfor-clause (list (create-motor-step-index-var step-index1 step-index2))) ) ) ) (t (list (create-step-clause (create-motor-step-index step-index1 step-index2) (reverse (cons (first str-list) *type-key-left*)) (create-waitfor-clause (cons (create-cog-step-index-var step-index1 step-index2) (cons (create-motor-step-index-var step-index1 (- step-index2 1)) nil)))) ) ) ) ) (nil (print "error! key not found!")) ;;error! key not found! ) ) ) ;; kmd added this; it might be wrong ;;;;;;;;;;;;;;;;; helper functions ;;;;;;;;;;;;;;;;;; ;; CHOOSE-HAND ;; args: key ;; description: Accepts a key in the form <key>-key and returns the hand that types it ;; return value: Hand that typed the key ;; notes: This is the knowledge of which hand types which key ;; that a touch-typist has "at her fingertips" ;; This means we are not actually using the keyboard at all ;; that may not be stupid for a touch typist (bej) (defun choose-hand (key) (cond ((equal key nil) nil) ((member key '(esc-key f1-key f2-key f3-key f4-key f5-key tilda-key excl-key at-key hash-key quest-key perc-key carrot-key bquote-key 1-key 2-key 3-key 4-key 5-key 6-key tab-key q-key w-key e-key r-key t-key caps-key a-key s-key d-key f-key g-key shft-key z-key x-key c-key v-key b-key ctrl-key win-key alt-key)) 'left) ((member key '(f6-key f7-key f8-key f9-key f10-key f11-key f12-key and-key aster-key left-paren-key right-paren-key dash-key equal-key plus-key 7-key 8-key 9-key 0-key hyphen-key equal-key bslash-key y-key u-key i-key o-key p-key [-key ]-key h-key j-key k-key l-key semi-key quote-key enter-key n-key m-key comma-key period-key slash-key shift-key space-key alt-key win-key select-key ctrl-key colon-key double-quote-key left-bracket-key right-bracket-key less-key greater-key question-key backslash-key)) 'right) (t "not a key we know") ) ) ;; CHOP-UP (mmatessa) ;; args: str ;; description: parses str into separate strings in a list, each string represents a "chunk" ;; return value: a list representing the string parsed into chunks (defun chop-up (str) (let* ((pos (or (position #\space str) (position #\return str))) (end (if pos (position-if-not #'(lambda (x) (or (equal x #\space) (equal x #\return))) str :start pos)))) (cond ((or (null pos) (null end)) (list str)) (t (cons (subseq str 0 end) (chop-up (subseq str end (length str)))))))) ;; STR2LIS ;; args: x ;; description: accepts a string and returns a list representing that string ;; e.g. (str2lis "elaine") => (E L A I N E) ;; author: <NAME> (defun str2lis (x) (let ((ans nil) (sub nil)) (dotimes (i (length x)) (setf sub (subseq x i (1+ i))) (push sub ans)) (reverse ans))) ;; STRING-TO-LIST ;; args: x ;; description: This converts a string to a list of characters with "-key" appended to each ;; character. ;; e.g. (string-to-list "hello") => (H-KEY L-KEY A-KEY I-KEY N-KEY E-KEY) ;; author: eyk (defun string-to-list (x) (append-all (mapcar 'char2key (str2lis x))) ) (defun append-all (lis) (if (null lis) nil (append (car lis) (append-all (cdr lis))))) ;; CHAR2KEY ;; args: x ;; description: This adds "-key" to each charcter in the list ;; author: (defun char2key (x) (if (or (and (char>= (char x 0) #\A) (char<= (char x 0) #\Z)) (char= (char x 0) #\~) (char= (char x 0) #\!) (char= (char x 0) #\@) (char= (char x 0) #\#) (char= (char x 0) #\$) (char= (char x 0) #\%) (char= (char x 0) #\^) (char= (char x 0) #\&) (char= (char x 0) #\*) (char= (char x 0) #\() (char= (char x 0) #\)) (char= (char x 0) #\_) (char= (char x 0) #\+) (char= (char x 0) #\{) (char= (char x 0) #\}) ;;(char= (char x 0) #\|) ;;errors occur on "|" (char= (char x 0) #\:) (char= (char x 0) #\") (char= (char x 0) #\<) (char= (char x 0) #\>) (char= (char x 0) #\?) (char= (char x 0) #\\)) (cons 'shft-key (list (to-dash-key x))) (list (to-dash-key x)) ) ) ;; TO-DASH-KEY ;; args: x ;; description: accepts a character and returns the equivalent id for the key (defun to-dash-key (x) (cond ((equal x " ") 'space-key) ((equal x " ") 'enter-key) ((equal x "`") 'bquote-key) ((equal x ",") 'comma-key) ((equal x ".") 'period-key) ((equal x "=") 'equal-key) ((equal x "-") 'hyphen-key) ((equal x "/") 'slash-key) ((equal x ";") 'semi-key) ((equal x "'") 'quote-key) ;;shifted characters ((equal x "~") 'tilda-key) ((equal x "!") 'excl-key) ((equal x "@") 'at-key) ((equal x "#") 'hash-key) ((equal x "$") 'quest-key) ((equal x "%") 'perc-key) ((equal x "^") 'carrot-key) ((equal x "&") 'and-key) ((equal x "*") 'aster-key) ((equal x "(") 'left-paren-key) ((equal x ")") 'right-paren-key) ((equal x "_") 'dash-key) ((equal x "+") 'plus-key) ((equal x "}") 'right-bracket-key) ((equal x "{") 'left-bracket-key) ((equal x ":") 'colon-key) ((equal x "<") 'less-key) ((equal x ">") 'greater-key) ((equal x "?") 'question-key) ((equal x "\"") 'double-quote-key) ((equal x "\\") 'backslash-key) ((string< x "0") 'char-key) (t (read-from-string (format nil "~a-key" x))))) ;; INC-LEFT-NUMCHAR-CNT ;; args: cur-hand ;; description: accepts one argument cur-hand (left or right) to determine whether to increment ;; returns: updated value ;; notes: this is a helper function called by create-initiate-keystroke-type-string-body ;; author: eyk (defun inc-left-numchar-cnt (cur-hand) (if (equal cur-hand 'left) 1 0) ) ;; INC-RIGHT-NUMCHAR-CNT ;; args: cur-hand ;; description: accepts one argument cur-hand (left or right) to determine whether to increment ;; returns: updated value ;; notes: this is a helper function called by create-initiate-keystroke-type-string-body ;; author: eyk (defun inc-right-numchar-cnt (cur-hand) (if (equal cur-hand 'right) 1 0) ) ;; INTEGER-TO-STRING ;; args: x ;; description: converts a digit x to a string ;; return value: "x" (defun integer-to-string (x) (prin1-to-string x)) ;; create-LEFT-NUMCHAR args: lis description: returns the number of ;; characters typed with the left hand in a string the argument lis is ;; in the form (h-key e-key l-key l-key o-key) for the string "hello" ;; author: eyk (defun create-left-numchar (lis) (cond ((equal nil lis) 0) ((equal 'left (choose-hand (first lis))) (+ 1 (create-left-numchar (rest lis)))) (t (+ 0 (create-left-numchar (rest lis))))) ) ;; create-RIGHT-NUMCHAR ;; args: lis ;; description: returns the number of characters typed with the right ;; hand in a string, the argument lis is in the form (h-key ;; e-key l-key l-key o-key) for the string "hello" ;; author: eyk (defun create-right-numchar (lis) (cond ((equal nil lis) 0) ((equal 'right (choose-hand (first lis))) (+ 1 (create-right-numchar (rest lis)))) (t (+ 0 (create-right-numchar (rest lis))))) ) ;;;;;;;;;;;;;;;;; functions to return step clauses for a given step, primitive, and waitfor condition ;;;;;;;;;;;; ;; create-TYPE-STRING-INDEX-CLAUSE args: string description: returns the ;; index clause for a given string to type return value: index clause ;; e.g. (create-type-string "elaine") => (index (type-string-elaine)) ;; author: eyk (defun create-type-string-index-clause (func-name) (list 'index (list 'TYPE-STRING-CREATED func-name))) ;; create-STEP-CLAUSE args: step-index atom, primitive list, waitfor ;; list description: returns the step clause for a given step-index ;; string, primitive list, and waitfor list return value: step clause ;; e.g. (create-step-clause 'c2 '(initiate-keystroke) '(waitfor ?c1)) => ;; (step c2 (initiate-keystroke) (waitfor ?c1)) author: eyk notes: NEED ;; TO CHECK FOR NIL WAITFOR LISTS (taken care of) (defun create-step-clause (step-index primitive-list waitfor-list) (cond ((equal waitfor-list nil) ;; no waitfors (append (list 'step step-index) (list primitive-list))) (t (append (append (list 'step step-index) (list primitive-list)) (list waitfor-list))))) ;; create-TERMINATE-CLAUSE ;; args: x ;; description: returns the termination clause for a given waitfor step index x ;; return value: termination clause ;; author: eyk (defun create-terminate-clause () (list 'step 't '(terminate) '(waitfor ?w)) ) ;;;;;;;;;;;;;;;;;;; functions to return waitfor clauses for step indexes ;;;;;;;;;;;;;;;;; ;; create-WAITFOR-CLAUSE args: list of step indexes description: returns ;; the waitfor clause for a list of waitfor for conditions (conjunctive) ;; return value: waitfor clause e.g (create-waitfor-clause '(?c3 ?m2)) ;; => (waitfor ?c3 ?m2) (defun create-waitfor-clause (lis) (cons 'waitfor lis) ) ;;;;;;;;;;;;;;;;;;; functions to return a step index (motor, cog, world) ;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;; ;; create-MOTOR-STEP-INDEX-VAR ;; args: step index ;; description: returns the string value of a motor step for a given index ;; return value: motor step e.g. (create-motor-step-index '5) => ?m5) (defun create-motor-step-index-var (num-char1 num-char2) (read-from-string (concatenate 'string "?m" (integer-to-string num-char1) "-" (integer-to-string num-char2)))) ;; create-COG-STEP-INDEX-VAR ;; args: step index ;; description: returns the string value of a cognitive step for a given index ;; return value: cognitive step e.g. (create-cog-step-index-str '5) => ?c5) (defun create-cog-step-index-var (num-char1 num-char2) (read-from-string (concatenate 'string "?c" (integer-to-string num-char1) "-" (integer-to-string num-char2)))) ;; create-WORLD-STEP-INDEX-VAR ;; args: step index ;; description: returns the string value of a world step for a given index ;; return value: world step e.g. (create-world-step-index-str '5) => ?w5) (defun create-world-step-index-var (num-char1 num-char2) (read-from-string (concatenate 'string "?w" (integer-to-string num-char1) "-" (integer-to-string num-char2)))) ;; create-MOTOR-STEP-INDEX ;; args: step index ;; description: returns the string value of a motor step for a given index ;; return value: motor step e.g. (create-motor-step-index '5) => m5) (defun create-motor-step-index (num-char1 num-char2) (read-from-string (concatenate 'string "m" (integer-to-string num-char1) "-" (integer-to-string num-char2)))) ;; create-COG-STEP-INDEX ;; args: step index ;; description: returns the string value of a cognitive step for a given index ;; return value: cognitive step e.g. (create-cog-step-index '5) => c5) (defun create-cog-step-index (num-char1 num-char2) (read-from-string (concatenate 'string "c" (integer-to-string num-char1) "-" (integer-to-string num-char2)))) ;; create-WORLD-STEP-INDEX ;; args: step index ;; description: returns the string value of a world step for a given index ;; return value: world step e.g. (create-world-step-index-str '5) => w5) (defun create-world-step-index (num-char1 num-char2) (read-from-string (concatenate 'string "w" (integer-to-string num-char1) "-" (integer-to-string num-char2)) ) ) ;; create-HOLD-VIRTUAL-RESOURCE-STEP-INDEX ;; args: step index ;; description: returns the string value of a cognitive step for a given index ;; return value: cognitive step e.g. (create-cog-step-index '5) => c5) (defun create-hold-virtual-resource-step-index (num-char1 num-char2 num-char3) (read-from-string (concatenate 'string "hvr" (integer-to-string num-char1) "-" (integer-to-string num-char2) "-" (integer-to-string num-char3)))) ;; create-RELEASE-VIRTUAL-RESOURCE-STEP-INDEX ;; args: step index ;; description: returns the string value of a cognitive step for a given index ;; return value: cognitive step e.g. (create-cog-step-index '5) => c5) (defun create-release-virtual-resource-step-index (num-char1 num-char2 num-char3) (read-from-string (concatenate 'string "rvr" (integer-to-string num-char1) "-" (integer-to-string num-char2) "-" (integer-to-string num-char3))))
true
;;;-*- Mode: Lisp; Package: :cl-user -*- ;;; ;;; apex/examples/apexlib/primitive-templates/typist.lisp ;;; ;;; Copyright: See apex/LICENSE ;;; Version: $Id: typist.lisp,v 1.7 2006/01/15 03:42:53 dalal Exp $ ;; Modified 3aug02 by PI:NAME:<NAME>END_PI and PI:NAME:<NAME>END_PI We changed the ;; hold-resource to be inside a hold-resource-step That step uses the ;; resource that it holds. This solved a problem that we had with the ;; CAD model, where contention for the left-hand-block caused the ;; template to lose ownership of all resources, which released the ;; typing-cognition-block, which allowed activities from later ;; templates to sneak in. Our solution removed the contention, and ;; hence made the CAD model run, but we still need to think about ;; whether the asa should remove resources as it is doing or if it ;; should do it some other way that does not cause the problem if ;; other unanticipated contentions arise. ;; The hold-resource-steps are at the top of this file. It is likely ;; that all templates should use them but we will decide about that ;; after the Cognitive Science 2002 Tutorial. ;; ;; modified 5/10/02 (eyk) ;;; -- wf. 12 January 2005. ;;; Version 2.4.x of Apex incorrectly converted these sequential ;;; procedures to put in a 'waitfor' on the 'hold-resource' step ;;; of these procedures. That is to say, it was not defined what it ;;; would mean to have a PROFILE step in :sequential procedures ;;; and Apex didn't signal an error. Rewriting these to have the ;;; a 'waitfor' that can't complete seems to solve the problems with ;;; the applications, but it might not be what is wanted. ;;; ;;;(procedure :sequential ;;; (index (hold-resource-step right-hand-block)) ;;; (profile right-hand-block) ;;; (hold-resource right-hand-block :ancestor 2)) ;;; ;;;(procedure :sequential ;;; (index (hold-resource-step left-hand-block)) ;;; (profile left-hand-block) ;;; (hold-resource left-hand-block :ancestor 2)) ;;; ;;;(procedure :sequential ;;; (index (hold-resource-step type-string-block)) ;;; (profile type-string-block) ;;; (hold-resource type-string-block :ancestor 2)) ;;; ;;;(procedure :sequential ;;; (index (hold-resource-step typing-cognition-block)) ;;; (profile typing-cognition-block) ;;; (hold-resource typing-cognition-block :ancestor 2)) (procedure ;; :sequential (index (hold-resource-step right-hand-block)) (profile right-hand-block) (step s1 (hold-resource right-hand-block :ancestor 2)) ;; (waitfor ?ever)) (step term (terminate) (waitfor ?s1))) (procedure ;; :sequential (index (hold-resource-step left-hand-block)) (profile left-hand-block) (step s1 (hold-resource left-hand-block :ancestor 2)) ;; (waitfor ?ever)) (step term (terminate) (waitfor ?s1))) (procedure ;; :sequential (index (hold-resource-step type-string-block)) (profile type-string-block) (step s1 (hold-resource type-string-block :ancestor 2)) ;; (waitfor ?ever)) (step term (terminate) (waitfor ?s1))) (procedure ;;:sequential (index (hold-resource-step typing-cognition-block)) (profile typing-cognition-block) (step s1 (hold-resource typing-cognition-block :ancestor 2)) ;; (waitfor ?ever)) (step term (terminate) (waitfor ?s1))) ;;;;;;;;;;; GLOBAL CONSTANTS ;;;;;;;; ;; COGNITION PRIMITIVES (setf *get-chunk* (list 'get-chunk)) (setf *initiate-keystroke* (list 'initiate-keystroke)) ;; LEFT-HAND PRIMITIVES (setf *type-key-left* (list 'type-key-left)) ;; RIGHT-HAND PRIMITIVES (setf *type-key-right* (list 'type-key-right)) ;; WORLD PRIMITIVE (setf *world* (list 'world)) ;;;;;;;;;;; GLOBAL VARIABLES ;;;;;;;; (setf *LAST-CHAR-HAND-GENSYM* nil) ;; Unique symbol of previous type-string template created ;; (if it exists). This is to keep track of a world event that ;; is generated at the end of every type-string template created. ;; If the current type-string template has a same-hand constraint ;; it needs to wait for the last motor activity of the previous ;; type-string template to begin the first initiate-keystroke ;; activity of the current template being generated. (setf *LAST-CHAR-HAND* nil) ;; Holds the hand that typed the last character of the ;; previous template. ;;;;;;;;;; TYPIST CODE ;;;;;;;;;;;;;; ;; TYPE-STRING ;; args: ?str ;; description: constructs one pdl template for a given string. ;; the pdl template is given a unique identifier. ;; after the pdl template is constructed, the pdl template is called. ;; return value: nothing ;(procedure :sequential ; (index (type-string ?str)) ; (construct-typing-pdl ?str => ?pdl-name) ; (TYPE-STRING-CREATED ?pdl-name) ;) (procedure (index (type-string ?str)) (step s1 (?this-step) (select ?this-step (depends-on '*R-hand-on* '((mouse home-to-keyboard) (keyboard no-op)))) (rank 1)) (step s2 (type-string-R-hand-on-keyboard ?str) (rank 2)) (step t (terminate) (waitfor ?s1 ?s2)) ) (procedure :sequential (index (type-string-R-hand-on-keyboard ?str)) (construct-typing-pdl ?str => ?pdl-name) (TYPE-STRING-CREATED ?pdl-name) ) (procedure :sequential (index (home-to-keyboard-before-typing)) (hold-resource-step right-hand-block) (initiate-home-to keyboard) (right-hand-home-to keyboard) (WORLD 0 *R-hand-on* keyboard)) ;; CONSTRUCT-TYPING-PDL ;; args: ?str ;; description: generates a new pdl template to type the string ?str. ;; a unique id is given to the template. ;; sets the hand of the last chararacter typed in ?str and unique id. ;; return value: the unique id for the template ;;;(procedure :special ;;; (index (construct-typing-pdl ?str)) ;;; (let ;;; ((func-name (gensym))) ;;create the new procedure name ;;; (eval (build-pdl ?str func-name)) ;;; (add-newest-proc) ;;; (setf *LAST-CHAR-HAND-GENSYM* (read-from-string (string func-name))) ;;; (setf *LAST-CHAR-HAND* (choose-hand (car (last (string-to-list ?str))))) ;;; func-name ;;; ) ;;;) (primitive (index (construct-typing-pdl ?str)) (return (let ((func-name (gensym))) ;;create the new procedure name (eval (build-pdl ?str func-name)) (add-newest-proc) (setf *LAST-CHAR-HAND-GENSYM* (read-from-string (string func-name))) (setf *LAST-CHAR-HAND* (choose-hand (car (last (string-to-list ?str))))) func-name ) )) ;; ADD-NEWEST-PROC (mfreed) ;; args: none ;; description: Call this after (eval (build-pdl ?str func-name)) in the procedure type-string. ;; return value: don't know ;; notes: This function is a hack, to be obsoleted after revising proc management mechanisms. (defun add-newest-proc () (add-procedure (first *proclib*) *agent*)) ;; BUILD-PDL ;; args: str func-name ;; description: returns a list representing the PDL procedure to type str ;; return value: a list representing the PDL template to type the string str ;; author: eyk (defun build-pdl (str func-name) (let* ((chunks (chop-up str))) (cons 'procedure (cons (create-type-string-index-clause func-name) (append (build-iter chunks 1 nil chunks) (append (list (create-step-clause 'w (append *world* (list 0) (list 'LAST-CHAR-HAND-GENSYM) (list (read-from-string (string func-name)))) (create-waitfor-clause (list (create-motor-step-index-var (length chunks) (+ (length (string-to-list (car (last chunks)))) 1))) ) )) (list (create-terminate-clause)) ) ) ) ) ) ) ;; BUILD-ITER ;; args: lis ;; ind ;; wait-for ;; orig-chunks ;; description: iterates through each chunk and calls build-pdl-chunk to create the pdl for each chunk ;; return value: the initiate-keystroke and type-key pdl for all the chunks of the type-string template (defun build-iter (lis ind wait-for orig-chunks) (if (null lis) nil (append (build-pdl-chunk (car lis) ind wait-for orig-chunks) (build-iter (cdr lis) (+ ind 1) (create-waitfor-clause (list (create-cog-step-index-var ind (+ (length (string-to-list (car lis))) 1) ) ) ) orig-chunks) ) ) ) ;; BUILD-PDL-CHUNK ;; args: str ;; ind ;; wait-for ;; orig-str-chunks-lis ;; description: creates the pdl for one particular chunk ;; return value: the initiate-keystroke and type-key pdl for ONE chunk of the type-string template (defun build-pdl-chunk (str ind wait-for orig-str-chunks-lis) (cons (create-step-clause (create-COG-STEP-INDEX ind 1) (cons 'get-chunk (list (read-from-string str))) wait-for) (cons ;; hold virtual resource - typing-cognition-block (create-step-clause (create-hold-virtual-resource-step-index ind 1 0) (list 'hold-resource-step 'typing-cognition-block) (create-waitfor-clause (list (create-cog-step-index-var ind 1))) ) (create-initiate-keystroke-type-string-body (string-to-list str) ind orig-str-chunks-lis) ) ) ) ;; create-INITIATE-KEYSTROKE-TYPE-STRING-BODY ;; args: orig-str-lis ;; description: takes a list of keys representing the string and returns the a list representing ;; the initiate-keystroke-type-string pdl for the entire string ;; return value: a list representing the PDL code for initiate-keystroke and type-key steps ;; for typing a chunk (defun create-initiate-keystroke-type-string-body (orig-str-lis step-index1 orig-str-chunks-lis) (do* ( ;; var1 init1 update ;; variables with no update on each iteration (str-total-numchar (length orig-str-lis)) (str-left-numchar (create-left-numchar orig-str-lis)) (str-right-numchar (create-right-numchar orig-str-lis)) (step-index2 2 (+ step-index2 1)) (prev-hand nil (choose-hand cur-key)) ;; variables with updates on each iteration (str-list orig-str-lis (rest str-list)) (cur-key (first orig-str-lis) (first str-list)) (cur-hand (choose-hand cur-key) (choose-hand cur-key)) (str-left-numchar-cnt (+ 0 (inc-left-numchar-cnt cur-hand)) (+ str-left-numchar-cnt (inc-left-numchar-cnt cur-hand))) (str-right-numchar-cnt (+ 0 (inc-right-numchar-cnt cur-hand)) (+ str-right-numchar-cnt (inc-right-numchar-cnt cur-hand))) (result-pdl-list (append (create-type-key-pdl str-total-numchar str-left-numchar str-right-numchar step-index1 step-index2 cur-hand str-left-numchar-cnt str-right-numchar-cnt str-list orig-str-chunks-lis) (append (create-initiate-keystroke-pdl str-list cur-hand prev-hand step-index1 step-index2 orig-str-chunks-lis) nil)) (append (create-type-key-pdl str-total-numchar str-left-numchar str-right-numchar step-index1 step-index2 cur-hand str-left-numchar-cnt str-right-numchar-cnt str-list orig-str-chunks-lis) (append (create-initiate-keystroke-pdl str-list cur-hand prev-hand step-index1 step-index2 orig-str-chunks-lis) result-pdl-list))) ) ;; test action1 .. action-n ((equal 1 (length str-list)) (reverse result-pdl-list) ) ) ;;end do* ) ;; create-INITIATE-KEYSTROKE-PDL ;; args: str-list cur-hand prev-hand step-index ;; description: takes 4 arguments. str-list represents the list of keys that yet to have ;; PDL generated. cur-hand is the hand needed to type the current key. ;; prev-hand is the hand needed to type the previous key (nil if first key). ;; step index is the current step. ;; return value: a list representing each a single initiate-keystroke step ;; author: eyk (defun create-initiate-keystroke-pdl (str-list cur-hand prev-hand step-index1 step-index2 orig-str-chunks-lis) (cond ((and (= step-index1 1) (= step-index2 2) (equal cur-hand *LAST-CHAR-HAND*)) ;; same-hand constraint across chunks BETWEEN templates for first initiate-keystroke cognitive operator (cond ((equal 1 (length str-list)) (list (create-step-clause (create-cog-step-index step-index1 step-index2) (reverse (cons (first str-list) *initiate-keystroke*)) (append (create-waitfor-clause (cons (create-cog-step-index-var step-index1 (- step-index2 1)) nil)) (list (list 'variable 'LAST-CHAR-HAND-GENSYM *LAST-CHAR-HAND-GENSYM*)) ) ) ;; release virtual resource - typing-cognition-block (create-step-clause (create-release-virtual-resource-step-index step-index1 step-index2 0) (list 'release-resource 'typing-cognition-block ':ancestor 1) (create-waitfor-clause (list (create-cog-step-index-var step-index1 step-index2))) ) ) ) (t (list (create-step-clause (create-cog-step-index step-index1 step-index2) (reverse (cons (first str-list) *initiate-keystroke*)) (append (create-waitfor-clause (cons (create-cog-step-index-var step-index1 (- step-index2 1)) nil)) (list (list 'variable 'LAST-CHAR-HAND-GENSYM *LAST-CHAR-HAND-GENSYM*)) ) ) ) ) ) ) ((and (> step-index1 1) (= step-index2 2) (equal cur-hand (choose-hand (nth (- (length (string-to-list (nth (- step-index1 2) orig-str-chunks-lis))) 1) (string-to-list (nth (- step-index1 2) orig-str-chunks-lis))) )) ) ;; same-hand constraint across chunks WITHIN templates ;; for first initiate-keystroke cognitive operator (list (create-step-clause (create-cog-step-index step-index1 step-index2) (reverse (cons (first str-list) *initiate-keystroke*)) (create-waitfor-clause (cons (create-cog-step-index-var step-index1 (- step-index2 1)) (cons (create-motor-step-index-var (- step-index1 1) (+ (length (string-to-list (nth (- step-index1 2) orig-str-chunks-lis))) 1)) nil)))) ) ) ((equal 1 (length str-list)) ;; last character (cond ((equal cur-hand prev-hand) (list (create-step-clause (create-cog-step-index step-index1 step-index2) (reverse (cons (first str-list) *initiate-keystroke*)) (create-waitfor-clause (cons (create-cog-step-index-var step-index1 (- step-index2 1)) (cons (create-motor-step-index-var step-index1 (- step-index2 1)) nil)))) ;; release virtual resource - typing-cognition-block (create-step-clause (create-release-virtual-resource-step-index step-index1 step-index2 0) (list 'release-resource 'typing-cognition-block ':ancestor 1) (create-waitfor-clause (list (create-cog-step-index-var step-index1 step-index2))) ) ) ) (t (list (create-step-clause (create-cog-step-index step-index1 step-index2) (reverse (cons (first str-list) *initiate-keystroke*)) (create-waitfor-clause (cons (create-cog-step-index-var step-index1 (- step-index2 1)) nil))) ;; release virtual resource - typing-cognition-block (create-step-clause (create-release-virtual-resource-step-index step-index1 step-index2 0) (list 'release-resource 'typing-cognition-block ':ancestor 1) (create-waitfor-clause (list (create-cog-step-index-var step-index1 step-index2))) ) ) ) ) ) (t ;; not last character (cond ((equal cur-hand prev-hand) (list (create-step-clause (create-cog-step-index step-index1 step-index2) (reverse (cons (first str-list) *initiate-keystroke*)) (create-waitfor-clause (cons (create-cog-step-index-var step-index1 (- step-index2 1)) (cons (create-motor-step-index-var step-index1 (- step-index2 1)) nil)))) ) ) (t (list (create-step-clause (create-cog-step-index step-index1 step-index2) (reverse (cons (first str-list) *initiate-keystroke*)) (create-waitfor-clause (cons (create-cog-step-index-var step-index1 (- step-index2 1)) nil))) ) ) ) ) ) ) ;; create-TYPE-KEY-PDL ;; args: str-total-numchar ;; str-left-numchar ;; str-right-numchar ;; step-index ;; cur-hand ;; str-left-numchar-cnt ;; str-right-numchar-cnt ;; str-list ;; description: takes 8 arguments. str-total-numchar is the total ;; number of characters in the string. str-left-numchar is ;; the total number of characters typed with the left-hand. ;; str-right-numchar is the total number of characters ;; typed with the right-hand. step-index is the number for ;; the current step to be generated. cur-hand is the hand ;; (left or right) used to type the current character. ;; str-left-numchar-cnt is a counter to determine how many ;; characters have been typed with the left hand. ;; str-right-numchar-cnt is a coutner to determine how many ;; characters have been typed with the right hand. ;; str-list is the list representation of the string to be ;; typed. ;; notes: this is a helper function called by ;; create-initiate-keystroke-type-string-body author: eyk (defun create-type-key-pdl (str-total-numchar str-left-numchar str-right-numchar step-index1 step-index2 cur-hand str-left-numchar-cnt str-right-numchar-cnt str-list orig-str-chunks-lis) (let* ((vr-index 0)) (cond ((equal str-total-numchar (length str-list)) ;first motor operator (cond ((> step-index1 1) ;; the current chunk is 2..n chunk (cond ((equal 'right cur-hand) (cond ((equal str-right-numchar str-right-numchar-cnt) (list (create-step-clause (create-motor-step-index step-index1 step-index2) (reverse (cons (first str-list) *type-key-right*)) (create-waitfor-clause (cons (create-cog-step-index-var step-index1 step-index2) (cons (create-motor-step-index-var (- step-index1 1) (+ (length (string-to-list (nth (- step-index1 2) orig-str-chunks-lis))) 1)) nil)))) (create-step-clause (create-hold-virtual-resource-step-index step-index1 step-index2 (+ vr-index 1)) (list 'hold-resource-step 'right-hand-block) (create-waitfor-clause (list (create-cog-step-index-var step-index1 step-index2))) ; PI:NAME:<NAME>END_PI told me to! ) (create-step-clause (create-hold-virtual-resource-step-index step-index1 step-index2 (+ vr-index 2)) (list 'hold-resource-step 'type-string-block) (create-waitfor-clause (list (create-cog-step-index-var step-index1 step-index2))) ) (create-step-clause (create-release-virtual-resource-step-index step-index1 step-index2 (+ vr-index 3)) (list 'release-resource 'right-hand-block ':ancestor 1) (create-waitfor-clause (list (create-motor-step-index-var step-index1 step-index2))) ) ) ) (t (list (create-step-clause (create-motor-step-index step-index1 step-index2) (reverse (cons (first str-list) *type-key-right*)) (create-waitfor-clause (cons (create-cog-step-index-var step-index1 step-index2) (cons (create-motor-step-index-var (- step-index1 1) (+ (length (string-to-list (nth (- step-index1 2) orig-str-chunks-lis))) 1)) nil)))) (create-step-clause (create-hold-virtual-resource-step-index step-index1 step-index2 (+ vr-index 1)) (list 'hold-resource-step 'right-hand-block) (create-waitfor-clause (list (create-motor-step-index-var step-index1 step-index2))) ) (create-step-clause (create-hold-virtual-resource-step-index step-index1 step-index2 (+ vr-index 2)) (list 'hold-resource-step 'type-string-block) (create-waitfor-clause (list (create-cog-step-index-var step-index1 step-index2))) ) ) ))) ((equal 'left cur-hand) (cond ((equal str-left-numchar str-left-numchar-cnt) (list (create-step-clause (create-motor-step-index step-index1 step-index2) (reverse (cons (first str-list) *type-key-left*)) (create-waitfor-clause (cons (create-cog-step-index-var step-index1 step-index2) (cons (create-motor-step-index-var (- step-index1 1) (+ (length (string-to-list (nth (- step-index1 2) orig-str-chunks-lis))) 1)) nil)))) (create-step-clause (create-hold-virtual-resource-step-index step-index1 step-index2 (+ vr-index 1)) (list 'hold-resource-step 'left-hand-block) (create-waitfor-clause (list (create-cog-step-index-var step-index1 step-index2))) ) (create-step-clause (create-hold-virtual-resource-step-index step-index1 step-index2 (+ vr-index 2)) (list 'hold-resource-step 'type-string-block) (create-waitfor-clause (list (create-cog-step-index-var step-index1 step-index2))) ) (create-step-clause (create-release-virtual-resource-step-index step-index1 step-index2 (+ vr-index 3)) (list 'release-resource 'left-hand-block ':ancestor 1) (create-waitfor-clause (list (create-motor-step-index-var step-index1 step-index2))) ) ) ) (t (list (create-step-clause (create-motor-step-index step-index1 step-index2) (reverse (cons (first str-list) *type-key-left*)) (create-waitfor-clause (cons (create-cog-step-index-var step-index1 step-index2) (cons (create-motor-step-index-var (- step-index1 1) (+ (length (string-to-list (nth (- step-index1 2) orig-str-chunks-lis))) 1)) nil)))) (create-step-clause (create-hold-virtual-resource-step-index step-index1 step-index2 (+ vr-index 1)) (list 'hold-resource-step 'left-hand-block) (create-waitfor-clause (list (create-cog-step-index-var step-index1 step-index2))) ) (create-step-clause (create-hold-virtual-resource-step-index step-index1 step-index2 (+ vr-index 2)) (list 'hold-resource-step 'type-string-block) (create-waitfor-clause (list (create-cog-step-index-var step-index1 step-index2))) ) ) ) )) ) ) (t ;; the current chunk is the first chunk (cond ((equal 'right cur-hand) (cond ((equal str-right-numchar str-right-numchar-cnt) (list (create-step-clause (create-motor-step-index step-index1 step-index2) (reverse (cons (first str-list) *type-key-right*)) (create-waitfor-clause (cons (create-cog-step-index-var step-index1 step-index2) nil))) (create-step-clause (create-hold-virtual-resource-step-index step-index1 step-index2 (+ vr-index 1)) (list 'hold-resource-step 'right-hand-block) (create-waitfor-clause (list (create-cog-step-index-var step-index1 step-index2))) ) (create-step-clause (create-hold-virtual-resource-step-index step-index1 step-index2 (+ vr-index 2)) (list 'hold-resource-step 'type-string-block) (create-waitfor-clause (list (create-cog-step-index-var step-index1 step-index2))) ) (create-step-clause (create-release-virtual-resource-step-index step-index1 step-index2 (+ vr-index 3)) (list 'release-resource 'right-hand-block ':ancestor 1) (create-waitfor-clause (list (create-motor-step-index-var step-index1 step-index2))) ) ) ) (t (list (create-step-clause (create-motor-step-index step-index1 step-index2) (reverse (cons (first str-list) *type-key-right*)) (create-waitfor-clause (cons (create-cog-step-index-var step-index1 step-index2) nil))) (create-step-clause (create-hold-virtual-resource-step-index step-index1 step-index2 (+ vr-index 1)) (list 'hold-resource-step 'right-hand-block) (create-waitfor-clause (list (create-cog-step-index-var step-index1 step-index2))) ) (create-step-clause (create-hold-virtual-resource-step-index step-index1 step-index2 (+ vr-index 2)) (list 'hold-resource-step 'type-string-block) (create-waitfor-clause (list (create-cog-step-index-var step-index1 step-index2))) ) ) ))) ((equal 'left cur-hand) (cond ((equal str-left-numchar str-left-numchar-cnt) (list (create-step-clause (create-motor-step-index step-index1 step-index2) (reverse (cons (first str-list) *type-key-left*)) (create-waitfor-clause (cons (create-cog-step-index-var step-index1 step-index2) nil))) (create-step-clause (create-hold-virtual-resource-step-index step-index1 step-index2 (+ vr-index 1)) (list 'hold-resource-step 'left-hand-block) (create-waitfor-clause (list (create-cog-step-index-var step-index1 step-index2))) ) (create-step-clause (create-hold-virtual-resource-step-index step-index1 step-index2 (+ vr-index 2)) (list 'hold-resource-step 'type-string-block) (create-waitfor-clause (list (create-cog-step-index-var step-index1 step-index2))) ) (create-step-clause (create-release-virtual-resource-step-index step-index1 step-index2 (+ vr-index 3)) (list 'release-resource 'left-hand-block ':ancestor 1) (create-waitfor-clause (list (create-motor-step-index-var step-index1 step-index2))) ) ) ) (t (list (create-step-clause (create-motor-step-index step-index1 step-index2) (reverse (cons (first str-list) *type-key-left*)) (create-waitfor-clause (cons (create-cog-step-index-var step-index1 step-index2) nil))) (create-step-clause (create-hold-virtual-resource-step-index step-index1 step-index2 (+ vr-index 1)) (list 'hold-resource-step 'left-hand-block) (create-waitfor-clause (list (create-cog-step-index-var step-index1 step-index2))) ) (create-step-clause (create-hold-virtual-resource-step-index step-index1 step-index2 (+ vr-index 2)) (list 'hold-resource-step 'type-string-block) (create-waitfor-clause (list (create-cog-step-index-var step-index1 step-index2))) ) ) ))) ) ) ) ) ((equal 'right cur-hand) ;right motor operator (cond ((equal 1 str-right-numchar-cnt) ;;type-key-right-first (list (create-step-clause (create-motor-step-index step-index1 step-index2) (reverse (cons (first str-list) *type-key-right*)) (create-waitfor-clause (cons (create-cog-step-index-var step-index1 step-index2) (cons (create-motor-step-index-var step-index1 (- step-index2 1)) nil)))) (create-step-clause (create-hold-virtual-resource-step-index step-index1 step-index2 (+ vr-index 1)) (list 'hold-resource-step 'right-hand-block) (create-waitfor-clause (list (create-cog-step-index-var step-index1 step-index2))) ) ) ) ((equal str-total-numchar (+ str-right-numchar-cnt str-left-numchar-cnt)) (list (create-step-clause (create-motor-step-index step-index1 step-index2) (reverse (cons (first str-list) *type-key-right*)) (create-waitfor-clause (cons (create-cog-step-index-var step-index1 step-index2) (cons (create-motor-step-index-var step-index1 (- step-index2 1)) nil)))) (create-step-clause (create-release-virtual-resource-step-index step-index1 step-index2 (+ vr-index 1)) (list 'release-resource 'right-hand-block ':ancestor 1) (create-waitfor-clause (list (create-motor-step-index-var step-index1 step-index2))) ) (create-step-clause (create-release-virtual-resource-step-index step-index1 step-index2 (+ vr-index 2)) (list 'release-resource 'type-string-block ':ancestor 1) (create-waitfor-clause (list (create-cog-step-index-var step-index1 step-index2))) ) ) ) ((equal str-right-numchar str-right-numchar-cnt) (list (create-step-clause (create-motor-step-index step-index1 step-index2) (reverse (cons (first str-list) *type-key-right*)) (create-waitfor-clause (cons (create-cog-step-index-var step-index1 step-index2) (cons (create-motor-step-index-var step-index1 (- step-index2 1)) nil)))) (create-step-clause (create-release-virtual-resource-step-index step-index1 step-index2 (+ vr-index 1)) (list 'release-resource 'right-hand-block ':ancestor 1) (create-waitfor-clause (list (create-motor-step-index-var step-index1 step-index2))) ) ) ) (t (list (create-step-clause (create-motor-step-index step-index1 step-index2) (reverse (cons (first str-list) *type-key-right*)) (create-waitfor-clause (cons (create-cog-step-index-var step-index1 step-index2) (cons (create-motor-step-index-var step-index1 (- step-index2 1)) nil)))) ) ) ) ) ((equal 'left cur-hand) (cond ((equal 1 str-left-numchar-cnt) ;;type-key-right-first (list (create-step-clause (create-motor-step-index step-index1 step-index2) (reverse (cons (first str-list) *type-key-left*)) (create-waitfor-clause (cons (create-cog-step-index-var step-index1 step-index2) (cons (create-motor-step-index-var step-index1 (- step-index2 1)) nil)))) (create-step-clause (create-hold-virtual-resource-step-index step-index1 step-index2 (+ vr-index 1)) (list 'hold-resource-step 'left-hand-block) (create-waitfor-clause (list (create-cog-step-index-var step-index1 step-index2))) ) ) ) ((equal str-total-numchar (+ str-right-numchar-cnt str-left-numchar-cnt)) (list (create-step-clause (create-motor-step-index step-index1 step-index2) (reverse (cons (first str-list) *type-key-left*)) (create-waitfor-clause (cons (create-cog-step-index-var step-index1 step-index2) (cons (create-motor-step-index-var step-index1 (- step-index2 1)) nil)))) (create-step-clause (create-release-virtual-resource-step-index step-index1 step-index2 (+ vr-index 1)) (list 'release-resource 'left-hand-block ':ancestor 1) (create-waitfor-clause (list (create-motor-step-index-var step-index1 step-index2))) ) (create-step-clause (create-release-virtual-resource-step-index step-index1 step-index2 (+ vr-index 2)) (list 'release-resource 'type-string-block ':ancestor 1) (create-waitfor-clause (list (create-cog-step-index-var step-index1 step-index2))) ) ) ) ((equal str-left-numchar str-left-numchar-cnt) (list (create-step-clause (create-motor-step-index step-index1 step-index2) (reverse (cons (first str-list) *type-key-left*)) (create-waitfor-clause (cons (create-cog-step-index-var step-index1 step-index2) (cons (create-motor-step-index-var step-index1 (- step-index2 1)) nil)))) (create-step-clause (create-release-virtual-resource-step-index step-index1 step-index2 (+ vr-index 1)) (list 'release-resource 'left-hand-block ':ancestor 1) (create-waitfor-clause (list (create-motor-step-index-var step-index1 step-index2))) ) ) ) (t (list (create-step-clause (create-motor-step-index step-index1 step-index2) (reverse (cons (first str-list) *type-key-left*)) (create-waitfor-clause (cons (create-cog-step-index-var step-index1 step-index2) (cons (create-motor-step-index-var step-index1 (- step-index2 1)) nil)))) ) ) ) ) (nil (print "error! key not found!")) ;;error! key not found! ) ) ) ;; kmd added this; it might be wrong ;;;;;;;;;;;;;;;;; helper functions ;;;;;;;;;;;;;;;;;; ;; CHOOSE-HAND ;; args: key ;; description: Accepts a key in the form <key>-key and returns the hand that types it ;; return value: Hand that typed the key ;; notes: This is the knowledge of which hand types which key ;; that a touch-typist has "at her fingertips" ;; This means we are not actually using the keyboard at all ;; that may not be stupid for a touch typist (bej) (defun choose-hand (key) (cond ((equal key nil) nil) ((member key '(esc-key f1-key f2-key f3-key f4-key f5-key tilda-key excl-key at-key hash-key quest-key perc-key carrot-key bquote-key 1-key 2-key 3-key 4-key 5-key 6-key tab-key q-key w-key e-key r-key t-key caps-key a-key s-key d-key f-key g-key shft-key z-key x-key c-key v-key b-key ctrl-key win-key alt-key)) 'left) ((member key '(f6-key f7-key f8-key f9-key f10-key f11-key f12-key and-key aster-key left-paren-key right-paren-key dash-key equal-key plus-key 7-key 8-key 9-key 0-key hyphen-key equal-key bslash-key y-key u-key i-key o-key p-key [-key ]-key h-key j-key k-key l-key semi-key quote-key enter-key n-key m-key comma-key period-key slash-key shift-key space-key alt-key win-key select-key ctrl-key colon-key double-quote-key left-bracket-key right-bracket-key less-key greater-key question-key backslash-key)) 'right) (t "not a key we know") ) ) ;; CHOP-UP (mmatessa) ;; args: str ;; description: parses str into separate strings in a list, each string represents a "chunk" ;; return value: a list representing the string parsed into chunks (defun chop-up (str) (let* ((pos (or (position #\space str) (position #\return str))) (end (if pos (position-if-not #'(lambda (x) (or (equal x #\space) (equal x #\return))) str :start pos)))) (cond ((or (null pos) (null end)) (list str)) (t (cons (subseq str 0 end) (chop-up (subseq str end (length str)))))))) ;; STR2LIS ;; args: x ;; description: accepts a string and returns a list representing that string ;; e.g. (str2lis "elaine") => (E L A I N E) ;; author: PI:NAME:<NAME>END_PI (defun str2lis (x) (let ((ans nil) (sub nil)) (dotimes (i (length x)) (setf sub (subseq x i (1+ i))) (push sub ans)) (reverse ans))) ;; STRING-TO-LIST ;; args: x ;; description: This converts a string to a list of characters with "-key" appended to each ;; character. ;; e.g. (string-to-list "hello") => (H-KEY L-KEY A-KEY I-KEY N-KEY E-KEY) ;; author: eyk (defun string-to-list (x) (append-all (mapcar 'char2key (str2lis x))) ) (defun append-all (lis) (if (null lis) nil (append (car lis) (append-all (cdr lis))))) ;; CHAR2KEY ;; args: x ;; description: This adds "-key" to each charcter in the list ;; author: (defun char2key (x) (if (or (and (char>= (char x 0) #\A) (char<= (char x 0) #\Z)) (char= (char x 0) #\~) (char= (char x 0) #\!) (char= (char x 0) #\@) (char= (char x 0) #\#) (char= (char x 0) #\$) (char= (char x 0) #\%) (char= (char x 0) #\^) (char= (char x 0) #\&) (char= (char x 0) #\*) (char= (char x 0) #\() (char= (char x 0) #\)) (char= (char x 0) #\_) (char= (char x 0) #\+) (char= (char x 0) #\{) (char= (char x 0) #\}) ;;(char= (char x 0) #\|) ;;errors occur on "|" (char= (char x 0) #\:) (char= (char x 0) #\") (char= (char x 0) #\<) (char= (char x 0) #\>) (char= (char x 0) #\?) (char= (char x 0) #\\)) (cons 'shft-key (list (to-dash-key x))) (list (to-dash-key x)) ) ) ;; TO-DASH-KEY ;; args: x ;; description: accepts a character and returns the equivalent id for the key (defun to-dash-key (x) (cond ((equal x " ") 'space-key) ((equal x " ") 'enter-key) ((equal x "`") 'bquote-key) ((equal x ",") 'comma-key) ((equal x ".") 'period-key) ((equal x "=") 'equal-key) ((equal x "-") 'hyphen-key) ((equal x "/") 'slash-key) ((equal x ";") 'semi-key) ((equal x "'") 'quote-key) ;;shifted characters ((equal x "~") 'tilda-key) ((equal x "!") 'excl-key) ((equal x "@") 'at-key) ((equal x "#") 'hash-key) ((equal x "$") 'quest-key) ((equal x "%") 'perc-key) ((equal x "^") 'carrot-key) ((equal x "&") 'and-key) ((equal x "*") 'aster-key) ((equal x "(") 'left-paren-key) ((equal x ")") 'right-paren-key) ((equal x "_") 'dash-key) ((equal x "+") 'plus-key) ((equal x "}") 'right-bracket-key) ((equal x "{") 'left-bracket-key) ((equal x ":") 'colon-key) ((equal x "<") 'less-key) ((equal x ">") 'greater-key) ((equal x "?") 'question-key) ((equal x "\"") 'double-quote-key) ((equal x "\\") 'backslash-key) ((string< x "0") 'char-key) (t (read-from-string (format nil "~a-key" x))))) ;; INC-LEFT-NUMCHAR-CNT ;; args: cur-hand ;; description: accepts one argument cur-hand (left or right) to determine whether to increment ;; returns: updated value ;; notes: this is a helper function called by create-initiate-keystroke-type-string-body ;; author: eyk (defun inc-left-numchar-cnt (cur-hand) (if (equal cur-hand 'left) 1 0) ) ;; INC-RIGHT-NUMCHAR-CNT ;; args: cur-hand ;; description: accepts one argument cur-hand (left or right) to determine whether to increment ;; returns: updated value ;; notes: this is a helper function called by create-initiate-keystroke-type-string-body ;; author: eyk (defun inc-right-numchar-cnt (cur-hand) (if (equal cur-hand 'right) 1 0) ) ;; INTEGER-TO-STRING ;; args: x ;; description: converts a digit x to a string ;; return value: "x" (defun integer-to-string (x) (prin1-to-string x)) ;; create-LEFT-NUMCHAR args: lis description: returns the number of ;; characters typed with the left hand in a string the argument lis is ;; in the form (h-key e-key l-key l-key o-key) for the string "hello" ;; author: eyk (defun create-left-numchar (lis) (cond ((equal nil lis) 0) ((equal 'left (choose-hand (first lis))) (+ 1 (create-left-numchar (rest lis)))) (t (+ 0 (create-left-numchar (rest lis))))) ) ;; create-RIGHT-NUMCHAR ;; args: lis ;; description: returns the number of characters typed with the right ;; hand in a string, the argument lis is in the form (h-key ;; e-key l-key l-key o-key) for the string "hello" ;; author: eyk (defun create-right-numchar (lis) (cond ((equal nil lis) 0) ((equal 'right (choose-hand (first lis))) (+ 1 (create-right-numchar (rest lis)))) (t (+ 0 (create-right-numchar (rest lis))))) ) ;;;;;;;;;;;;;;;;; functions to return step clauses for a given step, primitive, and waitfor condition ;;;;;;;;;;;; ;; create-TYPE-STRING-INDEX-CLAUSE args: string description: returns the ;; index clause for a given string to type return value: index clause ;; e.g. (create-type-string "elaine") => (index (type-string-elaine)) ;; author: eyk (defun create-type-string-index-clause (func-name) (list 'index (list 'TYPE-STRING-CREATED func-name))) ;; create-STEP-CLAUSE args: step-index atom, primitive list, waitfor ;; list description: returns the step clause for a given step-index ;; string, primitive list, and waitfor list return value: step clause ;; e.g. (create-step-clause 'c2 '(initiate-keystroke) '(waitfor ?c1)) => ;; (step c2 (initiate-keystroke) (waitfor ?c1)) author: eyk notes: NEED ;; TO CHECK FOR NIL WAITFOR LISTS (taken care of) (defun create-step-clause (step-index primitive-list waitfor-list) (cond ((equal waitfor-list nil) ;; no waitfors (append (list 'step step-index) (list primitive-list))) (t (append (append (list 'step step-index) (list primitive-list)) (list waitfor-list))))) ;; create-TERMINATE-CLAUSE ;; args: x ;; description: returns the termination clause for a given waitfor step index x ;; return value: termination clause ;; author: eyk (defun create-terminate-clause () (list 'step 't '(terminate) '(waitfor ?w)) ) ;;;;;;;;;;;;;;;;;;; functions to return waitfor clauses for step indexes ;;;;;;;;;;;;;;;;; ;; create-WAITFOR-CLAUSE args: list of step indexes description: returns ;; the waitfor clause for a list of waitfor for conditions (conjunctive) ;; return value: waitfor clause e.g (create-waitfor-clause '(?c3 ?m2)) ;; => (waitfor ?c3 ?m2) (defun create-waitfor-clause (lis) (cons 'waitfor lis) ) ;;;;;;;;;;;;;;;;;;; functions to return a step index (motor, cog, world) ;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;; ;; create-MOTOR-STEP-INDEX-VAR ;; args: step index ;; description: returns the string value of a motor step for a given index ;; return value: motor step e.g. (create-motor-step-index '5) => ?m5) (defun create-motor-step-index-var (num-char1 num-char2) (read-from-string (concatenate 'string "?m" (integer-to-string num-char1) "-" (integer-to-string num-char2)))) ;; create-COG-STEP-INDEX-VAR ;; args: step index ;; description: returns the string value of a cognitive step for a given index ;; return value: cognitive step e.g. (create-cog-step-index-str '5) => ?c5) (defun create-cog-step-index-var (num-char1 num-char2) (read-from-string (concatenate 'string "?c" (integer-to-string num-char1) "-" (integer-to-string num-char2)))) ;; create-WORLD-STEP-INDEX-VAR ;; args: step index ;; description: returns the string value of a world step for a given index ;; return value: world step e.g. (create-world-step-index-str '5) => ?w5) (defun create-world-step-index-var (num-char1 num-char2) (read-from-string (concatenate 'string "?w" (integer-to-string num-char1) "-" (integer-to-string num-char2)))) ;; create-MOTOR-STEP-INDEX ;; args: step index ;; description: returns the string value of a motor step for a given index ;; return value: motor step e.g. (create-motor-step-index '5) => m5) (defun create-motor-step-index (num-char1 num-char2) (read-from-string (concatenate 'string "m" (integer-to-string num-char1) "-" (integer-to-string num-char2)))) ;; create-COG-STEP-INDEX ;; args: step index ;; description: returns the string value of a cognitive step for a given index ;; return value: cognitive step e.g. (create-cog-step-index '5) => c5) (defun create-cog-step-index (num-char1 num-char2) (read-from-string (concatenate 'string "c" (integer-to-string num-char1) "-" (integer-to-string num-char2)))) ;; create-WORLD-STEP-INDEX ;; args: step index ;; description: returns the string value of a world step for a given index ;; return value: world step e.g. (create-world-step-index-str '5) => w5) (defun create-world-step-index (num-char1 num-char2) (read-from-string (concatenate 'string "w" (integer-to-string num-char1) "-" (integer-to-string num-char2)) ) ) ;; create-HOLD-VIRTUAL-RESOURCE-STEP-INDEX ;; args: step index ;; description: returns the string value of a cognitive step for a given index ;; return value: cognitive step e.g. (create-cog-step-index '5) => c5) (defun create-hold-virtual-resource-step-index (num-char1 num-char2 num-char3) (read-from-string (concatenate 'string "hvr" (integer-to-string num-char1) "-" (integer-to-string num-char2) "-" (integer-to-string num-char3)))) ;; create-RELEASE-VIRTUAL-RESOURCE-STEP-INDEX ;; args: step index ;; description: returns the string value of a cognitive step for a given index ;; return value: cognitive step e.g. (create-cog-step-index '5) => c5) (defun create-release-virtual-resource-step-index (num-char1 num-char2 num-char3) (read-from-string (concatenate 'string "rvr" (integer-to-string num-char1) "-" (integer-to-string num-char2) "-" (integer-to-string num-char3))))
[ { "context": "; DEALINGS IN THE SOFTWARE.\n;\n; Original author: Jared Davis <[email protected]>\n\n(in-package \"MILAWA\")\n(inc", "end": 1356, "score": 0.9996333122253418, "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 \"tautologie", "end": 1377, "score": 0.9999349117279053, "start": 1358, "tag": "EMAIL", "value": "[email protected]" }, { "context": " now need\n;; to show that T1=T2 <-> T1'=T2'.\n;;\n;; Shoenfield explains the proof as follows.\n;;\n;; 1. Use equal", "end": 23976, "score": 0.9148283004760742, "start": 23966, "tag": "NAME", "value": "Shoenfield" } ]
books/projects/milawa/ACL2/classic/equal-substitution.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 "tautologies") (include-book "../build/lambda") (set-verify-guards-eagerness 2) (set-case-split-limitations nil) (set-well-founded-relation ord<) (set-measure-function rank) ;; Let X' (a term) be obtained from X (another term) by replacing some ;; occurrences of terms A1,...,An by A1',...,An', respectively. If ;; |- A1 = A1', |- A2 = A2', ..., |- An = An' ;; Then ;; |- X = X' ;; ;; Furthermore, if Y' (a formula) is obtained from Y (another formula) ;; by similar replacements, then ;; |- Y <-> Y' ;; We introduce the function equals-for-equalsp, which takes as inputs the ;; terms x and y, and the list of formulas [A1, A2, ..., An]. We return true ;; if and only if y is obtainable from x by replacing some terms ti with other ;; terms si, where ti=si or si=ti is some Ai. ;; ;; This function is sort of like tautologyp1, in that it does not build a ;; proof, but is rather just an algorithm to decide if a proof can be ;; generated. (mutual-recursion (defund equal-substitutible-logic.termp (x y as) (declare (xargs :guard (and (logic.termp x) (logic.termp y) (logic.formula-listp as)))) (or (equal x y) (memberp (logic.pequal x y) as) (memberp (logic.pequal y x) as) (cond ((logic.constantp x) nil) ((logic.variablep x) nil) ((logic.functionp x) (and (logic.functionp y) (equal (logic.function-name x) (logic.function-name y)) (equal-substitutible-logic.term-listp (logic.function-args x) (logic.function-args y) as))) ((logic.lambdap x) (and (logic.lambdap y) (equal (logic.lambda-formals x) (logic.lambda-formals y)) (equal (logic.lambda-body x) (logic.lambda-body y)) (equal-substitutible-logic.term-listp (logic.lambda-actuals x) (logic.lambda-actuals y) as))) (t nil)))) (defund equal-substitutible-logic.term-listp (x y as) (declare (xargs :guard (and (logic.term-listp x) (logic.term-listp y) (logic.formula-listp as)))) (if (consp x) (and (consp y) (equal-substitutible-logic.termp (car x) (car y) as) (equal-substitutible-logic.term-listp (cdr x) (cdr y) as)) (not (consp y))))) (defthm equal-substitutible-logic.term-listp-of-cdrs-when-equal-substitutible-logic.term-listp (implies (and (equal-substitutible-logic.term-listp x y as) (consp x) (consp y)) (equal-substitutible-logic.term-listp (cdr x) (cdr y) as)) :hints(("Goal" :in-theory (enable equal-substitutible-logic.term-listp)))) (defthm equal-substitutible-logic.termp-of-cars-when-equal-substitutible-logic.term-listp (implies (and (equal-substitutible-logic.term-listp x y as) (consp x) (consp y)) (equal-substitutible-logic.termp (car x) (car y) as)) :hints(("Goal" :in-theory (enable equal-substitutible-logic.term-listp)))) (defthm equal-of-lengths-when-equal-substitutible-logic.term-listp (implies (equal-substitutible-logic.term-listp x y as) (equal (equal (len x) (len y)) t)) :hints(("Goal" :induct (cdr-cdr-induction x y) :in-theory (enable equal-substitutible-logic.term-listp)))) (defthm equal-substitutible-logic.term-listp-of-logic.lambda-actuals-when-logic.lambdaps (implies (and (equal-substitutible-logic.termp x y as) (logic.lambdap x) (logic.lambdap y) (not (equal x y)) (not (memberp (logic.pequal x y) as)) (not (memberp (logic.pequal y x) as))) (equal-substitutible-logic.term-listp (logic.lambda-actuals x) (logic.lambda-actuals y) as)) :hints(("Goal" :in-theory (enable equal-substitutible-logic.termp) :expand (equal-substitutible-logic.termp x y as)))) (defthm equal-substitutible-logic.term-listp-of-logic.function-args-when-logic.functionps (implies (and (equal-substitutible-logic.termp x y as) (logic.functionp x) (logic.functionp y) (not (equal x y)) (not (memberp (logic.pequal x y) as)) (not (memberp (logic.pequal y x) as))) (equal-substitutible-logic.term-listp (logic.function-args x) (logic.function-args y) as)) :hints(("Goal" :in-theory (enable equal-substitutible-logic.termp) :expand (equal-substitutible-logic.termp x y as)))) ;; Below we introduce equals-for-equals-bldr, which takes as inputs the terms x ;; and y, and the list of proofs [A1, A2, ..., An]. It should be the case that ;; these inputs satisfy equal-substitutible-logic.termp (i.e., using the conclusions ;; of the proofs A1...An). Our goal is to build a proof that x = y, by ;; utilizing the provided proofs as necessary. ;; ;; This function is sort of like tautologyp-bldr1, which builds a proof ;; whenever tautologyp1 says that some inputs are ok. In this case, we build a ;; proof when equal-substitutible-logic.termp says that the inputs are ok. (mutual-recursion (defund equal-substitutible-term-bldr (x y as) (declare (xargs :guard (and (logic.termp x) (logic.termp y) (logic.appeal-listp as) (equal-substitutible-logic.termp x y (logic.strip-conclusions as))) :verify-guards nil)) (cond ((equal x y) (build.reflexivity x)) ((memberp (logic.pequal x y) (logic.strip-conclusions as)) (logic.find-proof (logic.pequal x y) as)) ((memberp (logic.pequal y x) (logic.strip-conclusions as)) (build.commute-pequal (logic.find-proof (logic.pequal y x) as))) ((logic.functionp x) (if (and (logic.functionp y) (equal (logic.function-name x) (logic.function-name y))) (build.pequal-by-args (logic.function-name x) (equal-substitutible-term-list-bldr (logic.function-args x) (logic.function-args y) as)) nil)) ((logic.lambdap x) (if (and (logic.lambdap y) (equal (logic.lambda-formals x) (logic.lambda-formals y)) (equal (logic.lambda-body x) (logic.lambda-body y))) (build.lambda-pequal-by-args (logic.lambda-formals x) (logic.lambda-body x) (equal-substitutible-term-list-bldr (logic.lambda-actuals x) (logic.lambda-actuals y) as)) nil)) (t nil))) (defund equal-substitutible-term-list-bldr (x y as) (declare (xargs :guard (and (logic.term-listp x) (logic.term-listp y) (logic.appeal-listp as) (equal-substitutible-logic.term-listp x y (logic.strip-conclusions as))))) (if (consp x) (if (consp y) (cons (equal-substitutible-term-bldr (car x) (car y) as) (equal-substitutible-term-list-bldr (cdr x) (cdr y) as)) nil) nil))) (defthm len-of-equal-substitutible-term-list-bldr (implies (force (equal (len x) (len y))) (equal (len (equal-substitutible-term-list-bldr x y as)) (len x))) :hints(("Goal" :in-theory (enable equal-substitutible-term-list-bldr) :induct (cdr-cdr-induction x y)))) (defthm true-listp-of-equal-substitutible-term-list-bldr (equal (true-listp (equal-substitutible-term-list-bldr x y as)) t) :hints(("Goal" :in-theory (enable equal-substitutible-term-list-bldr) :induct (cdr-cdr-induction x y)))) (encapsulate () (local (defun my-induction (flag x y as) (declare (xargs :verify-guards nil)) (if (equal flag 'term) (cond ((equal x y) nil) ((memberp (logic.pequal x y) (logic.strip-conclusions as)) nil) ((memberp (logic.pequal y x) (logic.strip-conclusions as)) nil) ((logic.constantp x) nil) ((logic.variablep x) nil) ((logic.functionp x) (my-induction 'list (logic.function-args x) (logic.function-args y) as)) ((logic.lambdap x) (my-induction 'list (logic.lambda-actuals x) (logic.lambda-actuals y) as)) (t nil)) (if (and (consp x) (consp y)) (list (my-induction 'term (car x) (car y) as) (my-induction 'list (cdr x) (cdr y) as)) nil)))) (local (defthm lemma (if (equal flag 'term) (implies (and (logic.termp x) (logic.termp y) (logic.appeal-listp as) (equal-substitutible-logic.termp x y (logic.strip-conclusions as))) (and (logic.appealp (equal-substitutible-term-bldr x y as)) (equal (logic.conclusion (equal-substitutible-term-bldr x y as)) (logic.pequal x y)))) (implies (and (logic.term-listp x) (logic.term-listp y) (logic.appeal-listp as) (equal-substitutible-logic.term-listp x y (logic.strip-conclusions as))) (and (logic.appeal-listp (equal-substitutible-term-list-bldr x y as)) (equal (logic.strip-conclusions (equal-substitutible-term-list-bldr x y as)) (logic.pequal-list x y))))) :rule-classes nil :hints(("Goal" :induct (my-induction flag x y as) :in-theory (e/d (equal-substitutible-term-bldr equal-substitutible-term-list-bldr equal-substitutible-logic.termp equal-substitutible-logic.term-listp)))))) (defthm forcing-logic.appealp-of-equal-substitutible-term-bldr (implies (and (force (logic.termp x)) (force (logic.termp y)) (force (logic.appeal-listp as)) (force (equal-substitutible-logic.termp x y (logic.strip-conclusions as)))) (logic.appealp (equal-substitutible-term-bldr x y as))) :hints(("Goal" :use ((:instance lemma (flag 'term)))))) (defthm forcing-logic.appeal-listp-of-equal-substitutible-term-list-bldr (implies (and (force (logic.term-listp x)) (force (logic.term-listp y)) (force (logic.appeal-listp as)) (force (equal-substitutible-logic.term-listp x y (logic.strip-conclusions as)))) (logic.appeal-listp (equal-substitutible-term-list-bldr x y as))) :hints(("Goal" :use ((:instance lemma (flag 'list)))))) (defthm forcing-logic.conclusion-of-equal-substitutible-term-bldr (implies (and (force (logic.termp x)) (force (logic.termp y)) (force (logic.appeal-listp as)) (force (equal-substitutible-logic.termp x y (logic.strip-conclusions as)))) (equal (logic.conclusion (equal-substitutible-term-bldr x y as)) (logic.pequal x y))) :rule-classes ((:rewrite :backchain-limit-lst 0)) :hints(("Goal" :use ((:instance lemma (flag 'term)))))) (defthm forcing-logic.strip-conclusions-of-equal-substitutible-term-list-bldr (implies (and (force (logic.term-listp x)) (force (logic.term-listp y)) (force (logic.appeal-listp as)) (force (equal-substitutible-logic.term-listp x y (logic.strip-conclusions as)))) (equal (logic.strip-conclusions (equal-substitutible-term-list-bldr x y as)) (logic.pequal-list x y))) :rule-classes ((:rewrite :backchain-limit-lst 0)) :hints(("Goal" :use ((:instance lemma (flag 'list)))))) (local (defthm crock (implies (and (equal (logic.lambda-formals x) (logic.lambda-formals y)) (logic.termp x) (logic.termp y) (logic.lambdap x) (logic.lambdap y)) (equal (equal (len (logic.lambda-actuals x)) (len (logic.lambda-actuals y))) t)) :hints(("Goal" :in-theory (disable FORCING-EQUAL-LENS-OF-LOGIC.LAMBDA-FORMALS-AND-LOGIC.LAMBDA-ACTUALS) :use ((:instance FORCING-EQUAL-LENS-OF-LOGIC.LAMBDA-FORMALS-AND-LOGIC.LAMBDA-ACTUALS) (:instance FORCING-EQUAL-LENS-OF-LOGIC.LAMBDA-FORMALS-AND-LOGIC.LAMBDA-ACTUALS (x y))))))) (verify-guards equal-substitutible-term-bldr) (local (defthm lemma3 (if (equal flag 'term) (implies (and (logic.termp x) (logic.termp y) (logic.appeal-listp as) (equal-substitutible-logic.termp x y (logic.strip-conclusions as)) ;; --- (logic.term-atblp x atbl) (logic.term-atblp y atbl) (logic.proof-listp as axioms thms atbl) (memberp (axiom-reflexivity) axioms) (memberp (axiom-equality) axioms) (memberp (theorem-transitivity-of-pequal) thms) (memberp (theorem-commutativity-of-pequal) thms)) (logic.proofp (equal-substitutible-term-bldr x y as) axioms thms atbl)) (implies (and (logic.term-listp x) (logic.term-listp y) (logic.appeal-listp as) (equal-substitutible-logic.term-listp x y (logic.strip-conclusions as)) ;; --- (logic.term-list-atblp x atbl) (logic.term-list-atblp y atbl) (logic.proof-listp as axioms thms atbl) (memberp (axiom-reflexivity) axioms) (memberp (axiom-equality) axioms) (memberp (theorem-transitivity-of-pequal) thms) (memberp (theorem-commutativity-of-pequal) thms)) (logic.proof-listp (equal-substitutible-term-list-bldr x y as) axioms thms atbl))) :rule-classes nil :hints(("Goal" :induct (my-induction flag x y as) :in-theory (enable equal-substitutible-term-bldr equal-substitutible-term-list-bldr equal-substitutible-logic.termp equal-substitutible-logic.term-listp))))) (defthm forcing-logic.proofp-of-equal-substitutible-term-bldr (implies (force (and (logic.termp x) (logic.termp y) (logic.appeal-listp as) (equal-substitutible-logic.termp x y (logic.strip-conclusions as)) ;; --- (logic.term-atblp x atbl) (logic.term-atblp y atbl) (logic.proof-listp as axioms thms atbl) (memberp (axiom-reflexivity) axioms) (memberp (axiom-equality) axioms) (memberp (theorem-transitivity-of-pequal) thms) (memberp (theorem-commutativity-of-pequal) thms))) (logic.proofp (equal-substitutible-term-bldr x y as) axioms thms atbl)) :hints(("Goal" :use ((:instance lemma3 (flag 'term)))))) (defthm forcing-logic.proof-listp-of-equal-substitutible-term-list-bldr (implies (force (and (logic.term-listp x) (logic.term-listp y) (logic.appeal-listp as) (equal-substitutible-logic.term-listp x y (logic.strip-conclusions as)) ;; --- (logic.term-list-atblp x atbl) (logic.term-list-atblp y atbl) (logic.proof-listp as axioms thms atbl) (memberp (axiom-reflexivity) axioms) (memberp (axiom-equality) axioms) (memberp (theorem-transitivity-of-pequal) thms) (memberp (theorem-commutativity-of-pequal) thms))) (logic.proof-listp (equal-substitutible-term-list-bldr x y as) axioms thms atbl)) :hints(("Goal" :use ((:instance lemma3 (flag 'list))))))) ;; The second part of equals for equals is that, if a formula Y' is obtained ;; from some formula Y through replacements of equals for equals, then we ;; should be able to prove Y <-> Y'. (defund equal-substitutiblep (x y as) (declare (xargs :guard (and (logic.formulap x) (logic.formulap y) (logic.formula-listp as)))) (cond ((equal (logic.fmtype x) 'por*) (and (equal (logic.fmtype y) 'por*) (equal-substitutiblep (logic.vlhs x) (logic.vlhs y) as) (equal-substitutiblep (logic.vrhs x) (logic.vrhs y) as))) ((equal (logic.fmtype x) 'pnot*) (and (equal (logic.fmtype y) 'pnot*) (equal-substitutiblep (logic.~arg x) (logic.~arg y) as))) ((equal (logic.fmtype x) 'pequal*) (and (equal (logic.fmtype x) 'pequal*) (equal (logic.fmtype y) 'pequal*) (equal-substitutible-logic.termp (logic.=lhs x) (logic.=lhs y) as) (equal-substitutible-logic.termp (logic.=rhs x) (logic.=rhs y) as))) (t nil))) (defthm logic.fmtype-when-equal-substitutiblep-with-logic.por (implies (and (equal-substitutiblep x y as) (equal (logic.fmtype x) 'por*)) (equal (logic.fmtype y) 'por*)) :hints(("Goal" :in-theory (enable equal-substitutiblep)))) (defthm logic.fmtype-when-equal-substitutiblep-with-logic.pnot (implies (and (equal-substitutiblep x y as) (equal (logic.fmtype x) 'pnot*)) (equal (logic.fmtype y) 'pnot*)) :hints(("Goal" :in-theory (enable equal-substitutiblep)))) (defthm logic.fmtype-when-equal-substitutiblep-with-pequal (implies (and (equal-substitutiblep x y as) (equal (logic.fmtype x) 'pequal*)) (equal (logic.fmtype y) 'pequal*)) :hints(("Goal" :in-theory (enable equal-substitutiblep)))) (defthm equal-substitutiblep-of-recursive-calls-in-logic.por-case (implies (and (equal-substitutiblep x y as) (force (equal (logic.fmtype x) 'por*))) (and (equal-substitutiblep (logic.vlhs x) (logic.vlhs y) as) (equal-substitutiblep (logic.vrhs x) (logic.vrhs y) as))) :hints(("Goal" :in-theory (enable equal-substitutiblep)))) (defthm equal-substitutiblep-of-recursive-calls-in-logic.pnot-case (implies (and (equal-substitutiblep x y as) (force (equal (logic.fmtype x) 'pnot*))) (equal-substitutiblep (logic.~arg x) (logic.~arg y) as)) :hints(("Goal" :in-theory (enable equal-substitutiblep)))) (defthm equal-substitutible-logic.termp-of-recursive-calls-in-pequal-case (implies (and (equal-substitutiblep x y as) (force (equal (logic.fmtype x) 'pequal*))) (and (equal-substitutible-logic.termp (logic.=lhs x) (logic.=lhs y) as) (equal-substitutible-logic.termp (logic.=rhs x) (logic.=rhs y) as))) :hints(("Goal" :in-theory (enable equal-substitutiblep)))) ;; Note: This is like Shankar's function FORM-EQUAL-PROOF ;; ;; BOZO consider not using tautologies and building the proofs separately? (defund equal-substitutible-bldr (x y as) (declare (xargs :guard (and (logic.formulap x) (logic.formulap y) (logic.appeal-listp as) (equal-substitutiblep x y (logic.strip-conclusions as))) :verify-guards nil)) (cond ((equal (logic.fmtype x) 'por*) (tautological-consequence-bldr (logic.piff x y) (list (equal-substitutible-bldr (logic.vlhs x) (logic.vlhs y) as) (equal-substitutible-bldr (logic.vrhs x) (logic.vrhs y) as)))) ((equal (logic.fmtype x) 'pnot*) (tautological-consequence-bldr (logic.piff x y) (list (equal-substitutible-bldr (logic.~arg x) (logic.~arg y) as)))) ((equal (logic.fmtype x) 'pequal*) (let ((T1 (logic.=lhs x)) (T1-Prime (logic.=lhs y)) (T2 (logic.=rhs x)) (T2-Prime (logic.=rhs y))) (let* ((T1=T1-Prime (equal-substitutible-term-bldr T1 T1-Prime as)) (T2=T2-Prime (equal-substitutible-term-bldr T2 T2-Prime as)) (T1-Prime=T1 (build.commute-pequal T1=T1-Prime)) (T2-Prime=T2 (build.commute-pequal T2=T2-Prime))) (tautological-consequence-bldr (logic.piff x y) (list T1=T1-Prime T2=T2-Prime T1-Prime=T1 T2-Prime=T2 (build.equality T1 T1-Prime T2 T2-Prime) (build.equality T1-Prime T1 T2-Prime T2)))))) (t nil))) ;; Explanation of the Base Case ;; ;; In the base case above, we assume that we have two formulas, T1=T1' and ;; T2=T2', which are provable by the use of equals-for-equals. We now need ;; to show that T1=T2 <-> T1'=T2'. ;; ;; Shoenfield explains the proof as follows. ;; ;; 1. Use equals-for-equals to prove T1=T1', T2=T2'. ;; 2. Use commute-equal to prove T1'=T1, T2'=T2. ;; 3. Use the equality axiom to prove T1=T1' -> T2=T2' -> T1=T2' -> T1'=T2' ;; 4. Use the equality axiom to prove T1'=T1 -> T2'=T2 -> T1'=T2' -> T1=T2 ;; ;; Now, our goal T1=T2 <-> T1'=T2' is a tautological consequence of the ;; formulas produced in steps 1-4. ;; ;; We can "test this out" on some example formulas as below. You can run ;; this example to see that we do indeed have a tautological consequence. ;; ;; (tautological-consequencep ;; (logic.piff (logic.pequal 'T1 'T2) ;; (logic.pequal 'T1-Prime 'T2-Prime)) ;; (logic.strip-conclusions ;; (list ;; (build.axiom (logic.pequal 'T1 'T1-Prime)) ;; (build.axiom (logic.pequal 'T2 'T2-Prime)) ;; (build.axiom (logic.pequal 'T1-Prime 'T1)) ;; (build.axiom (logic.pequal 'T2-Prime 'T2)) ;; (build.equality 'T1 'T1-Prime 'T2 'T2-Prime) ;; (build.equality 'T1-Prime 'T1 'T2-Prime 'T2)))) ;; ;; But what we need to do is show this for arbitrary T1,T2,T1',T2' instead ;; of just for the above examples. (encapsulate () ;; BOZO i still don't like how we use logic.=lhs and logic.=rhs explicitly here. i'd ;; rather it used explicit variables instead. (local (defthm lemma (implies (and (force (logic.formulap x)) (force (logic.formulap y)) (force (equal (logic.fmtype x) 'pequal*)) (force (equal (logic.fmtype y) 'pequal*))) (tautological-consequencep (logic.piff x y) (list (logic.pequal (logic.=lhs x) (logic.=lhs y)) (logic.pequal (logic.=rhs x) (logic.=rhs y)) (logic.pequal (logic.=lhs y) (logic.=lhs x)) (logic.pequal (logic.=rhs y) (logic.=rhs x)) (logic.por (logic.pnot (logic.pequal (logic.=lhs x) (logic.=lhs y))) (logic.por (logic.pnot (logic.pequal (logic.=rhs x) (logic.=rhs y))) (logic.por (logic.pnot x) y))) (logic.por (logic.pnot (logic.pequal (logic.=lhs y) (logic.=lhs x))) (logic.por (logic.pnot (logic.pequal (logic.=rhs y) (logic.=rhs x))) (logic.por (logic.pnot y) x)))))) :hints(("Goal" :in-theory (e/d (tautological-consequencep) ;; This is a yucky looking hint, but ;; it's just for speed. (in-superset-when-in-subset-two in-superset-when-in-subset-one not-in-subset-when-not-in-superset-one not-in-subset-when-not-in-superset-two memberp-when-memberp-of-cdr memberp-when-not-consp subsetp-when-not-consp-two subsetp-of-cdr subsetp-when-not-consp)))))) (local (defthm lemma2 (implies (and (logic.formulap x) (logic.formulap y) (logic.appeal-listp as) (equal-substitutiblep x y (logic.strip-conclusions as))) (and (logic.appealp (equal-substitutible-bldr x y as)) (equal (logic.conclusion (equal-substitutible-bldr x y as)) (logic.piff x y)))) :hints(("Goal" :in-theory (enable equal-substitutible-bldr))))) (defthm forcing-logic.appealp-of-equal-substitutible-bldr (implies (and (force (logic.formulap x)) (force (logic.formulap y)) (force (logic.appeal-listp as)) (force (equal-substitutiblep x y (logic.strip-conclusions as)))) (logic.appealp (equal-substitutible-bldr x y as)))) (defthm forcing-logic.conclusion-of-equal-substitutible-bldr (implies (and (force (logic.formulap x)) (force (logic.formulap y)) (force (logic.appeal-listp as)) (force (equal-substitutiblep x y (logic.strip-conclusions as)))) (equal (logic.conclusion (equal-substitutible-bldr x y as)) (logic.piff x y))) :rule-classes ((:rewrite :backchain-limit-lst 0))) (verify-guards equal-substitutible-bldr) (defthm forcing-logic.proofp-of-equal-substitutible-bldr (implies (and (force (logic.formulap x)) (force (logic.formulap y)) (force (logic.appeal-listp as)) (force (equal-substitutiblep x y (logic.strip-conclusions as))) ;; --- (force (logic.formula-atblp x atbl)) (force (logic.formula-atblp y atbl)) (force (logic.proof-listp as axioms thms atbl)) (force (memberp (axiom-reflexivity) axioms)) (force (memberp (axiom-equality) axioms)) (force (memberp (theorem-transitivity-of-pequal) thms)) (force (memberp (theorem-commutativity-of-pequal) thms))) (logic.proofp (equal-substitutible-bldr x y as) axioms thms atbl)) :hints(("Goal" :in-theory (enable equal-substitutible-bldr))))) ;; As with the tautology and equivalence theorems, the equality theorem is ;; perhaps most often useful in the form below. Suppose that G is a formula ;; which is obtained from F by equality substitution of A1=A1' ... An=An'. ;; Then, if we have proofs of A1=A1' ... An=An' and F, we should be able to ;; prove G. This is the equal-consequence-bldr. (defund equal-consequence-bldr (g f as) (declare (xargs :guard (and (logic.formulap g) (logic.appealp f) (logic.appeal-listp as) (equal-substitutiblep (logic.conclusion f) g (logic.strip-conclusions as))) :verify-guards nil)) (let ((iff-f-g (equal-substitutible-bldr (logic.conclusion f) g as))) (tautological-consequence-bldr g (list iff-f-g f)))) (encapsulate () (local (defthm lemma (implies (and (logic.formulap f) (logic.formulap g)) (tautological-consequencep g (list (logic.piff f g) f))) :hints(("Goal" :in-theory (enable tautological-consequencep))))) (verify-guards equal-consequence-bldr) (defthm forcing-logic.conclusion-of-equal-consequence-bldr (implies (and (force (logic.formulap g)) (force (logic.appealp f)) (force (logic.appeal-listp as)) (force (equal-substitutiblep (logic.conclusion f) g (logic.strip-conclusions as)))) (equal (logic.conclusion (equal-consequence-bldr g f as)) g)) :hints(("Goal" :in-theory (enable equal-consequence-bldr)))) (defthm forcing-logic.appealp-of-equal-consequence-bldr (implies (and (force (logic.formulap g)) (force (logic.appealp f)) (force (logic.appeal-listp as)) (force (equal-substitutiblep (logic.conclusion f) g (logic.strip-conclusions as)))) (logic.appealp (equal-consequence-bldr g f as))) :hints(("Goal" :in-theory (enable equal-consequence-bldr)))) (defthm forcing-logic.proofp-of-equal-consequence-bldr (implies (and (force (logic.formulap g)) (force (logic.appealp f)) (force (logic.appeal-listp as)) (force (equal-substitutiblep (logic.conclusion f) g (logic.strip-conclusions as))) ;; --- (force (logic.formula-atblp g atbl)) (force (logic.proofp f axioms thms atbl)) (force (logic.proof-listp as axioms thms atbl)) (force (memberp (axiom-reflexivity) axioms)) (force (memberp (axiom-equality) axioms)) (force (memberp (theorem-transitivity-of-pequal) thms)) (force (memberp (theorem-commutativity-of-pequal) thms))) (logic.proofp (equal-consequence-bldr g f as) axioms thms atbl)) :hints(("Goal" :in-theory (enable equal-consequence-bldr))))) (defthm forcing-equal-substitutiblep-of-logic.pors (implies (and (force (logic.formulap a)) (force (logic.formulap b)) (force (logic.formulap c)) (force (logic.formulap d))) (equal (equal-substitutiblep (logic.por a b) (logic.por c d) proofs) (and (equal-substitutiblep a c proofs) (equal-substitutiblep b d proofs)))) :hints(("Goal" :in-theory (enable equal-substitutiblep)))) (defthm forcing-equal-substitutiblep-of-logic.pnots (implies (and (force (logic.formulap a)) (force (logic.formulap b))) (equal (equal-substitutiblep (logic.pnot a) (logic.pnot b) proofs) (equal-substitutiblep a b proofs))) :hints(("Goal" :in-theory (enable equal-substitutiblep)))) (defthm forcing-equal-substitutiblep-of-pequals (implies (and (force (logic.termp a)) (force (logic.termp b)) (force (logic.termp c)) (force (logic.termp d))) (equal (equal-substitutiblep (logic.pequal a b) (logic.pequal c d) proofs) (and (equal-substitutible-logic.termp a c proofs) (equal-substitutible-logic.termp b d proofs)))) :hints(("Goal" :in-theory (enable equal-substitutiblep)))) (defthm reflexivity-of-equal-substitutible-logic.termp (equal-substitutible-logic.termp x x proofs) :hints(("Goal" :in-theory (enable equal-substitutible-logic.termp)))) (defthm reflexivity-of-equal-substitutiblep (implies (force (logic.formulap x)) (equal-substitutiblep x x proofs)) :hints(("Goal" :in-theory (enable equal-substitutiblep)))) (defthm equal-substitutible-logic.termp-of-lhs-and-rhs-when-in-proofs (implies (and (memberp proof proofs) (force (logic.formulap proof)) ;; jcd:2006-04-05 added this hyp (force (equal (logic.fmtype proof) 'pequal*))) (equal-substitutible-logic.termp (logic.=lhs proof) (logic.=rhs proof) proofs)) :hints(("Goal" :in-theory (enable equal-substitutible-logic.termp)))) (defthm forcing-equal-substitutible-logic.termp-of-logic.functions (implies (and (force (logic.function-namep fn)) (force (true-listp args1)) (force (logic.term-listp args1)) (force (true-listp args2)) (force (logic.term-listp args2))) (equal (equal-substitutible-logic.termp (logic.function fn args1) (logic.function fn args2) proofs) (or (equal args1 args2) (memberp (logic.pequal (logic.function fn args1) (logic.function fn args2)) proofs) (memberp (logic.pequal (logic.function fn args2) (logic.function fn args1)) proofs) (equal-substitutible-logic.term-listp args1 args2 proofs)))) :hints(("Goal" :in-theory (enable equal-substitutible-logic.termp))))
36003
; 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 "tautologies") (include-book "../build/lambda") (set-verify-guards-eagerness 2) (set-case-split-limitations nil) (set-well-founded-relation ord<) (set-measure-function rank) ;; Let X' (a term) be obtained from X (another term) by replacing some ;; occurrences of terms A1,...,An by A1',...,An', respectively. If ;; |- A1 = A1', |- A2 = A2', ..., |- An = An' ;; Then ;; |- X = X' ;; ;; Furthermore, if Y' (a formula) is obtained from Y (another formula) ;; by similar replacements, then ;; |- Y <-> Y' ;; We introduce the function equals-for-equalsp, which takes as inputs the ;; terms x and y, and the list of formulas [A1, A2, ..., An]. We return true ;; if and only if y is obtainable from x by replacing some terms ti with other ;; terms si, where ti=si or si=ti is some Ai. ;; ;; This function is sort of like tautologyp1, in that it does not build a ;; proof, but is rather just an algorithm to decide if a proof can be ;; generated. (mutual-recursion (defund equal-substitutible-logic.termp (x y as) (declare (xargs :guard (and (logic.termp x) (logic.termp y) (logic.formula-listp as)))) (or (equal x y) (memberp (logic.pequal x y) as) (memberp (logic.pequal y x) as) (cond ((logic.constantp x) nil) ((logic.variablep x) nil) ((logic.functionp x) (and (logic.functionp y) (equal (logic.function-name x) (logic.function-name y)) (equal-substitutible-logic.term-listp (logic.function-args x) (logic.function-args y) as))) ((logic.lambdap x) (and (logic.lambdap y) (equal (logic.lambda-formals x) (logic.lambda-formals y)) (equal (logic.lambda-body x) (logic.lambda-body y)) (equal-substitutible-logic.term-listp (logic.lambda-actuals x) (logic.lambda-actuals y) as))) (t nil)))) (defund equal-substitutible-logic.term-listp (x y as) (declare (xargs :guard (and (logic.term-listp x) (logic.term-listp y) (logic.formula-listp as)))) (if (consp x) (and (consp y) (equal-substitutible-logic.termp (car x) (car y) as) (equal-substitutible-logic.term-listp (cdr x) (cdr y) as)) (not (consp y))))) (defthm equal-substitutible-logic.term-listp-of-cdrs-when-equal-substitutible-logic.term-listp (implies (and (equal-substitutible-logic.term-listp x y as) (consp x) (consp y)) (equal-substitutible-logic.term-listp (cdr x) (cdr y) as)) :hints(("Goal" :in-theory (enable equal-substitutible-logic.term-listp)))) (defthm equal-substitutible-logic.termp-of-cars-when-equal-substitutible-logic.term-listp (implies (and (equal-substitutible-logic.term-listp x y as) (consp x) (consp y)) (equal-substitutible-logic.termp (car x) (car y) as)) :hints(("Goal" :in-theory (enable equal-substitutible-logic.term-listp)))) (defthm equal-of-lengths-when-equal-substitutible-logic.term-listp (implies (equal-substitutible-logic.term-listp x y as) (equal (equal (len x) (len y)) t)) :hints(("Goal" :induct (cdr-cdr-induction x y) :in-theory (enable equal-substitutible-logic.term-listp)))) (defthm equal-substitutible-logic.term-listp-of-logic.lambda-actuals-when-logic.lambdaps (implies (and (equal-substitutible-logic.termp x y as) (logic.lambdap x) (logic.lambdap y) (not (equal x y)) (not (memberp (logic.pequal x y) as)) (not (memberp (logic.pequal y x) as))) (equal-substitutible-logic.term-listp (logic.lambda-actuals x) (logic.lambda-actuals y) as)) :hints(("Goal" :in-theory (enable equal-substitutible-logic.termp) :expand (equal-substitutible-logic.termp x y as)))) (defthm equal-substitutible-logic.term-listp-of-logic.function-args-when-logic.functionps (implies (and (equal-substitutible-logic.termp x y as) (logic.functionp x) (logic.functionp y) (not (equal x y)) (not (memberp (logic.pequal x y) as)) (not (memberp (logic.pequal y x) as))) (equal-substitutible-logic.term-listp (logic.function-args x) (logic.function-args y) as)) :hints(("Goal" :in-theory (enable equal-substitutible-logic.termp) :expand (equal-substitutible-logic.termp x y as)))) ;; Below we introduce equals-for-equals-bldr, which takes as inputs the terms x ;; and y, and the list of proofs [A1, A2, ..., An]. It should be the case that ;; these inputs satisfy equal-substitutible-logic.termp (i.e., using the conclusions ;; of the proofs A1...An). Our goal is to build a proof that x = y, by ;; utilizing the provided proofs as necessary. ;; ;; This function is sort of like tautologyp-bldr1, which builds a proof ;; whenever tautologyp1 says that some inputs are ok. In this case, we build a ;; proof when equal-substitutible-logic.termp says that the inputs are ok. (mutual-recursion (defund equal-substitutible-term-bldr (x y as) (declare (xargs :guard (and (logic.termp x) (logic.termp y) (logic.appeal-listp as) (equal-substitutible-logic.termp x y (logic.strip-conclusions as))) :verify-guards nil)) (cond ((equal x y) (build.reflexivity x)) ((memberp (logic.pequal x y) (logic.strip-conclusions as)) (logic.find-proof (logic.pequal x y) as)) ((memberp (logic.pequal y x) (logic.strip-conclusions as)) (build.commute-pequal (logic.find-proof (logic.pequal y x) as))) ((logic.functionp x) (if (and (logic.functionp y) (equal (logic.function-name x) (logic.function-name y))) (build.pequal-by-args (logic.function-name x) (equal-substitutible-term-list-bldr (logic.function-args x) (logic.function-args y) as)) nil)) ((logic.lambdap x) (if (and (logic.lambdap y) (equal (logic.lambda-formals x) (logic.lambda-formals y)) (equal (logic.lambda-body x) (logic.lambda-body y))) (build.lambda-pequal-by-args (logic.lambda-formals x) (logic.lambda-body x) (equal-substitutible-term-list-bldr (logic.lambda-actuals x) (logic.lambda-actuals y) as)) nil)) (t nil))) (defund equal-substitutible-term-list-bldr (x y as) (declare (xargs :guard (and (logic.term-listp x) (logic.term-listp y) (logic.appeal-listp as) (equal-substitutible-logic.term-listp x y (logic.strip-conclusions as))))) (if (consp x) (if (consp y) (cons (equal-substitutible-term-bldr (car x) (car y) as) (equal-substitutible-term-list-bldr (cdr x) (cdr y) as)) nil) nil))) (defthm len-of-equal-substitutible-term-list-bldr (implies (force (equal (len x) (len y))) (equal (len (equal-substitutible-term-list-bldr x y as)) (len x))) :hints(("Goal" :in-theory (enable equal-substitutible-term-list-bldr) :induct (cdr-cdr-induction x y)))) (defthm true-listp-of-equal-substitutible-term-list-bldr (equal (true-listp (equal-substitutible-term-list-bldr x y as)) t) :hints(("Goal" :in-theory (enable equal-substitutible-term-list-bldr) :induct (cdr-cdr-induction x y)))) (encapsulate () (local (defun my-induction (flag x y as) (declare (xargs :verify-guards nil)) (if (equal flag 'term) (cond ((equal x y) nil) ((memberp (logic.pequal x y) (logic.strip-conclusions as)) nil) ((memberp (logic.pequal y x) (logic.strip-conclusions as)) nil) ((logic.constantp x) nil) ((logic.variablep x) nil) ((logic.functionp x) (my-induction 'list (logic.function-args x) (logic.function-args y) as)) ((logic.lambdap x) (my-induction 'list (logic.lambda-actuals x) (logic.lambda-actuals y) as)) (t nil)) (if (and (consp x) (consp y)) (list (my-induction 'term (car x) (car y) as) (my-induction 'list (cdr x) (cdr y) as)) nil)))) (local (defthm lemma (if (equal flag 'term) (implies (and (logic.termp x) (logic.termp y) (logic.appeal-listp as) (equal-substitutible-logic.termp x y (logic.strip-conclusions as))) (and (logic.appealp (equal-substitutible-term-bldr x y as)) (equal (logic.conclusion (equal-substitutible-term-bldr x y as)) (logic.pequal x y)))) (implies (and (logic.term-listp x) (logic.term-listp y) (logic.appeal-listp as) (equal-substitutible-logic.term-listp x y (logic.strip-conclusions as))) (and (logic.appeal-listp (equal-substitutible-term-list-bldr x y as)) (equal (logic.strip-conclusions (equal-substitutible-term-list-bldr x y as)) (logic.pequal-list x y))))) :rule-classes nil :hints(("Goal" :induct (my-induction flag x y as) :in-theory (e/d (equal-substitutible-term-bldr equal-substitutible-term-list-bldr equal-substitutible-logic.termp equal-substitutible-logic.term-listp)))))) (defthm forcing-logic.appealp-of-equal-substitutible-term-bldr (implies (and (force (logic.termp x)) (force (logic.termp y)) (force (logic.appeal-listp as)) (force (equal-substitutible-logic.termp x y (logic.strip-conclusions as)))) (logic.appealp (equal-substitutible-term-bldr x y as))) :hints(("Goal" :use ((:instance lemma (flag 'term)))))) (defthm forcing-logic.appeal-listp-of-equal-substitutible-term-list-bldr (implies (and (force (logic.term-listp x)) (force (logic.term-listp y)) (force (logic.appeal-listp as)) (force (equal-substitutible-logic.term-listp x y (logic.strip-conclusions as)))) (logic.appeal-listp (equal-substitutible-term-list-bldr x y as))) :hints(("Goal" :use ((:instance lemma (flag 'list)))))) (defthm forcing-logic.conclusion-of-equal-substitutible-term-bldr (implies (and (force (logic.termp x)) (force (logic.termp y)) (force (logic.appeal-listp as)) (force (equal-substitutible-logic.termp x y (logic.strip-conclusions as)))) (equal (logic.conclusion (equal-substitutible-term-bldr x y as)) (logic.pequal x y))) :rule-classes ((:rewrite :backchain-limit-lst 0)) :hints(("Goal" :use ((:instance lemma (flag 'term)))))) (defthm forcing-logic.strip-conclusions-of-equal-substitutible-term-list-bldr (implies (and (force (logic.term-listp x)) (force (logic.term-listp y)) (force (logic.appeal-listp as)) (force (equal-substitutible-logic.term-listp x y (logic.strip-conclusions as)))) (equal (logic.strip-conclusions (equal-substitutible-term-list-bldr x y as)) (logic.pequal-list x y))) :rule-classes ((:rewrite :backchain-limit-lst 0)) :hints(("Goal" :use ((:instance lemma (flag 'list)))))) (local (defthm crock (implies (and (equal (logic.lambda-formals x) (logic.lambda-formals y)) (logic.termp x) (logic.termp y) (logic.lambdap x) (logic.lambdap y)) (equal (equal (len (logic.lambda-actuals x)) (len (logic.lambda-actuals y))) t)) :hints(("Goal" :in-theory (disable FORCING-EQUAL-LENS-OF-LOGIC.LAMBDA-FORMALS-AND-LOGIC.LAMBDA-ACTUALS) :use ((:instance FORCING-EQUAL-LENS-OF-LOGIC.LAMBDA-FORMALS-AND-LOGIC.LAMBDA-ACTUALS) (:instance FORCING-EQUAL-LENS-OF-LOGIC.LAMBDA-FORMALS-AND-LOGIC.LAMBDA-ACTUALS (x y))))))) (verify-guards equal-substitutible-term-bldr) (local (defthm lemma3 (if (equal flag 'term) (implies (and (logic.termp x) (logic.termp y) (logic.appeal-listp as) (equal-substitutible-logic.termp x y (logic.strip-conclusions as)) ;; --- (logic.term-atblp x atbl) (logic.term-atblp y atbl) (logic.proof-listp as axioms thms atbl) (memberp (axiom-reflexivity) axioms) (memberp (axiom-equality) axioms) (memberp (theorem-transitivity-of-pequal) thms) (memberp (theorem-commutativity-of-pequal) thms)) (logic.proofp (equal-substitutible-term-bldr x y as) axioms thms atbl)) (implies (and (logic.term-listp x) (logic.term-listp y) (logic.appeal-listp as) (equal-substitutible-logic.term-listp x y (logic.strip-conclusions as)) ;; --- (logic.term-list-atblp x atbl) (logic.term-list-atblp y atbl) (logic.proof-listp as axioms thms atbl) (memberp (axiom-reflexivity) axioms) (memberp (axiom-equality) axioms) (memberp (theorem-transitivity-of-pequal) thms) (memberp (theorem-commutativity-of-pequal) thms)) (logic.proof-listp (equal-substitutible-term-list-bldr x y as) axioms thms atbl))) :rule-classes nil :hints(("Goal" :induct (my-induction flag x y as) :in-theory (enable equal-substitutible-term-bldr equal-substitutible-term-list-bldr equal-substitutible-logic.termp equal-substitutible-logic.term-listp))))) (defthm forcing-logic.proofp-of-equal-substitutible-term-bldr (implies (force (and (logic.termp x) (logic.termp y) (logic.appeal-listp as) (equal-substitutible-logic.termp x y (logic.strip-conclusions as)) ;; --- (logic.term-atblp x atbl) (logic.term-atblp y atbl) (logic.proof-listp as axioms thms atbl) (memberp (axiom-reflexivity) axioms) (memberp (axiom-equality) axioms) (memberp (theorem-transitivity-of-pequal) thms) (memberp (theorem-commutativity-of-pequal) thms))) (logic.proofp (equal-substitutible-term-bldr x y as) axioms thms atbl)) :hints(("Goal" :use ((:instance lemma3 (flag 'term)))))) (defthm forcing-logic.proof-listp-of-equal-substitutible-term-list-bldr (implies (force (and (logic.term-listp x) (logic.term-listp y) (logic.appeal-listp as) (equal-substitutible-logic.term-listp x y (logic.strip-conclusions as)) ;; --- (logic.term-list-atblp x atbl) (logic.term-list-atblp y atbl) (logic.proof-listp as axioms thms atbl) (memberp (axiom-reflexivity) axioms) (memberp (axiom-equality) axioms) (memberp (theorem-transitivity-of-pequal) thms) (memberp (theorem-commutativity-of-pequal) thms))) (logic.proof-listp (equal-substitutible-term-list-bldr x y as) axioms thms atbl)) :hints(("Goal" :use ((:instance lemma3 (flag 'list))))))) ;; The second part of equals for equals is that, if a formula Y' is obtained ;; from some formula Y through replacements of equals for equals, then we ;; should be able to prove Y <-> Y'. (defund equal-substitutiblep (x y as) (declare (xargs :guard (and (logic.formulap x) (logic.formulap y) (logic.formula-listp as)))) (cond ((equal (logic.fmtype x) 'por*) (and (equal (logic.fmtype y) 'por*) (equal-substitutiblep (logic.vlhs x) (logic.vlhs y) as) (equal-substitutiblep (logic.vrhs x) (logic.vrhs y) as))) ((equal (logic.fmtype x) 'pnot*) (and (equal (logic.fmtype y) 'pnot*) (equal-substitutiblep (logic.~arg x) (logic.~arg y) as))) ((equal (logic.fmtype x) 'pequal*) (and (equal (logic.fmtype x) 'pequal*) (equal (logic.fmtype y) 'pequal*) (equal-substitutible-logic.termp (logic.=lhs x) (logic.=lhs y) as) (equal-substitutible-logic.termp (logic.=rhs x) (logic.=rhs y) as))) (t nil))) (defthm logic.fmtype-when-equal-substitutiblep-with-logic.por (implies (and (equal-substitutiblep x y as) (equal (logic.fmtype x) 'por*)) (equal (logic.fmtype y) 'por*)) :hints(("Goal" :in-theory (enable equal-substitutiblep)))) (defthm logic.fmtype-when-equal-substitutiblep-with-logic.pnot (implies (and (equal-substitutiblep x y as) (equal (logic.fmtype x) 'pnot*)) (equal (logic.fmtype y) 'pnot*)) :hints(("Goal" :in-theory (enable equal-substitutiblep)))) (defthm logic.fmtype-when-equal-substitutiblep-with-pequal (implies (and (equal-substitutiblep x y as) (equal (logic.fmtype x) 'pequal*)) (equal (logic.fmtype y) 'pequal*)) :hints(("Goal" :in-theory (enable equal-substitutiblep)))) (defthm equal-substitutiblep-of-recursive-calls-in-logic.por-case (implies (and (equal-substitutiblep x y as) (force (equal (logic.fmtype x) 'por*))) (and (equal-substitutiblep (logic.vlhs x) (logic.vlhs y) as) (equal-substitutiblep (logic.vrhs x) (logic.vrhs y) as))) :hints(("Goal" :in-theory (enable equal-substitutiblep)))) (defthm equal-substitutiblep-of-recursive-calls-in-logic.pnot-case (implies (and (equal-substitutiblep x y as) (force (equal (logic.fmtype x) 'pnot*))) (equal-substitutiblep (logic.~arg x) (logic.~arg y) as)) :hints(("Goal" :in-theory (enable equal-substitutiblep)))) (defthm equal-substitutible-logic.termp-of-recursive-calls-in-pequal-case (implies (and (equal-substitutiblep x y as) (force (equal (logic.fmtype x) 'pequal*))) (and (equal-substitutible-logic.termp (logic.=lhs x) (logic.=lhs y) as) (equal-substitutible-logic.termp (logic.=rhs x) (logic.=rhs y) as))) :hints(("Goal" :in-theory (enable equal-substitutiblep)))) ;; Note: This is like Shankar's function FORM-EQUAL-PROOF ;; ;; BOZO consider not using tautologies and building the proofs separately? (defund equal-substitutible-bldr (x y as) (declare (xargs :guard (and (logic.formulap x) (logic.formulap y) (logic.appeal-listp as) (equal-substitutiblep x y (logic.strip-conclusions as))) :verify-guards nil)) (cond ((equal (logic.fmtype x) 'por*) (tautological-consequence-bldr (logic.piff x y) (list (equal-substitutible-bldr (logic.vlhs x) (logic.vlhs y) as) (equal-substitutible-bldr (logic.vrhs x) (logic.vrhs y) as)))) ((equal (logic.fmtype x) 'pnot*) (tautological-consequence-bldr (logic.piff x y) (list (equal-substitutible-bldr (logic.~arg x) (logic.~arg y) as)))) ((equal (logic.fmtype x) 'pequal*) (let ((T1 (logic.=lhs x)) (T1-Prime (logic.=lhs y)) (T2 (logic.=rhs x)) (T2-Prime (logic.=rhs y))) (let* ((T1=T1-Prime (equal-substitutible-term-bldr T1 T1-Prime as)) (T2=T2-Prime (equal-substitutible-term-bldr T2 T2-Prime as)) (T1-Prime=T1 (build.commute-pequal T1=T1-Prime)) (T2-Prime=T2 (build.commute-pequal T2=T2-Prime))) (tautological-consequence-bldr (logic.piff x y) (list T1=T1-Prime T2=T2-Prime T1-Prime=T1 T2-Prime=T2 (build.equality T1 T1-Prime T2 T2-Prime) (build.equality T1-Prime T1 T2-Prime T2)))))) (t nil))) ;; Explanation of the Base Case ;; ;; In the base case above, we assume that we have two formulas, T1=T1' and ;; T2=T2', which are provable by the use of equals-for-equals. We now need ;; to show that T1=T2 <-> T1'=T2'. ;; ;; <NAME> explains the proof as follows. ;; ;; 1. Use equals-for-equals to prove T1=T1', T2=T2'. ;; 2. Use commute-equal to prove T1'=T1, T2'=T2. ;; 3. Use the equality axiom to prove T1=T1' -> T2=T2' -> T1=T2' -> T1'=T2' ;; 4. Use the equality axiom to prove T1'=T1 -> T2'=T2 -> T1'=T2' -> T1=T2 ;; ;; Now, our goal T1=T2 <-> T1'=T2' is a tautological consequence of the ;; formulas produced in steps 1-4. ;; ;; We can "test this out" on some example formulas as below. You can run ;; this example to see that we do indeed have a tautological consequence. ;; ;; (tautological-consequencep ;; (logic.piff (logic.pequal 'T1 'T2) ;; (logic.pequal 'T1-Prime 'T2-Prime)) ;; (logic.strip-conclusions ;; (list ;; (build.axiom (logic.pequal 'T1 'T1-Prime)) ;; (build.axiom (logic.pequal 'T2 'T2-Prime)) ;; (build.axiom (logic.pequal 'T1-Prime 'T1)) ;; (build.axiom (logic.pequal 'T2-Prime 'T2)) ;; (build.equality 'T1 'T1-Prime 'T2 'T2-Prime) ;; (build.equality 'T1-Prime 'T1 'T2-Prime 'T2)))) ;; ;; But what we need to do is show this for arbitrary T1,T2,T1',T2' instead ;; of just for the above examples. (encapsulate () ;; BOZO i still don't like how we use logic.=lhs and logic.=rhs explicitly here. i'd ;; rather it used explicit variables instead. (local (defthm lemma (implies (and (force (logic.formulap x)) (force (logic.formulap y)) (force (equal (logic.fmtype x) 'pequal*)) (force (equal (logic.fmtype y) 'pequal*))) (tautological-consequencep (logic.piff x y) (list (logic.pequal (logic.=lhs x) (logic.=lhs y)) (logic.pequal (logic.=rhs x) (logic.=rhs y)) (logic.pequal (logic.=lhs y) (logic.=lhs x)) (logic.pequal (logic.=rhs y) (logic.=rhs x)) (logic.por (logic.pnot (logic.pequal (logic.=lhs x) (logic.=lhs y))) (logic.por (logic.pnot (logic.pequal (logic.=rhs x) (logic.=rhs y))) (logic.por (logic.pnot x) y))) (logic.por (logic.pnot (logic.pequal (logic.=lhs y) (logic.=lhs x))) (logic.por (logic.pnot (logic.pequal (logic.=rhs y) (logic.=rhs x))) (logic.por (logic.pnot y) x)))))) :hints(("Goal" :in-theory (e/d (tautological-consequencep) ;; This is a yucky looking hint, but ;; it's just for speed. (in-superset-when-in-subset-two in-superset-when-in-subset-one not-in-subset-when-not-in-superset-one not-in-subset-when-not-in-superset-two memberp-when-memberp-of-cdr memberp-when-not-consp subsetp-when-not-consp-two subsetp-of-cdr subsetp-when-not-consp)))))) (local (defthm lemma2 (implies (and (logic.formulap x) (logic.formulap y) (logic.appeal-listp as) (equal-substitutiblep x y (logic.strip-conclusions as))) (and (logic.appealp (equal-substitutible-bldr x y as)) (equal (logic.conclusion (equal-substitutible-bldr x y as)) (logic.piff x y)))) :hints(("Goal" :in-theory (enable equal-substitutible-bldr))))) (defthm forcing-logic.appealp-of-equal-substitutible-bldr (implies (and (force (logic.formulap x)) (force (logic.formulap y)) (force (logic.appeal-listp as)) (force (equal-substitutiblep x y (logic.strip-conclusions as)))) (logic.appealp (equal-substitutible-bldr x y as)))) (defthm forcing-logic.conclusion-of-equal-substitutible-bldr (implies (and (force (logic.formulap x)) (force (logic.formulap y)) (force (logic.appeal-listp as)) (force (equal-substitutiblep x y (logic.strip-conclusions as)))) (equal (logic.conclusion (equal-substitutible-bldr x y as)) (logic.piff x y))) :rule-classes ((:rewrite :backchain-limit-lst 0))) (verify-guards equal-substitutible-bldr) (defthm forcing-logic.proofp-of-equal-substitutible-bldr (implies (and (force (logic.formulap x)) (force (logic.formulap y)) (force (logic.appeal-listp as)) (force (equal-substitutiblep x y (logic.strip-conclusions as))) ;; --- (force (logic.formula-atblp x atbl)) (force (logic.formula-atblp y atbl)) (force (logic.proof-listp as axioms thms atbl)) (force (memberp (axiom-reflexivity) axioms)) (force (memberp (axiom-equality) axioms)) (force (memberp (theorem-transitivity-of-pequal) thms)) (force (memberp (theorem-commutativity-of-pequal) thms))) (logic.proofp (equal-substitutible-bldr x y as) axioms thms atbl)) :hints(("Goal" :in-theory (enable equal-substitutible-bldr))))) ;; As with the tautology and equivalence theorems, the equality theorem is ;; perhaps most often useful in the form below. Suppose that G is a formula ;; which is obtained from F by equality substitution of A1=A1' ... An=An'. ;; Then, if we have proofs of A1=A1' ... An=An' and F, we should be able to ;; prove G. This is the equal-consequence-bldr. (defund equal-consequence-bldr (g f as) (declare (xargs :guard (and (logic.formulap g) (logic.appealp f) (logic.appeal-listp as) (equal-substitutiblep (logic.conclusion f) g (logic.strip-conclusions as))) :verify-guards nil)) (let ((iff-f-g (equal-substitutible-bldr (logic.conclusion f) g as))) (tautological-consequence-bldr g (list iff-f-g f)))) (encapsulate () (local (defthm lemma (implies (and (logic.formulap f) (logic.formulap g)) (tautological-consequencep g (list (logic.piff f g) f))) :hints(("Goal" :in-theory (enable tautological-consequencep))))) (verify-guards equal-consequence-bldr) (defthm forcing-logic.conclusion-of-equal-consequence-bldr (implies (and (force (logic.formulap g)) (force (logic.appealp f)) (force (logic.appeal-listp as)) (force (equal-substitutiblep (logic.conclusion f) g (logic.strip-conclusions as)))) (equal (logic.conclusion (equal-consequence-bldr g f as)) g)) :hints(("Goal" :in-theory (enable equal-consequence-bldr)))) (defthm forcing-logic.appealp-of-equal-consequence-bldr (implies (and (force (logic.formulap g)) (force (logic.appealp f)) (force (logic.appeal-listp as)) (force (equal-substitutiblep (logic.conclusion f) g (logic.strip-conclusions as)))) (logic.appealp (equal-consequence-bldr g f as))) :hints(("Goal" :in-theory (enable equal-consequence-bldr)))) (defthm forcing-logic.proofp-of-equal-consequence-bldr (implies (and (force (logic.formulap g)) (force (logic.appealp f)) (force (logic.appeal-listp as)) (force (equal-substitutiblep (logic.conclusion f) g (logic.strip-conclusions as))) ;; --- (force (logic.formula-atblp g atbl)) (force (logic.proofp f axioms thms atbl)) (force (logic.proof-listp as axioms thms atbl)) (force (memberp (axiom-reflexivity) axioms)) (force (memberp (axiom-equality) axioms)) (force (memberp (theorem-transitivity-of-pequal) thms)) (force (memberp (theorem-commutativity-of-pequal) thms))) (logic.proofp (equal-consequence-bldr g f as) axioms thms atbl)) :hints(("Goal" :in-theory (enable equal-consequence-bldr))))) (defthm forcing-equal-substitutiblep-of-logic.pors (implies (and (force (logic.formulap a)) (force (logic.formulap b)) (force (logic.formulap c)) (force (logic.formulap d))) (equal (equal-substitutiblep (logic.por a b) (logic.por c d) proofs) (and (equal-substitutiblep a c proofs) (equal-substitutiblep b d proofs)))) :hints(("Goal" :in-theory (enable equal-substitutiblep)))) (defthm forcing-equal-substitutiblep-of-logic.pnots (implies (and (force (logic.formulap a)) (force (logic.formulap b))) (equal (equal-substitutiblep (logic.pnot a) (logic.pnot b) proofs) (equal-substitutiblep a b proofs))) :hints(("Goal" :in-theory (enable equal-substitutiblep)))) (defthm forcing-equal-substitutiblep-of-pequals (implies (and (force (logic.termp a)) (force (logic.termp b)) (force (logic.termp c)) (force (logic.termp d))) (equal (equal-substitutiblep (logic.pequal a b) (logic.pequal c d) proofs) (and (equal-substitutible-logic.termp a c proofs) (equal-substitutible-logic.termp b d proofs)))) :hints(("Goal" :in-theory (enable equal-substitutiblep)))) (defthm reflexivity-of-equal-substitutible-logic.termp (equal-substitutible-logic.termp x x proofs) :hints(("Goal" :in-theory (enable equal-substitutible-logic.termp)))) (defthm reflexivity-of-equal-substitutiblep (implies (force (logic.formulap x)) (equal-substitutiblep x x proofs)) :hints(("Goal" :in-theory (enable equal-substitutiblep)))) (defthm equal-substitutible-logic.termp-of-lhs-and-rhs-when-in-proofs (implies (and (memberp proof proofs) (force (logic.formulap proof)) ;; jcd:2006-04-05 added this hyp (force (equal (logic.fmtype proof) 'pequal*))) (equal-substitutible-logic.termp (logic.=lhs proof) (logic.=rhs proof) proofs)) :hints(("Goal" :in-theory (enable equal-substitutible-logic.termp)))) (defthm forcing-equal-substitutible-logic.termp-of-logic.functions (implies (and (force (logic.function-namep fn)) (force (true-listp args1)) (force (logic.term-listp args1)) (force (true-listp args2)) (force (logic.term-listp args2))) (equal (equal-substitutible-logic.termp (logic.function fn args1) (logic.function fn args2) proofs) (or (equal args1 args2) (memberp (logic.pequal (logic.function fn args1) (logic.function fn args2)) proofs) (memberp (logic.pequal (logic.function fn args2) (logic.function fn args1)) proofs) (equal-substitutible-logic.term-listp args1 args2 proofs)))) :hints(("Goal" :in-theory (enable equal-substitutible-logic.termp))))
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 "tautologies") (include-book "../build/lambda") (set-verify-guards-eagerness 2) (set-case-split-limitations nil) (set-well-founded-relation ord<) (set-measure-function rank) ;; Let X' (a term) be obtained from X (another term) by replacing some ;; occurrences of terms A1,...,An by A1',...,An', respectively. If ;; |- A1 = A1', |- A2 = A2', ..., |- An = An' ;; Then ;; |- X = X' ;; ;; Furthermore, if Y' (a formula) is obtained from Y (another formula) ;; by similar replacements, then ;; |- Y <-> Y' ;; We introduce the function equals-for-equalsp, which takes as inputs the ;; terms x and y, and the list of formulas [A1, A2, ..., An]. We return true ;; if and only if y is obtainable from x by replacing some terms ti with other ;; terms si, where ti=si or si=ti is some Ai. ;; ;; This function is sort of like tautologyp1, in that it does not build a ;; proof, but is rather just an algorithm to decide if a proof can be ;; generated. (mutual-recursion (defund equal-substitutible-logic.termp (x y as) (declare (xargs :guard (and (logic.termp x) (logic.termp y) (logic.formula-listp as)))) (or (equal x y) (memberp (logic.pequal x y) as) (memberp (logic.pequal y x) as) (cond ((logic.constantp x) nil) ((logic.variablep x) nil) ((logic.functionp x) (and (logic.functionp y) (equal (logic.function-name x) (logic.function-name y)) (equal-substitutible-logic.term-listp (logic.function-args x) (logic.function-args y) as))) ((logic.lambdap x) (and (logic.lambdap y) (equal (logic.lambda-formals x) (logic.lambda-formals y)) (equal (logic.lambda-body x) (logic.lambda-body y)) (equal-substitutible-logic.term-listp (logic.lambda-actuals x) (logic.lambda-actuals y) as))) (t nil)))) (defund equal-substitutible-logic.term-listp (x y as) (declare (xargs :guard (and (logic.term-listp x) (logic.term-listp y) (logic.formula-listp as)))) (if (consp x) (and (consp y) (equal-substitutible-logic.termp (car x) (car y) as) (equal-substitutible-logic.term-listp (cdr x) (cdr y) as)) (not (consp y))))) (defthm equal-substitutible-logic.term-listp-of-cdrs-when-equal-substitutible-logic.term-listp (implies (and (equal-substitutible-logic.term-listp x y as) (consp x) (consp y)) (equal-substitutible-logic.term-listp (cdr x) (cdr y) as)) :hints(("Goal" :in-theory (enable equal-substitutible-logic.term-listp)))) (defthm equal-substitutible-logic.termp-of-cars-when-equal-substitutible-logic.term-listp (implies (and (equal-substitutible-logic.term-listp x y as) (consp x) (consp y)) (equal-substitutible-logic.termp (car x) (car y) as)) :hints(("Goal" :in-theory (enable equal-substitutible-logic.term-listp)))) (defthm equal-of-lengths-when-equal-substitutible-logic.term-listp (implies (equal-substitutible-logic.term-listp x y as) (equal (equal (len x) (len y)) t)) :hints(("Goal" :induct (cdr-cdr-induction x y) :in-theory (enable equal-substitutible-logic.term-listp)))) (defthm equal-substitutible-logic.term-listp-of-logic.lambda-actuals-when-logic.lambdaps (implies (and (equal-substitutible-logic.termp x y as) (logic.lambdap x) (logic.lambdap y) (not (equal x y)) (not (memberp (logic.pequal x y) as)) (not (memberp (logic.pequal y x) as))) (equal-substitutible-logic.term-listp (logic.lambda-actuals x) (logic.lambda-actuals y) as)) :hints(("Goal" :in-theory (enable equal-substitutible-logic.termp) :expand (equal-substitutible-logic.termp x y as)))) (defthm equal-substitutible-logic.term-listp-of-logic.function-args-when-logic.functionps (implies (and (equal-substitutible-logic.termp x y as) (logic.functionp x) (logic.functionp y) (not (equal x y)) (not (memberp (logic.pequal x y) as)) (not (memberp (logic.pequal y x) as))) (equal-substitutible-logic.term-listp (logic.function-args x) (logic.function-args y) as)) :hints(("Goal" :in-theory (enable equal-substitutible-logic.termp) :expand (equal-substitutible-logic.termp x y as)))) ;; Below we introduce equals-for-equals-bldr, which takes as inputs the terms x ;; and y, and the list of proofs [A1, A2, ..., An]. It should be the case that ;; these inputs satisfy equal-substitutible-logic.termp (i.e., using the conclusions ;; of the proofs A1...An). Our goal is to build a proof that x = y, by ;; utilizing the provided proofs as necessary. ;; ;; This function is sort of like tautologyp-bldr1, which builds a proof ;; whenever tautologyp1 says that some inputs are ok. In this case, we build a ;; proof when equal-substitutible-logic.termp says that the inputs are ok. (mutual-recursion (defund equal-substitutible-term-bldr (x y as) (declare (xargs :guard (and (logic.termp x) (logic.termp y) (logic.appeal-listp as) (equal-substitutible-logic.termp x y (logic.strip-conclusions as))) :verify-guards nil)) (cond ((equal x y) (build.reflexivity x)) ((memberp (logic.pequal x y) (logic.strip-conclusions as)) (logic.find-proof (logic.pequal x y) as)) ((memberp (logic.pequal y x) (logic.strip-conclusions as)) (build.commute-pequal (logic.find-proof (logic.pequal y x) as))) ((logic.functionp x) (if (and (logic.functionp y) (equal (logic.function-name x) (logic.function-name y))) (build.pequal-by-args (logic.function-name x) (equal-substitutible-term-list-bldr (logic.function-args x) (logic.function-args y) as)) nil)) ((logic.lambdap x) (if (and (logic.lambdap y) (equal (logic.lambda-formals x) (logic.lambda-formals y)) (equal (logic.lambda-body x) (logic.lambda-body y))) (build.lambda-pequal-by-args (logic.lambda-formals x) (logic.lambda-body x) (equal-substitutible-term-list-bldr (logic.lambda-actuals x) (logic.lambda-actuals y) as)) nil)) (t nil))) (defund equal-substitutible-term-list-bldr (x y as) (declare (xargs :guard (and (logic.term-listp x) (logic.term-listp y) (logic.appeal-listp as) (equal-substitutible-logic.term-listp x y (logic.strip-conclusions as))))) (if (consp x) (if (consp y) (cons (equal-substitutible-term-bldr (car x) (car y) as) (equal-substitutible-term-list-bldr (cdr x) (cdr y) as)) nil) nil))) (defthm len-of-equal-substitutible-term-list-bldr (implies (force (equal (len x) (len y))) (equal (len (equal-substitutible-term-list-bldr x y as)) (len x))) :hints(("Goal" :in-theory (enable equal-substitutible-term-list-bldr) :induct (cdr-cdr-induction x y)))) (defthm true-listp-of-equal-substitutible-term-list-bldr (equal (true-listp (equal-substitutible-term-list-bldr x y as)) t) :hints(("Goal" :in-theory (enable equal-substitutible-term-list-bldr) :induct (cdr-cdr-induction x y)))) (encapsulate () (local (defun my-induction (flag x y as) (declare (xargs :verify-guards nil)) (if (equal flag 'term) (cond ((equal x y) nil) ((memberp (logic.pequal x y) (logic.strip-conclusions as)) nil) ((memberp (logic.pequal y x) (logic.strip-conclusions as)) nil) ((logic.constantp x) nil) ((logic.variablep x) nil) ((logic.functionp x) (my-induction 'list (logic.function-args x) (logic.function-args y) as)) ((logic.lambdap x) (my-induction 'list (logic.lambda-actuals x) (logic.lambda-actuals y) as)) (t nil)) (if (and (consp x) (consp y)) (list (my-induction 'term (car x) (car y) as) (my-induction 'list (cdr x) (cdr y) as)) nil)))) (local (defthm lemma (if (equal flag 'term) (implies (and (logic.termp x) (logic.termp y) (logic.appeal-listp as) (equal-substitutible-logic.termp x y (logic.strip-conclusions as))) (and (logic.appealp (equal-substitutible-term-bldr x y as)) (equal (logic.conclusion (equal-substitutible-term-bldr x y as)) (logic.pequal x y)))) (implies (and (logic.term-listp x) (logic.term-listp y) (logic.appeal-listp as) (equal-substitutible-logic.term-listp x y (logic.strip-conclusions as))) (and (logic.appeal-listp (equal-substitutible-term-list-bldr x y as)) (equal (logic.strip-conclusions (equal-substitutible-term-list-bldr x y as)) (logic.pequal-list x y))))) :rule-classes nil :hints(("Goal" :induct (my-induction flag x y as) :in-theory (e/d (equal-substitutible-term-bldr equal-substitutible-term-list-bldr equal-substitutible-logic.termp equal-substitutible-logic.term-listp)))))) (defthm forcing-logic.appealp-of-equal-substitutible-term-bldr (implies (and (force (logic.termp x)) (force (logic.termp y)) (force (logic.appeal-listp as)) (force (equal-substitutible-logic.termp x y (logic.strip-conclusions as)))) (logic.appealp (equal-substitutible-term-bldr x y as))) :hints(("Goal" :use ((:instance lemma (flag 'term)))))) (defthm forcing-logic.appeal-listp-of-equal-substitutible-term-list-bldr (implies (and (force (logic.term-listp x)) (force (logic.term-listp y)) (force (logic.appeal-listp as)) (force (equal-substitutible-logic.term-listp x y (logic.strip-conclusions as)))) (logic.appeal-listp (equal-substitutible-term-list-bldr x y as))) :hints(("Goal" :use ((:instance lemma (flag 'list)))))) (defthm forcing-logic.conclusion-of-equal-substitutible-term-bldr (implies (and (force (logic.termp x)) (force (logic.termp y)) (force (logic.appeal-listp as)) (force (equal-substitutible-logic.termp x y (logic.strip-conclusions as)))) (equal (logic.conclusion (equal-substitutible-term-bldr x y as)) (logic.pequal x y))) :rule-classes ((:rewrite :backchain-limit-lst 0)) :hints(("Goal" :use ((:instance lemma (flag 'term)))))) (defthm forcing-logic.strip-conclusions-of-equal-substitutible-term-list-bldr (implies (and (force (logic.term-listp x)) (force (logic.term-listp y)) (force (logic.appeal-listp as)) (force (equal-substitutible-logic.term-listp x y (logic.strip-conclusions as)))) (equal (logic.strip-conclusions (equal-substitutible-term-list-bldr x y as)) (logic.pequal-list x y))) :rule-classes ((:rewrite :backchain-limit-lst 0)) :hints(("Goal" :use ((:instance lemma (flag 'list)))))) (local (defthm crock (implies (and (equal (logic.lambda-formals x) (logic.lambda-formals y)) (logic.termp x) (logic.termp y) (logic.lambdap x) (logic.lambdap y)) (equal (equal (len (logic.lambda-actuals x)) (len (logic.lambda-actuals y))) t)) :hints(("Goal" :in-theory (disable FORCING-EQUAL-LENS-OF-LOGIC.LAMBDA-FORMALS-AND-LOGIC.LAMBDA-ACTUALS) :use ((:instance FORCING-EQUAL-LENS-OF-LOGIC.LAMBDA-FORMALS-AND-LOGIC.LAMBDA-ACTUALS) (:instance FORCING-EQUAL-LENS-OF-LOGIC.LAMBDA-FORMALS-AND-LOGIC.LAMBDA-ACTUALS (x y))))))) (verify-guards equal-substitutible-term-bldr) (local (defthm lemma3 (if (equal flag 'term) (implies (and (logic.termp x) (logic.termp y) (logic.appeal-listp as) (equal-substitutible-logic.termp x y (logic.strip-conclusions as)) ;; --- (logic.term-atblp x atbl) (logic.term-atblp y atbl) (logic.proof-listp as axioms thms atbl) (memberp (axiom-reflexivity) axioms) (memberp (axiom-equality) axioms) (memberp (theorem-transitivity-of-pequal) thms) (memberp (theorem-commutativity-of-pequal) thms)) (logic.proofp (equal-substitutible-term-bldr x y as) axioms thms atbl)) (implies (and (logic.term-listp x) (logic.term-listp y) (logic.appeal-listp as) (equal-substitutible-logic.term-listp x y (logic.strip-conclusions as)) ;; --- (logic.term-list-atblp x atbl) (logic.term-list-atblp y atbl) (logic.proof-listp as axioms thms atbl) (memberp (axiom-reflexivity) axioms) (memberp (axiom-equality) axioms) (memberp (theorem-transitivity-of-pequal) thms) (memberp (theorem-commutativity-of-pequal) thms)) (logic.proof-listp (equal-substitutible-term-list-bldr x y as) axioms thms atbl))) :rule-classes nil :hints(("Goal" :induct (my-induction flag x y as) :in-theory (enable equal-substitutible-term-bldr equal-substitutible-term-list-bldr equal-substitutible-logic.termp equal-substitutible-logic.term-listp))))) (defthm forcing-logic.proofp-of-equal-substitutible-term-bldr (implies (force (and (logic.termp x) (logic.termp y) (logic.appeal-listp as) (equal-substitutible-logic.termp x y (logic.strip-conclusions as)) ;; --- (logic.term-atblp x atbl) (logic.term-atblp y atbl) (logic.proof-listp as axioms thms atbl) (memberp (axiom-reflexivity) axioms) (memberp (axiom-equality) axioms) (memberp (theorem-transitivity-of-pequal) thms) (memberp (theorem-commutativity-of-pequal) thms))) (logic.proofp (equal-substitutible-term-bldr x y as) axioms thms atbl)) :hints(("Goal" :use ((:instance lemma3 (flag 'term)))))) (defthm forcing-logic.proof-listp-of-equal-substitutible-term-list-bldr (implies (force (and (logic.term-listp x) (logic.term-listp y) (logic.appeal-listp as) (equal-substitutible-logic.term-listp x y (logic.strip-conclusions as)) ;; --- (logic.term-list-atblp x atbl) (logic.term-list-atblp y atbl) (logic.proof-listp as axioms thms atbl) (memberp (axiom-reflexivity) axioms) (memberp (axiom-equality) axioms) (memberp (theorem-transitivity-of-pequal) thms) (memberp (theorem-commutativity-of-pequal) thms))) (logic.proof-listp (equal-substitutible-term-list-bldr x y as) axioms thms atbl)) :hints(("Goal" :use ((:instance lemma3 (flag 'list))))))) ;; The second part of equals for equals is that, if a formula Y' is obtained ;; from some formula Y through replacements of equals for equals, then we ;; should be able to prove Y <-> Y'. (defund equal-substitutiblep (x y as) (declare (xargs :guard (and (logic.formulap x) (logic.formulap y) (logic.formula-listp as)))) (cond ((equal (logic.fmtype x) 'por*) (and (equal (logic.fmtype y) 'por*) (equal-substitutiblep (logic.vlhs x) (logic.vlhs y) as) (equal-substitutiblep (logic.vrhs x) (logic.vrhs y) as))) ((equal (logic.fmtype x) 'pnot*) (and (equal (logic.fmtype y) 'pnot*) (equal-substitutiblep (logic.~arg x) (logic.~arg y) as))) ((equal (logic.fmtype x) 'pequal*) (and (equal (logic.fmtype x) 'pequal*) (equal (logic.fmtype y) 'pequal*) (equal-substitutible-logic.termp (logic.=lhs x) (logic.=lhs y) as) (equal-substitutible-logic.termp (logic.=rhs x) (logic.=rhs y) as))) (t nil))) (defthm logic.fmtype-when-equal-substitutiblep-with-logic.por (implies (and (equal-substitutiblep x y as) (equal (logic.fmtype x) 'por*)) (equal (logic.fmtype y) 'por*)) :hints(("Goal" :in-theory (enable equal-substitutiblep)))) (defthm logic.fmtype-when-equal-substitutiblep-with-logic.pnot (implies (and (equal-substitutiblep x y as) (equal (logic.fmtype x) 'pnot*)) (equal (logic.fmtype y) 'pnot*)) :hints(("Goal" :in-theory (enable equal-substitutiblep)))) (defthm logic.fmtype-when-equal-substitutiblep-with-pequal (implies (and (equal-substitutiblep x y as) (equal (logic.fmtype x) 'pequal*)) (equal (logic.fmtype y) 'pequal*)) :hints(("Goal" :in-theory (enable equal-substitutiblep)))) (defthm equal-substitutiblep-of-recursive-calls-in-logic.por-case (implies (and (equal-substitutiblep x y as) (force (equal (logic.fmtype x) 'por*))) (and (equal-substitutiblep (logic.vlhs x) (logic.vlhs y) as) (equal-substitutiblep (logic.vrhs x) (logic.vrhs y) as))) :hints(("Goal" :in-theory (enable equal-substitutiblep)))) (defthm equal-substitutiblep-of-recursive-calls-in-logic.pnot-case (implies (and (equal-substitutiblep x y as) (force (equal (logic.fmtype x) 'pnot*))) (equal-substitutiblep (logic.~arg x) (logic.~arg y) as)) :hints(("Goal" :in-theory (enable equal-substitutiblep)))) (defthm equal-substitutible-logic.termp-of-recursive-calls-in-pequal-case (implies (and (equal-substitutiblep x y as) (force (equal (logic.fmtype x) 'pequal*))) (and (equal-substitutible-logic.termp (logic.=lhs x) (logic.=lhs y) as) (equal-substitutible-logic.termp (logic.=rhs x) (logic.=rhs y) as))) :hints(("Goal" :in-theory (enable equal-substitutiblep)))) ;; Note: This is like Shankar's function FORM-EQUAL-PROOF ;; ;; BOZO consider not using tautologies and building the proofs separately? (defund equal-substitutible-bldr (x y as) (declare (xargs :guard (and (logic.formulap x) (logic.formulap y) (logic.appeal-listp as) (equal-substitutiblep x y (logic.strip-conclusions as))) :verify-guards nil)) (cond ((equal (logic.fmtype x) 'por*) (tautological-consequence-bldr (logic.piff x y) (list (equal-substitutible-bldr (logic.vlhs x) (logic.vlhs y) as) (equal-substitutible-bldr (logic.vrhs x) (logic.vrhs y) as)))) ((equal (logic.fmtype x) 'pnot*) (tautological-consequence-bldr (logic.piff x y) (list (equal-substitutible-bldr (logic.~arg x) (logic.~arg y) as)))) ((equal (logic.fmtype x) 'pequal*) (let ((T1 (logic.=lhs x)) (T1-Prime (logic.=lhs y)) (T2 (logic.=rhs x)) (T2-Prime (logic.=rhs y))) (let* ((T1=T1-Prime (equal-substitutible-term-bldr T1 T1-Prime as)) (T2=T2-Prime (equal-substitutible-term-bldr T2 T2-Prime as)) (T1-Prime=T1 (build.commute-pequal T1=T1-Prime)) (T2-Prime=T2 (build.commute-pequal T2=T2-Prime))) (tautological-consequence-bldr (logic.piff x y) (list T1=T1-Prime T2=T2-Prime T1-Prime=T1 T2-Prime=T2 (build.equality T1 T1-Prime T2 T2-Prime) (build.equality T1-Prime T1 T2-Prime T2)))))) (t nil))) ;; Explanation of the Base Case ;; ;; In the base case above, we assume that we have two formulas, T1=T1' and ;; T2=T2', which are provable by the use of equals-for-equals. We now need ;; to show that T1=T2 <-> T1'=T2'. ;; ;; PI:NAME:<NAME>END_PI explains the proof as follows. ;; ;; 1. Use equals-for-equals to prove T1=T1', T2=T2'. ;; 2. Use commute-equal to prove T1'=T1, T2'=T2. ;; 3. Use the equality axiom to prove T1=T1' -> T2=T2' -> T1=T2' -> T1'=T2' ;; 4. Use the equality axiom to prove T1'=T1 -> T2'=T2 -> T1'=T2' -> T1=T2 ;; ;; Now, our goal T1=T2 <-> T1'=T2' is a tautological consequence of the ;; formulas produced in steps 1-4. ;; ;; We can "test this out" on some example formulas as below. You can run ;; this example to see that we do indeed have a tautological consequence. ;; ;; (tautological-consequencep ;; (logic.piff (logic.pequal 'T1 'T2) ;; (logic.pequal 'T1-Prime 'T2-Prime)) ;; (logic.strip-conclusions ;; (list ;; (build.axiom (logic.pequal 'T1 'T1-Prime)) ;; (build.axiom (logic.pequal 'T2 'T2-Prime)) ;; (build.axiom (logic.pequal 'T1-Prime 'T1)) ;; (build.axiom (logic.pequal 'T2-Prime 'T2)) ;; (build.equality 'T1 'T1-Prime 'T2 'T2-Prime) ;; (build.equality 'T1-Prime 'T1 'T2-Prime 'T2)))) ;; ;; But what we need to do is show this for arbitrary T1,T2,T1',T2' instead ;; of just for the above examples. (encapsulate () ;; BOZO i still don't like how we use logic.=lhs and logic.=rhs explicitly here. i'd ;; rather it used explicit variables instead. (local (defthm lemma (implies (and (force (logic.formulap x)) (force (logic.formulap y)) (force (equal (logic.fmtype x) 'pequal*)) (force (equal (logic.fmtype y) 'pequal*))) (tautological-consequencep (logic.piff x y) (list (logic.pequal (logic.=lhs x) (logic.=lhs y)) (logic.pequal (logic.=rhs x) (logic.=rhs y)) (logic.pequal (logic.=lhs y) (logic.=lhs x)) (logic.pequal (logic.=rhs y) (logic.=rhs x)) (logic.por (logic.pnot (logic.pequal (logic.=lhs x) (logic.=lhs y))) (logic.por (logic.pnot (logic.pequal (logic.=rhs x) (logic.=rhs y))) (logic.por (logic.pnot x) y))) (logic.por (logic.pnot (logic.pequal (logic.=lhs y) (logic.=lhs x))) (logic.por (logic.pnot (logic.pequal (logic.=rhs y) (logic.=rhs x))) (logic.por (logic.pnot y) x)))))) :hints(("Goal" :in-theory (e/d (tautological-consequencep) ;; This is a yucky looking hint, but ;; it's just for speed. (in-superset-when-in-subset-two in-superset-when-in-subset-one not-in-subset-when-not-in-superset-one not-in-subset-when-not-in-superset-two memberp-when-memberp-of-cdr memberp-when-not-consp subsetp-when-not-consp-two subsetp-of-cdr subsetp-when-not-consp)))))) (local (defthm lemma2 (implies (and (logic.formulap x) (logic.formulap y) (logic.appeal-listp as) (equal-substitutiblep x y (logic.strip-conclusions as))) (and (logic.appealp (equal-substitutible-bldr x y as)) (equal (logic.conclusion (equal-substitutible-bldr x y as)) (logic.piff x y)))) :hints(("Goal" :in-theory (enable equal-substitutible-bldr))))) (defthm forcing-logic.appealp-of-equal-substitutible-bldr (implies (and (force (logic.formulap x)) (force (logic.formulap y)) (force (logic.appeal-listp as)) (force (equal-substitutiblep x y (logic.strip-conclusions as)))) (logic.appealp (equal-substitutible-bldr x y as)))) (defthm forcing-logic.conclusion-of-equal-substitutible-bldr (implies (and (force (logic.formulap x)) (force (logic.formulap y)) (force (logic.appeal-listp as)) (force (equal-substitutiblep x y (logic.strip-conclusions as)))) (equal (logic.conclusion (equal-substitutible-bldr x y as)) (logic.piff x y))) :rule-classes ((:rewrite :backchain-limit-lst 0))) (verify-guards equal-substitutible-bldr) (defthm forcing-logic.proofp-of-equal-substitutible-bldr (implies (and (force (logic.formulap x)) (force (logic.formulap y)) (force (logic.appeal-listp as)) (force (equal-substitutiblep x y (logic.strip-conclusions as))) ;; --- (force (logic.formula-atblp x atbl)) (force (logic.formula-atblp y atbl)) (force (logic.proof-listp as axioms thms atbl)) (force (memberp (axiom-reflexivity) axioms)) (force (memberp (axiom-equality) axioms)) (force (memberp (theorem-transitivity-of-pequal) thms)) (force (memberp (theorem-commutativity-of-pequal) thms))) (logic.proofp (equal-substitutible-bldr x y as) axioms thms atbl)) :hints(("Goal" :in-theory (enable equal-substitutible-bldr))))) ;; As with the tautology and equivalence theorems, the equality theorem is ;; perhaps most often useful in the form below. Suppose that G is a formula ;; which is obtained from F by equality substitution of A1=A1' ... An=An'. ;; Then, if we have proofs of A1=A1' ... An=An' and F, we should be able to ;; prove G. This is the equal-consequence-bldr. (defund equal-consequence-bldr (g f as) (declare (xargs :guard (and (logic.formulap g) (logic.appealp f) (logic.appeal-listp as) (equal-substitutiblep (logic.conclusion f) g (logic.strip-conclusions as))) :verify-guards nil)) (let ((iff-f-g (equal-substitutible-bldr (logic.conclusion f) g as))) (tautological-consequence-bldr g (list iff-f-g f)))) (encapsulate () (local (defthm lemma (implies (and (logic.formulap f) (logic.formulap g)) (tautological-consequencep g (list (logic.piff f g) f))) :hints(("Goal" :in-theory (enable tautological-consequencep))))) (verify-guards equal-consequence-bldr) (defthm forcing-logic.conclusion-of-equal-consequence-bldr (implies (and (force (logic.formulap g)) (force (logic.appealp f)) (force (logic.appeal-listp as)) (force (equal-substitutiblep (logic.conclusion f) g (logic.strip-conclusions as)))) (equal (logic.conclusion (equal-consequence-bldr g f as)) g)) :hints(("Goal" :in-theory (enable equal-consequence-bldr)))) (defthm forcing-logic.appealp-of-equal-consequence-bldr (implies (and (force (logic.formulap g)) (force (logic.appealp f)) (force (logic.appeal-listp as)) (force (equal-substitutiblep (logic.conclusion f) g (logic.strip-conclusions as)))) (logic.appealp (equal-consequence-bldr g f as))) :hints(("Goal" :in-theory (enable equal-consequence-bldr)))) (defthm forcing-logic.proofp-of-equal-consequence-bldr (implies (and (force (logic.formulap g)) (force (logic.appealp f)) (force (logic.appeal-listp as)) (force (equal-substitutiblep (logic.conclusion f) g (logic.strip-conclusions as))) ;; --- (force (logic.formula-atblp g atbl)) (force (logic.proofp f axioms thms atbl)) (force (logic.proof-listp as axioms thms atbl)) (force (memberp (axiom-reflexivity) axioms)) (force (memberp (axiom-equality) axioms)) (force (memberp (theorem-transitivity-of-pequal) thms)) (force (memberp (theorem-commutativity-of-pequal) thms))) (logic.proofp (equal-consequence-bldr g f as) axioms thms atbl)) :hints(("Goal" :in-theory (enable equal-consequence-bldr))))) (defthm forcing-equal-substitutiblep-of-logic.pors (implies (and (force (logic.formulap a)) (force (logic.formulap b)) (force (logic.formulap c)) (force (logic.formulap d))) (equal (equal-substitutiblep (logic.por a b) (logic.por c d) proofs) (and (equal-substitutiblep a c proofs) (equal-substitutiblep b d proofs)))) :hints(("Goal" :in-theory (enable equal-substitutiblep)))) (defthm forcing-equal-substitutiblep-of-logic.pnots (implies (and (force (logic.formulap a)) (force (logic.formulap b))) (equal (equal-substitutiblep (logic.pnot a) (logic.pnot b) proofs) (equal-substitutiblep a b proofs))) :hints(("Goal" :in-theory (enable equal-substitutiblep)))) (defthm forcing-equal-substitutiblep-of-pequals (implies (and (force (logic.termp a)) (force (logic.termp b)) (force (logic.termp c)) (force (logic.termp d))) (equal (equal-substitutiblep (logic.pequal a b) (logic.pequal c d) proofs) (and (equal-substitutible-logic.termp a c proofs) (equal-substitutible-logic.termp b d proofs)))) :hints(("Goal" :in-theory (enable equal-substitutiblep)))) (defthm reflexivity-of-equal-substitutible-logic.termp (equal-substitutible-logic.termp x x proofs) :hints(("Goal" :in-theory (enable equal-substitutible-logic.termp)))) (defthm reflexivity-of-equal-substitutiblep (implies (force (logic.formulap x)) (equal-substitutiblep x x proofs)) :hints(("Goal" :in-theory (enable equal-substitutiblep)))) (defthm equal-substitutible-logic.termp-of-lhs-and-rhs-when-in-proofs (implies (and (memberp proof proofs) (force (logic.formulap proof)) ;; jcd:2006-04-05 added this hyp (force (equal (logic.fmtype proof) 'pequal*))) (equal-substitutible-logic.termp (logic.=lhs proof) (logic.=rhs proof) proofs)) :hints(("Goal" :in-theory (enable equal-substitutible-logic.termp)))) (defthm forcing-equal-substitutible-logic.termp-of-logic.functions (implies (and (force (logic.function-namep fn)) (force (true-listp args1)) (force (logic.term-listp args1)) (force (true-listp args2)) (force (logic.term-listp args2))) (equal (equal-substitutible-logic.termp (logic.function fn args1) (logic.function fn args2) proofs) (or (equal args1 args2) (memberp (logic.pequal (logic.function fn args1) (logic.function fn args2)) proofs) (memberp (logic.pequal (logic.function fn args2) (logic.function fn args1)) proofs) (equal-substitutible-logic.term-listp args1 args2 proofs)))) :hints(("Goal" :in-theory (enable equal-substitutible-logic.termp))))
[ { "context": ";-*- Mode: Lisp -*-\n;;;; Author: Paul Dietz\n;;;; Created: Sat Jul 3 08:50:40 2004\n;;;; Cont", "end": 49, "score": 0.9998544454574585, "start": 39, "tag": "NAME", "value": "Paul Dietz" } ]
programs/ansi-test/printer/pprint-indent.lsp
TeamSPoon/wam_common_lisp_devel_workspace
8
;-*- Mode: Lisp -*- ;;;; Author: Paul Dietz ;;;; Created: Sat Jul 3 08:50:40 2004 ;;;; Contains: Tests of PPRINT-INDENT (in-package :cl-test) (deftest pprint-indent.1 (with-standard-io-syntax (let ((*print-pretty* nil)) (with-open-stream (*standard-output* (make-string-output-stream)) (pprint-indent :block 0)))) nil) (deftest pprint-indent.2 (with-standard-io-syntax (let ((*print-pretty* nil)) (with-open-stream (*standard-output* (make-broadcast-stream)) (pprint-indent :current 0)))) nil) (deftest pprint-indent.3 (with-standard-io-syntax (let ((*print-pretty* nil)) (with-open-stream (s (make-string-output-stream)) (pprint-indent :current 10 s)))) nil) (deftest pprint-indent.4 (with-standard-io-syntax (let ((*print-pretty* nil)) (with-open-stream (s (make-string-output-stream)) (pprint-indent :block 1/2 s)))) nil) (deftest pprint-indent.5 (with-standard-io-syntax (let ((*print-pretty* nil)) (with-open-stream (s (make-string-output-stream)) (pprint-indent :block 0.1 s)))) nil) (deftest pprint-indent.6 (with-standard-io-syntax (let ((*print-pretty* nil)) (loop for x in '(1.0s0 1.0f0 1.0d0 1.0l0) unless (equal (multiple-value-list (with-open-stream (s (make-string-output-stream)) (pprint-indent :block x s))) '(nil)) collect x))) nil) (deftest pprint-indent.7 (with-standard-io-syntax (let ((*print-pretty* nil)) (with-open-stream (*standard-output* (make-broadcast-stream)) (pprint-indent :current 0 nil)))) nil) (deftest pprint-indent.8 (with-standard-io-syntax (let ((*print-pretty* nil)) (with-open-stream (os (make-string-output-stream)) (with-open-stream (is (make-string-input-stream "")) (with-open-stream (*terminal-io* (make-two-way-stream is os)) (pprint-indent :current 0 t)))))) nil) ;;; Now test with pprint-logical-block ;;; :current (deftest pprint-indent.9 (with-standard-io-syntax (let ((*print-pretty* t) (*print-readably* nil) (*print-right-margin* 100) (*print-escape* nil)) (with-output-to-string (os) (pprint-logical-block (os '(|M| |M|)) (write '|M| :stream os) (pprint-indent :current 3 os) (pprint-newline :mandatory os) (write '|M| :stream os))))) "M M") (deftest pprint-indent.10 (with-standard-io-syntax (let ((*print-pretty* t) (*print-readably* nil) (*print-right-margin* 100) (*print-escape* nil)) (with-output-to-string (os) (pprint-logical-block (os '(|M| |M|) :prefix "(" :suffix ")") (write '|M| :stream os) (pprint-indent :current 1 os) (pprint-newline :mandatory os) (write '|M| :stream os))))) "(M M)") (deftest pprint-indent.11 (with-standard-io-syntax (let ((*print-pretty* t) (*print-readably* nil) (*print-right-margin* 100) (*print-escape* nil)) (with-output-to-string (os) (pprint-logical-block (os '(|M| |M|) :prefix "(" :suffix ")") (write '|M| :stream os) (pprint-indent :current -1 os) (pprint-newline :mandatory os) (write '|M| :stream os))))) "(M M)") (deftest pprint-indent.12 (with-standard-io-syntax (let ((*print-pretty* t) (*print-readably* nil) (*print-right-margin* 100) (*print-escape* nil)) (with-output-to-string (os) (pprint-logical-block (os '(|M| |M|) :prefix "(" :suffix ")") (write '|M| :stream os) (pprint-indent :current -2.0 os) (pprint-newline :mandatory os) (write '|M| :stream os))))) "(M M)") ;;; :block (deftest pprint-indent.13 (with-standard-io-syntax (let ((*print-pretty* t) (*print-readably* nil) (*print-right-margin* 100) (*print-escape* nil)) (with-output-to-string (os) (pprint-logical-block (os '(|M| |M|)) (write '|MMM| :stream os) (pprint-indent :block 0 os) (pprint-newline :mandatory os) (write '|MMMMM| :stream os))))) "MMM MMMMM") (deftest pprint-indent.13a (with-standard-io-syntax (let ((*print-pretty* t) (*print-readably* nil) (*print-right-margin* 100) (*print-escape* nil)) (with-output-to-string (os) (pprint-logical-block (os '(|M| |M|) :prefix "(" :suffix ")") (write '|MMM| :stream os) (pprint-indent :block 0 os) (pprint-newline :mandatory os) (write '|MMMMM| :stream os))))) "(MMM MMMMM)") (deftest pprint-indent.14 (with-standard-io-syntax (let ((*print-pretty* t) (*print-readably* nil) (*print-right-margin* 100) (*print-escape* nil)) (with-output-to-string (os) (pprint-logical-block (os '(|M| |M|)) (write '|MMM| :stream os) (pprint-indent :block 1 os) (pprint-newline :mandatory os) (write '|MMMMM| :stream os))))) "MMM MMMMM") (deftest pprint-indent.15 (with-standard-io-syntax (let ((*print-pretty* t) (*print-readably* nil) (*print-right-margin* 100) (*print-escape* nil)) (with-output-to-string (os) (pprint-logical-block (os '(|M| |M|)) (write '|MMM| :stream os) (pprint-indent :block -1 os) (pprint-newline :mandatory os) (write '|MMMMM| :stream os))))) "MMM MMMMM") (deftest pprint-indent.16 (loop for n in '(3.0s0 3.0f0 3.0d0 3.0l0) unless (string= (with-standard-io-syntax (let ((*print-pretty* t) (*print-readably* nil) (*print-right-margin* 100) (*print-escape* nil)) (with-output-to-string (os) (pprint-logical-block (os '(|M| |M|)) (write '|MMM| :stream os) (pprint-indent :block n os) (pprint-newline :mandatory os) (write '|MMMMM| :stream os))))) "MMM MMMMM") collect n) nil) ;;; *print-pretty* must be true for pprint-indent to have an effect (deftest pprint-indent.17 (with-standard-io-syntax (let ((*print-pretty* t) (*print-readably* nil) (*print-right-margin* 100) (*print-escape* nil)) (with-output-to-string (os) (pprint-logical-block (os '(|M| |M|)) (write '|M| :stream os) (let ((*print-pretty* nil)) (pprint-indent :current 3 os)) (pprint-newline :mandatory os) (write '|M| :stream os))))) "M M") (deftest pprint-indent.18 (with-standard-io-syntax (let ((*print-pretty* t) (*print-readably* nil) (*print-right-margin* 100) (*print-escape* nil)) (with-output-to-string (os) (pprint-logical-block (os '(|M| |M|)) (write '|M| :stream os) (let ((*print-pretty* nil)) (pprint-indent :block 3 os)) (pprint-newline :mandatory os) (write '|M| :stream os))))) "M M") ;;; indentation interaction with :per-line-prefix (deftest pprint-indent.19 (with-standard-io-syntax (let ((*print-pretty* t) (*print-readably* nil) (*print-right-margin* 100) (*print-escape* nil)) (with-output-to-string (os) (pprint-logical-block (os '(|M| |M| |M|) :per-line-prefix ">>>>") (write '|M| :stream os) (pprint-indent :block 2 os) (write #\Space :stream os) (write '|M| :stream os) (pprint-newline :mandatory os) (write '|M| :stream os))))) ">>>>M M >>>> M") (deftest pprint-indent.20 (with-standard-io-syntax (let ((*print-pretty* t) (*print-readably* nil) (*print-right-margin* 100) (*print-escape* nil)) (with-output-to-string (os) (pprint-logical-block (os '(|M| |M|) :per-line-prefix ">>>>") (write '|M| :stream os) (pprint-indent :block -1 os) (pprint-newline :mandatory os) (write '|M| :stream os))))) ">>>>M >>>>M") (deftest pprint-indent.21 (with-standard-io-syntax (let ((*print-pretty* t) (*print-readably* nil) (*print-right-margin* 100) (*print-escape* nil)) (with-output-to-string (os) (pprint-logical-block (os '(|M| |M| |M| |M|) :per-line-prefix ">>>>") (write '|M| :stream os) (pprint-indent :block 3 os) (pprint-newline :mandatory os) (write '|M| :stream os) (pprint-indent :current -2 os) (pprint-newline :mandatory os) (write '|M| :stream os) (pprint-indent :current -5 os) (pprint-newline :mandatory os) (write '|M| :stream os) )))) ">>>>M >>>> M >>>> M >>>>M") ;;; In miser mode, indentation is ignored (deftest pprint-indent.22 (with-standard-io-syntax (let ((*print-pretty* t) (*print-readably* nil) (*print-right-margin* 100) (*print-miser-width* 200) (*print-escape* nil)) (with-output-to-string (os) (pprint-logical-block (os '(1 2 3) :prefix "(" :suffix ")") (write 1 :stream os) (pprint-indent :current 1 os) (pprint-newline :mandatory os) (write 2 :stream os) (pprint-indent :block 3 os) (pprint-newline :mandatory os) (write 3 :stream os))))) "(1 2 3)") ;;; TERPRI or printing newline characters does not invoke indentation (deftest pprint-indent.23 (with-standard-io-syntax (let ((*print-pretty* t) (*print-readably* nil) (*print-right-margin* 100) (*print-escape* nil)) (with-output-to-string (os) (pprint-logical-block (os '(1 2 3 4)) (pprint-indent :block 2 os) (write 1 :stream os) (terpri os) (write 2 :stream os) (write #\Newline :stream os) (write 3 :stream os) (pprint-newline :mandatory os) (write 4 :stream os))))) "1 2 3 4") ;;; Error cases (deftest pprint-indent.error.1 (signals-error (pprint-indent) program-error) t) (deftest pprint-indent.error.2 (signals-error (pprint-indent :current) program-error) t) (deftest pprint-indent.error.3 (signals-error (pprint-indent :block 0 *standard-output* nil) program-error) t) (deftest pprint-indent.error.4 (loop for x in *mini-universe* when (and (not (member x '(:block :current))) (not (eval `(signals-error (pprint-indent ',x 0) error)))) collect x) nil) (deftest pprint-indent.error.4-unsafe (loop for x in *mini-universe* when (and (not (member x '(:block :current))) (not (eval `(signals-error (locally (declare (optimize (safety 0))) (pprint-indent ',x 0)) error)))) collect x) nil)
53675
;-*- Mode: Lisp -*- ;;;; Author: <NAME> ;;;; Created: Sat Jul 3 08:50:40 2004 ;;;; Contains: Tests of PPRINT-INDENT (in-package :cl-test) (deftest pprint-indent.1 (with-standard-io-syntax (let ((*print-pretty* nil)) (with-open-stream (*standard-output* (make-string-output-stream)) (pprint-indent :block 0)))) nil) (deftest pprint-indent.2 (with-standard-io-syntax (let ((*print-pretty* nil)) (with-open-stream (*standard-output* (make-broadcast-stream)) (pprint-indent :current 0)))) nil) (deftest pprint-indent.3 (with-standard-io-syntax (let ((*print-pretty* nil)) (with-open-stream (s (make-string-output-stream)) (pprint-indent :current 10 s)))) nil) (deftest pprint-indent.4 (with-standard-io-syntax (let ((*print-pretty* nil)) (with-open-stream (s (make-string-output-stream)) (pprint-indent :block 1/2 s)))) nil) (deftest pprint-indent.5 (with-standard-io-syntax (let ((*print-pretty* nil)) (with-open-stream (s (make-string-output-stream)) (pprint-indent :block 0.1 s)))) nil) (deftest pprint-indent.6 (with-standard-io-syntax (let ((*print-pretty* nil)) (loop for x in '(1.0s0 1.0f0 1.0d0 1.0l0) unless (equal (multiple-value-list (with-open-stream (s (make-string-output-stream)) (pprint-indent :block x s))) '(nil)) collect x))) nil) (deftest pprint-indent.7 (with-standard-io-syntax (let ((*print-pretty* nil)) (with-open-stream (*standard-output* (make-broadcast-stream)) (pprint-indent :current 0 nil)))) nil) (deftest pprint-indent.8 (with-standard-io-syntax (let ((*print-pretty* nil)) (with-open-stream (os (make-string-output-stream)) (with-open-stream (is (make-string-input-stream "")) (with-open-stream (*terminal-io* (make-two-way-stream is os)) (pprint-indent :current 0 t)))))) nil) ;;; Now test with pprint-logical-block ;;; :current (deftest pprint-indent.9 (with-standard-io-syntax (let ((*print-pretty* t) (*print-readably* nil) (*print-right-margin* 100) (*print-escape* nil)) (with-output-to-string (os) (pprint-logical-block (os '(|M| |M|)) (write '|M| :stream os) (pprint-indent :current 3 os) (pprint-newline :mandatory os) (write '|M| :stream os))))) "M M") (deftest pprint-indent.10 (with-standard-io-syntax (let ((*print-pretty* t) (*print-readably* nil) (*print-right-margin* 100) (*print-escape* nil)) (with-output-to-string (os) (pprint-logical-block (os '(|M| |M|) :prefix "(" :suffix ")") (write '|M| :stream os) (pprint-indent :current 1 os) (pprint-newline :mandatory os) (write '|M| :stream os))))) "(M M)") (deftest pprint-indent.11 (with-standard-io-syntax (let ((*print-pretty* t) (*print-readably* nil) (*print-right-margin* 100) (*print-escape* nil)) (with-output-to-string (os) (pprint-logical-block (os '(|M| |M|) :prefix "(" :suffix ")") (write '|M| :stream os) (pprint-indent :current -1 os) (pprint-newline :mandatory os) (write '|M| :stream os))))) "(M M)") (deftest pprint-indent.12 (with-standard-io-syntax (let ((*print-pretty* t) (*print-readably* nil) (*print-right-margin* 100) (*print-escape* nil)) (with-output-to-string (os) (pprint-logical-block (os '(|M| |M|) :prefix "(" :suffix ")") (write '|M| :stream os) (pprint-indent :current -2.0 os) (pprint-newline :mandatory os) (write '|M| :stream os))))) "(M M)") ;;; :block (deftest pprint-indent.13 (with-standard-io-syntax (let ((*print-pretty* t) (*print-readably* nil) (*print-right-margin* 100) (*print-escape* nil)) (with-output-to-string (os) (pprint-logical-block (os '(|M| |M|)) (write '|MMM| :stream os) (pprint-indent :block 0 os) (pprint-newline :mandatory os) (write '|MMMMM| :stream os))))) "MMM MMMMM") (deftest pprint-indent.13a (with-standard-io-syntax (let ((*print-pretty* t) (*print-readably* nil) (*print-right-margin* 100) (*print-escape* nil)) (with-output-to-string (os) (pprint-logical-block (os '(|M| |M|) :prefix "(" :suffix ")") (write '|MMM| :stream os) (pprint-indent :block 0 os) (pprint-newline :mandatory os) (write '|MMMMM| :stream os))))) "(MMM MMMMM)") (deftest pprint-indent.14 (with-standard-io-syntax (let ((*print-pretty* t) (*print-readably* nil) (*print-right-margin* 100) (*print-escape* nil)) (with-output-to-string (os) (pprint-logical-block (os '(|M| |M|)) (write '|MMM| :stream os) (pprint-indent :block 1 os) (pprint-newline :mandatory os) (write '|MMMMM| :stream os))))) "MMM MMMMM") (deftest pprint-indent.15 (with-standard-io-syntax (let ((*print-pretty* t) (*print-readably* nil) (*print-right-margin* 100) (*print-escape* nil)) (with-output-to-string (os) (pprint-logical-block (os '(|M| |M|)) (write '|MMM| :stream os) (pprint-indent :block -1 os) (pprint-newline :mandatory os) (write '|MMMMM| :stream os))))) "MMM MMMMM") (deftest pprint-indent.16 (loop for n in '(3.0s0 3.0f0 3.0d0 3.0l0) unless (string= (with-standard-io-syntax (let ((*print-pretty* t) (*print-readably* nil) (*print-right-margin* 100) (*print-escape* nil)) (with-output-to-string (os) (pprint-logical-block (os '(|M| |M|)) (write '|MMM| :stream os) (pprint-indent :block n os) (pprint-newline :mandatory os) (write '|MMMMM| :stream os))))) "MMM MMMMM") collect n) nil) ;;; *print-pretty* must be true for pprint-indent to have an effect (deftest pprint-indent.17 (with-standard-io-syntax (let ((*print-pretty* t) (*print-readably* nil) (*print-right-margin* 100) (*print-escape* nil)) (with-output-to-string (os) (pprint-logical-block (os '(|M| |M|)) (write '|M| :stream os) (let ((*print-pretty* nil)) (pprint-indent :current 3 os)) (pprint-newline :mandatory os) (write '|M| :stream os))))) "M M") (deftest pprint-indent.18 (with-standard-io-syntax (let ((*print-pretty* t) (*print-readably* nil) (*print-right-margin* 100) (*print-escape* nil)) (with-output-to-string (os) (pprint-logical-block (os '(|M| |M|)) (write '|M| :stream os) (let ((*print-pretty* nil)) (pprint-indent :block 3 os)) (pprint-newline :mandatory os) (write '|M| :stream os))))) "M M") ;;; indentation interaction with :per-line-prefix (deftest pprint-indent.19 (with-standard-io-syntax (let ((*print-pretty* t) (*print-readably* nil) (*print-right-margin* 100) (*print-escape* nil)) (with-output-to-string (os) (pprint-logical-block (os '(|M| |M| |M|) :per-line-prefix ">>>>") (write '|M| :stream os) (pprint-indent :block 2 os) (write #\Space :stream os) (write '|M| :stream os) (pprint-newline :mandatory os) (write '|M| :stream os))))) ">>>>M M >>>> M") (deftest pprint-indent.20 (with-standard-io-syntax (let ((*print-pretty* t) (*print-readably* nil) (*print-right-margin* 100) (*print-escape* nil)) (with-output-to-string (os) (pprint-logical-block (os '(|M| |M|) :per-line-prefix ">>>>") (write '|M| :stream os) (pprint-indent :block -1 os) (pprint-newline :mandatory os) (write '|M| :stream os))))) ">>>>M >>>>M") (deftest pprint-indent.21 (with-standard-io-syntax (let ((*print-pretty* t) (*print-readably* nil) (*print-right-margin* 100) (*print-escape* nil)) (with-output-to-string (os) (pprint-logical-block (os '(|M| |M| |M| |M|) :per-line-prefix ">>>>") (write '|M| :stream os) (pprint-indent :block 3 os) (pprint-newline :mandatory os) (write '|M| :stream os) (pprint-indent :current -2 os) (pprint-newline :mandatory os) (write '|M| :stream os) (pprint-indent :current -5 os) (pprint-newline :mandatory os) (write '|M| :stream os) )))) ">>>>M >>>> M >>>> M >>>>M") ;;; In miser mode, indentation is ignored (deftest pprint-indent.22 (with-standard-io-syntax (let ((*print-pretty* t) (*print-readably* nil) (*print-right-margin* 100) (*print-miser-width* 200) (*print-escape* nil)) (with-output-to-string (os) (pprint-logical-block (os '(1 2 3) :prefix "(" :suffix ")") (write 1 :stream os) (pprint-indent :current 1 os) (pprint-newline :mandatory os) (write 2 :stream os) (pprint-indent :block 3 os) (pprint-newline :mandatory os) (write 3 :stream os))))) "(1 2 3)") ;;; TERPRI or printing newline characters does not invoke indentation (deftest pprint-indent.23 (with-standard-io-syntax (let ((*print-pretty* t) (*print-readably* nil) (*print-right-margin* 100) (*print-escape* nil)) (with-output-to-string (os) (pprint-logical-block (os '(1 2 3 4)) (pprint-indent :block 2 os) (write 1 :stream os) (terpri os) (write 2 :stream os) (write #\Newline :stream os) (write 3 :stream os) (pprint-newline :mandatory os) (write 4 :stream os))))) "1 2 3 4") ;;; Error cases (deftest pprint-indent.error.1 (signals-error (pprint-indent) program-error) t) (deftest pprint-indent.error.2 (signals-error (pprint-indent :current) program-error) t) (deftest pprint-indent.error.3 (signals-error (pprint-indent :block 0 *standard-output* nil) program-error) t) (deftest pprint-indent.error.4 (loop for x in *mini-universe* when (and (not (member x '(:block :current))) (not (eval `(signals-error (pprint-indent ',x 0) error)))) collect x) nil) (deftest pprint-indent.error.4-unsafe (loop for x in *mini-universe* when (and (not (member x '(:block :current))) (not (eval `(signals-error (locally (declare (optimize (safety 0))) (pprint-indent ',x 0)) error)))) collect x) nil)
true
;-*- Mode: Lisp -*- ;;;; Author: PI:NAME:<NAME>END_PI ;;;; Created: Sat Jul 3 08:50:40 2004 ;;;; Contains: Tests of PPRINT-INDENT (in-package :cl-test) (deftest pprint-indent.1 (with-standard-io-syntax (let ((*print-pretty* nil)) (with-open-stream (*standard-output* (make-string-output-stream)) (pprint-indent :block 0)))) nil) (deftest pprint-indent.2 (with-standard-io-syntax (let ((*print-pretty* nil)) (with-open-stream (*standard-output* (make-broadcast-stream)) (pprint-indent :current 0)))) nil) (deftest pprint-indent.3 (with-standard-io-syntax (let ((*print-pretty* nil)) (with-open-stream (s (make-string-output-stream)) (pprint-indent :current 10 s)))) nil) (deftest pprint-indent.4 (with-standard-io-syntax (let ((*print-pretty* nil)) (with-open-stream (s (make-string-output-stream)) (pprint-indent :block 1/2 s)))) nil) (deftest pprint-indent.5 (with-standard-io-syntax (let ((*print-pretty* nil)) (with-open-stream (s (make-string-output-stream)) (pprint-indent :block 0.1 s)))) nil) (deftest pprint-indent.6 (with-standard-io-syntax (let ((*print-pretty* nil)) (loop for x in '(1.0s0 1.0f0 1.0d0 1.0l0) unless (equal (multiple-value-list (with-open-stream (s (make-string-output-stream)) (pprint-indent :block x s))) '(nil)) collect x))) nil) (deftest pprint-indent.7 (with-standard-io-syntax (let ((*print-pretty* nil)) (with-open-stream (*standard-output* (make-broadcast-stream)) (pprint-indent :current 0 nil)))) nil) (deftest pprint-indent.8 (with-standard-io-syntax (let ((*print-pretty* nil)) (with-open-stream (os (make-string-output-stream)) (with-open-stream (is (make-string-input-stream "")) (with-open-stream (*terminal-io* (make-two-way-stream is os)) (pprint-indent :current 0 t)))))) nil) ;;; Now test with pprint-logical-block ;;; :current (deftest pprint-indent.9 (with-standard-io-syntax (let ((*print-pretty* t) (*print-readably* nil) (*print-right-margin* 100) (*print-escape* nil)) (with-output-to-string (os) (pprint-logical-block (os '(|M| |M|)) (write '|M| :stream os) (pprint-indent :current 3 os) (pprint-newline :mandatory os) (write '|M| :stream os))))) "M M") (deftest pprint-indent.10 (with-standard-io-syntax (let ((*print-pretty* t) (*print-readably* nil) (*print-right-margin* 100) (*print-escape* nil)) (with-output-to-string (os) (pprint-logical-block (os '(|M| |M|) :prefix "(" :suffix ")") (write '|M| :stream os) (pprint-indent :current 1 os) (pprint-newline :mandatory os) (write '|M| :stream os))))) "(M M)") (deftest pprint-indent.11 (with-standard-io-syntax (let ((*print-pretty* t) (*print-readably* nil) (*print-right-margin* 100) (*print-escape* nil)) (with-output-to-string (os) (pprint-logical-block (os '(|M| |M|) :prefix "(" :suffix ")") (write '|M| :stream os) (pprint-indent :current -1 os) (pprint-newline :mandatory os) (write '|M| :stream os))))) "(M M)") (deftest pprint-indent.12 (with-standard-io-syntax (let ((*print-pretty* t) (*print-readably* nil) (*print-right-margin* 100) (*print-escape* nil)) (with-output-to-string (os) (pprint-logical-block (os '(|M| |M|) :prefix "(" :suffix ")") (write '|M| :stream os) (pprint-indent :current -2.0 os) (pprint-newline :mandatory os) (write '|M| :stream os))))) "(M M)") ;;; :block (deftest pprint-indent.13 (with-standard-io-syntax (let ((*print-pretty* t) (*print-readably* nil) (*print-right-margin* 100) (*print-escape* nil)) (with-output-to-string (os) (pprint-logical-block (os '(|M| |M|)) (write '|MMM| :stream os) (pprint-indent :block 0 os) (pprint-newline :mandatory os) (write '|MMMMM| :stream os))))) "MMM MMMMM") (deftest pprint-indent.13a (with-standard-io-syntax (let ((*print-pretty* t) (*print-readably* nil) (*print-right-margin* 100) (*print-escape* nil)) (with-output-to-string (os) (pprint-logical-block (os '(|M| |M|) :prefix "(" :suffix ")") (write '|MMM| :stream os) (pprint-indent :block 0 os) (pprint-newline :mandatory os) (write '|MMMMM| :stream os))))) "(MMM MMMMM)") (deftest pprint-indent.14 (with-standard-io-syntax (let ((*print-pretty* t) (*print-readably* nil) (*print-right-margin* 100) (*print-escape* nil)) (with-output-to-string (os) (pprint-logical-block (os '(|M| |M|)) (write '|MMM| :stream os) (pprint-indent :block 1 os) (pprint-newline :mandatory os) (write '|MMMMM| :stream os))))) "MMM MMMMM") (deftest pprint-indent.15 (with-standard-io-syntax (let ((*print-pretty* t) (*print-readably* nil) (*print-right-margin* 100) (*print-escape* nil)) (with-output-to-string (os) (pprint-logical-block (os '(|M| |M|)) (write '|MMM| :stream os) (pprint-indent :block -1 os) (pprint-newline :mandatory os) (write '|MMMMM| :stream os))))) "MMM MMMMM") (deftest pprint-indent.16 (loop for n in '(3.0s0 3.0f0 3.0d0 3.0l0) unless (string= (with-standard-io-syntax (let ((*print-pretty* t) (*print-readably* nil) (*print-right-margin* 100) (*print-escape* nil)) (with-output-to-string (os) (pprint-logical-block (os '(|M| |M|)) (write '|MMM| :stream os) (pprint-indent :block n os) (pprint-newline :mandatory os) (write '|MMMMM| :stream os))))) "MMM MMMMM") collect n) nil) ;;; *print-pretty* must be true for pprint-indent to have an effect (deftest pprint-indent.17 (with-standard-io-syntax (let ((*print-pretty* t) (*print-readably* nil) (*print-right-margin* 100) (*print-escape* nil)) (with-output-to-string (os) (pprint-logical-block (os '(|M| |M|)) (write '|M| :stream os) (let ((*print-pretty* nil)) (pprint-indent :current 3 os)) (pprint-newline :mandatory os) (write '|M| :stream os))))) "M M") (deftest pprint-indent.18 (with-standard-io-syntax (let ((*print-pretty* t) (*print-readably* nil) (*print-right-margin* 100) (*print-escape* nil)) (with-output-to-string (os) (pprint-logical-block (os '(|M| |M|)) (write '|M| :stream os) (let ((*print-pretty* nil)) (pprint-indent :block 3 os)) (pprint-newline :mandatory os) (write '|M| :stream os))))) "M M") ;;; indentation interaction with :per-line-prefix (deftest pprint-indent.19 (with-standard-io-syntax (let ((*print-pretty* t) (*print-readably* nil) (*print-right-margin* 100) (*print-escape* nil)) (with-output-to-string (os) (pprint-logical-block (os '(|M| |M| |M|) :per-line-prefix ">>>>") (write '|M| :stream os) (pprint-indent :block 2 os) (write #\Space :stream os) (write '|M| :stream os) (pprint-newline :mandatory os) (write '|M| :stream os))))) ">>>>M M >>>> M") (deftest pprint-indent.20 (with-standard-io-syntax (let ((*print-pretty* t) (*print-readably* nil) (*print-right-margin* 100) (*print-escape* nil)) (with-output-to-string (os) (pprint-logical-block (os '(|M| |M|) :per-line-prefix ">>>>") (write '|M| :stream os) (pprint-indent :block -1 os) (pprint-newline :mandatory os) (write '|M| :stream os))))) ">>>>M >>>>M") (deftest pprint-indent.21 (with-standard-io-syntax (let ((*print-pretty* t) (*print-readably* nil) (*print-right-margin* 100) (*print-escape* nil)) (with-output-to-string (os) (pprint-logical-block (os '(|M| |M| |M| |M|) :per-line-prefix ">>>>") (write '|M| :stream os) (pprint-indent :block 3 os) (pprint-newline :mandatory os) (write '|M| :stream os) (pprint-indent :current -2 os) (pprint-newline :mandatory os) (write '|M| :stream os) (pprint-indent :current -5 os) (pprint-newline :mandatory os) (write '|M| :stream os) )))) ">>>>M >>>> M >>>> M >>>>M") ;;; In miser mode, indentation is ignored (deftest pprint-indent.22 (with-standard-io-syntax (let ((*print-pretty* t) (*print-readably* nil) (*print-right-margin* 100) (*print-miser-width* 200) (*print-escape* nil)) (with-output-to-string (os) (pprint-logical-block (os '(1 2 3) :prefix "(" :suffix ")") (write 1 :stream os) (pprint-indent :current 1 os) (pprint-newline :mandatory os) (write 2 :stream os) (pprint-indent :block 3 os) (pprint-newline :mandatory os) (write 3 :stream os))))) "(1 2 3)") ;;; TERPRI or printing newline characters does not invoke indentation (deftest pprint-indent.23 (with-standard-io-syntax (let ((*print-pretty* t) (*print-readably* nil) (*print-right-margin* 100) (*print-escape* nil)) (with-output-to-string (os) (pprint-logical-block (os '(1 2 3 4)) (pprint-indent :block 2 os) (write 1 :stream os) (terpri os) (write 2 :stream os) (write #\Newline :stream os) (write 3 :stream os) (pprint-newline :mandatory os) (write 4 :stream os))))) "1 2 3 4") ;;; Error cases (deftest pprint-indent.error.1 (signals-error (pprint-indent) program-error) t) (deftest pprint-indent.error.2 (signals-error (pprint-indent :current) program-error) t) (deftest pprint-indent.error.3 (signals-error (pprint-indent :block 0 *standard-output* nil) program-error) t) (deftest pprint-indent.error.4 (loop for x in *mini-universe* when (and (not (member x '(:block :current))) (not (eval `(signals-error (pprint-indent ',x 0) error)))) collect x) nil) (deftest pprint-indent.error.4-unsafe (loop for x in *mini-universe* when (and (not (member x '(:block :current))) (not (eval `(signals-error (locally (declare (optimize (safety 0))) (pprint-indent ',x 0)) error)))) collect x) nil)
[ { "context": ";;;; eight-queens.lisp\n;;;; Copyright (c) 2013 Robert Smith\n\n;;;; The classical eight queens problem.\n\n(defst", "end": 59, "score": 0.9996960163116455, "start": 47, "tag": "NAME", "value": "Robert Smith" } ]
miscellaneous_exercises/eight-queens.lisp
stylewarning/lisp-random
56
;;;; eight-queens.lisp ;;;; Copyright (c) 2013 Robert Smith ;;;; The classical eight queens problem. (defstruct queen row col) (defun queens (n) "Create a function which generates new queens for a board of size N. The resulting function will take the row and column of a queen ROW and COL, and return a queen at that position." (let ((cache (make-hash-table))) (lambda (row col) (let* ((coord (+ col (* row n))) (lookup (gethash coord cache))) (if lookup lookup (setf (gethash coord cache) (make-queen :row row :col col))))))) (defun attacksp (p q) "Does the queen Q attack queen P?" (flet ((row= (p q) (= (queen-row p) (queen-row q))) (col= (p q) (= (queen-col p) (queen-col q))) (diag= (p q) (= (abs (- (queen-row p) (queen-row q))) (abs (- (queen-col p) (queen-col q)))))) (or (row= p q) (col= p q) (diag= p q)))) (defun safep (new-queen queens) "Is the queen NEW-QUEEN safe with the set of queens QUEENS?" (notany (lambda (queen) (attacksp queen new-queen)) queens)) (defun solve (n) "Compute the solutions to the N-queens problem." (let ((queen (queens n))) (labels ((rec (row col pos sols) (cond ;; We've reached the last row. Accumulate the ;; solutions. ((= row n) (cons (reverse pos) sols)) ;; We've reached the last column, return the ;; solutions found so far. ((= col n) sols) ;; Check the next positions. If the queen is safe, ;; add it, and compute the possible arrangements of ;; queens in the next row, and continue by placing ;; the queen in the next column. (t (let ((q (funcall queen row col))) (if (safep q pos) (rec row (1+ col) pos (rec (1+ row) 0 (cons q pos) sols)) (rec row (1+ col) pos sols))))))) (rec 0 0 nil nil)))) (defun bench (&optional (max 11)) (dotimes (i max) (format t "~A queens problem: ~A~%" (1+ i) (length (solve (1+ i)))))) ;;; START ;; User time = 1.434 ;; System time = 0.004 ;; Elapsed time = 1.454 ;; Allocation = 76066680 bytes ;;; QUEEN CACHING ;; User time = 1.381 ;; System time = 0.002 ;; Elapsed time = 1.387 ;; Allocation = 4185256 bytes ;;;; MICRO-OPTIMIZATIONS ;;; We can exploit regularities in the solution: ;;; ;;; * We can pre-allocate solution vectors, since we know each ;;; solution is a set of N queens. ;;; ;;; * We only need to store the column of each queen, since the ;;; ordering of the solutions is fixed. That is, we always have ;;; queens sorted by row. ;;; ;;; * We can optimize the structure to use conses instead. ;;; ;;; * Since recursive backtracking is used, the problem is only ;;; feasible for smaller numbers. As such, we can take advantage ;;; of this and optimize for fixnum-sized quantities.
64668
;;;; eight-queens.lisp ;;;; Copyright (c) 2013 <NAME> ;;;; The classical eight queens problem. (defstruct queen row col) (defun queens (n) "Create a function which generates new queens for a board of size N. The resulting function will take the row and column of a queen ROW and COL, and return a queen at that position." (let ((cache (make-hash-table))) (lambda (row col) (let* ((coord (+ col (* row n))) (lookup (gethash coord cache))) (if lookup lookup (setf (gethash coord cache) (make-queen :row row :col col))))))) (defun attacksp (p q) "Does the queen Q attack queen P?" (flet ((row= (p q) (= (queen-row p) (queen-row q))) (col= (p q) (= (queen-col p) (queen-col q))) (diag= (p q) (= (abs (- (queen-row p) (queen-row q))) (abs (- (queen-col p) (queen-col q)))))) (or (row= p q) (col= p q) (diag= p q)))) (defun safep (new-queen queens) "Is the queen NEW-QUEEN safe with the set of queens QUEENS?" (notany (lambda (queen) (attacksp queen new-queen)) queens)) (defun solve (n) "Compute the solutions to the N-queens problem." (let ((queen (queens n))) (labels ((rec (row col pos sols) (cond ;; We've reached the last row. Accumulate the ;; solutions. ((= row n) (cons (reverse pos) sols)) ;; We've reached the last column, return the ;; solutions found so far. ((= col n) sols) ;; Check the next positions. If the queen is safe, ;; add it, and compute the possible arrangements of ;; queens in the next row, and continue by placing ;; the queen in the next column. (t (let ((q (funcall queen row col))) (if (safep q pos) (rec row (1+ col) pos (rec (1+ row) 0 (cons q pos) sols)) (rec row (1+ col) pos sols))))))) (rec 0 0 nil nil)))) (defun bench (&optional (max 11)) (dotimes (i max) (format t "~A queens problem: ~A~%" (1+ i) (length (solve (1+ i)))))) ;;; START ;; User time = 1.434 ;; System time = 0.004 ;; Elapsed time = 1.454 ;; Allocation = 76066680 bytes ;;; QUEEN CACHING ;; User time = 1.381 ;; System time = 0.002 ;; Elapsed time = 1.387 ;; Allocation = 4185256 bytes ;;;; MICRO-OPTIMIZATIONS ;;; We can exploit regularities in the solution: ;;; ;;; * We can pre-allocate solution vectors, since we know each ;;; solution is a set of N queens. ;;; ;;; * We only need to store the column of each queen, since the ;;; ordering of the solutions is fixed. That is, we always have ;;; queens sorted by row. ;;; ;;; * We can optimize the structure to use conses instead. ;;; ;;; * Since recursive backtracking is used, the problem is only ;;; feasible for smaller numbers. As such, we can take advantage ;;; of this and optimize for fixnum-sized quantities.
true
;;;; eight-queens.lisp ;;;; Copyright (c) 2013 PI:NAME:<NAME>END_PI ;;;; The classical eight queens problem. (defstruct queen row col) (defun queens (n) "Create a function which generates new queens for a board of size N. The resulting function will take the row and column of a queen ROW and COL, and return a queen at that position." (let ((cache (make-hash-table))) (lambda (row col) (let* ((coord (+ col (* row n))) (lookup (gethash coord cache))) (if lookup lookup (setf (gethash coord cache) (make-queen :row row :col col))))))) (defun attacksp (p q) "Does the queen Q attack queen P?" (flet ((row= (p q) (= (queen-row p) (queen-row q))) (col= (p q) (= (queen-col p) (queen-col q))) (diag= (p q) (= (abs (- (queen-row p) (queen-row q))) (abs (- (queen-col p) (queen-col q)))))) (or (row= p q) (col= p q) (diag= p q)))) (defun safep (new-queen queens) "Is the queen NEW-QUEEN safe with the set of queens QUEENS?" (notany (lambda (queen) (attacksp queen new-queen)) queens)) (defun solve (n) "Compute the solutions to the N-queens problem." (let ((queen (queens n))) (labels ((rec (row col pos sols) (cond ;; We've reached the last row. Accumulate the ;; solutions. ((= row n) (cons (reverse pos) sols)) ;; We've reached the last column, return the ;; solutions found so far. ((= col n) sols) ;; Check the next positions. If the queen is safe, ;; add it, and compute the possible arrangements of ;; queens in the next row, and continue by placing ;; the queen in the next column. (t (let ((q (funcall queen row col))) (if (safep q pos) (rec row (1+ col) pos (rec (1+ row) 0 (cons q pos) sols)) (rec row (1+ col) pos sols))))))) (rec 0 0 nil nil)))) (defun bench (&optional (max 11)) (dotimes (i max) (format t "~A queens problem: ~A~%" (1+ i) (length (solve (1+ i)))))) ;;; START ;; User time = 1.434 ;; System time = 0.004 ;; Elapsed time = 1.454 ;; Allocation = 76066680 bytes ;;; QUEEN CACHING ;; User time = 1.381 ;; System time = 0.002 ;; Elapsed time = 1.387 ;; Allocation = 4185256 bytes ;;;; MICRO-OPTIMIZATIONS ;;; We can exploit regularities in the solution: ;;; ;;; * We can pre-allocate solution vectors, since we know each ;;; solution is a set of N queens. ;;; ;;; * We only need to store the column of each queen, since the ;;; ordering of the solutions is fixed. That is, we always have ;;; queens sorted by row. ;;; ;;; * We can optimize the structure to use conses instead. ;;; ;;; * Since recursive backtracking is used, the problem is only ;;; feasible for smaller numbers. As such, we can take advantage ;;; of this and optimize for fixnum-sized quantities.
[ { "context": "e: COMMON-LISP-USER -*-\n\n#| simple-header\n\nAuthor: Gary King\n\nDISCUSSION\n\n|#\n\n(in-package #:common-lisp-user)\n", "end": 85, "score": 0.9998774528503418, "start": 76, "tag": "NAME", "value": "Gary King" }, { "context": "(defsystem clnuplot\n :version \"0.2.2\"\n :author \"Gary Warren King <[email protected]>\"\n :maintainer \"Gary Warren", "end": 283, "score": 0.9998871088027954, "start": 267, "tag": "NAME", "value": "Gary Warren King" }, { "context": "t\n :version \"0.2.2\"\n :author \"Gary Warren King <[email protected]>\"\n :maintainer \"Gary Warren King <gwking@metaban", "end": 304, "score": 0.999931275844574, "start": 285, "tag": "EMAIL", "value": "[email protected]" }, { "context": "Warren King <[email protected]>\"\n :maintainer \"Gary Warren King <[email protected]>\"\n :licence \"MIT License\"\n ", "end": 338, "score": 0.9998890161514282, "start": 322, "tag": "NAME", "value": "Gary Warren King" }, { "context": "[email protected]>\"\n :maintainer \"Gary Warren King <[email protected]>\"\n :licence \"MIT License\"\n :description \"Common", "end": 359, "score": 0.9999307990074158, "start": 340, "tag": "EMAIL", "value": "[email protected]" } ]
clnuplot.asd
gwkkwg/clnuplot
1
;;;-*- Mode: Lisp; Package: COMMON-LISP-USER -*- #| simple-header Author: Gary King DISCUSSION |# (in-package #:common-lisp-user) (defpackage #:clnuplot-system (:use #:asdf #:cl)) (in-package #:clnuplot-system) (defsystem clnuplot :version "0.2.2" :author "Gary Warren King <[email protected]>" :maintainer "Gary Warren King <[email protected]>" :licence "MIT License" :description "Common Lisp interface to GNUPlot." :components ((:module "dev" :components ((:file "package") (:file "utilities" :depends-on ("package")) (:file "plots" :depends-on ("utilities")) (:file "roc-curves" :depends-on ("plots")) (:file "plot-window" :depends-on ("plots")) (:static-file "notes.text") (:static-file "examples")))) :depends-on (:cl-containers :cl-mathstats :metabang-bind :trivial-shell))
43017
;;;-*- Mode: Lisp; Package: COMMON-LISP-USER -*- #| simple-header Author: <NAME> DISCUSSION |# (in-package #:common-lisp-user) (defpackage #:clnuplot-system (:use #:asdf #:cl)) (in-package #:clnuplot-system) (defsystem clnuplot :version "0.2.2" :author "<NAME> <<EMAIL>>" :maintainer "<NAME> <<EMAIL>>" :licence "MIT License" :description "Common Lisp interface to GNUPlot." :components ((:module "dev" :components ((:file "package") (:file "utilities" :depends-on ("package")) (:file "plots" :depends-on ("utilities")) (:file "roc-curves" :depends-on ("plots")) (:file "plot-window" :depends-on ("plots")) (:static-file "notes.text") (:static-file "examples")))) :depends-on (:cl-containers :cl-mathstats :metabang-bind :trivial-shell))
true
;;;-*- Mode: Lisp; Package: COMMON-LISP-USER -*- #| simple-header Author: PI:NAME:<NAME>END_PI DISCUSSION |# (in-package #:common-lisp-user) (defpackage #:clnuplot-system (:use #:asdf #:cl)) (in-package #:clnuplot-system) (defsystem clnuplot :version "0.2.2" :author "PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>" :maintainer "PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>" :licence "MIT License" :description "Common Lisp interface to GNUPlot." :components ((:module "dev" :components ((:file "package") (:file "utilities" :depends-on ("package")) (:file "plots" :depends-on ("utilities")) (:file "roc-curves" :depends-on ("plots")) (:file "plot-window" :depends-on ("plots")) (:static-file "notes.text") (:static-file "examples")))) :depends-on (:cl-containers :cl-mathstats :metabang-bind :trivial-shell))
[ { "context": "; DEALINGS IN THE SOFTWARE.\n;\n; Original author: Mertcan Temel <[email protected]>\n\n;; Mertcan Temel\n\n(in-package ", "end": 1280, "score": 0.9998410940170288, "start": 1267, "tag": "NAME", "value": "Mertcan Temel" }, { "context": "THE SOFTWARE.\n;\n; Original author: Mertcan Temel <[email protected]>\n\n;; Mertcan Temel\n\n(in-package \"SVL\")\n\n(include-", "end": 1297, "score": 0.9999312162399292, "start": 1282, "tag": "EMAIL", "value": "[email protected]" }, { "context": "iginal author: Mertcan Temel <[email protected]>\n\n;; Mertcan Temel\n\n(in-package \"SVL\")\n\n(include-book \"centaur/sv/sv", "end": 1316, "score": 0.9166620373725891, "start": 1303, "tag": "NAME", "value": "Mertcan Temel" } ]
books/centaur/svl/svl-run-to-svex-alist.lisp
KestrelInstitute/acl2
305
; SVL - Listener-based Hierachical Symbolic Vector Hardware Analysis Framework ; Copyright (C) 2019 Centaur Technology ; ; License: (An MIT/X11-style license) ; ; Permission is hereby granted, free of charge, to any person obtaining a ; copy of this software and associated documentation files (the "Software"), ; to deal in the Software without restriction, including without limitation ; the rights to use, copy, modify, merge, publish, distribute, sublicense, ; and/or sell copies of the Software, and to permit persons to whom the ; Software is furnished to do so, subject to the following conditions: ; ; The above copyright notice and this permission notice shall be included in ; all copies or substantial portions of the Software. ; ; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR ; IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, ; FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE ; AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER ; LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING ; FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER ; DEALINGS IN THE SOFTWARE. ; ; Original author: Mertcan Temel <[email protected]> ;; Mertcan Temel (in-package "SVL") (include-book "centaur/sv/svex/eval" :dir :system) (include-book "projects/rp-rewriter/top" :dir :system) (include-book "centaur/svl/svex-simplify" :dir :system) (include-book "centaur/svl/svl-openers" :dir :system) (include-book "centaur/svl/svexl/svexl-correct" :dir :system) (local (include-book "projects/rp-rewriter/proofs/rp-rw-lemmas" :dir :system)) (rp::def-rp-rule$ t nil assoc-equal-opener-when-not-equal (implies (not (equal key1 key2)) (equal (assoc-equal key1 (cons (cons key2 val) rest)) (assoc-equal key1 rest)))) (rp::def-rp-rule$ t nil assoc-equal-opener-when-equal (implies t (equal (assoc-equal key (cons (cons key val) rest)) (cons key val)))) ;; :i-am-here ;; (rp::def-rp-rule$ ;; t t ;; bits-of-bits-exact-match ;; (implies (and (natp x) ;; (natp y)) ;; (equal (bits (bits term x y) x y ) ;; (bits term x y ))) ;; :hints (("Goal" ;; :in-theory (e/d () ())))) (defconst *svl-compose-rules* (reverse '(svex-alist-eval-opener-nil svex-alist-eval-opener-cons ;;svex-eval-is-svex-eval-wog ;;svexlist-eval-is-svexlist-eval-wog svl-start-env-opener-error svl-start-env-cons-1 svl-start-env-nil svl-start-env-cons-2 svl-retrieve-values-opener-error svl-retrieve-values-nil svl-retrieve-values-cons-1 svl-retrieve-values-cons-2 save-wires-to-env-wires-opener-error save-wires-to-env-wires-cons-1 save-wires-to-env-wires-nil save-wires-to-env-wires-cons-2 save-wires-to-env-wires-cons-3 svex-env-append-opener-error svex-env-append-opener-cons svex-env-append-opener-nil create-next-env-for-wires-opener-nil create-next-env-for-wires-opener-cons svl-save-mod-outputs-opener-error svl-save-mod-outputs-nil svl-save-mod-outputs-cons svl-well-ranked-module-is-svl-well-ranked-module$ svl-run-phase-opener-error svl-run-phase-occs-opener-error svl-run-phase-is-svl-run-phase-wog svl-run-phase-occs-is-svl-run-phase-occs-wog svl-run-phase-wog-opener-error svl-run-phase-wog-opener ;;rp::svl-run-phase-wog-opener_lambda-opener svl-run-phase-occs-wog-opener-error svl-run-phase-occs-wog-opener-nil svl-run-phase-occs-wog-opener-cons-assign svl-run-phase-occs-wog-opener-cons-module ;;rp::svl-run-phase-occs-wog-opener-cons-module_lambda-opener pairlis3-opener-error pairlis3-opener-done pairlis3-opener-cons svl-run-save-output-opener-error svl-run-save-output-opener-nil svl-run-save-output-opener-cons ;;rp::svl-run-save-output-opener-cons_lambda-opener svl-run-aux-opener-error svl-run-aux-wog-opener-error svl-run-aux-is-svl-run-aux-wog svl-run-aux-wog-opener-nil svl-run-aux-opener-cons ;;rp::svl-run-aux-opener-cons_lambda-opener svl-run-opener-error svl-run-def-opener ;;rp::svl-run-def-opener_lambda-opener sv::4veclist-p-of-cons SV::SVEX-ENV-P-when-cons SV::SVEX-ENV-FIX-opener SV::SVEX-ENV-P-nil RP::CONSP-CONS svexlist-list-eval-wog-opener-error svexlist-list-eval-wog-opener-cons svexlist-list-eval-wog-opener-nil ;;svexlist-eval-wog-is-svexlist-eval svexlist-eval-wog-cons-def svexlist-eval-wog-nil-def rp::make-fast-alist-def return-last entry-4vec-fix cdr-cons car-cons acons assoc-equal-opener-when-not-equal assoc-equal-opener-when-equal append-of-cons 4vec-part-install-is-sbits-without-inserting-bits ;;4vec-part-install-is-sbits 4vec-part-select-is-bits svexllist-correct svexl-correct svexl-node-kind-is-svexl-node-kind-wog svexl-node-kind-wog-is-svexl-node-kind svexl-nodelist-eval-wog-of-cons svexl-nodelist-eval-wog-of-nil svexllist-eval-is-svexllist-eval-wog svexl-eval-is-svexl-eval-wog svexl-eval-wog-for-rp ;;rp::svexl-eval-wog-opener_lambda-opener svex-env-fastlookup-wog-def RP::APPEND-OF-NIL SVEXL-EVAL-AUX-WOG-nil svexl-eval-aux-wog-cons ;;rp::svexl-eval-aux-wog-cons_lambda-opener svexl-node-eval-is-svexl-node-eval-wog svexl-nodelist-eval-is-svexl-nodelist-eval-wog svexl-eval-aux-is-svexl-eval-aux-wog rp::force$-fail rp::force$-of-t ))) (define alist-term-to-entry-list (term) (case-match term (('cons ('cons key val) rest) (b* (((mv keys vals) (alist-term-to-entry-list rest))) (mv (cons key keys) (cons val vals)))) (''nil (mv nil nil)) (& (mv (hard-error 'alist-term-to-entry-list "Unexpected alist-term ~p0 ~%" (list (cons #\0 term))) nil)))) (local (Include-Book "projects/rp-rewriter/proofs/extract-formula-lemmas" :dir :system)) (local (Include-Book "projects/rp-rewriter/proofs/rp-state-functions-lemmas" :dir :system)) (define rw-svl-run-to-svex-alist ((term rp::rp-termp) &key (context 'nil) (state 'state) (rp::rp-state 'rp::rp-state)) :guard (and (rp::rp-term-listp context)) :verify-guards nil :prepwork ((local (defthm valid-rw-step-limit (implies (rp::rp-statep rp::rp-state) (and (natp (rp::rw-step-limit rp-state)) (unsigned-byte-p 58 (rp::rw-step-limit rp-state)) (integerp (rp::rw-step-limit rp-state)))) :hints (("Goal" :do-not-induct t :in-theory (e/d (rp::rp-statep RP::RW-STEP-LIMITP) (unsigned-byte-p)))))) (local (defthm rp-statep-of-not-simplified-action (implies (and (rp::rp-statep rp-state) (symbolp x)) (RP::RP-STATEP (RP::UPDATE-NOT-SIMPLIFIED-ACTION x RP-STATE))) :hints (("Goal" :in-theory (e/d (RP::RP-STATEP) ()))))) (local (in-theory (e/d () (unsigned-byte-p natp RP::UPDATE-NOT-SIMPLIFIED-ACTION RP::NOT-SIMPLIFIED-ACTION rp::rw-step-limit))))) (b* ((world (w state)) ;; do not let rp-rewriter complain when simplified term is not ''t (- (rp::check-if-clause-processor-up-to-date world)) (tmp-rp-not-simplified-action (rp::not-simplified-action rp::rp-state)) (rp::rp-state (rp::update-not-simplified-action :none rp::rp-state)) (rp::rp-state (rp::rp-state-new-run rp::rp-state)) (rp::rp-state (rp::rp-state-init-rules nil nil nil rp::rp-state state)) ((mv context rp::rp-state) (rp::rp-rw-subterms context nil nil nil (rp::rw-step-limit rp::rp-state) rp::rp-state state)) ((mv rw rp::rp-state) (rp::rp-rw term nil context nil nil (rp::rw-step-limit rp::rp-state) rp::rp-state state)) (rp::rp-state (rp::update-not-simplified-action tmp-rp-not-simplified-action rp::rp-state)) ((mv keys vals) (alist-term-to-entry-list rw)) ((mv err svexlist) (svl::4vec-to-svex-lst vals nil t)) #|((mv err svex-res) (svl::4vec-to-svex rw nil nil))||# (- (and err (hard-error ; ; 'rw-svl-run-to-svex-alist ; ; "There was a problem while converting the term below to its ~ svex equivalent. Read above for the printed messages. ~p0 ~%" (list (cons #\0 rw))))) (svex-alist (pairlis$ (rp::unquote-all keys) svexlist)) ) (mv svex-alist rp::rp-state)) /// (Local (defthm true-listp-of-unquote-all (implies (true-listp x) (true-listp (rp::unquote-all x))))) (Local (defthm true-listp-of-alist-term-to-entry-list (implies t;; (true-listp x) (true-listp (mv-nth 0 (alist-term-to-entry-list x)))) :hints (("Goal" :in-theory (e/d (alist-term-to-entry-list) ()))))) (local (defthm unsigned-byte-p-58-of-rw-step-limit (implies (force (rp::rp-statep rp::rp-state)) (UNSIGNED-BYTE-P 58 (RP::RW-STEP-LIMIT rp::rp-state))))) (verify-guards rw-svl-run-to-svex-alist-fn :hints (("Goal" :do-not-induct t :in-theory (e/d (rp::rp-statep rp::not-simplified-action rp::not-simplified-actionp) (rp::rw-step-limit)))))) (progn (define svl-run-to-svex-alist-create-env-aux (vars) (if (atom vars) ''nil `(cons (cons ',(car vars) ,(car vars)) ,(svl-run-to-svex-alist-create-env-aux (cdr vars))))) (define get-vars-from-port-binds (port-binds) :mode :program (b* ((lst (strip-cdrs port-binds)) (lst (acl2::flatten lst))) (loop$ for x in lst when (and (symbolp x) (let* ((x (symbol-name x))) (and (not (equal x "_")) (not (equal x "~")) (not (equal x "X")) (not (equal x "-")) (not (equal x "x"))))) collect x))) (define svl-run-to-svex-alist-fn-create-env (binds-ins-alist) :mode :program (b* ((vars (get-vars-from-port-binds binds-ins-alist))) `(make-fast-alist ,(svl-run-to-svex-alist-create-env-aux vars)))) (define svl-run-to-svex-alist-create-hyp (binds-ins-alist) :mode :program (b* ((vars (get-vars-from-port-binds binds-ins-alist))) (loop$ for x in vars collect `(sv::4vec-p ,x))))) (define svl-run->svex-alist-aux (&key modname binds-ins-alist binds-out-alist svl-design svex-alist-name rw-rule-name) (b* (((unless (and modname binds-ins-alist binds-out-alist svl-design svex-alist-name rw-rule-name)) (hard-error 'svl-run-compose-fn "You need to assign values to keys ~ modname~ binds-ins-alist~ binds-out-alist~ svl-design~ svex-alist-name rw-rule-name ~%" nil))) `(encapsulate nil (local (rp::disable-all-rules)) (local (rp::enable-rules *svl-compose-rules*)) (local (memoize 'rp::rp-equal)) (local (rp::disable-exc-counterpart fmt-to-comment-window)) (local (rp::disable-all-meta-rules)) (local (rp::enable-meta-rules ;; bits-of-meta-fn ;; concat-meta ;; 4vec-rsh-of-meta svex-eval-wog-meta-main svexl-node-eval-wog-meta-main rp::HONS-ACONS-META rp::FAST-ALIST-FREE-META rp::ASSOC-EQ-VALS-META rp::HONS-GET-META rp::RP-EQUAL-META rp::MV-NTH-META)) (with-output :off :all :gag-mode nil (make-event (b* ((env (svl-run-to-svex-alist-fn-create-env ,binds-ins-alist)) (?hyp (svl-run-to-svex-alist-create-hyp ,binds-ins-alist)) (?hyp (append hyp (list `(equal env ,env)))) (?hyp (list '(sv::svex-env-p svex-env))) (term `(svl::svl-run ',,modname svex-env ',,binds-ins-alist ',,binds-out-alist ',,svl-design)) ((mv svex-alist rp::rp-state) (rw-svl-run-to-svex-alist term :context hyp))) (mv nil `(progn (defconst ,',svex-alist-name ',svex-alist) (defthmd ,',rw-rule-name (implies (and ,@hyp) (equal (svl::svl-run ,',modname svex-env ,',binds-ins-alist ,',binds-out-alist ,',svl-design) (sv::svex-alist-eval ,',svex-alist-name svex-env))) :hints (("Goal" :do-not-induct t :rw-cache-state nil :do-not '(preprocess generalize fertilize) :clause-processor (rp::rp-cl :runes nil :new-synps nil))) ) #|(rp::disable-rules '(,',rw-rule-name))||# #|(in-theory (disable ,',rw-rule-name))||# (value-triple (cw "~%An svex-alist ~p0 and a disabled rewrite ~ rule ~p1 are created. ~%~%" ',',svex-alist-name ',',rw-rule-name)) ) state rp::rp-state))))))) (defmacro svl-run->svex-alist (&key modname binds-ins-alist binds-out-alist svl-design svex-alist-name rw-rule-name) (svl-run->svex-alist-aux :modname modname :binds-ins-alist binds-ins-alist :binds-out-alist binds-out-alist :svl-design svl-design :rw-rule-name rw-rule-name :svex-alist-name svex-alist-name)) (xdoc::defxdoc svl-run->svex-alist :parents (acl2::svl) :short "Convert an SVL design to an @(see sv::svex-alist)." :long " <p> Using @(see rp::rp-rewriter), converts an SVL design usign svl-run to an @(see sv::svex-alist). </p> <code> @(' (svl-run->svex-alist :modname <modname> :svl-design <svl-design> :binds-ins-alist <binds-ins-alist> :binds-out-alist <binds-out-alist> :svex-alist-name <svex-alist-name> :rw-rule-name <rw-rule-name>) ') </code> <p>Users should provide a value for all the keys.</p> <p>modname: name of the main module in an SVL design.</p> <p>svl-design: SVL design constant. </p> <p>binds-ins-alist: Input simulation pattern constant similar to inputs key of @(see acl2::defsvtv). </p> <p>binds-out-alist: Output simulation pattern constant similar to outputs key of @(see acl2::defsvtv). </p> <p>svex-alist-name: when the SVL-design is converted to an svex-alist, the program will create a constant provided by svex-alist-name.</p> <p> rw-rule-name: the program also creates a rewrite rule with this given name. The LHS of this rewrite rule is svl-run of the given module with given configuration, and the RHS is svex-alist-eval of the newly generated svex-alist. </p> <p>The keys in created svex-alist are the variables designated in binds-out-alist. The variables in the values (svexes) share the same name as the variables from binds-ins-alist. </p> <p> An example call to svl-run-compose is given below. It submits an event that exports svl-run-top-module-composed and *svl-run-top-module-composed*. <code> @(' (svl-run->svex-alist :modname \"top_module\" :binds-ins-alist *ins-alist* :binds-out-alist *outs-alist* :svl-design *svl-netlist* :rw-rule-name svl-run-top-module-composed :svex-alist-name *svl-run-top-module-composed*) ') </code> </p> <p> This will produce a constant *svl-run-top-module-composed*, which has the svex-alist representation of the given svl-run instance; and a rewrite rule with the name svl-run-top-module-composed, which rewrites the svl-run instance to evaluation of this svex-alist. See @(see svl::svl-run) for concrete examples of the first four keys (:modname, :binds-ins-alist, :binds-out-alist, :svl-design). </p> ")
74138
; SVL - Listener-based Hierachical Symbolic Vector Hardware Analysis Framework ; Copyright (C) 2019 Centaur Technology ; ; License: (An MIT/X11-style license) ; ; Permission is hereby granted, free of charge, to any person obtaining a ; copy of this software and associated documentation files (the "Software"), ; to deal in the Software without restriction, including without limitation ; the rights to use, copy, modify, merge, publish, distribute, sublicense, ; and/or sell copies of the Software, and to permit persons to whom the ; Software is furnished to do so, subject to the following conditions: ; ; The above copyright notice and this permission notice shall be included in ; all copies or substantial portions of the Software. ; ; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR ; IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, ; FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE ; AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER ; LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING ; FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER ; DEALINGS IN THE SOFTWARE. ; ; Original author: <NAME> <<EMAIL>> ;; <NAME> (in-package "SVL") (include-book "centaur/sv/svex/eval" :dir :system) (include-book "projects/rp-rewriter/top" :dir :system) (include-book "centaur/svl/svex-simplify" :dir :system) (include-book "centaur/svl/svl-openers" :dir :system) (include-book "centaur/svl/svexl/svexl-correct" :dir :system) (local (include-book "projects/rp-rewriter/proofs/rp-rw-lemmas" :dir :system)) (rp::def-rp-rule$ t nil assoc-equal-opener-when-not-equal (implies (not (equal key1 key2)) (equal (assoc-equal key1 (cons (cons key2 val) rest)) (assoc-equal key1 rest)))) (rp::def-rp-rule$ t nil assoc-equal-opener-when-equal (implies t (equal (assoc-equal key (cons (cons key val) rest)) (cons key val)))) ;; :i-am-here ;; (rp::def-rp-rule$ ;; t t ;; bits-of-bits-exact-match ;; (implies (and (natp x) ;; (natp y)) ;; (equal (bits (bits term x y) x y ) ;; (bits term x y ))) ;; :hints (("Goal" ;; :in-theory (e/d () ())))) (defconst *svl-compose-rules* (reverse '(svex-alist-eval-opener-nil svex-alist-eval-opener-cons ;;svex-eval-is-svex-eval-wog ;;svexlist-eval-is-svexlist-eval-wog svl-start-env-opener-error svl-start-env-cons-1 svl-start-env-nil svl-start-env-cons-2 svl-retrieve-values-opener-error svl-retrieve-values-nil svl-retrieve-values-cons-1 svl-retrieve-values-cons-2 save-wires-to-env-wires-opener-error save-wires-to-env-wires-cons-1 save-wires-to-env-wires-nil save-wires-to-env-wires-cons-2 save-wires-to-env-wires-cons-3 svex-env-append-opener-error svex-env-append-opener-cons svex-env-append-opener-nil create-next-env-for-wires-opener-nil create-next-env-for-wires-opener-cons svl-save-mod-outputs-opener-error svl-save-mod-outputs-nil svl-save-mod-outputs-cons svl-well-ranked-module-is-svl-well-ranked-module$ svl-run-phase-opener-error svl-run-phase-occs-opener-error svl-run-phase-is-svl-run-phase-wog svl-run-phase-occs-is-svl-run-phase-occs-wog svl-run-phase-wog-opener-error svl-run-phase-wog-opener ;;rp::svl-run-phase-wog-opener_lambda-opener svl-run-phase-occs-wog-opener-error svl-run-phase-occs-wog-opener-nil svl-run-phase-occs-wog-opener-cons-assign svl-run-phase-occs-wog-opener-cons-module ;;rp::svl-run-phase-occs-wog-opener-cons-module_lambda-opener pairlis3-opener-error pairlis3-opener-done pairlis3-opener-cons svl-run-save-output-opener-error svl-run-save-output-opener-nil svl-run-save-output-opener-cons ;;rp::svl-run-save-output-opener-cons_lambda-opener svl-run-aux-opener-error svl-run-aux-wog-opener-error svl-run-aux-is-svl-run-aux-wog svl-run-aux-wog-opener-nil svl-run-aux-opener-cons ;;rp::svl-run-aux-opener-cons_lambda-opener svl-run-opener-error svl-run-def-opener ;;rp::svl-run-def-opener_lambda-opener sv::4veclist-p-of-cons SV::SVEX-ENV-P-when-cons SV::SVEX-ENV-FIX-opener SV::SVEX-ENV-P-nil RP::CONSP-CONS svexlist-list-eval-wog-opener-error svexlist-list-eval-wog-opener-cons svexlist-list-eval-wog-opener-nil ;;svexlist-eval-wog-is-svexlist-eval svexlist-eval-wog-cons-def svexlist-eval-wog-nil-def rp::make-fast-alist-def return-last entry-4vec-fix cdr-cons car-cons acons assoc-equal-opener-when-not-equal assoc-equal-opener-when-equal append-of-cons 4vec-part-install-is-sbits-without-inserting-bits ;;4vec-part-install-is-sbits 4vec-part-select-is-bits svexllist-correct svexl-correct svexl-node-kind-is-svexl-node-kind-wog svexl-node-kind-wog-is-svexl-node-kind svexl-nodelist-eval-wog-of-cons svexl-nodelist-eval-wog-of-nil svexllist-eval-is-svexllist-eval-wog svexl-eval-is-svexl-eval-wog svexl-eval-wog-for-rp ;;rp::svexl-eval-wog-opener_lambda-opener svex-env-fastlookup-wog-def RP::APPEND-OF-NIL SVEXL-EVAL-AUX-WOG-nil svexl-eval-aux-wog-cons ;;rp::svexl-eval-aux-wog-cons_lambda-opener svexl-node-eval-is-svexl-node-eval-wog svexl-nodelist-eval-is-svexl-nodelist-eval-wog svexl-eval-aux-is-svexl-eval-aux-wog rp::force$-fail rp::force$-of-t ))) (define alist-term-to-entry-list (term) (case-match term (('cons ('cons key val) rest) (b* (((mv keys vals) (alist-term-to-entry-list rest))) (mv (cons key keys) (cons val vals)))) (''nil (mv nil nil)) (& (mv (hard-error 'alist-term-to-entry-list "Unexpected alist-term ~p0 ~%" (list (cons #\0 term))) nil)))) (local (Include-Book "projects/rp-rewriter/proofs/extract-formula-lemmas" :dir :system)) (local (Include-Book "projects/rp-rewriter/proofs/rp-state-functions-lemmas" :dir :system)) (define rw-svl-run-to-svex-alist ((term rp::rp-termp) &key (context 'nil) (state 'state) (rp::rp-state 'rp::rp-state)) :guard (and (rp::rp-term-listp context)) :verify-guards nil :prepwork ((local (defthm valid-rw-step-limit (implies (rp::rp-statep rp::rp-state) (and (natp (rp::rw-step-limit rp-state)) (unsigned-byte-p 58 (rp::rw-step-limit rp-state)) (integerp (rp::rw-step-limit rp-state)))) :hints (("Goal" :do-not-induct t :in-theory (e/d (rp::rp-statep RP::RW-STEP-LIMITP) (unsigned-byte-p)))))) (local (defthm rp-statep-of-not-simplified-action (implies (and (rp::rp-statep rp-state) (symbolp x)) (RP::RP-STATEP (RP::UPDATE-NOT-SIMPLIFIED-ACTION x RP-STATE))) :hints (("Goal" :in-theory (e/d (RP::RP-STATEP) ()))))) (local (in-theory (e/d () (unsigned-byte-p natp RP::UPDATE-NOT-SIMPLIFIED-ACTION RP::NOT-SIMPLIFIED-ACTION rp::rw-step-limit))))) (b* ((world (w state)) ;; do not let rp-rewriter complain when simplified term is not ''t (- (rp::check-if-clause-processor-up-to-date world)) (tmp-rp-not-simplified-action (rp::not-simplified-action rp::rp-state)) (rp::rp-state (rp::update-not-simplified-action :none rp::rp-state)) (rp::rp-state (rp::rp-state-new-run rp::rp-state)) (rp::rp-state (rp::rp-state-init-rules nil nil nil rp::rp-state state)) ((mv context rp::rp-state) (rp::rp-rw-subterms context nil nil nil (rp::rw-step-limit rp::rp-state) rp::rp-state state)) ((mv rw rp::rp-state) (rp::rp-rw term nil context nil nil (rp::rw-step-limit rp::rp-state) rp::rp-state state)) (rp::rp-state (rp::update-not-simplified-action tmp-rp-not-simplified-action rp::rp-state)) ((mv keys vals) (alist-term-to-entry-list rw)) ((mv err svexlist) (svl::4vec-to-svex-lst vals nil t)) #|((mv err svex-res) (svl::4vec-to-svex rw nil nil))||# (- (and err (hard-error ; ; 'rw-svl-run-to-svex-alist ; ; "There was a problem while converting the term below to its ~ svex equivalent. Read above for the printed messages. ~p0 ~%" (list (cons #\0 rw))))) (svex-alist (pairlis$ (rp::unquote-all keys) svexlist)) ) (mv svex-alist rp::rp-state)) /// (Local (defthm true-listp-of-unquote-all (implies (true-listp x) (true-listp (rp::unquote-all x))))) (Local (defthm true-listp-of-alist-term-to-entry-list (implies t;; (true-listp x) (true-listp (mv-nth 0 (alist-term-to-entry-list x)))) :hints (("Goal" :in-theory (e/d (alist-term-to-entry-list) ()))))) (local (defthm unsigned-byte-p-58-of-rw-step-limit (implies (force (rp::rp-statep rp::rp-state)) (UNSIGNED-BYTE-P 58 (RP::RW-STEP-LIMIT rp::rp-state))))) (verify-guards rw-svl-run-to-svex-alist-fn :hints (("Goal" :do-not-induct t :in-theory (e/d (rp::rp-statep rp::not-simplified-action rp::not-simplified-actionp) (rp::rw-step-limit)))))) (progn (define svl-run-to-svex-alist-create-env-aux (vars) (if (atom vars) ''nil `(cons (cons ',(car vars) ,(car vars)) ,(svl-run-to-svex-alist-create-env-aux (cdr vars))))) (define get-vars-from-port-binds (port-binds) :mode :program (b* ((lst (strip-cdrs port-binds)) (lst (acl2::flatten lst))) (loop$ for x in lst when (and (symbolp x) (let* ((x (symbol-name x))) (and (not (equal x "_")) (not (equal x "~")) (not (equal x "X")) (not (equal x "-")) (not (equal x "x"))))) collect x))) (define svl-run-to-svex-alist-fn-create-env (binds-ins-alist) :mode :program (b* ((vars (get-vars-from-port-binds binds-ins-alist))) `(make-fast-alist ,(svl-run-to-svex-alist-create-env-aux vars)))) (define svl-run-to-svex-alist-create-hyp (binds-ins-alist) :mode :program (b* ((vars (get-vars-from-port-binds binds-ins-alist))) (loop$ for x in vars collect `(sv::4vec-p ,x))))) (define svl-run->svex-alist-aux (&key modname binds-ins-alist binds-out-alist svl-design svex-alist-name rw-rule-name) (b* (((unless (and modname binds-ins-alist binds-out-alist svl-design svex-alist-name rw-rule-name)) (hard-error 'svl-run-compose-fn "You need to assign values to keys ~ modname~ binds-ins-alist~ binds-out-alist~ svl-design~ svex-alist-name rw-rule-name ~%" nil))) `(encapsulate nil (local (rp::disable-all-rules)) (local (rp::enable-rules *svl-compose-rules*)) (local (memoize 'rp::rp-equal)) (local (rp::disable-exc-counterpart fmt-to-comment-window)) (local (rp::disable-all-meta-rules)) (local (rp::enable-meta-rules ;; bits-of-meta-fn ;; concat-meta ;; 4vec-rsh-of-meta svex-eval-wog-meta-main svexl-node-eval-wog-meta-main rp::HONS-ACONS-META rp::FAST-ALIST-FREE-META rp::ASSOC-EQ-VALS-META rp::HONS-GET-META rp::RP-EQUAL-META rp::MV-NTH-META)) (with-output :off :all :gag-mode nil (make-event (b* ((env (svl-run-to-svex-alist-fn-create-env ,binds-ins-alist)) (?hyp (svl-run-to-svex-alist-create-hyp ,binds-ins-alist)) (?hyp (append hyp (list `(equal env ,env)))) (?hyp (list '(sv::svex-env-p svex-env))) (term `(svl::svl-run ',,modname svex-env ',,binds-ins-alist ',,binds-out-alist ',,svl-design)) ((mv svex-alist rp::rp-state) (rw-svl-run-to-svex-alist term :context hyp))) (mv nil `(progn (defconst ,',svex-alist-name ',svex-alist) (defthmd ,',rw-rule-name (implies (and ,@hyp) (equal (svl::svl-run ,',modname svex-env ,',binds-ins-alist ,',binds-out-alist ,',svl-design) (sv::svex-alist-eval ,',svex-alist-name svex-env))) :hints (("Goal" :do-not-induct t :rw-cache-state nil :do-not '(preprocess generalize fertilize) :clause-processor (rp::rp-cl :runes nil :new-synps nil))) ) #|(rp::disable-rules '(,',rw-rule-name))||# #|(in-theory (disable ,',rw-rule-name))||# (value-triple (cw "~%An svex-alist ~p0 and a disabled rewrite ~ rule ~p1 are created. ~%~%" ',',svex-alist-name ',',rw-rule-name)) ) state rp::rp-state))))))) (defmacro svl-run->svex-alist (&key modname binds-ins-alist binds-out-alist svl-design svex-alist-name rw-rule-name) (svl-run->svex-alist-aux :modname modname :binds-ins-alist binds-ins-alist :binds-out-alist binds-out-alist :svl-design svl-design :rw-rule-name rw-rule-name :svex-alist-name svex-alist-name)) (xdoc::defxdoc svl-run->svex-alist :parents (acl2::svl) :short "Convert an SVL design to an @(see sv::svex-alist)." :long " <p> Using @(see rp::rp-rewriter), converts an SVL design usign svl-run to an @(see sv::svex-alist). </p> <code> @(' (svl-run->svex-alist :modname <modname> :svl-design <svl-design> :binds-ins-alist <binds-ins-alist> :binds-out-alist <binds-out-alist> :svex-alist-name <svex-alist-name> :rw-rule-name <rw-rule-name>) ') </code> <p>Users should provide a value for all the keys.</p> <p>modname: name of the main module in an SVL design.</p> <p>svl-design: SVL design constant. </p> <p>binds-ins-alist: Input simulation pattern constant similar to inputs key of @(see acl2::defsvtv). </p> <p>binds-out-alist: Output simulation pattern constant similar to outputs key of @(see acl2::defsvtv). </p> <p>svex-alist-name: when the SVL-design is converted to an svex-alist, the program will create a constant provided by svex-alist-name.</p> <p> rw-rule-name: the program also creates a rewrite rule with this given name. The LHS of this rewrite rule is svl-run of the given module with given configuration, and the RHS is svex-alist-eval of the newly generated svex-alist. </p> <p>The keys in created svex-alist are the variables designated in binds-out-alist. The variables in the values (svexes) share the same name as the variables from binds-ins-alist. </p> <p> An example call to svl-run-compose is given below. It submits an event that exports svl-run-top-module-composed and *svl-run-top-module-composed*. <code> @(' (svl-run->svex-alist :modname \"top_module\" :binds-ins-alist *ins-alist* :binds-out-alist *outs-alist* :svl-design *svl-netlist* :rw-rule-name svl-run-top-module-composed :svex-alist-name *svl-run-top-module-composed*) ') </code> </p> <p> This will produce a constant *svl-run-top-module-composed*, which has the svex-alist representation of the given svl-run instance; and a rewrite rule with the name svl-run-top-module-composed, which rewrites the svl-run instance to evaluation of this svex-alist. See @(see svl::svl-run) for concrete examples of the first four keys (:modname, :binds-ins-alist, :binds-out-alist, :svl-design). </p> ")
true
; SVL - Listener-based Hierachical Symbolic Vector Hardware Analysis Framework ; Copyright (C) 2019 Centaur Technology ; ; License: (An MIT/X11-style license) ; ; Permission is hereby granted, free of charge, to any person obtaining a ; copy of this software and associated documentation files (the "Software"), ; to deal in the Software without restriction, including without limitation ; the rights to use, copy, modify, merge, publish, distribute, sublicense, ; and/or sell copies of the Software, and to permit persons to whom the ; Software is furnished to do so, subject to the following conditions: ; ; The above copyright notice and this permission notice shall be included in ; all copies or substantial portions of the Software. ; ; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR ; IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, ; FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE ; AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER ; LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING ; FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER ; DEALINGS IN THE SOFTWARE. ; ; Original author: PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> ;; PI:NAME:<NAME>END_PI (in-package "SVL") (include-book "centaur/sv/svex/eval" :dir :system) (include-book "projects/rp-rewriter/top" :dir :system) (include-book "centaur/svl/svex-simplify" :dir :system) (include-book "centaur/svl/svl-openers" :dir :system) (include-book "centaur/svl/svexl/svexl-correct" :dir :system) (local (include-book "projects/rp-rewriter/proofs/rp-rw-lemmas" :dir :system)) (rp::def-rp-rule$ t nil assoc-equal-opener-when-not-equal (implies (not (equal key1 key2)) (equal (assoc-equal key1 (cons (cons key2 val) rest)) (assoc-equal key1 rest)))) (rp::def-rp-rule$ t nil assoc-equal-opener-when-equal (implies t (equal (assoc-equal key (cons (cons key val) rest)) (cons key val)))) ;; :i-am-here ;; (rp::def-rp-rule$ ;; t t ;; bits-of-bits-exact-match ;; (implies (and (natp x) ;; (natp y)) ;; (equal (bits (bits term x y) x y ) ;; (bits term x y ))) ;; :hints (("Goal" ;; :in-theory (e/d () ())))) (defconst *svl-compose-rules* (reverse '(svex-alist-eval-opener-nil svex-alist-eval-opener-cons ;;svex-eval-is-svex-eval-wog ;;svexlist-eval-is-svexlist-eval-wog svl-start-env-opener-error svl-start-env-cons-1 svl-start-env-nil svl-start-env-cons-2 svl-retrieve-values-opener-error svl-retrieve-values-nil svl-retrieve-values-cons-1 svl-retrieve-values-cons-2 save-wires-to-env-wires-opener-error save-wires-to-env-wires-cons-1 save-wires-to-env-wires-nil save-wires-to-env-wires-cons-2 save-wires-to-env-wires-cons-3 svex-env-append-opener-error svex-env-append-opener-cons svex-env-append-opener-nil create-next-env-for-wires-opener-nil create-next-env-for-wires-opener-cons svl-save-mod-outputs-opener-error svl-save-mod-outputs-nil svl-save-mod-outputs-cons svl-well-ranked-module-is-svl-well-ranked-module$ svl-run-phase-opener-error svl-run-phase-occs-opener-error svl-run-phase-is-svl-run-phase-wog svl-run-phase-occs-is-svl-run-phase-occs-wog svl-run-phase-wog-opener-error svl-run-phase-wog-opener ;;rp::svl-run-phase-wog-opener_lambda-opener svl-run-phase-occs-wog-opener-error svl-run-phase-occs-wog-opener-nil svl-run-phase-occs-wog-opener-cons-assign svl-run-phase-occs-wog-opener-cons-module ;;rp::svl-run-phase-occs-wog-opener-cons-module_lambda-opener pairlis3-opener-error pairlis3-opener-done pairlis3-opener-cons svl-run-save-output-opener-error svl-run-save-output-opener-nil svl-run-save-output-opener-cons ;;rp::svl-run-save-output-opener-cons_lambda-opener svl-run-aux-opener-error svl-run-aux-wog-opener-error svl-run-aux-is-svl-run-aux-wog svl-run-aux-wog-opener-nil svl-run-aux-opener-cons ;;rp::svl-run-aux-opener-cons_lambda-opener svl-run-opener-error svl-run-def-opener ;;rp::svl-run-def-opener_lambda-opener sv::4veclist-p-of-cons SV::SVEX-ENV-P-when-cons SV::SVEX-ENV-FIX-opener SV::SVEX-ENV-P-nil RP::CONSP-CONS svexlist-list-eval-wog-opener-error svexlist-list-eval-wog-opener-cons svexlist-list-eval-wog-opener-nil ;;svexlist-eval-wog-is-svexlist-eval svexlist-eval-wog-cons-def svexlist-eval-wog-nil-def rp::make-fast-alist-def return-last entry-4vec-fix cdr-cons car-cons acons assoc-equal-opener-when-not-equal assoc-equal-opener-when-equal append-of-cons 4vec-part-install-is-sbits-without-inserting-bits ;;4vec-part-install-is-sbits 4vec-part-select-is-bits svexllist-correct svexl-correct svexl-node-kind-is-svexl-node-kind-wog svexl-node-kind-wog-is-svexl-node-kind svexl-nodelist-eval-wog-of-cons svexl-nodelist-eval-wog-of-nil svexllist-eval-is-svexllist-eval-wog svexl-eval-is-svexl-eval-wog svexl-eval-wog-for-rp ;;rp::svexl-eval-wog-opener_lambda-opener svex-env-fastlookup-wog-def RP::APPEND-OF-NIL SVEXL-EVAL-AUX-WOG-nil svexl-eval-aux-wog-cons ;;rp::svexl-eval-aux-wog-cons_lambda-opener svexl-node-eval-is-svexl-node-eval-wog svexl-nodelist-eval-is-svexl-nodelist-eval-wog svexl-eval-aux-is-svexl-eval-aux-wog rp::force$-fail rp::force$-of-t ))) (define alist-term-to-entry-list (term) (case-match term (('cons ('cons key val) rest) (b* (((mv keys vals) (alist-term-to-entry-list rest))) (mv (cons key keys) (cons val vals)))) (''nil (mv nil nil)) (& (mv (hard-error 'alist-term-to-entry-list "Unexpected alist-term ~p0 ~%" (list (cons #\0 term))) nil)))) (local (Include-Book "projects/rp-rewriter/proofs/extract-formula-lemmas" :dir :system)) (local (Include-Book "projects/rp-rewriter/proofs/rp-state-functions-lemmas" :dir :system)) (define rw-svl-run-to-svex-alist ((term rp::rp-termp) &key (context 'nil) (state 'state) (rp::rp-state 'rp::rp-state)) :guard (and (rp::rp-term-listp context)) :verify-guards nil :prepwork ((local (defthm valid-rw-step-limit (implies (rp::rp-statep rp::rp-state) (and (natp (rp::rw-step-limit rp-state)) (unsigned-byte-p 58 (rp::rw-step-limit rp-state)) (integerp (rp::rw-step-limit rp-state)))) :hints (("Goal" :do-not-induct t :in-theory (e/d (rp::rp-statep RP::RW-STEP-LIMITP) (unsigned-byte-p)))))) (local (defthm rp-statep-of-not-simplified-action (implies (and (rp::rp-statep rp-state) (symbolp x)) (RP::RP-STATEP (RP::UPDATE-NOT-SIMPLIFIED-ACTION x RP-STATE))) :hints (("Goal" :in-theory (e/d (RP::RP-STATEP) ()))))) (local (in-theory (e/d () (unsigned-byte-p natp RP::UPDATE-NOT-SIMPLIFIED-ACTION RP::NOT-SIMPLIFIED-ACTION rp::rw-step-limit))))) (b* ((world (w state)) ;; do not let rp-rewriter complain when simplified term is not ''t (- (rp::check-if-clause-processor-up-to-date world)) (tmp-rp-not-simplified-action (rp::not-simplified-action rp::rp-state)) (rp::rp-state (rp::update-not-simplified-action :none rp::rp-state)) (rp::rp-state (rp::rp-state-new-run rp::rp-state)) (rp::rp-state (rp::rp-state-init-rules nil nil nil rp::rp-state state)) ((mv context rp::rp-state) (rp::rp-rw-subterms context nil nil nil (rp::rw-step-limit rp::rp-state) rp::rp-state state)) ((mv rw rp::rp-state) (rp::rp-rw term nil context nil nil (rp::rw-step-limit rp::rp-state) rp::rp-state state)) (rp::rp-state (rp::update-not-simplified-action tmp-rp-not-simplified-action rp::rp-state)) ((mv keys vals) (alist-term-to-entry-list rw)) ((mv err svexlist) (svl::4vec-to-svex-lst vals nil t)) #|((mv err svex-res) (svl::4vec-to-svex rw nil nil))||# (- (and err (hard-error ; ; 'rw-svl-run-to-svex-alist ; ; "There was a problem while converting the term below to its ~ svex equivalent. Read above for the printed messages. ~p0 ~%" (list (cons #\0 rw))))) (svex-alist (pairlis$ (rp::unquote-all keys) svexlist)) ) (mv svex-alist rp::rp-state)) /// (Local (defthm true-listp-of-unquote-all (implies (true-listp x) (true-listp (rp::unquote-all x))))) (Local (defthm true-listp-of-alist-term-to-entry-list (implies t;; (true-listp x) (true-listp (mv-nth 0 (alist-term-to-entry-list x)))) :hints (("Goal" :in-theory (e/d (alist-term-to-entry-list) ()))))) (local (defthm unsigned-byte-p-58-of-rw-step-limit (implies (force (rp::rp-statep rp::rp-state)) (UNSIGNED-BYTE-P 58 (RP::RW-STEP-LIMIT rp::rp-state))))) (verify-guards rw-svl-run-to-svex-alist-fn :hints (("Goal" :do-not-induct t :in-theory (e/d (rp::rp-statep rp::not-simplified-action rp::not-simplified-actionp) (rp::rw-step-limit)))))) (progn (define svl-run-to-svex-alist-create-env-aux (vars) (if (atom vars) ''nil `(cons (cons ',(car vars) ,(car vars)) ,(svl-run-to-svex-alist-create-env-aux (cdr vars))))) (define get-vars-from-port-binds (port-binds) :mode :program (b* ((lst (strip-cdrs port-binds)) (lst (acl2::flatten lst))) (loop$ for x in lst when (and (symbolp x) (let* ((x (symbol-name x))) (and (not (equal x "_")) (not (equal x "~")) (not (equal x "X")) (not (equal x "-")) (not (equal x "x"))))) collect x))) (define svl-run-to-svex-alist-fn-create-env (binds-ins-alist) :mode :program (b* ((vars (get-vars-from-port-binds binds-ins-alist))) `(make-fast-alist ,(svl-run-to-svex-alist-create-env-aux vars)))) (define svl-run-to-svex-alist-create-hyp (binds-ins-alist) :mode :program (b* ((vars (get-vars-from-port-binds binds-ins-alist))) (loop$ for x in vars collect `(sv::4vec-p ,x))))) (define svl-run->svex-alist-aux (&key modname binds-ins-alist binds-out-alist svl-design svex-alist-name rw-rule-name) (b* (((unless (and modname binds-ins-alist binds-out-alist svl-design svex-alist-name rw-rule-name)) (hard-error 'svl-run-compose-fn "You need to assign values to keys ~ modname~ binds-ins-alist~ binds-out-alist~ svl-design~ svex-alist-name rw-rule-name ~%" nil))) `(encapsulate nil (local (rp::disable-all-rules)) (local (rp::enable-rules *svl-compose-rules*)) (local (memoize 'rp::rp-equal)) (local (rp::disable-exc-counterpart fmt-to-comment-window)) (local (rp::disable-all-meta-rules)) (local (rp::enable-meta-rules ;; bits-of-meta-fn ;; concat-meta ;; 4vec-rsh-of-meta svex-eval-wog-meta-main svexl-node-eval-wog-meta-main rp::HONS-ACONS-META rp::FAST-ALIST-FREE-META rp::ASSOC-EQ-VALS-META rp::HONS-GET-META rp::RP-EQUAL-META rp::MV-NTH-META)) (with-output :off :all :gag-mode nil (make-event (b* ((env (svl-run-to-svex-alist-fn-create-env ,binds-ins-alist)) (?hyp (svl-run-to-svex-alist-create-hyp ,binds-ins-alist)) (?hyp (append hyp (list `(equal env ,env)))) (?hyp (list '(sv::svex-env-p svex-env))) (term `(svl::svl-run ',,modname svex-env ',,binds-ins-alist ',,binds-out-alist ',,svl-design)) ((mv svex-alist rp::rp-state) (rw-svl-run-to-svex-alist term :context hyp))) (mv nil `(progn (defconst ,',svex-alist-name ',svex-alist) (defthmd ,',rw-rule-name (implies (and ,@hyp) (equal (svl::svl-run ,',modname svex-env ,',binds-ins-alist ,',binds-out-alist ,',svl-design) (sv::svex-alist-eval ,',svex-alist-name svex-env))) :hints (("Goal" :do-not-induct t :rw-cache-state nil :do-not '(preprocess generalize fertilize) :clause-processor (rp::rp-cl :runes nil :new-synps nil))) ) #|(rp::disable-rules '(,',rw-rule-name))||# #|(in-theory (disable ,',rw-rule-name))||# (value-triple (cw "~%An svex-alist ~p0 and a disabled rewrite ~ rule ~p1 are created. ~%~%" ',',svex-alist-name ',',rw-rule-name)) ) state rp::rp-state))))))) (defmacro svl-run->svex-alist (&key modname binds-ins-alist binds-out-alist svl-design svex-alist-name rw-rule-name) (svl-run->svex-alist-aux :modname modname :binds-ins-alist binds-ins-alist :binds-out-alist binds-out-alist :svl-design svl-design :rw-rule-name rw-rule-name :svex-alist-name svex-alist-name)) (xdoc::defxdoc svl-run->svex-alist :parents (acl2::svl) :short "Convert an SVL design to an @(see sv::svex-alist)." :long " <p> Using @(see rp::rp-rewriter), converts an SVL design usign svl-run to an @(see sv::svex-alist). </p> <code> @(' (svl-run->svex-alist :modname <modname> :svl-design <svl-design> :binds-ins-alist <binds-ins-alist> :binds-out-alist <binds-out-alist> :svex-alist-name <svex-alist-name> :rw-rule-name <rw-rule-name>) ') </code> <p>Users should provide a value for all the keys.</p> <p>modname: name of the main module in an SVL design.</p> <p>svl-design: SVL design constant. </p> <p>binds-ins-alist: Input simulation pattern constant similar to inputs key of @(see acl2::defsvtv). </p> <p>binds-out-alist: Output simulation pattern constant similar to outputs key of @(see acl2::defsvtv). </p> <p>svex-alist-name: when the SVL-design is converted to an svex-alist, the program will create a constant provided by svex-alist-name.</p> <p> rw-rule-name: the program also creates a rewrite rule with this given name. The LHS of this rewrite rule is svl-run of the given module with given configuration, and the RHS is svex-alist-eval of the newly generated svex-alist. </p> <p>The keys in created svex-alist are the variables designated in binds-out-alist. The variables in the values (svexes) share the same name as the variables from binds-ins-alist. </p> <p> An example call to svl-run-compose is given below. It submits an event that exports svl-run-top-module-composed and *svl-run-top-module-composed*. <code> @(' (svl-run->svex-alist :modname \"top_module\" :binds-ins-alist *ins-alist* :binds-out-alist *outs-alist* :svl-design *svl-netlist* :rw-rule-name svl-run-top-module-composed :svex-alist-name *svl-run-top-module-composed*) ') </code> </p> <p> This will produce a constant *svl-run-top-module-composed*, which has the svex-alist representation of the given svl-run instance; and a rewrite rule with the name svl-run-top-module-composed, which rewrites the svl-run instance to evaluation of this svex-alist. See @(see svl::svl-run) for concrete examples of the first four keys (:modname, :binds-ins-alist, :binds-out-alist, :svl-design). </p> ")
[ { "context": "le\n :name \"creole\"\n :version \"0.1.2\"\n :author \"Takeru Ohta\"\n :description \"Convert between multibyte charse", "end": 96, "score": 0.9998779296875, "start": 85, "tag": "NAME", "value": "Takeru Ohta" } ]
creole.asd
sile/creole
1
(in-package :asdf) (defsystem creole :name "creole" :version "0.1.2" :author "Takeru Ohta" :description "Convert between multibyte charset and unicode string" :depends-on (:charseq) :serial t :components ((:file "package") (:file "util") (:file "constant") (:file "trie") (:file "external-format") (:file "utf16") (:file "utf8") (:file "string-to-octets") (:file "octets-to-string")))
85248
(in-package :asdf) (defsystem creole :name "creole" :version "0.1.2" :author "<NAME>" :description "Convert between multibyte charset and unicode string" :depends-on (:charseq) :serial t :components ((:file "package") (:file "util") (:file "constant") (:file "trie") (:file "external-format") (:file "utf16") (:file "utf8") (:file "string-to-octets") (:file "octets-to-string")))
true
(in-package :asdf) (defsystem creole :name "creole" :version "0.1.2" :author "PI:NAME:<NAME>END_PI" :description "Convert between multibyte charset and unicode string" :depends-on (:charseq) :serial t :components ((:file "package") (:file "util") (:file "constant") (:file "trie") (:file "external-format") (:file "utf16") (:file "utf8") (:file "string-to-octets") (:file "octets-to-string")))
[ { "context": "***************************\n;;; Copyright (c) 1991 Venue\n;;; All rights reserved.\n;;; ********************", "end": 185, "score": 0.99697345495224, "start": 180, "tag": "NAME", "value": "Venue" }, { "context": "+Genera-Release-8\t Rel-8\n\t #+imach Ivory\n\t #+Cloe-Runtime\t Cloe\n #+Lucid ", "end": 7224, "score": 0.5063250660896301, "start": 7223, "tag": "NAME", "value": "I" }, { "context": ":make-buffer-current b))))\n\n\n;;;\n;;; [email protected]\n;;; z30083%[email protected]", "end": 28207, "score": 0.999563455581665, "start": 28189, "tag": "EMAIL", "value": "[email protected]" }, { "context": ";;\n;;; [email protected]\n;;; z30083%[email protected]\n;;; [email protected]\n;;; mcvax!harlqn.co.uk!ch", "end": 28261, "score": 0.9172744750976562, "start": 28219, "tag": "EMAIL", "value": "[email protected]" }, { "context": "083%[email protected]\n;;; [email protected]\n;;; [email protected]\n;;; \n#+", "end": 28285, "score": 0.9997096657752991, "start": 28266, "tag": "EMAIL", "value": "[email protected]" }, { "context": "relay.csnet\n;;; [email protected]\n;;; [email protected]\n;;; \n#+Genera\n(defun mai", "end": 28302, "score": 0.7114169597625732, "start": 28300, "tag": "EMAIL", "value": "qn" }, { "context": "ay.csnet\n;;; [email protected]\n;;; [email protected]\n;;; \n#+Genera\n(defun mail-c", "end": 28305, "score": 0.7974008917808533, "start": 28303, "tag": "EMAIL", "value": "co" }, { "context": "csnet\n;;; [email protected]\n;;; [email protected]\n;;; \n#+Genera\n(defun mail-clos", "end": 28308, "score": 0.8120958209037781, "start": 28306, "tag": "EMAIL", "value": "uk" }, { "context": "et\n;;; [email protected]\n;;; [email protected]\n;;; \n#+Genera\n(defun mail-clos (to)\n (let* ((ori", "end": 28327, "score": 0.9997007250785828, "start": 28309, "tag": "EMAIL", "value": "[email protected]" } ]
clos/defsys.lisp
FultonBrowne/medley
152
;;;-*-Mode:LISP; Package:(CLOS LISP 1000); Base:10; Syntax:Common-lisp -*- ;;; ;;; ************************************************************************* ;;; Copyright (c) 1991 Venue ;;; All rights reserved. ;;; ************************************************************************* ;;; ;;; Some support stuff for compiling and loading CLOS. It would be nice if ;;; there was some portable make-system we could all agree to share for a ;;; while. At least until people really get databases and stuff. ;;; ;;; *** *** ;;; *** DIRECTIONS FOR INSTALLING CLOS AT YOUR SITE *** ;;; *** *** ;;; ;;; To get CLOS working at your site you should: ;;; ;;; - Get all the CLOS source files from Xerox. The complete list of source ;;; file names can be found in the defsystem for CLOS which appears towards ;;; the end of this file. ;;; ;;; - Edit the variable *clos-directory* below to specify the directory at ;;; your site where the clos sources and binaries will be. This variable ;;; can be found by searching from this point for the string "***" in ;;; this file. ;;; ;;; - Use the function (clos::compile-clos) to compile CLOS for your site. ;;; ;;; - Once CLOS has been compiled it can be loaded with (clos::load-clos). ;;; Note that CLOS cannot be loaded on top of itself, nor can it be ;;; loaded into the same world it was compiled in. ;;; (in-package "CLOS" :use (list (or (find-package :walker) (make-package :walker :use '(:lisp))) (or (find-package :iterate) (make-package :iterate :use '(:lisp :walker))) (find-package :lisp))) (export (intern (symbol-name :iterate) ;Have to do this here, (find-package :iterate)) ;because in the defsystem (find-package :iterate)) ;(later in this file) ;we use the symbol iterate ;to name the file ;;; ;;; Sure, its weird for this to be here, but in order to follow the rules ;;; about order of export and all that stuff, we can't put it in PKG before ;;; we want to use it. ;;; (defvar *the-clos-package* (find-package :clos)) (defvar *clos-system-date* "5/10/91 Interim CLOS release") ;;; ;;; Various hacks to get people's *features* into better shape. ;;; (eval-when (compile load eval) #+(and Symbolics Lispm) (multiple-value-bind (major minor) (sct:get-release-version) (etypecase minor (integer) (string (setf minor (parse-integer minor :junk-allowed t)))) (pushnew :genera *features*) (ecase major ((6) (pushnew :genera-release-6 *features*)) ((7) (pushnew :genera-release-7 *features*) (ecase minor ((0 1) (pushnew :genera-release-7-1 *features*)) ((2) (pushnew :genera-release-7-2 *features*)) ((3) (pushnew :genera-release-7-3 *features*)) ((4) (pushnew :genera-release-7-4 *features*)))) ((8) (pushnew :genera-release-8 *features*) (ecase minor ((0) (pushnew :genera-release-8-0 *features*)) ((1) (pushnew :genera-release-8-1 *features*)))))) #+CLOE-Runtime (let ((version (lisp-implementation-version))) (when (string-equal version "2.0" :end1 (min 3 (length version))) (pushnew :cloe-release-2 *features*))) (dolist (feature *features*) (when (and (symbolp feature) ;3600!! (equal (symbol-name feature) "CMU")) (pushnew :CMU *features*))) #+TI (if (eq (si:local-binary-file-type) :xld) (pushnew ':ti-release-3 *features*) (pushnew ':ti-release-2 *features*)) #+Lucid (when (search "IBM RT PC" (machine-type)) (pushnew :ibm-rt-pc *features*)) #+ExCL (cond ((search "sun3" (lisp-implementation-version)) (push :sun3 *features*)) ((search "sun4" (lisp-implementation-version)) (push :sun4 *features*))) #+(and HP Lucid) (push :HP-Lucid *features*) #+(and HP (not Lucid)) (push :HP-HPLabs *features*) #+Xerox (case il:makesysname (:lyric (push :Xerox-Lyric *features*)) (otherwise (pushnew :Xerox-Medley *features*))) ;;; ;;; For KCL and IBCL, push the symbol :turbo-closure on the list *features* ;;; if you have installed turbo-closure patch. See the file kcl-mods.text ;;; for details. ;;; ;;; The xkcl version of KCL has this fixed already. ;;; #+xkcl(pushnew :turbo-closure *features*) ) ;;; Yet Another Sort Of General System Facility and friends. ;;; ;;; The entry points are defsystem and operate-on-system. defsystem is used ;;; to define a new system and the files with their load/compile constraints. ;;; Operate-on-system is used to operate on a system defined that has been ;;; defined by defsystem. For example: #|| (defsystem my-very-own-system "/usr/myname/lisp/" ((classes (precom) () ()) (methods (precom classes) (classes) ()) (precom () (classes methods) (classes methods)))) This defsystem should be read as follows: * Define a system named MY-VERY-OWN-SYSTEM, the sources and binaries should be in the directory "/usr/me/lisp/". There are three files in the system, there are named classes, methods and precom. (The extension the filenames have depends on the lisp you are running in.) * For the first file, classes, the (precom) in the line means that the file precom should be loaded before this file is loaded. The first () means that no other files need to be loaded before this file is compiled. The second () means that changes in other files don't force this file to be recompiled. * For the second file, methods, the (precom classes) means that both of the files precom and classes must be loaded before this file can be loaded. The (classes) means that the file classes must be loaded before this file can be compiled. The () means that changes in other files don't force this file to be recompiled. * For the third file, precom, the first () means that no other files need to be loaded before this file is loaded. The first use of (classes methods) means that both classes and methods must be loaded before this file can be compiled. The second use of (classes methods) mean that whenever either classes or methods changes precom must be recompiled. Then you can compile your system with: (operate-on-system 'my-very-own-system :compile) and load your system with: (operate-on-system 'my-very-own-system :load) ||# ;;; (defvar *system-directory*) ;;; ;;; *port* is a list of symbols (in the CLOS package) which represent the ;;; Common Lisp in which we are now running. Many of the facilities in ;;; defsys use the value of *port* rather than #+ and #- to conditionalize ;;; the way they work. ;;; (defvar *port* '(#+Genera Genera ; #+Genera-Release-6 Rel-6 ; #+Genera-Release-7-1 Rel-7 #+Genera-Release-7-2 Rel-7 #+Genera-Release-7-3 Rel-7 #+Genera-Release-7-1 Rel-7-1 #+Genera-Release-7-2 Rel-7-2 #+Genera-Release-7-3 Rel-7-2 ;OK for now #+Genera-Release-7-4 Rel-7-2 ;OK for now #+Genera-Release-8 Rel-8 #+imach Ivory #+Cloe-Runtime Cloe #+Lucid Lucid #+Xerox Xerox #+Xerox-Lyric Xerox-Lyric #+Xerox-Medley Xerox-Medley #+TI TI #+(and dec vax common) Vaxlisp #+KCL KCL #+IBCL IBCL #+excl excl #+(and excl sun4) excl-sun4 #+:CMU CMU #+HP-HPLabs HP-HPLabs #+:gclisp gclisp #+pyramid pyramid #+:coral coral)) ;;; ;;; When you get a copy of CLOS (by tape or by FTP), the sources files will ;;; have extensions of ".lisp" in particular, this file will be defsys.lisp. ;;; The preferred way to install clos is to rename these files to have the ;;; extension which your lisp likes to use for its files. Alternately, it ;;; is possible not to rename the files. If the files are not renamed to ;;; the proper convention, the second line of the following defvar should ;;; be changed to: ;;; (let ((files-renamed-p nil) ;;; ;;; Note: Something people installing CLOS on a machine running Unix ;;; might find useful. If you want to change the extensions ;;; of the source files from ".lisp" to ".lsp", *all* you have ;;; to do is the following: ;;; ;;; % foreach i (*.lisp) ;;; ? mv $i $i:r.lsp ;;; ? end ;;; % ;;; ;;; I am sure that a lot of people already know that, and some ;;; Unix hackers may say, "jeez who doesn't know that". Those ;;; same Unix hackers are invited to fix mv so that I can type ;;; "mv *.lisp *.lsp". ;;; (defvar *pathname-extensions* (let ((files-renamed-p t) (proper-extensions (car '(#+(and Genera (not imach)) ("lisp" . "bin") #+(and Genera imach) ("lisp" . "ibin") #+Cloe-Runtime ("l" . "fasl") #+(and dec common vax (not ultrix)) ("LSP" . "FAS") #+(and dec common vax ultrix) ("lsp" . "fas") #+KCL ("lsp" . "o") #+IBCL ("lsp" . "o") #+Xerox ("lisp" . "dfasl") #+(and Lucid MC68000) ("lisp" . "lbin") #+(and Lucid VAX) ("lisp" . "vbin") #+(and Lucid Prime) ("lisp" . "pbin") #+(and Lucid SUNRise) ("lisp" . "sbin") #+(and Lucid SPARC) ("lisp" . "sbin") #+(and Lucid IBM-RT-PC) ("lisp" . "bbin") #+(and Lucid MIPS) ("lisp" . "mbin") #+(and Lucid PRISM) ("lisp" . "abin") #+(and Lucid PA) ("lisp" . "hbin") #+excl ("cl" . "fasl") #+:CMU ("slisp" . "sfasl") #+HP ("l" . "b") #+TI ("lisp" . #.(string (si::local-binary-file-type))) #+:gclisp ("LSP" . "F2S") #+pyramid ("clisp" . "o") #+:coral ("lisp" . "fasl") )))) (cond ((null proper-extensions) '("l" . "lbin")) ((null files-renamed-p) (cons "lisp" (cdr proper-extensions))) (t proper-extensions)))) (eval-when (compile load eval) (defun get-system (name) (get name 'system-definition)) (defun set-system (name new-value) (setf (get name 'system-definition) new-value)) (defmacro defsystem (name directory files) `(set-system ',name (list #'(lambda () ,directory) (make-modules ',files) ',(mapcar #'car files)))) ) ;;; ;;; The internal datastructure used when operating on a system. ;;; (defstruct (module (:constructor make-module (name)) (:print-function (lambda (m s d) (declare (ignore d)) (format s "#<Module ~A>" (module-name m))))) name load-env comp-env recomp-reasons) (defun make-modules (system-description) (let ((modules ())) (labels ((get-module (name) (or (find name modules :key #'module-name) (progn (setq modules (cons (make-module name) modules)) (car modules)))) (parse-spec (spec) (if (eq spec 't) (reverse (cdr modules)) (case (car spec) (+ (append (reverse (cdr modules)) (mapcar #'get-module (cdr spec)))) (- (let ((rem (mapcar #'get-module (cdr spec)))) (remove-if #'(lambda (m) (member m rem)) (reverse (cdr modules))))) (otherwise (mapcar #'get-module spec)))))) (dolist (file system-description) (let* ((name (car file)) (port (car (cddddr file))) (module nil)) (when (or (null port) (member port *port*)) (setq module (get-module name)) (setf (module-load-env module) (parse-spec (cadr file)) (module-comp-env module) (parse-spec (caddr file)) (module-recomp-reasons module) (parse-spec (cadddr file)))))) (let ((filenames (mapcar #'car system-description))) (sort modules #'(lambda (name1 name2) (member name2 (member name1 filenames))) :key #'module-name))))) (defun make-transformations (modules filter make-transform) (let ((transforms (list nil))) (dolist (m modules) (when (funcall filter m transforms) (funcall make-transform m transforms))) (reverse (cdr transforms)))) (defun make-compile-transformation (module transforms) (unless (dolist (trans transforms) (and (eq (car trans) ':compile) (eq (cadr trans) module) (return t))) (dolist (c (module-comp-env module)) (make-load-transformation c transforms)) (setf (cdr transforms) (remove-if #'(lambda (trans) (and (eq (car trans) :load) (eq (cadr trans) module))) (cdr transforms))) (push `(:compile ,module) (cdr transforms)))) (defvar *being-loaded* ()) (defun make-load-transformation (module transforms) (if (assoc module *being-loaded*) (throw module (setf (cdr transforms) (cdr (assoc module *being-loaded*)))) (let ((*being-loaded* (cons (cons module (cdr transforms)) *being-loaded*))) (catch module (unless (dolist (trans transforms) (when (and (eq (car trans) ':load) (eq (cadr trans) module)) (return t))) (dolist (l (module-load-env module)) (make-load-transformation l transforms)) (push `(:load ,module) (cdr transforms))))))) (defun make-load-without-dependencies-transformation (module transforms) (unless (dolist (trans transforms) (and (eq (car trans) ':load) (eq (cadr trans) module) (return trans))) (push `(:load ,module) (cdr transforms)))) (defun compile-filter (module transforms) (or (dolist (r (module-recomp-reasons module)) (when (dolist (transform transforms) (when (and (eq (car transform) ':compile) (eq (cadr transform) r)) (return t))) (return t))) (null (probe-file (make-binary-pathname (module-name module)))) (> (file-write-date (make-source-pathname (module-name module))) (file-write-date (make-binary-pathname (module-name module)))))) (defun operate-on-system (name mode &optional arg print-only) (let ((system (get-system name))) (unless system (error "Can't find system with name ~S." name)) (let ((*system-directory* (funcall (car system))) (modules (cadr system)) (transformations ())) (labels ((load-source (name pathname) (format t "~&Loading source of ~A..." name) (or print-only (load pathname))) (load-binary (name pathname) (format t "~&Loading binary of ~A..." name) (or print-only (load pathname))) (load-module (m) (let* ((name (module-name m)) (*load-verbose* nil) (binary (make-binary-pathname name))) (load-binary name binary))) (compile-module (m) (format t "~&Compiling ~A..." (module-name m)) (unless print-only (let ((name (module-name m))) (compile-file (make-source-pathname name) :output-file (make-pathname :defaults (make-binary-pathname name) :version :newest))))) (xcl:true (&rest ignore) (declare (ignore ignore)) 't)) (setq transformations (ecase mode (:compile ;; Compile any files that have changed and any other files ;; that require recompilation when another file has been ;; recompiled. (make-transformations modules #'compile-filter #'make-compile-transformation)) (:recompile ;; Force recompilation of all files. (make-transformations modules #'xcl:true #'make-compile-transformation)) (:recompile-some ;; Force recompilation of some files. Also compile the ;; files that require recompilation when another file has ;; been recompiled. (make-transformations modules #'(lambda (m transforms) (or (member (module-name m) arg) (compile-filter m transforms))) #'make-compile-transformation)) (:query-compile ;; Ask the user which files to compile. Compile those ;; and any other files which must be recompiled when ;; another file has been recompiled. (make-transformations modules #'(lambda (m transforms) (or (compile-filter m transforms) (y-or-n-p "Compile ~A?" (module-name m)))) #'make-compile-transformation)) (:confirm-compile ;; Offer the user a chance to prevent a file from being ;; recompiled. (make-transformations modules #'(lambda (m transforms) (and (compile-filter m transforms) (y-or-n-p "Go ahead and compile ~A?" (module-name m)))) #'make-compile-transformation)) (:load ;; Load the whole system. (make-transformations modules #'xcl:true #'make-load-transformation)) (:query-load ;; Load only those files the user says to load. (make-transformations modules #'(lambda (m transforms) (declare (ignore transforms)) (y-or-n-p "Load ~A?" (module-name m))) #'make-load-without-dependencies-transformation)))) (#+Genera compiler:compiler-warnings-context-bind #+TI COMPILER:COMPILER-WARNINGS-CONTEXT-BIND #+:LCL3.0 lucid-common-lisp:with-deferred-warnings #-(or Genera TI :LCL3.0) progn (loop (when (null transformations) (return t)) (let ((transform (pop transformations))) (ecase (car transform) (:compile (compile-module (cadr transform))) (:load (load-module (cadr transform))))))))))) (defun make-source-pathname (name) (make-pathname-internal name :source)) (defun make-binary-pathname (name) (make-pathname-internal name :binary)) (defun make-pathname-internal (name type) (let* ((extension (ecase type (:source (car *pathname-extensions*)) (:binary (cdr *pathname-extensions*)))) (directory (pathname (etypecase *system-directory* (string *system-directory*) (pathname *system-directory*) (cons (ecase type (:source (car *system-directory*)) (:binary (cdr *system-directory*))))))) (pathname (make-pathname :name (string-downcase (string name)) :type extension :defaults directory :version :newest))) #+Genera (setq pathname (zl:send pathname :new-raw-name (pathname-name pathname)) pathname (zl:send pathname :new-raw-type (pathname-type pathname))) pathname)) ;;; *** SITE SPECIFIC CLOS DIRECTORY *** ;;; ;;; *clos-directory* is a variable which specifies the directory clos is stored ;;; in at your site. If the value of the variable is a single pathname, the ;;; sources and binaries should be stored in that directory. If the value of ;;; that directory is a cons, the CAR should be the source directory and the ;;; CDR should be the binary directory. ;;; ;;; By default, the value of *clos-directory* is set to the directory that ;;; this file is loaded from. This makes it simple to keep multiple copies ;;; of CLOS in different places, just load defsys from the same directory as ;;; the copy of CLOS you want to use. ;;; ;;; Note that the value of *CLOS-DIRECTORY* is set using a DEFVAR. This is ;;; done to make it possible for users to set it in their init file and then ;;; load this file. The value set in the init file will override the value ;;; here. ;;; ;;; *** *** (defun load-truename (&optional (errorp nil)) (flet ((bad-time () (when errorp (error "LOAD-TRUENAME called but a file isn't being loaded.")))) #+Lispm (or sys:fdefine-file-pathname (bad-time)) #+excl excl::*source-pathname* #+Xerox (pathname (or (il:fullname *standard-input*) (bad-time))) #+(and dec vax common) (truename (sys::source-file #'load-truename)) ;; ;; The following use of `lucid::' is a kludge for 2.1 and 3.0 ;; compatibility. In 2.1 it was in the SYSTEM package, and i ;; 3.0 it's in the LUCID-COMMON-LISP package. ;; #+LUCID (or lucid::*source-pathname* (bad-time)) #-(or Lispm excl Xerox (and dec vax common) LUCID) nil)) #-Symbolics (defvar *clos-directory* (or (load-truename t) (error "Because load-truename is not implemented in this port~%~ of CLOS, you must manually edit the definition of the~%~ variable *clos-directory* in the file defsys.lisp."))) #+Genera (defvar *clos-directory* (let ((source (load-truename t))) (flet ((subdir (name) (scl:send source :new-pathname :raw-directory (append (scl:send source :raw-directory) (list name))))) (cons source #+genera-release-7-2 (subdir "rel-7-2") #+genera-release-7-3 (subdir "rel-7-3") #+genera-release-7-4 (subdir "rel-7-4") #+genera-release-8-0 (subdir "rel-8-0") #+genera-release-8-1 (subdir "rel-8-1") )))) #+Cloe-Runtime (defvar *clos-directory* (pathname "/usr3/hornig/clos/")) (defsystem clos *clos-directory* ;; ;; file load compile files which port ;; environment environment force the of ;; recompilation ;; of this file ;; ( (patch t t () xerox) (pkg t t ()) (walk (pkg) (pkg) ()) (iterate t t ()) (macros t t ()) (low (pkg macros) t (macros)) (low2 (low) (low) (low) Xerox) (fin t t (low)) (defclass t t (low)) (defs t t (defclass macros iterate)) (fngen t t (low)) (lap t t (low)) (plap t t (low)) (cache t t (low defs)) (dlap t t (defs low fin cache lap)) (boot t t (defs fin)) (vector t t (boot defs cache fin)) (slots t t (vector boot defs low cache fin)) (init t t (vector boot defs low cache fin)) (std-class t t (vector boot defs low cache fin slots)) (cpl t t (vector boot defs low cache fin slots)) (braid t t (boot defs low fin cache)) (fsc t t (defclass boot defs low fin cache)) (methods t t (defclass boot defs low fin cache)) (combin t t (defclass boot defs low fin cache)) (dfun t t (dlap)) (fixup (+ precom1 precom2 precom4) t (boot defs low fin)) (defcombin t t (defclass boot defs low fin)) (ctypes t t (defclass defcombin)) (construct t t (defclass boot defs low)) (env t t (defclass boot defs low fin)) (compat t t ()) (precom1 (dlap) t (defs low cache fin dfun)) (precom2 (dlap) t (defs low cache fin dfun)) (precom4 (dlap) t (defs low cache fin dfun)) (clos-env t t () Xerox) (web-editor t t () Xerox) (new-clos-browser t t () Xerox) )) (defun compile-clos (&optional m) (let (#+:coral(ccl::*warn-if-redefine-kernel* nil) #+Lucid (lcl:*redefinition-action* nil) #+excl (excl::*redefinition-warnings* nil) #+Genera (sys:inhibit-fdefine-warnings t) ) (cond ((null m) (operate-on-system 'clos :compile)) ((eq m :print) (operate-on-system 'clos :compile () t)) ((eq m :query) (operate-on-system 'clos :query-compile)) ((eq m :confirm) (operate-on-system 'clos :confirm-compile)) ((eq m 't) (operate-on-system 'clos :recompile)) ((listp m) (operate-on-system 'clos :compile-from m)) ((symbolp m) (operate-on-system 'clos :recompile-some `(,m)))))) (defun load-clos (&optional m) (let (#+:coral(ccl::*warn-if-redefine-kernel* nil) #+Lucid (lcl:*redefinition-action* nil) #+excl (excl::*redefinition-warnings* nil) #+Genera (sys:inhibit-fdefine-warnings t) ) (cond ((null m) (operate-on-system 'clos :load)) ((eq m :query) (operate-on-system 'clos :query-load))) (pushnew :clos *features*))) #+Genera ;;; Make sure Genera bug mail contains the CLOS bug data. A little ;;; kludgy, but what the heck. If they didn't mean for people to do ;;; this, they wouldn't have made private patch notes be flavored ;;; objects, right? Right. (progn (scl:defflavor clos-private-patch-info ((description)) ()) (scl:defmethod (sct::private-patch-info-description clos-private-patch-info) () (or description (setf description (string-append "CLOS version: " *clos-system-date*)))) (scl:defmethod (sct::private-patch-info-pathname clos-private-patch-info) () *clos-directory*) (unless (find-if #'(lambda (x) (typep x 'clos-private-patch-info)) sct::*private-patch-info*) (push (scl:make-instance 'clos-private-patch-info) sct::*private-patch-info*))) (defun bug-report-info (&optional (stream *standard-output*)) (format stream "~&CLOS system date: ~A~ ~&Lisp Implementation type: ~A~ ~&Lisp Implementation version: ~A~ ~&*features*: ~S" *clos-system-date* (lisp-implementation-type) (lisp-implementation-version) *features*)) ;;;; ;;; ;;; This stuff is not intended for external use. ;;; (defun rename-clos () (dolist (f (cadr (get-system 'clos))) (let ((old nil) (new nil)) (let ((*system-directory* *default-pathname-defaults*)) (setq old (make-source-pathname (car f)))) (setq new (make-source-pathname (car f))) (rename-file old new)))) #+Genera (defun edit-clos () (dolist (f (cadr (get-system 'clos))) (let ((*system-directory* *clos-directory*)) (zwei:find-file (make-source-pathname (car f)))))) #+Genera (defun hardcopy-clos (&optional query-p) (let ((files (mapcar #'(lambda (f) (setq f (car f)) (and (or (not query-p) (y-or-n-p "~A? " f)) f)) (cadr (get-system 'clos)))) (b zwei:*interval*)) (unwind-protect (dolist (f files) (when f (multiple-value-bind (ignore b) (zwei:find-file (make-source-pathname f)) (zwei:hardcopy-buffer b)))) (zwei:make-buffer-current b)))) ;;; ;;; [email protected] ;;; z30083%[email protected] ;;; [email protected] ;;; [email protected] ;;; #+Genera (defun mail-clos (to) (let* ((original-buffer zwei:*interval*) (*system-directory* (pathname "vaxc:/user/ftp/pub/clos/") ;(funcall (car (get-system 'clos))) ) (files (list* 'defsys 'test (caddr (get-system 'clos)))) (total-number (length files)) (file nil) (number-of-lines 0) (i 0) (mail-buffer nil)) (unwind-protect (loop (when (null files) (return nil)) (setq file (pop files)) (incf i) (multiple-value-bind (ignore b) (zwei:find-file (make-source-pathname file)) (setq number-of-lines (zwei:count-lines b)) (zwei:com-mail-internal t :initial-to to :initial-body b :initial-subject (format nil "CLOS file ~A (~A of ~A) ~D lines" file i total-number number-of-lines)) (setq mail-buffer zwei:*interval*) (zwei:com-exit-com-mail) (format t "~&Just sent ~A (~A of ~A)." b i total-number) (zwei:kill-buffer mail-buffer))) (zwei:make-buffer-current original-buffer))))
91906
;;;-*-Mode:LISP; Package:(CLOS LISP 1000); Base:10; Syntax:Common-lisp -*- ;;; ;;; ************************************************************************* ;;; Copyright (c) 1991 <NAME> ;;; All rights reserved. ;;; ************************************************************************* ;;; ;;; Some support stuff for compiling and loading CLOS. It would be nice if ;;; there was some portable make-system we could all agree to share for a ;;; while. At least until people really get databases and stuff. ;;; ;;; *** *** ;;; *** DIRECTIONS FOR INSTALLING CLOS AT YOUR SITE *** ;;; *** *** ;;; ;;; To get CLOS working at your site you should: ;;; ;;; - Get all the CLOS source files from Xerox. The complete list of source ;;; file names can be found in the defsystem for CLOS which appears towards ;;; the end of this file. ;;; ;;; - Edit the variable *clos-directory* below to specify the directory at ;;; your site where the clos sources and binaries will be. This variable ;;; can be found by searching from this point for the string "***" in ;;; this file. ;;; ;;; - Use the function (clos::compile-clos) to compile CLOS for your site. ;;; ;;; - Once CLOS has been compiled it can be loaded with (clos::load-clos). ;;; Note that CLOS cannot be loaded on top of itself, nor can it be ;;; loaded into the same world it was compiled in. ;;; (in-package "CLOS" :use (list (or (find-package :walker) (make-package :walker :use '(:lisp))) (or (find-package :iterate) (make-package :iterate :use '(:lisp :walker))) (find-package :lisp))) (export (intern (symbol-name :iterate) ;Have to do this here, (find-package :iterate)) ;because in the defsystem (find-package :iterate)) ;(later in this file) ;we use the symbol iterate ;to name the file ;;; ;;; Sure, its weird for this to be here, but in order to follow the rules ;;; about order of export and all that stuff, we can't put it in PKG before ;;; we want to use it. ;;; (defvar *the-clos-package* (find-package :clos)) (defvar *clos-system-date* "5/10/91 Interim CLOS release") ;;; ;;; Various hacks to get people's *features* into better shape. ;;; (eval-when (compile load eval) #+(and Symbolics Lispm) (multiple-value-bind (major minor) (sct:get-release-version) (etypecase minor (integer) (string (setf minor (parse-integer minor :junk-allowed t)))) (pushnew :genera *features*) (ecase major ((6) (pushnew :genera-release-6 *features*)) ((7) (pushnew :genera-release-7 *features*) (ecase minor ((0 1) (pushnew :genera-release-7-1 *features*)) ((2) (pushnew :genera-release-7-2 *features*)) ((3) (pushnew :genera-release-7-3 *features*)) ((4) (pushnew :genera-release-7-4 *features*)))) ((8) (pushnew :genera-release-8 *features*) (ecase minor ((0) (pushnew :genera-release-8-0 *features*)) ((1) (pushnew :genera-release-8-1 *features*)))))) #+CLOE-Runtime (let ((version (lisp-implementation-version))) (when (string-equal version "2.0" :end1 (min 3 (length version))) (pushnew :cloe-release-2 *features*))) (dolist (feature *features*) (when (and (symbolp feature) ;3600!! (equal (symbol-name feature) "CMU")) (pushnew :CMU *features*))) #+TI (if (eq (si:local-binary-file-type) :xld) (pushnew ':ti-release-3 *features*) (pushnew ':ti-release-2 *features*)) #+Lucid (when (search "IBM RT PC" (machine-type)) (pushnew :ibm-rt-pc *features*)) #+ExCL (cond ((search "sun3" (lisp-implementation-version)) (push :sun3 *features*)) ((search "sun4" (lisp-implementation-version)) (push :sun4 *features*))) #+(and HP Lucid) (push :HP-Lucid *features*) #+(and HP (not Lucid)) (push :HP-HPLabs *features*) #+Xerox (case il:makesysname (:lyric (push :Xerox-Lyric *features*)) (otherwise (pushnew :Xerox-Medley *features*))) ;;; ;;; For KCL and IBCL, push the symbol :turbo-closure on the list *features* ;;; if you have installed turbo-closure patch. See the file kcl-mods.text ;;; for details. ;;; ;;; The xkcl version of KCL has this fixed already. ;;; #+xkcl(pushnew :turbo-closure *features*) ) ;;; Yet Another Sort Of General System Facility and friends. ;;; ;;; The entry points are defsystem and operate-on-system. defsystem is used ;;; to define a new system and the files with their load/compile constraints. ;;; Operate-on-system is used to operate on a system defined that has been ;;; defined by defsystem. For example: #|| (defsystem my-very-own-system "/usr/myname/lisp/" ((classes (precom) () ()) (methods (precom classes) (classes) ()) (precom () (classes methods) (classes methods)))) This defsystem should be read as follows: * Define a system named MY-VERY-OWN-SYSTEM, the sources and binaries should be in the directory "/usr/me/lisp/". There are three files in the system, there are named classes, methods and precom. (The extension the filenames have depends on the lisp you are running in.) * For the first file, classes, the (precom) in the line means that the file precom should be loaded before this file is loaded. The first () means that no other files need to be loaded before this file is compiled. The second () means that changes in other files don't force this file to be recompiled. * For the second file, methods, the (precom classes) means that both of the files precom and classes must be loaded before this file can be loaded. The (classes) means that the file classes must be loaded before this file can be compiled. The () means that changes in other files don't force this file to be recompiled. * For the third file, precom, the first () means that no other files need to be loaded before this file is loaded. The first use of (classes methods) means that both classes and methods must be loaded before this file can be compiled. The second use of (classes methods) mean that whenever either classes or methods changes precom must be recompiled. Then you can compile your system with: (operate-on-system 'my-very-own-system :compile) and load your system with: (operate-on-system 'my-very-own-system :load) ||# ;;; (defvar *system-directory*) ;;; ;;; *port* is a list of symbols (in the CLOS package) which represent the ;;; Common Lisp in which we are now running. Many of the facilities in ;;; defsys use the value of *port* rather than #+ and #- to conditionalize ;;; the way they work. ;;; (defvar *port* '(#+Genera Genera ; #+Genera-Release-6 Rel-6 ; #+Genera-Release-7-1 Rel-7 #+Genera-Release-7-2 Rel-7 #+Genera-Release-7-3 Rel-7 #+Genera-Release-7-1 Rel-7-1 #+Genera-Release-7-2 Rel-7-2 #+Genera-Release-7-3 Rel-7-2 ;OK for now #+Genera-Release-7-4 Rel-7-2 ;OK for now #+Genera-Release-8 Rel-8 #+imach <NAME>vory #+Cloe-Runtime Cloe #+Lucid Lucid #+Xerox Xerox #+Xerox-Lyric Xerox-Lyric #+Xerox-Medley Xerox-Medley #+TI TI #+(and dec vax common) Vaxlisp #+KCL KCL #+IBCL IBCL #+excl excl #+(and excl sun4) excl-sun4 #+:CMU CMU #+HP-HPLabs HP-HPLabs #+:gclisp gclisp #+pyramid pyramid #+:coral coral)) ;;; ;;; When you get a copy of CLOS (by tape or by FTP), the sources files will ;;; have extensions of ".lisp" in particular, this file will be defsys.lisp. ;;; The preferred way to install clos is to rename these files to have the ;;; extension which your lisp likes to use for its files. Alternately, it ;;; is possible not to rename the files. If the files are not renamed to ;;; the proper convention, the second line of the following defvar should ;;; be changed to: ;;; (let ((files-renamed-p nil) ;;; ;;; Note: Something people installing CLOS on a machine running Unix ;;; might find useful. If you want to change the extensions ;;; of the source files from ".lisp" to ".lsp", *all* you have ;;; to do is the following: ;;; ;;; % foreach i (*.lisp) ;;; ? mv $i $i:r.lsp ;;; ? end ;;; % ;;; ;;; I am sure that a lot of people already know that, and some ;;; Unix hackers may say, "jeez who doesn't know that". Those ;;; same Unix hackers are invited to fix mv so that I can type ;;; "mv *.lisp *.lsp". ;;; (defvar *pathname-extensions* (let ((files-renamed-p t) (proper-extensions (car '(#+(and Genera (not imach)) ("lisp" . "bin") #+(and Genera imach) ("lisp" . "ibin") #+Cloe-Runtime ("l" . "fasl") #+(and dec common vax (not ultrix)) ("LSP" . "FAS") #+(and dec common vax ultrix) ("lsp" . "fas") #+KCL ("lsp" . "o") #+IBCL ("lsp" . "o") #+Xerox ("lisp" . "dfasl") #+(and Lucid MC68000) ("lisp" . "lbin") #+(and Lucid VAX) ("lisp" . "vbin") #+(and Lucid Prime) ("lisp" . "pbin") #+(and Lucid SUNRise) ("lisp" . "sbin") #+(and Lucid SPARC) ("lisp" . "sbin") #+(and Lucid IBM-RT-PC) ("lisp" . "bbin") #+(and Lucid MIPS) ("lisp" . "mbin") #+(and Lucid PRISM) ("lisp" . "abin") #+(and Lucid PA) ("lisp" . "hbin") #+excl ("cl" . "fasl") #+:CMU ("slisp" . "sfasl") #+HP ("l" . "b") #+TI ("lisp" . #.(string (si::local-binary-file-type))) #+:gclisp ("LSP" . "F2S") #+pyramid ("clisp" . "o") #+:coral ("lisp" . "fasl") )))) (cond ((null proper-extensions) '("l" . "lbin")) ((null files-renamed-p) (cons "lisp" (cdr proper-extensions))) (t proper-extensions)))) (eval-when (compile load eval) (defun get-system (name) (get name 'system-definition)) (defun set-system (name new-value) (setf (get name 'system-definition) new-value)) (defmacro defsystem (name directory files) `(set-system ',name (list #'(lambda () ,directory) (make-modules ',files) ',(mapcar #'car files)))) ) ;;; ;;; The internal datastructure used when operating on a system. ;;; (defstruct (module (:constructor make-module (name)) (:print-function (lambda (m s d) (declare (ignore d)) (format s "#<Module ~A>" (module-name m))))) name load-env comp-env recomp-reasons) (defun make-modules (system-description) (let ((modules ())) (labels ((get-module (name) (or (find name modules :key #'module-name) (progn (setq modules (cons (make-module name) modules)) (car modules)))) (parse-spec (spec) (if (eq spec 't) (reverse (cdr modules)) (case (car spec) (+ (append (reverse (cdr modules)) (mapcar #'get-module (cdr spec)))) (- (let ((rem (mapcar #'get-module (cdr spec)))) (remove-if #'(lambda (m) (member m rem)) (reverse (cdr modules))))) (otherwise (mapcar #'get-module spec)))))) (dolist (file system-description) (let* ((name (car file)) (port (car (cddddr file))) (module nil)) (when (or (null port) (member port *port*)) (setq module (get-module name)) (setf (module-load-env module) (parse-spec (cadr file)) (module-comp-env module) (parse-spec (caddr file)) (module-recomp-reasons module) (parse-spec (cadddr file)))))) (let ((filenames (mapcar #'car system-description))) (sort modules #'(lambda (name1 name2) (member name2 (member name1 filenames))) :key #'module-name))))) (defun make-transformations (modules filter make-transform) (let ((transforms (list nil))) (dolist (m modules) (when (funcall filter m transforms) (funcall make-transform m transforms))) (reverse (cdr transforms)))) (defun make-compile-transformation (module transforms) (unless (dolist (trans transforms) (and (eq (car trans) ':compile) (eq (cadr trans) module) (return t))) (dolist (c (module-comp-env module)) (make-load-transformation c transforms)) (setf (cdr transforms) (remove-if #'(lambda (trans) (and (eq (car trans) :load) (eq (cadr trans) module))) (cdr transforms))) (push `(:compile ,module) (cdr transforms)))) (defvar *being-loaded* ()) (defun make-load-transformation (module transforms) (if (assoc module *being-loaded*) (throw module (setf (cdr transforms) (cdr (assoc module *being-loaded*)))) (let ((*being-loaded* (cons (cons module (cdr transforms)) *being-loaded*))) (catch module (unless (dolist (trans transforms) (when (and (eq (car trans) ':load) (eq (cadr trans) module)) (return t))) (dolist (l (module-load-env module)) (make-load-transformation l transforms)) (push `(:load ,module) (cdr transforms))))))) (defun make-load-without-dependencies-transformation (module transforms) (unless (dolist (trans transforms) (and (eq (car trans) ':load) (eq (cadr trans) module) (return trans))) (push `(:load ,module) (cdr transforms)))) (defun compile-filter (module transforms) (or (dolist (r (module-recomp-reasons module)) (when (dolist (transform transforms) (when (and (eq (car transform) ':compile) (eq (cadr transform) r)) (return t))) (return t))) (null (probe-file (make-binary-pathname (module-name module)))) (> (file-write-date (make-source-pathname (module-name module))) (file-write-date (make-binary-pathname (module-name module)))))) (defun operate-on-system (name mode &optional arg print-only) (let ((system (get-system name))) (unless system (error "Can't find system with name ~S." name)) (let ((*system-directory* (funcall (car system))) (modules (cadr system)) (transformations ())) (labels ((load-source (name pathname) (format t "~&Loading source of ~A..." name) (or print-only (load pathname))) (load-binary (name pathname) (format t "~&Loading binary of ~A..." name) (or print-only (load pathname))) (load-module (m) (let* ((name (module-name m)) (*load-verbose* nil) (binary (make-binary-pathname name))) (load-binary name binary))) (compile-module (m) (format t "~&Compiling ~A..." (module-name m)) (unless print-only (let ((name (module-name m))) (compile-file (make-source-pathname name) :output-file (make-pathname :defaults (make-binary-pathname name) :version :newest))))) (xcl:true (&rest ignore) (declare (ignore ignore)) 't)) (setq transformations (ecase mode (:compile ;; Compile any files that have changed and any other files ;; that require recompilation when another file has been ;; recompiled. (make-transformations modules #'compile-filter #'make-compile-transformation)) (:recompile ;; Force recompilation of all files. (make-transformations modules #'xcl:true #'make-compile-transformation)) (:recompile-some ;; Force recompilation of some files. Also compile the ;; files that require recompilation when another file has ;; been recompiled. (make-transformations modules #'(lambda (m transforms) (or (member (module-name m) arg) (compile-filter m transforms))) #'make-compile-transformation)) (:query-compile ;; Ask the user which files to compile. Compile those ;; and any other files which must be recompiled when ;; another file has been recompiled. (make-transformations modules #'(lambda (m transforms) (or (compile-filter m transforms) (y-or-n-p "Compile ~A?" (module-name m)))) #'make-compile-transformation)) (:confirm-compile ;; Offer the user a chance to prevent a file from being ;; recompiled. (make-transformations modules #'(lambda (m transforms) (and (compile-filter m transforms) (y-or-n-p "Go ahead and compile ~A?" (module-name m)))) #'make-compile-transformation)) (:load ;; Load the whole system. (make-transformations modules #'xcl:true #'make-load-transformation)) (:query-load ;; Load only those files the user says to load. (make-transformations modules #'(lambda (m transforms) (declare (ignore transforms)) (y-or-n-p "Load ~A?" (module-name m))) #'make-load-without-dependencies-transformation)))) (#+Genera compiler:compiler-warnings-context-bind #+TI COMPILER:COMPILER-WARNINGS-CONTEXT-BIND #+:LCL3.0 lucid-common-lisp:with-deferred-warnings #-(or Genera TI :LCL3.0) progn (loop (when (null transformations) (return t)) (let ((transform (pop transformations))) (ecase (car transform) (:compile (compile-module (cadr transform))) (:load (load-module (cadr transform))))))))))) (defun make-source-pathname (name) (make-pathname-internal name :source)) (defun make-binary-pathname (name) (make-pathname-internal name :binary)) (defun make-pathname-internal (name type) (let* ((extension (ecase type (:source (car *pathname-extensions*)) (:binary (cdr *pathname-extensions*)))) (directory (pathname (etypecase *system-directory* (string *system-directory*) (pathname *system-directory*) (cons (ecase type (:source (car *system-directory*)) (:binary (cdr *system-directory*))))))) (pathname (make-pathname :name (string-downcase (string name)) :type extension :defaults directory :version :newest))) #+Genera (setq pathname (zl:send pathname :new-raw-name (pathname-name pathname)) pathname (zl:send pathname :new-raw-type (pathname-type pathname))) pathname)) ;;; *** SITE SPECIFIC CLOS DIRECTORY *** ;;; ;;; *clos-directory* is a variable which specifies the directory clos is stored ;;; in at your site. If the value of the variable is a single pathname, the ;;; sources and binaries should be stored in that directory. If the value of ;;; that directory is a cons, the CAR should be the source directory and the ;;; CDR should be the binary directory. ;;; ;;; By default, the value of *clos-directory* is set to the directory that ;;; this file is loaded from. This makes it simple to keep multiple copies ;;; of CLOS in different places, just load defsys from the same directory as ;;; the copy of CLOS you want to use. ;;; ;;; Note that the value of *CLOS-DIRECTORY* is set using a DEFVAR. This is ;;; done to make it possible for users to set it in their init file and then ;;; load this file. The value set in the init file will override the value ;;; here. ;;; ;;; *** *** (defun load-truename (&optional (errorp nil)) (flet ((bad-time () (when errorp (error "LOAD-TRUENAME called but a file isn't being loaded.")))) #+Lispm (or sys:fdefine-file-pathname (bad-time)) #+excl excl::*source-pathname* #+Xerox (pathname (or (il:fullname *standard-input*) (bad-time))) #+(and dec vax common) (truename (sys::source-file #'load-truename)) ;; ;; The following use of `lucid::' is a kludge for 2.1 and 3.0 ;; compatibility. In 2.1 it was in the SYSTEM package, and i ;; 3.0 it's in the LUCID-COMMON-LISP package. ;; #+LUCID (or lucid::*source-pathname* (bad-time)) #-(or Lispm excl Xerox (and dec vax common) LUCID) nil)) #-Symbolics (defvar *clos-directory* (or (load-truename t) (error "Because load-truename is not implemented in this port~%~ of CLOS, you must manually edit the definition of the~%~ variable *clos-directory* in the file defsys.lisp."))) #+Genera (defvar *clos-directory* (let ((source (load-truename t))) (flet ((subdir (name) (scl:send source :new-pathname :raw-directory (append (scl:send source :raw-directory) (list name))))) (cons source #+genera-release-7-2 (subdir "rel-7-2") #+genera-release-7-3 (subdir "rel-7-3") #+genera-release-7-4 (subdir "rel-7-4") #+genera-release-8-0 (subdir "rel-8-0") #+genera-release-8-1 (subdir "rel-8-1") )))) #+Cloe-Runtime (defvar *clos-directory* (pathname "/usr3/hornig/clos/")) (defsystem clos *clos-directory* ;; ;; file load compile files which port ;; environment environment force the of ;; recompilation ;; of this file ;; ( (patch t t () xerox) (pkg t t ()) (walk (pkg) (pkg) ()) (iterate t t ()) (macros t t ()) (low (pkg macros) t (macros)) (low2 (low) (low) (low) Xerox) (fin t t (low)) (defclass t t (low)) (defs t t (defclass macros iterate)) (fngen t t (low)) (lap t t (low)) (plap t t (low)) (cache t t (low defs)) (dlap t t (defs low fin cache lap)) (boot t t (defs fin)) (vector t t (boot defs cache fin)) (slots t t (vector boot defs low cache fin)) (init t t (vector boot defs low cache fin)) (std-class t t (vector boot defs low cache fin slots)) (cpl t t (vector boot defs low cache fin slots)) (braid t t (boot defs low fin cache)) (fsc t t (defclass boot defs low fin cache)) (methods t t (defclass boot defs low fin cache)) (combin t t (defclass boot defs low fin cache)) (dfun t t (dlap)) (fixup (+ precom1 precom2 precom4) t (boot defs low fin)) (defcombin t t (defclass boot defs low fin)) (ctypes t t (defclass defcombin)) (construct t t (defclass boot defs low)) (env t t (defclass boot defs low fin)) (compat t t ()) (precom1 (dlap) t (defs low cache fin dfun)) (precom2 (dlap) t (defs low cache fin dfun)) (precom4 (dlap) t (defs low cache fin dfun)) (clos-env t t () Xerox) (web-editor t t () Xerox) (new-clos-browser t t () Xerox) )) (defun compile-clos (&optional m) (let (#+:coral(ccl::*warn-if-redefine-kernel* nil) #+Lucid (lcl:*redefinition-action* nil) #+excl (excl::*redefinition-warnings* nil) #+Genera (sys:inhibit-fdefine-warnings t) ) (cond ((null m) (operate-on-system 'clos :compile)) ((eq m :print) (operate-on-system 'clos :compile () t)) ((eq m :query) (operate-on-system 'clos :query-compile)) ((eq m :confirm) (operate-on-system 'clos :confirm-compile)) ((eq m 't) (operate-on-system 'clos :recompile)) ((listp m) (operate-on-system 'clos :compile-from m)) ((symbolp m) (operate-on-system 'clos :recompile-some `(,m)))))) (defun load-clos (&optional m) (let (#+:coral(ccl::*warn-if-redefine-kernel* nil) #+Lucid (lcl:*redefinition-action* nil) #+excl (excl::*redefinition-warnings* nil) #+Genera (sys:inhibit-fdefine-warnings t) ) (cond ((null m) (operate-on-system 'clos :load)) ((eq m :query) (operate-on-system 'clos :query-load))) (pushnew :clos *features*))) #+Genera ;;; Make sure Genera bug mail contains the CLOS bug data. A little ;;; kludgy, but what the heck. If they didn't mean for people to do ;;; this, they wouldn't have made private patch notes be flavored ;;; objects, right? Right. (progn (scl:defflavor clos-private-patch-info ((description)) ()) (scl:defmethod (sct::private-patch-info-description clos-private-patch-info) () (or description (setf description (string-append "CLOS version: " *clos-system-date*)))) (scl:defmethod (sct::private-patch-info-pathname clos-private-patch-info) () *clos-directory*) (unless (find-if #'(lambda (x) (typep x 'clos-private-patch-info)) sct::*private-patch-info*) (push (scl:make-instance 'clos-private-patch-info) sct::*private-patch-info*))) (defun bug-report-info (&optional (stream *standard-output*)) (format stream "~&CLOS system date: ~A~ ~&Lisp Implementation type: ~A~ ~&Lisp Implementation version: ~A~ ~&*features*: ~S" *clos-system-date* (lisp-implementation-type) (lisp-implementation-version) *features*)) ;;;; ;;; ;;; This stuff is not intended for external use. ;;; (defun rename-clos () (dolist (f (cadr (get-system 'clos))) (let ((old nil) (new nil)) (let ((*system-directory* *default-pathname-defaults*)) (setq old (make-source-pathname (car f)))) (setq new (make-source-pathname (car f))) (rename-file old new)))) #+Genera (defun edit-clos () (dolist (f (cadr (get-system 'clos))) (let ((*system-directory* *clos-directory*)) (zwei:find-file (make-source-pathname (car f)))))) #+Genera (defun hardcopy-clos (&optional query-p) (let ((files (mapcar #'(lambda (f) (setq f (car f)) (and (or (not query-p) (y-or-n-p "~A? " f)) f)) (cadr (get-system 'clos)))) (b zwei:*interval*)) (unwind-protect (dolist (f files) (when f (multiple-value-bind (ignore b) (zwei:find-file (make-source-pathname f)) (zwei:hardcopy-buffer b)))) (zwei:make-buffer-current b)))) ;;; ;;; unido!ztivax!<EMAIL> ;;; z30083%<EMAIL> ;;; <EMAIL> ;;; mcvax!harl<EMAIL>.<EMAIL>.<EMAIL>!<EMAIL> ;;; #+Genera (defun mail-clos (to) (let* ((original-buffer zwei:*interval*) (*system-directory* (pathname "vaxc:/user/ftp/pub/clos/") ;(funcall (car (get-system 'clos))) ) (files (list* 'defsys 'test (caddr (get-system 'clos)))) (total-number (length files)) (file nil) (number-of-lines 0) (i 0) (mail-buffer nil)) (unwind-protect (loop (when (null files) (return nil)) (setq file (pop files)) (incf i) (multiple-value-bind (ignore b) (zwei:find-file (make-source-pathname file)) (setq number-of-lines (zwei:count-lines b)) (zwei:com-mail-internal t :initial-to to :initial-body b :initial-subject (format nil "CLOS file ~A (~A of ~A) ~D lines" file i total-number number-of-lines)) (setq mail-buffer zwei:*interval*) (zwei:com-exit-com-mail) (format t "~&Just sent ~A (~A of ~A)." b i total-number) (zwei:kill-buffer mail-buffer))) (zwei:make-buffer-current original-buffer))))
true
;;;-*-Mode:LISP; Package:(CLOS LISP 1000); Base:10; Syntax:Common-lisp -*- ;;; ;;; ************************************************************************* ;;; Copyright (c) 1991 PI:NAME:<NAME>END_PI ;;; All rights reserved. ;;; ************************************************************************* ;;; ;;; Some support stuff for compiling and loading CLOS. It would be nice if ;;; there was some portable make-system we could all agree to share for a ;;; while. At least until people really get databases and stuff. ;;; ;;; *** *** ;;; *** DIRECTIONS FOR INSTALLING CLOS AT YOUR SITE *** ;;; *** *** ;;; ;;; To get CLOS working at your site you should: ;;; ;;; - Get all the CLOS source files from Xerox. The complete list of source ;;; file names can be found in the defsystem for CLOS which appears towards ;;; the end of this file. ;;; ;;; - Edit the variable *clos-directory* below to specify the directory at ;;; your site where the clos sources and binaries will be. This variable ;;; can be found by searching from this point for the string "***" in ;;; this file. ;;; ;;; - Use the function (clos::compile-clos) to compile CLOS for your site. ;;; ;;; - Once CLOS has been compiled it can be loaded with (clos::load-clos). ;;; Note that CLOS cannot be loaded on top of itself, nor can it be ;;; loaded into the same world it was compiled in. ;;; (in-package "CLOS" :use (list (or (find-package :walker) (make-package :walker :use '(:lisp))) (or (find-package :iterate) (make-package :iterate :use '(:lisp :walker))) (find-package :lisp))) (export (intern (symbol-name :iterate) ;Have to do this here, (find-package :iterate)) ;because in the defsystem (find-package :iterate)) ;(later in this file) ;we use the symbol iterate ;to name the file ;;; ;;; Sure, its weird for this to be here, but in order to follow the rules ;;; about order of export and all that stuff, we can't put it in PKG before ;;; we want to use it. ;;; (defvar *the-clos-package* (find-package :clos)) (defvar *clos-system-date* "5/10/91 Interim CLOS release") ;;; ;;; Various hacks to get people's *features* into better shape. ;;; (eval-when (compile load eval) #+(and Symbolics Lispm) (multiple-value-bind (major minor) (sct:get-release-version) (etypecase minor (integer) (string (setf minor (parse-integer minor :junk-allowed t)))) (pushnew :genera *features*) (ecase major ((6) (pushnew :genera-release-6 *features*)) ((7) (pushnew :genera-release-7 *features*) (ecase minor ((0 1) (pushnew :genera-release-7-1 *features*)) ((2) (pushnew :genera-release-7-2 *features*)) ((3) (pushnew :genera-release-7-3 *features*)) ((4) (pushnew :genera-release-7-4 *features*)))) ((8) (pushnew :genera-release-8 *features*) (ecase minor ((0) (pushnew :genera-release-8-0 *features*)) ((1) (pushnew :genera-release-8-1 *features*)))))) #+CLOE-Runtime (let ((version (lisp-implementation-version))) (when (string-equal version "2.0" :end1 (min 3 (length version))) (pushnew :cloe-release-2 *features*))) (dolist (feature *features*) (when (and (symbolp feature) ;3600!! (equal (symbol-name feature) "CMU")) (pushnew :CMU *features*))) #+TI (if (eq (si:local-binary-file-type) :xld) (pushnew ':ti-release-3 *features*) (pushnew ':ti-release-2 *features*)) #+Lucid (when (search "IBM RT PC" (machine-type)) (pushnew :ibm-rt-pc *features*)) #+ExCL (cond ((search "sun3" (lisp-implementation-version)) (push :sun3 *features*)) ((search "sun4" (lisp-implementation-version)) (push :sun4 *features*))) #+(and HP Lucid) (push :HP-Lucid *features*) #+(and HP (not Lucid)) (push :HP-HPLabs *features*) #+Xerox (case il:makesysname (:lyric (push :Xerox-Lyric *features*)) (otherwise (pushnew :Xerox-Medley *features*))) ;;; ;;; For KCL and IBCL, push the symbol :turbo-closure on the list *features* ;;; if you have installed turbo-closure patch. See the file kcl-mods.text ;;; for details. ;;; ;;; The xkcl version of KCL has this fixed already. ;;; #+xkcl(pushnew :turbo-closure *features*) ) ;;; Yet Another Sort Of General System Facility and friends. ;;; ;;; The entry points are defsystem and operate-on-system. defsystem is used ;;; to define a new system and the files with their load/compile constraints. ;;; Operate-on-system is used to operate on a system defined that has been ;;; defined by defsystem. For example: #|| (defsystem my-very-own-system "/usr/myname/lisp/" ((classes (precom) () ()) (methods (precom classes) (classes) ()) (precom () (classes methods) (classes methods)))) This defsystem should be read as follows: * Define a system named MY-VERY-OWN-SYSTEM, the sources and binaries should be in the directory "/usr/me/lisp/". There are three files in the system, there are named classes, methods and precom. (The extension the filenames have depends on the lisp you are running in.) * For the first file, classes, the (precom) in the line means that the file precom should be loaded before this file is loaded. The first () means that no other files need to be loaded before this file is compiled. The second () means that changes in other files don't force this file to be recompiled. * For the second file, methods, the (precom classes) means that both of the files precom and classes must be loaded before this file can be loaded. The (classes) means that the file classes must be loaded before this file can be compiled. The () means that changes in other files don't force this file to be recompiled. * For the third file, precom, the first () means that no other files need to be loaded before this file is loaded. The first use of (classes methods) means that both classes and methods must be loaded before this file can be compiled. The second use of (classes methods) mean that whenever either classes or methods changes precom must be recompiled. Then you can compile your system with: (operate-on-system 'my-very-own-system :compile) and load your system with: (operate-on-system 'my-very-own-system :load) ||# ;;; (defvar *system-directory*) ;;; ;;; *port* is a list of symbols (in the CLOS package) which represent the ;;; Common Lisp in which we are now running. Many of the facilities in ;;; defsys use the value of *port* rather than #+ and #- to conditionalize ;;; the way they work. ;;; (defvar *port* '(#+Genera Genera ; #+Genera-Release-6 Rel-6 ; #+Genera-Release-7-1 Rel-7 #+Genera-Release-7-2 Rel-7 #+Genera-Release-7-3 Rel-7 #+Genera-Release-7-1 Rel-7-1 #+Genera-Release-7-2 Rel-7-2 #+Genera-Release-7-3 Rel-7-2 ;OK for now #+Genera-Release-7-4 Rel-7-2 ;OK for now #+Genera-Release-8 Rel-8 #+imach PI:NAME:<NAME>END_PIvory #+Cloe-Runtime Cloe #+Lucid Lucid #+Xerox Xerox #+Xerox-Lyric Xerox-Lyric #+Xerox-Medley Xerox-Medley #+TI TI #+(and dec vax common) Vaxlisp #+KCL KCL #+IBCL IBCL #+excl excl #+(and excl sun4) excl-sun4 #+:CMU CMU #+HP-HPLabs HP-HPLabs #+:gclisp gclisp #+pyramid pyramid #+:coral coral)) ;;; ;;; When you get a copy of CLOS (by tape or by FTP), the sources files will ;;; have extensions of ".lisp" in particular, this file will be defsys.lisp. ;;; The preferred way to install clos is to rename these files to have the ;;; extension which your lisp likes to use for its files. Alternately, it ;;; is possible not to rename the files. If the files are not renamed to ;;; the proper convention, the second line of the following defvar should ;;; be changed to: ;;; (let ((files-renamed-p nil) ;;; ;;; Note: Something people installing CLOS on a machine running Unix ;;; might find useful. If you want to change the extensions ;;; of the source files from ".lisp" to ".lsp", *all* you have ;;; to do is the following: ;;; ;;; % foreach i (*.lisp) ;;; ? mv $i $i:r.lsp ;;; ? end ;;; % ;;; ;;; I am sure that a lot of people already know that, and some ;;; Unix hackers may say, "jeez who doesn't know that". Those ;;; same Unix hackers are invited to fix mv so that I can type ;;; "mv *.lisp *.lsp". ;;; (defvar *pathname-extensions* (let ((files-renamed-p t) (proper-extensions (car '(#+(and Genera (not imach)) ("lisp" . "bin") #+(and Genera imach) ("lisp" . "ibin") #+Cloe-Runtime ("l" . "fasl") #+(and dec common vax (not ultrix)) ("LSP" . "FAS") #+(and dec common vax ultrix) ("lsp" . "fas") #+KCL ("lsp" . "o") #+IBCL ("lsp" . "o") #+Xerox ("lisp" . "dfasl") #+(and Lucid MC68000) ("lisp" . "lbin") #+(and Lucid VAX) ("lisp" . "vbin") #+(and Lucid Prime) ("lisp" . "pbin") #+(and Lucid SUNRise) ("lisp" . "sbin") #+(and Lucid SPARC) ("lisp" . "sbin") #+(and Lucid IBM-RT-PC) ("lisp" . "bbin") #+(and Lucid MIPS) ("lisp" . "mbin") #+(and Lucid PRISM) ("lisp" . "abin") #+(and Lucid PA) ("lisp" . "hbin") #+excl ("cl" . "fasl") #+:CMU ("slisp" . "sfasl") #+HP ("l" . "b") #+TI ("lisp" . #.(string (si::local-binary-file-type))) #+:gclisp ("LSP" . "F2S") #+pyramid ("clisp" . "o") #+:coral ("lisp" . "fasl") )))) (cond ((null proper-extensions) '("l" . "lbin")) ((null files-renamed-p) (cons "lisp" (cdr proper-extensions))) (t proper-extensions)))) (eval-when (compile load eval) (defun get-system (name) (get name 'system-definition)) (defun set-system (name new-value) (setf (get name 'system-definition) new-value)) (defmacro defsystem (name directory files) `(set-system ',name (list #'(lambda () ,directory) (make-modules ',files) ',(mapcar #'car files)))) ) ;;; ;;; The internal datastructure used when operating on a system. ;;; (defstruct (module (:constructor make-module (name)) (:print-function (lambda (m s d) (declare (ignore d)) (format s "#<Module ~A>" (module-name m))))) name load-env comp-env recomp-reasons) (defun make-modules (system-description) (let ((modules ())) (labels ((get-module (name) (or (find name modules :key #'module-name) (progn (setq modules (cons (make-module name) modules)) (car modules)))) (parse-spec (spec) (if (eq spec 't) (reverse (cdr modules)) (case (car spec) (+ (append (reverse (cdr modules)) (mapcar #'get-module (cdr spec)))) (- (let ((rem (mapcar #'get-module (cdr spec)))) (remove-if #'(lambda (m) (member m rem)) (reverse (cdr modules))))) (otherwise (mapcar #'get-module spec)))))) (dolist (file system-description) (let* ((name (car file)) (port (car (cddddr file))) (module nil)) (when (or (null port) (member port *port*)) (setq module (get-module name)) (setf (module-load-env module) (parse-spec (cadr file)) (module-comp-env module) (parse-spec (caddr file)) (module-recomp-reasons module) (parse-spec (cadddr file)))))) (let ((filenames (mapcar #'car system-description))) (sort modules #'(lambda (name1 name2) (member name2 (member name1 filenames))) :key #'module-name))))) (defun make-transformations (modules filter make-transform) (let ((transforms (list nil))) (dolist (m modules) (when (funcall filter m transforms) (funcall make-transform m transforms))) (reverse (cdr transforms)))) (defun make-compile-transformation (module transforms) (unless (dolist (trans transforms) (and (eq (car trans) ':compile) (eq (cadr trans) module) (return t))) (dolist (c (module-comp-env module)) (make-load-transformation c transforms)) (setf (cdr transforms) (remove-if #'(lambda (trans) (and (eq (car trans) :load) (eq (cadr trans) module))) (cdr transforms))) (push `(:compile ,module) (cdr transforms)))) (defvar *being-loaded* ()) (defun make-load-transformation (module transforms) (if (assoc module *being-loaded*) (throw module (setf (cdr transforms) (cdr (assoc module *being-loaded*)))) (let ((*being-loaded* (cons (cons module (cdr transforms)) *being-loaded*))) (catch module (unless (dolist (trans transforms) (when (and (eq (car trans) ':load) (eq (cadr trans) module)) (return t))) (dolist (l (module-load-env module)) (make-load-transformation l transforms)) (push `(:load ,module) (cdr transforms))))))) (defun make-load-without-dependencies-transformation (module transforms) (unless (dolist (trans transforms) (and (eq (car trans) ':load) (eq (cadr trans) module) (return trans))) (push `(:load ,module) (cdr transforms)))) (defun compile-filter (module transforms) (or (dolist (r (module-recomp-reasons module)) (when (dolist (transform transforms) (when (and (eq (car transform) ':compile) (eq (cadr transform) r)) (return t))) (return t))) (null (probe-file (make-binary-pathname (module-name module)))) (> (file-write-date (make-source-pathname (module-name module))) (file-write-date (make-binary-pathname (module-name module)))))) (defun operate-on-system (name mode &optional arg print-only) (let ((system (get-system name))) (unless system (error "Can't find system with name ~S." name)) (let ((*system-directory* (funcall (car system))) (modules (cadr system)) (transformations ())) (labels ((load-source (name pathname) (format t "~&Loading source of ~A..." name) (or print-only (load pathname))) (load-binary (name pathname) (format t "~&Loading binary of ~A..." name) (or print-only (load pathname))) (load-module (m) (let* ((name (module-name m)) (*load-verbose* nil) (binary (make-binary-pathname name))) (load-binary name binary))) (compile-module (m) (format t "~&Compiling ~A..." (module-name m)) (unless print-only (let ((name (module-name m))) (compile-file (make-source-pathname name) :output-file (make-pathname :defaults (make-binary-pathname name) :version :newest))))) (xcl:true (&rest ignore) (declare (ignore ignore)) 't)) (setq transformations (ecase mode (:compile ;; Compile any files that have changed and any other files ;; that require recompilation when another file has been ;; recompiled. (make-transformations modules #'compile-filter #'make-compile-transformation)) (:recompile ;; Force recompilation of all files. (make-transformations modules #'xcl:true #'make-compile-transformation)) (:recompile-some ;; Force recompilation of some files. Also compile the ;; files that require recompilation when another file has ;; been recompiled. (make-transformations modules #'(lambda (m transforms) (or (member (module-name m) arg) (compile-filter m transforms))) #'make-compile-transformation)) (:query-compile ;; Ask the user which files to compile. Compile those ;; and any other files which must be recompiled when ;; another file has been recompiled. (make-transformations modules #'(lambda (m transforms) (or (compile-filter m transforms) (y-or-n-p "Compile ~A?" (module-name m)))) #'make-compile-transformation)) (:confirm-compile ;; Offer the user a chance to prevent a file from being ;; recompiled. (make-transformations modules #'(lambda (m transforms) (and (compile-filter m transforms) (y-or-n-p "Go ahead and compile ~A?" (module-name m)))) #'make-compile-transformation)) (:load ;; Load the whole system. (make-transformations modules #'xcl:true #'make-load-transformation)) (:query-load ;; Load only those files the user says to load. (make-transformations modules #'(lambda (m transforms) (declare (ignore transforms)) (y-or-n-p "Load ~A?" (module-name m))) #'make-load-without-dependencies-transformation)))) (#+Genera compiler:compiler-warnings-context-bind #+TI COMPILER:COMPILER-WARNINGS-CONTEXT-BIND #+:LCL3.0 lucid-common-lisp:with-deferred-warnings #-(or Genera TI :LCL3.0) progn (loop (when (null transformations) (return t)) (let ((transform (pop transformations))) (ecase (car transform) (:compile (compile-module (cadr transform))) (:load (load-module (cadr transform))))))))))) (defun make-source-pathname (name) (make-pathname-internal name :source)) (defun make-binary-pathname (name) (make-pathname-internal name :binary)) (defun make-pathname-internal (name type) (let* ((extension (ecase type (:source (car *pathname-extensions*)) (:binary (cdr *pathname-extensions*)))) (directory (pathname (etypecase *system-directory* (string *system-directory*) (pathname *system-directory*) (cons (ecase type (:source (car *system-directory*)) (:binary (cdr *system-directory*))))))) (pathname (make-pathname :name (string-downcase (string name)) :type extension :defaults directory :version :newest))) #+Genera (setq pathname (zl:send pathname :new-raw-name (pathname-name pathname)) pathname (zl:send pathname :new-raw-type (pathname-type pathname))) pathname)) ;;; *** SITE SPECIFIC CLOS DIRECTORY *** ;;; ;;; *clos-directory* is a variable which specifies the directory clos is stored ;;; in at your site. If the value of the variable is a single pathname, the ;;; sources and binaries should be stored in that directory. If the value of ;;; that directory is a cons, the CAR should be the source directory and the ;;; CDR should be the binary directory. ;;; ;;; By default, the value of *clos-directory* is set to the directory that ;;; this file is loaded from. This makes it simple to keep multiple copies ;;; of CLOS in different places, just load defsys from the same directory as ;;; the copy of CLOS you want to use. ;;; ;;; Note that the value of *CLOS-DIRECTORY* is set using a DEFVAR. This is ;;; done to make it possible for users to set it in their init file and then ;;; load this file. The value set in the init file will override the value ;;; here. ;;; ;;; *** *** (defun load-truename (&optional (errorp nil)) (flet ((bad-time () (when errorp (error "LOAD-TRUENAME called but a file isn't being loaded.")))) #+Lispm (or sys:fdefine-file-pathname (bad-time)) #+excl excl::*source-pathname* #+Xerox (pathname (or (il:fullname *standard-input*) (bad-time))) #+(and dec vax common) (truename (sys::source-file #'load-truename)) ;; ;; The following use of `lucid::' is a kludge for 2.1 and 3.0 ;; compatibility. In 2.1 it was in the SYSTEM package, and i ;; 3.0 it's in the LUCID-COMMON-LISP package. ;; #+LUCID (or lucid::*source-pathname* (bad-time)) #-(or Lispm excl Xerox (and dec vax common) LUCID) nil)) #-Symbolics (defvar *clos-directory* (or (load-truename t) (error "Because load-truename is not implemented in this port~%~ of CLOS, you must manually edit the definition of the~%~ variable *clos-directory* in the file defsys.lisp."))) #+Genera (defvar *clos-directory* (let ((source (load-truename t))) (flet ((subdir (name) (scl:send source :new-pathname :raw-directory (append (scl:send source :raw-directory) (list name))))) (cons source #+genera-release-7-2 (subdir "rel-7-2") #+genera-release-7-3 (subdir "rel-7-3") #+genera-release-7-4 (subdir "rel-7-4") #+genera-release-8-0 (subdir "rel-8-0") #+genera-release-8-1 (subdir "rel-8-1") )))) #+Cloe-Runtime (defvar *clos-directory* (pathname "/usr3/hornig/clos/")) (defsystem clos *clos-directory* ;; ;; file load compile files which port ;; environment environment force the of ;; recompilation ;; of this file ;; ( (patch t t () xerox) (pkg t t ()) (walk (pkg) (pkg) ()) (iterate t t ()) (macros t t ()) (low (pkg macros) t (macros)) (low2 (low) (low) (low) Xerox) (fin t t (low)) (defclass t t (low)) (defs t t (defclass macros iterate)) (fngen t t (low)) (lap t t (low)) (plap t t (low)) (cache t t (low defs)) (dlap t t (defs low fin cache lap)) (boot t t (defs fin)) (vector t t (boot defs cache fin)) (slots t t (vector boot defs low cache fin)) (init t t (vector boot defs low cache fin)) (std-class t t (vector boot defs low cache fin slots)) (cpl t t (vector boot defs low cache fin slots)) (braid t t (boot defs low fin cache)) (fsc t t (defclass boot defs low fin cache)) (methods t t (defclass boot defs low fin cache)) (combin t t (defclass boot defs low fin cache)) (dfun t t (dlap)) (fixup (+ precom1 precom2 precom4) t (boot defs low fin)) (defcombin t t (defclass boot defs low fin)) (ctypes t t (defclass defcombin)) (construct t t (defclass boot defs low)) (env t t (defclass boot defs low fin)) (compat t t ()) (precom1 (dlap) t (defs low cache fin dfun)) (precom2 (dlap) t (defs low cache fin dfun)) (precom4 (dlap) t (defs low cache fin dfun)) (clos-env t t () Xerox) (web-editor t t () Xerox) (new-clos-browser t t () Xerox) )) (defun compile-clos (&optional m) (let (#+:coral(ccl::*warn-if-redefine-kernel* nil) #+Lucid (lcl:*redefinition-action* nil) #+excl (excl::*redefinition-warnings* nil) #+Genera (sys:inhibit-fdefine-warnings t) ) (cond ((null m) (operate-on-system 'clos :compile)) ((eq m :print) (operate-on-system 'clos :compile () t)) ((eq m :query) (operate-on-system 'clos :query-compile)) ((eq m :confirm) (operate-on-system 'clos :confirm-compile)) ((eq m 't) (operate-on-system 'clos :recompile)) ((listp m) (operate-on-system 'clos :compile-from m)) ((symbolp m) (operate-on-system 'clos :recompile-some `(,m)))))) (defun load-clos (&optional m) (let (#+:coral(ccl::*warn-if-redefine-kernel* nil) #+Lucid (lcl:*redefinition-action* nil) #+excl (excl::*redefinition-warnings* nil) #+Genera (sys:inhibit-fdefine-warnings t) ) (cond ((null m) (operate-on-system 'clos :load)) ((eq m :query) (operate-on-system 'clos :query-load))) (pushnew :clos *features*))) #+Genera ;;; Make sure Genera bug mail contains the CLOS bug data. A little ;;; kludgy, but what the heck. If they didn't mean for people to do ;;; this, they wouldn't have made private patch notes be flavored ;;; objects, right? Right. (progn (scl:defflavor clos-private-patch-info ((description)) ()) (scl:defmethod (sct::private-patch-info-description clos-private-patch-info) () (or description (setf description (string-append "CLOS version: " *clos-system-date*)))) (scl:defmethod (sct::private-patch-info-pathname clos-private-patch-info) () *clos-directory*) (unless (find-if #'(lambda (x) (typep x 'clos-private-patch-info)) sct::*private-patch-info*) (push (scl:make-instance 'clos-private-patch-info) sct::*private-patch-info*))) (defun bug-report-info (&optional (stream *standard-output*)) (format stream "~&CLOS system date: ~A~ ~&Lisp Implementation type: ~A~ ~&Lisp Implementation version: ~A~ ~&*features*: ~S" *clos-system-date* (lisp-implementation-type) (lisp-implementation-version) *features*)) ;;;; ;;; ;;; This stuff is not intended for external use. ;;; (defun rename-clos () (dolist (f (cadr (get-system 'clos))) (let ((old nil) (new nil)) (let ((*system-directory* *default-pathname-defaults*)) (setq old (make-source-pathname (car f)))) (setq new (make-source-pathname (car f))) (rename-file old new)))) #+Genera (defun edit-clos () (dolist (f (cadr (get-system 'clos))) (let ((*system-directory* *clos-directory*)) (zwei:find-file (make-source-pathname (car f)))))) #+Genera (defun hardcopy-clos (&optional query-p) (let ((files (mapcar #'(lambda (f) (setq f (car f)) (and (or (not query-p) (y-or-n-p "~A? " f)) f)) (cadr (get-system 'clos)))) (b zwei:*interval*)) (unwind-protect (dolist (f files) (when f (multiple-value-bind (ignore b) (zwei:find-file (make-source-pathname f)) (zwei:hardcopy-buffer b)))) (zwei:make-buffer-current b)))) ;;; ;;; unido!ztivax!PI:EMAIL:<EMAIL>END_PI ;;; z30083%PI:EMAIL:<EMAIL>END_PI ;;; PI:EMAIL:<EMAIL>END_PI ;;; mcvax!harlPI:EMAIL:<EMAIL>END_PI.PI:EMAIL:<EMAIL>END_PI.PI:EMAIL:<EMAIL>END_PI!PI:EMAIL:<EMAIL>END_PI ;;; #+Genera (defun mail-clos (to) (let* ((original-buffer zwei:*interval*) (*system-directory* (pathname "vaxc:/user/ftp/pub/clos/") ;(funcall (car (get-system 'clos))) ) (files (list* 'defsys 'test (caddr (get-system 'clos)))) (total-number (length files)) (file nil) (number-of-lines 0) (i 0) (mail-buffer nil)) (unwind-protect (loop (when (null files) (return nil)) (setq file (pop files)) (incf i) (multiple-value-bind (ignore b) (zwei:find-file (make-source-pathname file)) (setq number-of-lines (zwei:count-lines b)) (zwei:com-mail-internal t :initial-to to :initial-body b :initial-subject (format nil "CLOS file ~A (~A of ~A) ~D lines" file i total-number number-of-lines)) (setq mail-buffer zwei:*interval*) (zwei:com-exit-com-mail) (format t "~&Just sent ~A (~A of ~A)." b i total-number) (zwei:kill-buffer mail-buffer))) (zwei:make-buffer-current original-buffer))))
[ { "context": "(asdf:defsystem #:xcall\n\n :author \"Jean-Philippe Paradis <[email protected]>\"\n\n ;; See the UNLI", "end": 57, "score": 0.9998653531074524, "start": 36, "tag": "NAME", "value": "Jean-Philippe Paradis" }, { "context": "system #:xcall\n\n :author \"Jean-Philippe Paradis <[email protected]>\"\n\n ;; See the UNLICENSE file for details.\n :li", "end": 86, "score": 0.9999176263809204, "start": 59, "tag": "EMAIL", "value": "[email protected]" } ]
xcall.asd
Hexstream-not-yet-ready/xcall
0
(asdf:defsystem #:xcall :author "Jean-Philippe Paradis <[email protected]>" ;; See the UNLICENSE file for details. :license "Public Domain" :description "Maps a template over the cartesian product of trees of alternative forms provided within." :depends-on ("trivial-jumptables" "trivial-macroexpand-all" "bubble-operator-upwards") :version "0.1" :serial cl:t :components ((:file "package") (:file "analyze") (:file "main")) :in-order-to ((asdf:test-op (asdf:test-op #:xcall_tests))))
80362
(asdf:defsystem #:xcall :author "<NAME> <<EMAIL>>" ;; See the UNLICENSE file for details. :license "Public Domain" :description "Maps a template over the cartesian product of trees of alternative forms provided within." :depends-on ("trivial-jumptables" "trivial-macroexpand-all" "bubble-operator-upwards") :version "0.1" :serial cl:t :components ((:file "package") (:file "analyze") (:file "main")) :in-order-to ((asdf:test-op (asdf:test-op #:xcall_tests))))
true
(asdf:defsystem #:xcall :author "PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>" ;; See the UNLICENSE file for details. :license "Public Domain" :description "Maps a template over the cartesian product of trees of alternative forms provided within." :depends-on ("trivial-jumptables" "trivial-macroexpand-all" "bubble-operator-upwards") :version "0.1" :serial cl:t :components ((:file "package") (:file "analyze") (:file "main")) :in-order-to ((asdf:test-op (asdf:test-op #:xcall_tests))))
[ { "context": ";; Ahmad Hisham, Mohammed Al Mehdar, Fred Morcos\n\n(defstruct (FOL", "end": 15, "score": 0.9998564720153809, "start": 3, "tag": "NAME", "value": "Ahmad Hisham" }, { "context": ";; Ahmad Hisham, Mohammed Al Mehdar, Fred Morcos\n\n(defstruct (FOLTerm\n(:print-functio", "end": 35, "score": 0.9998592138290405, "start": 17, "tag": "NAME", "value": "Mohammed Al Mehdar" }, { "context": ";; Ahmad Hisham, Mohammed Al Mehdar, Fred Morcos\n\n(defstruct (FOLTerm\n(:print-function\n ", "end": 48, "score": 0.999839186668396, "start": 37, "tag": "NAME", "value": "Fred Morcos" } ]
Projects/Partial Order Planner/PartialOrderPlanner.lisp
fredmorcos/attic
2
;; Ahmad Hisham, Mohammed Al Mehdar, Fred Morcos (defstruct (FOLTerm (:print-function (lambda (struct stream depth) (declare (ignore depth)) (format stream "[~A ~A ~A]" (FOLTerm-isPositive struct) (FOLTerm-predicateName struct) (FOLTerm-symbolsList struct)))) ) isPositive predicateName symbolsList) (defstruct action preConds name effects) (defstruct link LHS RHS preCond) (defstruct plan actions links orderings) (defparameter plan nil) (defun makeMinimalPlan (start finish) (make-plan :actions (cons start (cons finish '())) :links '() :orderings (cons (make-link :LHS 'Start :RHS 'Finish) '()) ) ) (defun preCondIsComplete (preCond) (dotimes (i (length (plan-links plan))) (setf l (nth i (plan-links plan))) (if (eql (link-RHS l) preCond) 't) ) preCond ) (defun actionIsComplete (action) (dotimes (i (length (action-preConds action))) (setf o (nth i (action-preConds action))) (setf res (preCondIsComplete o)) (if (not (null res)) (return-from actionIsComplete res)) ) ) (defun isSolution () (dotimes (i (length (plan-actions plan))) (setf a (nth i (plan-actions plan))) (setf res (actionIsComplete a)) (if (not (null res)) (return-from isSolution res)) ) ) (defun getOps (preCond operators) (setf res '()) (dotimes (i (length operators)) (setf o (nth i operators)) (dotimes (j (length (action-effects o))) (setf e (nth j (action-effects o))) (princ preCond) (princ e) (setf subs (match preCond e)) ;; (princ subs) ;; (if (not (null subs)) (cons (substitute subs o) res)) ) ) res ) (defun variablep (x) "The variablep function tests if the given symbol is a variable(denoted by ? as first character) or not. It takes one argument as input. It returns t if the first character of x's symbol name is a ? and nil otherwise." ( and (symbolp x) (char= (char (symbol-name x) 0) #\?) )) (defun match (cond1 cond2) (setf l1 (FOLTerm-symbolsList cond1)) (setf l2 (FOLTerm-symbolsList cond2)) (setf res '()) (if (and (predEql cond1 cond2) (eql (length l1) (length l2))) (dotimes (i (length l2)) (setf tmp (nth i l2)) (if (variablep tmp) (if (alreadyAssigned tmp (nth i l1) res) (setf res(cons (cons tmp (cons (nth i l1) '())) res)) (return-from alreadyAssigned nil)) ) ) ) res ) (defun alreadyAssigned (var const list) (dotimes (i (length list)) (if (and (eql var (first (nth i list))) (not (eql const (second (nth i list))))) (return-from alreadyAssigned nil)) ) 't ) (defun predEql (cond1 cond2) (if (and (eql (FOLTerm-isPositive cond1) (FOLTerm-isPositive cond2)) (eql (FOLTerm-predicateName cond1) (FOLTerm-predicateName cond2))) t nil ) ) (defun getPlan (start finish operators) (setf plan (makeMinimalPlan start finish)) ;; (loop (setf subGoal (isSolution)) (princ subGoal) ;; (when (null subGoal) (return p)) (getOps subGoal operators) ;; ) ) (defun main () (setf start (make-action :preConds '() :name (make-FOLTerm :isPositive 't :predicateName 'Start :symbolsList '()) :effects '() )) (setf (action-effects start) (cons (make-FOLTerm :isPositive 't :predicateName 'At :symbolsList '(Home)) (action-effects start))) (setf (action-effects start) (cons (make-FOLTerm :isPositive 't :predicateName 'Sells :symbolsList '(HWS Drill)) (action-effects start))) (setf (action-effects start) (cons (make-FOLTerm :isPositive 't :predicateName 'Sells :symbolsList '(SM Milk)) (action-effects start))) (setf (action-effects start) (cons (make-FOLTerm :isPositive 't :predicateName 'Sells :symbolsList '(SM Banana)) (action-effects start))) (setf finish (make-action :preConds '() :name (make-FOLTerm :isPositive 't :predicateName 'Finish :symbolsList '()) :effects '() )) (setf (action-preConds finish) (cons (make-FOLTerm :isPositive 't :predicateName 'At :symbolsList '(Home)) (action-preConds finish))) (setf (action-preConds finish) (cons (make-FOLTerm :isPositive 't :predicateName 'Have :symbolsList '(Drill)) (action-preConds finish))) (setf (action-preConds finish) (cons (make-FOLTerm :isPositive 't :predicateName 'Have :symbolsList '(Milk)) (action-preConds finish))) (setf (action-preConds finish) (cons (make-FOLTerm :isPositive 't :predicateName 'Have :symbolsList '(Banana)) (action-preConds finish))) (setf go (make-action :preConds '() :name (make-FOLTerm :isPositive 't :predicateName 'Go :symbolsList '(?there)) :effects '() )) (setf (action-preConds go) (cons (make-FOLTerm :isPositive 't :predicateName 'At :symbolsList '(?here)) (action-preConds go))) (setf (action-effects go) (cons (make-FOLTerm :isPositive 't :predicateName 'At :symbolsList '(?there)) (action-effects go))) (setf (action-effects go) (cons (make-FOLTerm :isPositive 'n :predicateName 'At :symbolsList '(?here)) (action-effects go))) (setf buy (make-action :preConds '() :name (make-FOLTerm :isPositive 't :predicateName 'Buy :symbolsList '(?x)) :effects '() )) (setf (action-preConds buy) (cons (make-FOLTerm :isPositive 't :predicateName 'At :symbolsList '(?store)) (action-preConds buy))) (setf (action-preConds buy) (cons (make-FOLTerm :isPositive 't :predicateName 'Sells :symbolsList '(?store ?x)) (action-preConds buy))) (setf (action-effects buy) (cons (make-FOLTerm :isPositive 't :predicateName 'Have :symbolsList '(?x)) (action-effects buy))) (setf operators (cons go (cons buy '()))) (getPlan start finish operators) ;; (linearize p) )
56270
;; <NAME>, <NAME>, <NAME> (defstruct (FOLTerm (:print-function (lambda (struct stream depth) (declare (ignore depth)) (format stream "[~A ~A ~A]" (FOLTerm-isPositive struct) (FOLTerm-predicateName struct) (FOLTerm-symbolsList struct)))) ) isPositive predicateName symbolsList) (defstruct action preConds name effects) (defstruct link LHS RHS preCond) (defstruct plan actions links orderings) (defparameter plan nil) (defun makeMinimalPlan (start finish) (make-plan :actions (cons start (cons finish '())) :links '() :orderings (cons (make-link :LHS 'Start :RHS 'Finish) '()) ) ) (defun preCondIsComplete (preCond) (dotimes (i (length (plan-links plan))) (setf l (nth i (plan-links plan))) (if (eql (link-RHS l) preCond) 't) ) preCond ) (defun actionIsComplete (action) (dotimes (i (length (action-preConds action))) (setf o (nth i (action-preConds action))) (setf res (preCondIsComplete o)) (if (not (null res)) (return-from actionIsComplete res)) ) ) (defun isSolution () (dotimes (i (length (plan-actions plan))) (setf a (nth i (plan-actions plan))) (setf res (actionIsComplete a)) (if (not (null res)) (return-from isSolution res)) ) ) (defun getOps (preCond operators) (setf res '()) (dotimes (i (length operators)) (setf o (nth i operators)) (dotimes (j (length (action-effects o))) (setf e (nth j (action-effects o))) (princ preCond) (princ e) (setf subs (match preCond e)) ;; (princ subs) ;; (if (not (null subs)) (cons (substitute subs o) res)) ) ) res ) (defun variablep (x) "The variablep function tests if the given symbol is a variable(denoted by ? as first character) or not. It takes one argument as input. It returns t if the first character of x's symbol name is a ? and nil otherwise." ( and (symbolp x) (char= (char (symbol-name x) 0) #\?) )) (defun match (cond1 cond2) (setf l1 (FOLTerm-symbolsList cond1)) (setf l2 (FOLTerm-symbolsList cond2)) (setf res '()) (if (and (predEql cond1 cond2) (eql (length l1) (length l2))) (dotimes (i (length l2)) (setf tmp (nth i l2)) (if (variablep tmp) (if (alreadyAssigned tmp (nth i l1) res) (setf res(cons (cons tmp (cons (nth i l1) '())) res)) (return-from alreadyAssigned nil)) ) ) ) res ) (defun alreadyAssigned (var const list) (dotimes (i (length list)) (if (and (eql var (first (nth i list))) (not (eql const (second (nth i list))))) (return-from alreadyAssigned nil)) ) 't ) (defun predEql (cond1 cond2) (if (and (eql (FOLTerm-isPositive cond1) (FOLTerm-isPositive cond2)) (eql (FOLTerm-predicateName cond1) (FOLTerm-predicateName cond2))) t nil ) ) (defun getPlan (start finish operators) (setf plan (makeMinimalPlan start finish)) ;; (loop (setf subGoal (isSolution)) (princ subGoal) ;; (when (null subGoal) (return p)) (getOps subGoal operators) ;; ) ) (defun main () (setf start (make-action :preConds '() :name (make-FOLTerm :isPositive 't :predicateName 'Start :symbolsList '()) :effects '() )) (setf (action-effects start) (cons (make-FOLTerm :isPositive 't :predicateName 'At :symbolsList '(Home)) (action-effects start))) (setf (action-effects start) (cons (make-FOLTerm :isPositive 't :predicateName 'Sells :symbolsList '(HWS Drill)) (action-effects start))) (setf (action-effects start) (cons (make-FOLTerm :isPositive 't :predicateName 'Sells :symbolsList '(SM Milk)) (action-effects start))) (setf (action-effects start) (cons (make-FOLTerm :isPositive 't :predicateName 'Sells :symbolsList '(SM Banana)) (action-effects start))) (setf finish (make-action :preConds '() :name (make-FOLTerm :isPositive 't :predicateName 'Finish :symbolsList '()) :effects '() )) (setf (action-preConds finish) (cons (make-FOLTerm :isPositive 't :predicateName 'At :symbolsList '(Home)) (action-preConds finish))) (setf (action-preConds finish) (cons (make-FOLTerm :isPositive 't :predicateName 'Have :symbolsList '(Drill)) (action-preConds finish))) (setf (action-preConds finish) (cons (make-FOLTerm :isPositive 't :predicateName 'Have :symbolsList '(Milk)) (action-preConds finish))) (setf (action-preConds finish) (cons (make-FOLTerm :isPositive 't :predicateName 'Have :symbolsList '(Banana)) (action-preConds finish))) (setf go (make-action :preConds '() :name (make-FOLTerm :isPositive 't :predicateName 'Go :symbolsList '(?there)) :effects '() )) (setf (action-preConds go) (cons (make-FOLTerm :isPositive 't :predicateName 'At :symbolsList '(?here)) (action-preConds go))) (setf (action-effects go) (cons (make-FOLTerm :isPositive 't :predicateName 'At :symbolsList '(?there)) (action-effects go))) (setf (action-effects go) (cons (make-FOLTerm :isPositive 'n :predicateName 'At :symbolsList '(?here)) (action-effects go))) (setf buy (make-action :preConds '() :name (make-FOLTerm :isPositive 't :predicateName 'Buy :symbolsList '(?x)) :effects '() )) (setf (action-preConds buy) (cons (make-FOLTerm :isPositive 't :predicateName 'At :symbolsList '(?store)) (action-preConds buy))) (setf (action-preConds buy) (cons (make-FOLTerm :isPositive 't :predicateName 'Sells :symbolsList '(?store ?x)) (action-preConds buy))) (setf (action-effects buy) (cons (make-FOLTerm :isPositive 't :predicateName 'Have :symbolsList '(?x)) (action-effects buy))) (setf operators (cons go (cons buy '()))) (getPlan start finish operators) ;; (linearize p) )
true
;; PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI (defstruct (FOLTerm (:print-function (lambda (struct stream depth) (declare (ignore depth)) (format stream "[~A ~A ~A]" (FOLTerm-isPositive struct) (FOLTerm-predicateName struct) (FOLTerm-symbolsList struct)))) ) isPositive predicateName symbolsList) (defstruct action preConds name effects) (defstruct link LHS RHS preCond) (defstruct plan actions links orderings) (defparameter plan nil) (defun makeMinimalPlan (start finish) (make-plan :actions (cons start (cons finish '())) :links '() :orderings (cons (make-link :LHS 'Start :RHS 'Finish) '()) ) ) (defun preCondIsComplete (preCond) (dotimes (i (length (plan-links plan))) (setf l (nth i (plan-links plan))) (if (eql (link-RHS l) preCond) 't) ) preCond ) (defun actionIsComplete (action) (dotimes (i (length (action-preConds action))) (setf o (nth i (action-preConds action))) (setf res (preCondIsComplete o)) (if (not (null res)) (return-from actionIsComplete res)) ) ) (defun isSolution () (dotimes (i (length (plan-actions plan))) (setf a (nth i (plan-actions plan))) (setf res (actionIsComplete a)) (if (not (null res)) (return-from isSolution res)) ) ) (defun getOps (preCond operators) (setf res '()) (dotimes (i (length operators)) (setf o (nth i operators)) (dotimes (j (length (action-effects o))) (setf e (nth j (action-effects o))) (princ preCond) (princ e) (setf subs (match preCond e)) ;; (princ subs) ;; (if (not (null subs)) (cons (substitute subs o) res)) ) ) res ) (defun variablep (x) "The variablep function tests if the given symbol is a variable(denoted by ? as first character) or not. It takes one argument as input. It returns t if the first character of x's symbol name is a ? and nil otherwise." ( and (symbolp x) (char= (char (symbol-name x) 0) #\?) )) (defun match (cond1 cond2) (setf l1 (FOLTerm-symbolsList cond1)) (setf l2 (FOLTerm-symbolsList cond2)) (setf res '()) (if (and (predEql cond1 cond2) (eql (length l1) (length l2))) (dotimes (i (length l2)) (setf tmp (nth i l2)) (if (variablep tmp) (if (alreadyAssigned tmp (nth i l1) res) (setf res(cons (cons tmp (cons (nth i l1) '())) res)) (return-from alreadyAssigned nil)) ) ) ) res ) (defun alreadyAssigned (var const list) (dotimes (i (length list)) (if (and (eql var (first (nth i list))) (not (eql const (second (nth i list))))) (return-from alreadyAssigned nil)) ) 't ) (defun predEql (cond1 cond2) (if (and (eql (FOLTerm-isPositive cond1) (FOLTerm-isPositive cond2)) (eql (FOLTerm-predicateName cond1) (FOLTerm-predicateName cond2))) t nil ) ) (defun getPlan (start finish operators) (setf plan (makeMinimalPlan start finish)) ;; (loop (setf subGoal (isSolution)) (princ subGoal) ;; (when (null subGoal) (return p)) (getOps subGoal operators) ;; ) ) (defun main () (setf start (make-action :preConds '() :name (make-FOLTerm :isPositive 't :predicateName 'Start :symbolsList '()) :effects '() )) (setf (action-effects start) (cons (make-FOLTerm :isPositive 't :predicateName 'At :symbolsList '(Home)) (action-effects start))) (setf (action-effects start) (cons (make-FOLTerm :isPositive 't :predicateName 'Sells :symbolsList '(HWS Drill)) (action-effects start))) (setf (action-effects start) (cons (make-FOLTerm :isPositive 't :predicateName 'Sells :symbolsList '(SM Milk)) (action-effects start))) (setf (action-effects start) (cons (make-FOLTerm :isPositive 't :predicateName 'Sells :symbolsList '(SM Banana)) (action-effects start))) (setf finish (make-action :preConds '() :name (make-FOLTerm :isPositive 't :predicateName 'Finish :symbolsList '()) :effects '() )) (setf (action-preConds finish) (cons (make-FOLTerm :isPositive 't :predicateName 'At :symbolsList '(Home)) (action-preConds finish))) (setf (action-preConds finish) (cons (make-FOLTerm :isPositive 't :predicateName 'Have :symbolsList '(Drill)) (action-preConds finish))) (setf (action-preConds finish) (cons (make-FOLTerm :isPositive 't :predicateName 'Have :symbolsList '(Milk)) (action-preConds finish))) (setf (action-preConds finish) (cons (make-FOLTerm :isPositive 't :predicateName 'Have :symbolsList '(Banana)) (action-preConds finish))) (setf go (make-action :preConds '() :name (make-FOLTerm :isPositive 't :predicateName 'Go :symbolsList '(?there)) :effects '() )) (setf (action-preConds go) (cons (make-FOLTerm :isPositive 't :predicateName 'At :symbolsList '(?here)) (action-preConds go))) (setf (action-effects go) (cons (make-FOLTerm :isPositive 't :predicateName 'At :symbolsList '(?there)) (action-effects go))) (setf (action-effects go) (cons (make-FOLTerm :isPositive 'n :predicateName 'At :symbolsList '(?here)) (action-effects go))) (setf buy (make-action :preConds '() :name (make-FOLTerm :isPositive 't :predicateName 'Buy :symbolsList '(?x)) :effects '() )) (setf (action-preConds buy) (cons (make-FOLTerm :isPositive 't :predicateName 'At :symbolsList '(?store)) (action-preConds buy))) (setf (action-preConds buy) (cons (make-FOLTerm :isPositive 't :predicateName 'Sells :symbolsList '(?store ?x)) (action-preConds buy))) (setf (action-effects buy) (cons (make-FOLTerm :isPositive 't :predicateName 'Have :symbolsList '(?x)) (action-effects buy))) (setf operators (cons go (cons buy '()))) (getPlan start finish operators) ;; (linearize p) )
[ { "context": "; DEALINGS IN THE SOFTWARE.\n;\n; Original author: Jared Davis <[email protected]>\n\n(in-package \"MILAWA\")\n(inc", "end": 1356, "score": 0.9996196627616882, "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 \"pand\")\n(se", "end": 1377, "score": 0.9999353885650635, "start": 1358, "tag": "EMAIL", "value": "[email protected]" } ]
books/projects/milawa/ACL2/logic/piff.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 "pand") (set-verify-guards-eagerness 2) (set-case-split-limitations nil) (set-well-founded-relation ord<) (set-measure-function rank) ;; BOZO Dammit I hate this stupid file too. I wish it would die in a fire. ;; Recall that F <-> G is an abbreviation for (F -> G) ^ (G -> F). ;; I.e., (~F v G) ^ (~G v F) (defund logic.iff-structurep (x) (declare (xargs :guard t)) (and (logic.and-structurep x) (let ((or-not-f-g (logic.andlhs x)) (or-not-g-f (logic.andrhs x))) (and (equal (logic.fmtype or-not-f-g) 'por*) (equal (logic.fmtype or-not-g-f) 'por*) (let ((not-f (logic.vlhs or-not-f-g)) (not-g (logic.vlhs or-not-g-f))) (and (equal (logic.fmtype not-f) 'pnot*) (equal (logic.fmtype not-g) 'pnot*) (equal (logic.~arg not-f) (logic.vrhs or-not-g-f)) (equal (logic.~arg not-g) (logic.vrhs or-not-f-g)))))))) (defthm booleanp-of-logic.iff-structurep (booleanp (logic.iff-structurep x)) :hints(("Goal" :in-theory (enable logic.iff-structurep)))) (defund logic.ifflhs (x) (declare (xargs :guard (logic.iff-structurep x) :guard-hints (("Goal" :in-theory (enable logic.iff-structurep))))) (logic.vrhs ;; F (logic.andrhs ;; (~G v F) x))) ;; (~F v G) ^ (~G v F) (defund logic.iffrhs (x) (declare (xargs :guard (logic.iff-structurep x) :guard-hints (("Goal" :in-theory (enable logic.iff-structurep))))) (logic.vrhs ;; G (logic.andlhs ;; (~F v G) x))) ;; (~F v G) ^ (~G v F) (defund logic.piff (x y) (declare (xargs :guard (and (logic.formulap x) (logic.formulap y)))) (logic.pand (logic.por (logic.pnot x) y) (logic.por (logic.pnot y) x))) (in-theory (disable (:executable-counterpart logic.piff))) (defthm logic.piff-under-iff (iff (logic.piff x y) t) :hints(("Goal" :in-theory (enable logic.piff)))) (defthm forcing-logic.iff-structurep-of-logic.piff (implies (and (force (logic.formulap x)) (force (logic.formulap y))) (equal (logic.iff-structurep (logic.piff x y)) t)) :hints(("Goal" :in-theory (enable logic.piff logic.iff-structurep)))) (defthm forcing-logic.formulap-of-logic.piff (implies (and (force (logic.formulap x)) (force (logic.formulap y))) (equal (logic.formulap (logic.piff x y)) t)) :hints(("Goal" :in-theory (enable logic.piff)))) (defthm forcing-logic.formula-atblp-of-logic.piff (implies (and (force (logic.formula-atblp x atbl)) (force (logic.formula-atblp y atbl))) (equal (logic.formula-atblp (logic.piff x y) atbl) t)) :hints(("Goal" :in-theory (enable logic.piff)))) (defthm forcing-logic.formulap-of-logic.ifflhs (implies (force (logic.iff-structurep x)) (equal (logic.formulap (logic.ifflhs x)) t)) :hints(("Goal" :in-theory (enable logic.ifflhs logic.iff-structurep)))) (defthm forcing-logic.formulap-of-logic.iffrhs (implies (force (logic.iff-structurep x)) (equal (logic.formulap (logic.iffrhs x)) t)) :hints(("Goal" :in-theory (enable logic.iffrhs logic.iff-structurep)))) (defthm forcing-logic.formula-atblp-of-logic.ifflhs (implies (and (force (logic.iff-structurep x)) (force (logic.formula-atblp x atbl))) (equal (logic.formula-atblp (logic.ifflhs x) atbl) t)) :hints(("Goal" :in-theory (enable logic.ifflhs logic.iff-structurep)))) (defthm forcing-logic.formula-atblp-of-logic.iffrhs (implies (and (force (logic.iff-structurep x)) (force (logic.formula-atblp x atbl))) (equal (logic.formula-atblp (logic.iffrhs x) atbl) t)) :hints(("Goal" :in-theory (enable logic.iffrhs logic.iff-structurep)))) (defthm forcing-logic.ifflhs-of-logic.piff (implies (and (force (logic.formulap x)) (force (logic.formulap y))) (equal (logic.ifflhs (logic.piff x y)) x)) :rule-classes ((:rewrite :backchain-limit-lst 0)) :hints(("Goal" :in-theory (enable logic.ifflhs logic.piff)))) (defthm forcing-logic.iffrhs-of-logic.piff (implies (and (force (logic.formulap x)) (force (logic.formulap y))) (equal (logic.iffrhs (logic.piff x y)) y)) :rule-classes ((:rewrite :backchain-limit-lst 0)) :hints(("Goal" :in-theory (enable logic.iffrhs logic.piff))))
7776
; 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 "pand") (set-verify-guards-eagerness 2) (set-case-split-limitations nil) (set-well-founded-relation ord<) (set-measure-function rank) ;; BOZO Dammit I hate this stupid file too. I wish it would die in a fire. ;; Recall that F <-> G is an abbreviation for (F -> G) ^ (G -> F). ;; I.e., (~F v G) ^ (~G v F) (defund logic.iff-structurep (x) (declare (xargs :guard t)) (and (logic.and-structurep x) (let ((or-not-f-g (logic.andlhs x)) (or-not-g-f (logic.andrhs x))) (and (equal (logic.fmtype or-not-f-g) 'por*) (equal (logic.fmtype or-not-g-f) 'por*) (let ((not-f (logic.vlhs or-not-f-g)) (not-g (logic.vlhs or-not-g-f))) (and (equal (logic.fmtype not-f) 'pnot*) (equal (logic.fmtype not-g) 'pnot*) (equal (logic.~arg not-f) (logic.vrhs or-not-g-f)) (equal (logic.~arg not-g) (logic.vrhs or-not-f-g)))))))) (defthm booleanp-of-logic.iff-structurep (booleanp (logic.iff-structurep x)) :hints(("Goal" :in-theory (enable logic.iff-structurep)))) (defund logic.ifflhs (x) (declare (xargs :guard (logic.iff-structurep x) :guard-hints (("Goal" :in-theory (enable logic.iff-structurep))))) (logic.vrhs ;; F (logic.andrhs ;; (~G v F) x))) ;; (~F v G) ^ (~G v F) (defund logic.iffrhs (x) (declare (xargs :guard (logic.iff-structurep x) :guard-hints (("Goal" :in-theory (enable logic.iff-structurep))))) (logic.vrhs ;; G (logic.andlhs ;; (~F v G) x))) ;; (~F v G) ^ (~G v F) (defund logic.piff (x y) (declare (xargs :guard (and (logic.formulap x) (logic.formulap y)))) (logic.pand (logic.por (logic.pnot x) y) (logic.por (logic.pnot y) x))) (in-theory (disable (:executable-counterpart logic.piff))) (defthm logic.piff-under-iff (iff (logic.piff x y) t) :hints(("Goal" :in-theory (enable logic.piff)))) (defthm forcing-logic.iff-structurep-of-logic.piff (implies (and (force (logic.formulap x)) (force (logic.formulap y))) (equal (logic.iff-structurep (logic.piff x y)) t)) :hints(("Goal" :in-theory (enable logic.piff logic.iff-structurep)))) (defthm forcing-logic.formulap-of-logic.piff (implies (and (force (logic.formulap x)) (force (logic.formulap y))) (equal (logic.formulap (logic.piff x y)) t)) :hints(("Goal" :in-theory (enable logic.piff)))) (defthm forcing-logic.formula-atblp-of-logic.piff (implies (and (force (logic.formula-atblp x atbl)) (force (logic.formula-atblp y atbl))) (equal (logic.formula-atblp (logic.piff x y) atbl) t)) :hints(("Goal" :in-theory (enable logic.piff)))) (defthm forcing-logic.formulap-of-logic.ifflhs (implies (force (logic.iff-structurep x)) (equal (logic.formulap (logic.ifflhs x)) t)) :hints(("Goal" :in-theory (enable logic.ifflhs logic.iff-structurep)))) (defthm forcing-logic.formulap-of-logic.iffrhs (implies (force (logic.iff-structurep x)) (equal (logic.formulap (logic.iffrhs x)) t)) :hints(("Goal" :in-theory (enable logic.iffrhs logic.iff-structurep)))) (defthm forcing-logic.formula-atblp-of-logic.ifflhs (implies (and (force (logic.iff-structurep x)) (force (logic.formula-atblp x atbl))) (equal (logic.formula-atblp (logic.ifflhs x) atbl) t)) :hints(("Goal" :in-theory (enable logic.ifflhs logic.iff-structurep)))) (defthm forcing-logic.formula-atblp-of-logic.iffrhs (implies (and (force (logic.iff-structurep x)) (force (logic.formula-atblp x atbl))) (equal (logic.formula-atblp (logic.iffrhs x) atbl) t)) :hints(("Goal" :in-theory (enable logic.iffrhs logic.iff-structurep)))) (defthm forcing-logic.ifflhs-of-logic.piff (implies (and (force (logic.formulap x)) (force (logic.formulap y))) (equal (logic.ifflhs (logic.piff x y)) x)) :rule-classes ((:rewrite :backchain-limit-lst 0)) :hints(("Goal" :in-theory (enable logic.ifflhs logic.piff)))) (defthm forcing-logic.iffrhs-of-logic.piff (implies (and (force (logic.formulap x)) (force (logic.formulap y))) (equal (logic.iffrhs (logic.piff x y)) y)) :rule-classes ((:rewrite :backchain-limit-lst 0)) :hints(("Goal" :in-theory (enable logic.iffrhs logic.piff))))
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 "pand") (set-verify-guards-eagerness 2) (set-case-split-limitations nil) (set-well-founded-relation ord<) (set-measure-function rank) ;; BOZO Dammit I hate this stupid file too. I wish it would die in a fire. ;; Recall that F <-> G is an abbreviation for (F -> G) ^ (G -> F). ;; I.e., (~F v G) ^ (~G v F) (defund logic.iff-structurep (x) (declare (xargs :guard t)) (and (logic.and-structurep x) (let ((or-not-f-g (logic.andlhs x)) (or-not-g-f (logic.andrhs x))) (and (equal (logic.fmtype or-not-f-g) 'por*) (equal (logic.fmtype or-not-g-f) 'por*) (let ((not-f (logic.vlhs or-not-f-g)) (not-g (logic.vlhs or-not-g-f))) (and (equal (logic.fmtype not-f) 'pnot*) (equal (logic.fmtype not-g) 'pnot*) (equal (logic.~arg not-f) (logic.vrhs or-not-g-f)) (equal (logic.~arg not-g) (logic.vrhs or-not-f-g)))))))) (defthm booleanp-of-logic.iff-structurep (booleanp (logic.iff-structurep x)) :hints(("Goal" :in-theory (enable logic.iff-structurep)))) (defund logic.ifflhs (x) (declare (xargs :guard (logic.iff-structurep x) :guard-hints (("Goal" :in-theory (enable logic.iff-structurep))))) (logic.vrhs ;; F (logic.andrhs ;; (~G v F) x))) ;; (~F v G) ^ (~G v F) (defund logic.iffrhs (x) (declare (xargs :guard (logic.iff-structurep x) :guard-hints (("Goal" :in-theory (enable logic.iff-structurep))))) (logic.vrhs ;; G (logic.andlhs ;; (~F v G) x))) ;; (~F v G) ^ (~G v F) (defund logic.piff (x y) (declare (xargs :guard (and (logic.formulap x) (logic.formulap y)))) (logic.pand (logic.por (logic.pnot x) y) (logic.por (logic.pnot y) x))) (in-theory (disable (:executable-counterpart logic.piff))) (defthm logic.piff-under-iff (iff (logic.piff x y) t) :hints(("Goal" :in-theory (enable logic.piff)))) (defthm forcing-logic.iff-structurep-of-logic.piff (implies (and (force (logic.formulap x)) (force (logic.formulap y))) (equal (logic.iff-structurep (logic.piff x y)) t)) :hints(("Goal" :in-theory (enable logic.piff logic.iff-structurep)))) (defthm forcing-logic.formulap-of-logic.piff (implies (and (force (logic.formulap x)) (force (logic.formulap y))) (equal (logic.formulap (logic.piff x y)) t)) :hints(("Goal" :in-theory (enable logic.piff)))) (defthm forcing-logic.formula-atblp-of-logic.piff (implies (and (force (logic.formula-atblp x atbl)) (force (logic.formula-atblp y atbl))) (equal (logic.formula-atblp (logic.piff x y) atbl) t)) :hints(("Goal" :in-theory (enable logic.piff)))) (defthm forcing-logic.formulap-of-logic.ifflhs (implies (force (logic.iff-structurep x)) (equal (logic.formulap (logic.ifflhs x)) t)) :hints(("Goal" :in-theory (enable logic.ifflhs logic.iff-structurep)))) (defthm forcing-logic.formulap-of-logic.iffrhs (implies (force (logic.iff-structurep x)) (equal (logic.formulap (logic.iffrhs x)) t)) :hints(("Goal" :in-theory (enable logic.iffrhs logic.iff-structurep)))) (defthm forcing-logic.formula-atblp-of-logic.ifflhs (implies (and (force (logic.iff-structurep x)) (force (logic.formula-atblp x atbl))) (equal (logic.formula-atblp (logic.ifflhs x) atbl) t)) :hints(("Goal" :in-theory (enable logic.ifflhs logic.iff-structurep)))) (defthm forcing-logic.formula-atblp-of-logic.iffrhs (implies (and (force (logic.iff-structurep x)) (force (logic.formula-atblp x atbl))) (equal (logic.formula-atblp (logic.iffrhs x) atbl) t)) :hints(("Goal" :in-theory (enable logic.iffrhs logic.iff-structurep)))) (defthm forcing-logic.ifflhs-of-logic.piff (implies (and (force (logic.formulap x)) (force (logic.formulap y))) (equal (logic.ifflhs (logic.piff x y)) x)) :rule-classes ((:rewrite :backchain-limit-lst 0)) :hints(("Goal" :in-theory (enable logic.ifflhs logic.piff)))) (defthm forcing-logic.iffrhs-of-logic.piff (implies (and (force (logic.formulap x)) (force (logic.formulap y))) (equal (logic.iffrhs (logic.piff x y)) y)) :rule-classes ((:rewrite :backchain-limit-lst 0)) :hints(("Goal" :in-theory (enable logic.iffrhs logic.piff))))
[ { "context": ";;;\n;;; Copyright 2016 Clozure Associates\n;;;\n;;; Licensed under the Apache License, Versio", "end": 41, "score": 0.9967852234840393, "start": 23, "tag": "NAME", "value": "Clozure Associates" } ]
mac-ui/ccl-application.lisp
digikar99/ccl
732
;;; ;;; Copyright 2016 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") #| Cocoa applications typically do not subclass NSApplication. Instead, they customize behavior via NSApplication's delegate and via other custom controller objects. A Cocoa application written using CCL is not a typical Cocoa application. One way to approach the construction of an application in CCL is to begin with the IDE as a baseline, and then extend it until it turns into the desired application. Thus, we want the programmer to be able to define things like the application delegate, custom document types, and so forth. The Cocoa-based IDE shouldn't usurp those. We can implement most custom behavior in a custom controller object, but it seems likely that we'll at least want to be able to have some object on the responder chain. Since we want to leave the application delegate to the user, it seems NSApplication is our best bet for that. |# (defclass ccl-application (ns:ns-application) () (:metaclass ns:+ns-object)) (objc:defmethod (#/finishLaunching :void) ((self ccl-application)) ;; This method is called by #/run before it starts the event loop. ;; NSApplicationWillFinishLaunchingNotification is posted from here. ;; If there are things that must take place before those ;; notifications are processed, this is where we can make that ;; happen. We can certainly have some controller object register ;; for NSApplicationWillFinishLaunchingNotification, but I don't ;; believe that we can be sure about the order in which the ;; registered observers are called. (call-next-method)) ;;; In Cocoa, many UI-related calls must be made only on the "main" ;;; (i.e., the initial) thread. Here we implement some support for ;;; calling lisp functions on the main thread. (defstatic *interrupt-id-map* (make-id-map)) (objc:defmethod (#/lispInterrupt: :void) ((self ccl-application) id) (funcall (id-map-free-object *interrupt-id-map* (#/intValue id))) (#/release id)) (defun %interrupt-event-process (f wait) (#/performSelectorOnMainThread:withObject:waitUntilDone: *nsapp* (objc:@selector #/lispInterrupt:) ;; The NSNumber instance is released in #/lispInterrupt: above (#/initWithInt: (#/alloc ns:ns-number) (assign-id-map-id *interrupt-id-map* f)) wait))
73773
;;; ;;; Copyright 2016 <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") #| Cocoa applications typically do not subclass NSApplication. Instead, they customize behavior via NSApplication's delegate and via other custom controller objects. A Cocoa application written using CCL is not a typical Cocoa application. One way to approach the construction of an application in CCL is to begin with the IDE as a baseline, and then extend it until it turns into the desired application. Thus, we want the programmer to be able to define things like the application delegate, custom document types, and so forth. The Cocoa-based IDE shouldn't usurp those. We can implement most custom behavior in a custom controller object, but it seems likely that we'll at least want to be able to have some object on the responder chain. Since we want to leave the application delegate to the user, it seems NSApplication is our best bet for that. |# (defclass ccl-application (ns:ns-application) () (:metaclass ns:+ns-object)) (objc:defmethod (#/finishLaunching :void) ((self ccl-application)) ;; This method is called by #/run before it starts the event loop. ;; NSApplicationWillFinishLaunchingNotification is posted from here. ;; If there are things that must take place before those ;; notifications are processed, this is where we can make that ;; happen. We can certainly have some controller object register ;; for NSApplicationWillFinishLaunchingNotification, but I don't ;; believe that we can be sure about the order in which the ;; registered observers are called. (call-next-method)) ;;; In Cocoa, many UI-related calls must be made only on the "main" ;;; (i.e., the initial) thread. Here we implement some support for ;;; calling lisp functions on the main thread. (defstatic *interrupt-id-map* (make-id-map)) (objc:defmethod (#/lispInterrupt: :void) ((self ccl-application) id) (funcall (id-map-free-object *interrupt-id-map* (#/intValue id))) (#/release id)) (defun %interrupt-event-process (f wait) (#/performSelectorOnMainThread:withObject:waitUntilDone: *nsapp* (objc:@selector #/lispInterrupt:) ;; The NSNumber instance is released in #/lispInterrupt: above (#/initWithInt: (#/alloc ns:ns-number) (assign-id-map-id *interrupt-id-map* f)) wait))
true
;;; ;;; Copyright 2016 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") #| Cocoa applications typically do not subclass NSApplication. Instead, they customize behavior via NSApplication's delegate and via other custom controller objects. A Cocoa application written using CCL is not a typical Cocoa application. One way to approach the construction of an application in CCL is to begin with the IDE as a baseline, and then extend it until it turns into the desired application. Thus, we want the programmer to be able to define things like the application delegate, custom document types, and so forth. The Cocoa-based IDE shouldn't usurp those. We can implement most custom behavior in a custom controller object, but it seems likely that we'll at least want to be able to have some object on the responder chain. Since we want to leave the application delegate to the user, it seems NSApplication is our best bet for that. |# (defclass ccl-application (ns:ns-application) () (:metaclass ns:+ns-object)) (objc:defmethod (#/finishLaunching :void) ((self ccl-application)) ;; This method is called by #/run before it starts the event loop. ;; NSApplicationWillFinishLaunchingNotification is posted from here. ;; If there are things that must take place before those ;; notifications are processed, this is where we can make that ;; happen. We can certainly have some controller object register ;; for NSApplicationWillFinishLaunchingNotification, but I don't ;; believe that we can be sure about the order in which the ;; registered observers are called. (call-next-method)) ;;; In Cocoa, many UI-related calls must be made only on the "main" ;;; (i.e., the initial) thread. Here we implement some support for ;;; calling lisp functions on the main thread. (defstatic *interrupt-id-map* (make-id-map)) (objc:defmethod (#/lispInterrupt: :void) ((self ccl-application) id) (funcall (id-map-free-object *interrupt-id-map* (#/intValue id))) (#/release id)) (defun %interrupt-event-process (f wait) (#/performSelectorOnMainThread:withObject:waitUntilDone: *nsapp* (objc:@selector #/lispInterrupt:) ;; The NSNumber instance is released in #/lispInterrupt: above (#/initWithInt: (#/alloc ns:ns-number) (assign-id-map-id *interrupt-id-map* f)) wait))
[ { "context": "; DEALINGS IN THE SOFTWARE.\n;\n; Original author: Jared Davis <[email protected]>\n;\n; Modified 8/2014 by Matt ", "end": 1395, "score": 0.9998047947883606, "start": 1384, "tag": "NAME", "value": "Jared Davis" }, { "context": "N THE SOFTWARE.\n;\n; Original author: Jared Davis <[email protected]>\n;\n; Modified 8/2014 by Matt Kaufmann to make fun", "end": 1415, "score": 0.9999338984489441, "start": 1397, "tag": "EMAIL", "value": "[email protected]" }, { "context": " Davis <[email protected]>\n;\n; Modified 8/2014 by Matt Kaufmann to make functions tail recursive, to avoid\n; erro", "end": 1453, "score": 0.9995749592781067, "start": 1440, "tag": "NAME", "value": "Matt Kaufmann" }, { "context": "ro CL (at least).\n\n(in-package \"ACL2\")\n\n; Added by Matt K., May 2015. Improvement observed when certificat", "end": 1585, "score": 0.999749481678009, "start": 1579, "tag": "NAME", "value": "Matt K" } ]
books/system/hons-check/memoize-tests.lisp
nzt/acl2
1
; Memoize Sanity Checking ; Copyright (C) 2011-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]> ; ; Modified 8/2014 by Matt Kaufmann to make functions tail recursive, to avoid ; errors in LispWorks and Allegro CL (at least). (in-package "ACL2") ; Added by Matt K., May 2015. Improvement observed when certification used ; the :delay strategy: ; 92.53 sec. vs. 314.30 sec. (value-triple (set-gc-strategy :delay)) (include-book "std/testing/assert-bang" :dir :system) (include-book "std/lists/flatten" :dir :system) (include-book "std/util/bstar" :dir :system) ; cert_param: (hons-only) ; This file does nothing useful and should never be included in another ; book. We just do some very basic computations to make sure the memoize ; system seems to be working right. (defun f1 (x) (declare (xargs :guard t)) x) (defun f1-list-tailrec (x acc) (declare (xargs :guard (true-listp acc))) (if (atom x) (reverse acc) (f1-list-tailrec (cdr x) (cons (f1 (car x)) acc)))) (defun f1-list (x) (declare (xargs :guard t)) (f1-list-tailrec x nil)) (defun f2 (x) (declare (xargs :guard t)) (cons x x)) (defun f2-list-tailrec (x acc) (declare (xargs :guard (true-listp acc))) (if (atom x) (reverse acc) (f2-list-tailrec (cdr x) (cons (f2 (car x)) acc)))) (defun f2-list (x) (declare (xargs :guard t)) (f2-list-tailrec x nil)) (defun f3 (x) (declare (xargs :guard t)) (mv x (cons 1 x))) (defun f3-list-tailrec (x acc) (declare (xargs :guard (true-listp acc))) (if (atom x) (reverse acc) (mv-let (a b) (f3 (car x)) (f3-list-tailrec (cdr x) (list* b a acc))))) (defun f3-list (x) (declare (xargs :guard t)) (f3-list-tailrec x nil)) (defun f4 (x y) (declare (xargs :guard t)) (cons 1/2 (cons x y))) (defun f4-list-tailrec (x acc) (declare (xargs :guard (true-listp acc))) (if (atom x) (reverse acc) (if (atom (cdr x)) (reverse acc) (f4-list-tailrec (cdr x) (cons (f4 (first x) (second x)) acc))))) (defun f4-list (x) (declare (xargs :guard t)) (f4-list-tailrec x nil)) (defun f5 (x y) (declare (xargs :guard t)) (mv x y)) (defun f5-list-tailrec (x acc) (declare (xargs :guard (true-listp acc))) (if (atom x) (reverse acc) (if (atom (cdr x)) (reverse acc) (mv-let (a b) (f5 (first x) (second x)) (f5-list-tailrec (cdr x) (list* b a acc)))))) (defun f5-list (x) (declare (xargs :guard t)) (f5-list-tailrec x nil)) (defun f6 (x y z) (declare (xargs :guard t)) (list x y z)) (defun f6-list-tailrec (x acc) (declare (xargs :guard (true-listp acc))) (if (atom x) (reverse acc) (if (atom (cdr x)) (reverse acc) (if (atom (cddr x)) (reverse acc) (f6-list-tailrec (cdr x) (cons (f6 (first x) (second x) (third x)) acc)))))) (defun f6-list (x) (declare (xargs :guard t)) (f6-list-tailrec x nil)) (defconst *stuff* ;; A list with lots of different kinds of objects '(0 1 2 3 4 nil t a b c d 1/2 1/3 1/5 -1 -2 -3 -4 -1/2 -1/3 -1/4 #c(0 1) #c(0 2) #c(1 2) #c(-1 -2) #c(-2 -3) #c(-1 -3) #c(1 0) #c(3 0) #c(-1 0) #c(0 0) #\a #\b #\c #\d "foo" "bar" "baz" (1 . 2) (1 . 3) (a b c d))) (defun nats (n) (if (zp n) nil (cons n (nats (1- n))))) (comp t) ; needed for GCL (and maybe other Lisps) (defconst *data* (flatten (append (make-list 1000 :initial-element *stuff*) (hons-copy (make-list 1000 :initial-element *stuff*))))) (defconst *f1-test* (f1-list *data*)) (defconst *f2-test* (f2-list *data*)) (defconst *f3-test* (f3-list *data*)) (defconst *f4-test* (f4-list *data*)) (defconst *f5-test* (f5-list *data*)) (defconst *f6-test* (f6-list *data*)) (memoize 'f1) (memoize 'f2) (memoize 'f3) (memoize 'f4) (memoize 'f5) (memoize 'f6) (assert! (equal *f1-test* (f1-list *data*))) (assert! (equal *f2-test* (f2-list *data*))) (assert! (equal *f3-test* (f3-list *data*))) (assert! (equal *f4-test* (f4-list *data*))) (assert! (equal *f5-test* (f5-list *data*))) (assert! (equal *f6-test* (f6-list *data*))) (value-triple (memsum)) (unmemoize 'f1) (unmemoize 'f2) (unmemoize 'f3) (unmemoize 'f4) (unmemoize 'f5) (unmemoize 'f6) (memoize 'f1 :condition '(not (equal x -1/3))) (memoize 'f2 :condition '(not (equal x -1/3))) (memoize 'f3 :condition '(not (equal x -1/3))) (memoize 'f4 :condition '(not (equal x -1/3))) (memoize 'f5 :condition '(not (equal x -1/3))) (memoize 'f6 :condition '(not (equal x -1/3))) (assert! (equal *f1-test* (f1-list *data*))) (assert! (equal *f2-test* (f2-list *data*))) (assert! (equal *f3-test* (f3-list *data*))) (assert! (equal *f4-test* (f4-list *data*))) (assert! (equal *f5-test* (f5-list *data*))) (assert! (equal *f6-test* (f6-list *data*))) (value-triple (memsum)) (unmemoize 'f1) (unmemoize 'f2) (unmemoize 'f3) (unmemoize 'f4) (unmemoize 'f5) (unmemoize 'f6) ;; (defun show-me-default-hons-space (from) ;; (declare (xargs :guard t) ;; (ignorable from)) ;; (er hard? 'show-me-default-hons-space ;; "Raw lisp definition not installed")) ;; (defttag :show-me-default-hons-space) ;; (progn! ;; (set-raw-mode t) ;; (defun show-me-default-hons-space (from) ;; (format t "~S: Default-hs is ~S~%" ;; from ;; (funcall (intern "%ADDRESS-OF" "CCL") *default-hs*)) ;; nil)) (defun test-simultaneously-acons () ; We may need to verify guards to execute the raw Lisp (parallelized) version ; of pand. (declare (xargs :verify-guards t)) (pand (progn$ ;; (show-me-default-hons-space 'thread-1-pre) ;; (hons-summary) (hons-acons 1 2 nil) ;; (show-me-default-hons-space 'thread-1-post) ;; (hons-summary) t) (progn$ ;; (show-me-default-hons-space 'thread-2-pre) ;; (hons-summary) (hons-acons 2 3 nil) ;; (show-me-default-hons-space 'thread-2-post) ;; (hons-summary) t))) (assert! (test-simultaneously-acons)) (defun test-simultaneously-acons-with-spec-mv-let () ; We must verify guards to execute the raw Lisp (parallelized) version of ; spec-mv-let. (declare (xargs :verify-guards t)) (spec-mv-let (x) (hons-acons 1 2 nil) (mv-let (y z) (mv (hons-acons 3 4 nil) 6) (if t (+ (caar x) (cdar x) (caar y) (cdar y) z) (+ (caar y) (cadr y) z))))) (assert! (test-simultaneously-acons-with-spec-mv-let)) (defun test-simultaneously-hons () ; We may need to verify guards to execute the raw Lisp (parallelized) version ; of pand. (declare (xargs :verify-guards t)) (pand (hons 1 2) (hons 3 4))) (assert! (test-simultaneously-hons)) (defun test-simultaneously-hons-with-spec-mv-let () ; We must verify guards to execute the raw Lisp (parallelized) version of ; spec-mv-let. (declare (xargs :verify-guards t)) (spec-mv-let (x) (hons 7 8) (mv-let (y z) (mv (hons 9 10) 11) (if t (+ (car x) (cdr x) (car y) (cdr y) z) (+ (car y) (cdr y) z))))) (assert! (test-simultaneously-hons-with-spec-mv-let)) (defun make-memoized-alist (x) (declare (xargs :guard t)) (make-fast-alist (cons (cons 'x x) '(("a" . 1) (b . 2) (c . 3))))) (memoize 'make-memoized-alist) (defun do-stuff-to-fast-alist (n alist) (declare (xargs :guard (natp n))) (b* (((when (zp n)) alist) (?a (hons-get 'a alist)) (?b (hons-get 'b alist)) (?c (hons-get 'c alist)) (alist (hons-acons n n alist))) (do-stuff-to-fast-alist (- n 1) alist))) (comp t) (defconst *spec* (do-stuff-to-fast-alist 1000 (make-memoized-alist 5))) (defun check-both-with-pand (n) (declare (xargs :guard (natp n))) (pand (equal (do-stuff-to-fast-alist n (make-fast-alist (make-memoized-alist 5))) *spec*) (equal (do-stuff-to-fast-alist n (make-fast-alist (make-memoized-alist 5))) *spec*))) (assert! (check-both-with-pand 1000)) ;; Basic check to try to see if threads will interfere with one another (defun add-some-honses (x acc) (declare (xargs :guard t)) (if (atom x) acc (add-some-honses (cdr x) (list* (hons-copy (car x)) (hons (car x) (car x)) acc)))) (defun thread1 (x) (declare (xargs :guard t)) (let ((x (add-some-honses x x))) (list (f1-list x) (f2-list x) (f3-list x) (f4-list x) (f5-list x) (f6-list x)))) (defun thread2 (x) (declare (xargs :guard t)) (let ((x (add-some-honses x x))) (list (f2-list x) (f4-list x) (f6-list x) (f1-list x) (f3-list x) (f5-list x)))) (comp t) ;; so gcl will compile add-some-honses instead of stack overflowing (defconst *thread1-spec* (thread1 *data*)) (defconst *thread2-spec* (thread2 *data*)) (defun check-thread1 (n) (declare (xargs :guard (natp n))) (if (zp n) t (and (equal *thread1-spec* (thread1 *data*)) (check-thread1 (- n 1))))) (defun check-thread2 (n) (declare (xargs :guard (natp n))) (if (zp n) t (and (equal *thread2-spec* (thread2 *data*)) (check-thread2 (- n 1))))) (defun check-both (n) (declare (xargs :guard (natp n))) (pand (check-thread1 n) (check-thread2 n))) ;; Timings on compute-1-1: ;; - ACL2(hp): no memoization: 12.33 seconds (many GC messages) ;; - ACL2(h): no memoization: 15.54 seconds (many GC messages) (assert! (time$ (check-both 100))) (value-triple (clear-memoize-tables)) (memoize 'f1) (memoize 'f2 :condition '(not (equal x -1/3))) (memoize 'f3) (memoize 'f4 :condition '(not (equal x -1/3))) (memoize 'f5) (memoize 'f6 :condition '(not (equal x -1/3))) ;; Timings on compute-1-1: ;; - ACL2(hp): memoization, lock contention: 242 seconds (many gc messages) ;; - ACL2(h): memoization, no lock contention: 61 seconds (many gc messages) (assert! (time$ (check-both 100)))
68776
; Memoize Sanity Checking ; Copyright (C) 2011-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>> ; ; Modified 8/2014 by <NAME> to make functions tail recursive, to avoid ; errors in LispWorks and Allegro CL (at least). (in-package "ACL2") ; Added by <NAME>., May 2015. Improvement observed when certification used ; the :delay strategy: ; 92.53 sec. vs. 314.30 sec. (value-triple (set-gc-strategy :delay)) (include-book "std/testing/assert-bang" :dir :system) (include-book "std/lists/flatten" :dir :system) (include-book "std/util/bstar" :dir :system) ; cert_param: (hons-only) ; This file does nothing useful and should never be included in another ; book. We just do some very basic computations to make sure the memoize ; system seems to be working right. (defun f1 (x) (declare (xargs :guard t)) x) (defun f1-list-tailrec (x acc) (declare (xargs :guard (true-listp acc))) (if (atom x) (reverse acc) (f1-list-tailrec (cdr x) (cons (f1 (car x)) acc)))) (defun f1-list (x) (declare (xargs :guard t)) (f1-list-tailrec x nil)) (defun f2 (x) (declare (xargs :guard t)) (cons x x)) (defun f2-list-tailrec (x acc) (declare (xargs :guard (true-listp acc))) (if (atom x) (reverse acc) (f2-list-tailrec (cdr x) (cons (f2 (car x)) acc)))) (defun f2-list (x) (declare (xargs :guard t)) (f2-list-tailrec x nil)) (defun f3 (x) (declare (xargs :guard t)) (mv x (cons 1 x))) (defun f3-list-tailrec (x acc) (declare (xargs :guard (true-listp acc))) (if (atom x) (reverse acc) (mv-let (a b) (f3 (car x)) (f3-list-tailrec (cdr x) (list* b a acc))))) (defun f3-list (x) (declare (xargs :guard t)) (f3-list-tailrec x nil)) (defun f4 (x y) (declare (xargs :guard t)) (cons 1/2 (cons x y))) (defun f4-list-tailrec (x acc) (declare (xargs :guard (true-listp acc))) (if (atom x) (reverse acc) (if (atom (cdr x)) (reverse acc) (f4-list-tailrec (cdr x) (cons (f4 (first x) (second x)) acc))))) (defun f4-list (x) (declare (xargs :guard t)) (f4-list-tailrec x nil)) (defun f5 (x y) (declare (xargs :guard t)) (mv x y)) (defun f5-list-tailrec (x acc) (declare (xargs :guard (true-listp acc))) (if (atom x) (reverse acc) (if (atom (cdr x)) (reverse acc) (mv-let (a b) (f5 (first x) (second x)) (f5-list-tailrec (cdr x) (list* b a acc)))))) (defun f5-list (x) (declare (xargs :guard t)) (f5-list-tailrec x nil)) (defun f6 (x y z) (declare (xargs :guard t)) (list x y z)) (defun f6-list-tailrec (x acc) (declare (xargs :guard (true-listp acc))) (if (atom x) (reverse acc) (if (atom (cdr x)) (reverse acc) (if (atom (cddr x)) (reverse acc) (f6-list-tailrec (cdr x) (cons (f6 (first x) (second x) (third x)) acc)))))) (defun f6-list (x) (declare (xargs :guard t)) (f6-list-tailrec x nil)) (defconst *stuff* ;; A list with lots of different kinds of objects '(0 1 2 3 4 nil t a b c d 1/2 1/3 1/5 -1 -2 -3 -4 -1/2 -1/3 -1/4 #c(0 1) #c(0 2) #c(1 2) #c(-1 -2) #c(-2 -3) #c(-1 -3) #c(1 0) #c(3 0) #c(-1 0) #c(0 0) #\a #\b #\c #\d "foo" "bar" "baz" (1 . 2) (1 . 3) (a b c d))) (defun nats (n) (if (zp n) nil (cons n (nats (1- n))))) (comp t) ; needed for GCL (and maybe other Lisps) (defconst *data* (flatten (append (make-list 1000 :initial-element *stuff*) (hons-copy (make-list 1000 :initial-element *stuff*))))) (defconst *f1-test* (f1-list *data*)) (defconst *f2-test* (f2-list *data*)) (defconst *f3-test* (f3-list *data*)) (defconst *f4-test* (f4-list *data*)) (defconst *f5-test* (f5-list *data*)) (defconst *f6-test* (f6-list *data*)) (memoize 'f1) (memoize 'f2) (memoize 'f3) (memoize 'f4) (memoize 'f5) (memoize 'f6) (assert! (equal *f1-test* (f1-list *data*))) (assert! (equal *f2-test* (f2-list *data*))) (assert! (equal *f3-test* (f3-list *data*))) (assert! (equal *f4-test* (f4-list *data*))) (assert! (equal *f5-test* (f5-list *data*))) (assert! (equal *f6-test* (f6-list *data*))) (value-triple (memsum)) (unmemoize 'f1) (unmemoize 'f2) (unmemoize 'f3) (unmemoize 'f4) (unmemoize 'f5) (unmemoize 'f6) (memoize 'f1 :condition '(not (equal x -1/3))) (memoize 'f2 :condition '(not (equal x -1/3))) (memoize 'f3 :condition '(not (equal x -1/3))) (memoize 'f4 :condition '(not (equal x -1/3))) (memoize 'f5 :condition '(not (equal x -1/3))) (memoize 'f6 :condition '(not (equal x -1/3))) (assert! (equal *f1-test* (f1-list *data*))) (assert! (equal *f2-test* (f2-list *data*))) (assert! (equal *f3-test* (f3-list *data*))) (assert! (equal *f4-test* (f4-list *data*))) (assert! (equal *f5-test* (f5-list *data*))) (assert! (equal *f6-test* (f6-list *data*))) (value-triple (memsum)) (unmemoize 'f1) (unmemoize 'f2) (unmemoize 'f3) (unmemoize 'f4) (unmemoize 'f5) (unmemoize 'f6) ;; (defun show-me-default-hons-space (from) ;; (declare (xargs :guard t) ;; (ignorable from)) ;; (er hard? 'show-me-default-hons-space ;; "Raw lisp definition not installed")) ;; (defttag :show-me-default-hons-space) ;; (progn! ;; (set-raw-mode t) ;; (defun show-me-default-hons-space (from) ;; (format t "~S: Default-hs is ~S~%" ;; from ;; (funcall (intern "%ADDRESS-OF" "CCL") *default-hs*)) ;; nil)) (defun test-simultaneously-acons () ; We may need to verify guards to execute the raw Lisp (parallelized) version ; of pand. (declare (xargs :verify-guards t)) (pand (progn$ ;; (show-me-default-hons-space 'thread-1-pre) ;; (hons-summary) (hons-acons 1 2 nil) ;; (show-me-default-hons-space 'thread-1-post) ;; (hons-summary) t) (progn$ ;; (show-me-default-hons-space 'thread-2-pre) ;; (hons-summary) (hons-acons 2 3 nil) ;; (show-me-default-hons-space 'thread-2-post) ;; (hons-summary) t))) (assert! (test-simultaneously-acons)) (defun test-simultaneously-acons-with-spec-mv-let () ; We must verify guards to execute the raw Lisp (parallelized) version of ; spec-mv-let. (declare (xargs :verify-guards t)) (spec-mv-let (x) (hons-acons 1 2 nil) (mv-let (y z) (mv (hons-acons 3 4 nil) 6) (if t (+ (caar x) (cdar x) (caar y) (cdar y) z) (+ (caar y) (cadr y) z))))) (assert! (test-simultaneously-acons-with-spec-mv-let)) (defun test-simultaneously-hons () ; We may need to verify guards to execute the raw Lisp (parallelized) version ; of pand. (declare (xargs :verify-guards t)) (pand (hons 1 2) (hons 3 4))) (assert! (test-simultaneously-hons)) (defun test-simultaneously-hons-with-spec-mv-let () ; We must verify guards to execute the raw Lisp (parallelized) version of ; spec-mv-let. (declare (xargs :verify-guards t)) (spec-mv-let (x) (hons 7 8) (mv-let (y z) (mv (hons 9 10) 11) (if t (+ (car x) (cdr x) (car y) (cdr y) z) (+ (car y) (cdr y) z))))) (assert! (test-simultaneously-hons-with-spec-mv-let)) (defun make-memoized-alist (x) (declare (xargs :guard t)) (make-fast-alist (cons (cons 'x x) '(("a" . 1) (b . 2) (c . 3))))) (memoize 'make-memoized-alist) (defun do-stuff-to-fast-alist (n alist) (declare (xargs :guard (natp n))) (b* (((when (zp n)) alist) (?a (hons-get 'a alist)) (?b (hons-get 'b alist)) (?c (hons-get 'c alist)) (alist (hons-acons n n alist))) (do-stuff-to-fast-alist (- n 1) alist))) (comp t) (defconst *spec* (do-stuff-to-fast-alist 1000 (make-memoized-alist 5))) (defun check-both-with-pand (n) (declare (xargs :guard (natp n))) (pand (equal (do-stuff-to-fast-alist n (make-fast-alist (make-memoized-alist 5))) *spec*) (equal (do-stuff-to-fast-alist n (make-fast-alist (make-memoized-alist 5))) *spec*))) (assert! (check-both-with-pand 1000)) ;; Basic check to try to see if threads will interfere with one another (defun add-some-honses (x acc) (declare (xargs :guard t)) (if (atom x) acc (add-some-honses (cdr x) (list* (hons-copy (car x)) (hons (car x) (car x)) acc)))) (defun thread1 (x) (declare (xargs :guard t)) (let ((x (add-some-honses x x))) (list (f1-list x) (f2-list x) (f3-list x) (f4-list x) (f5-list x) (f6-list x)))) (defun thread2 (x) (declare (xargs :guard t)) (let ((x (add-some-honses x x))) (list (f2-list x) (f4-list x) (f6-list x) (f1-list x) (f3-list x) (f5-list x)))) (comp t) ;; so gcl will compile add-some-honses instead of stack overflowing (defconst *thread1-spec* (thread1 *data*)) (defconst *thread2-spec* (thread2 *data*)) (defun check-thread1 (n) (declare (xargs :guard (natp n))) (if (zp n) t (and (equal *thread1-spec* (thread1 *data*)) (check-thread1 (- n 1))))) (defun check-thread2 (n) (declare (xargs :guard (natp n))) (if (zp n) t (and (equal *thread2-spec* (thread2 *data*)) (check-thread2 (- n 1))))) (defun check-both (n) (declare (xargs :guard (natp n))) (pand (check-thread1 n) (check-thread2 n))) ;; Timings on compute-1-1: ;; - ACL2(hp): no memoization: 12.33 seconds (many GC messages) ;; - ACL2(h): no memoization: 15.54 seconds (many GC messages) (assert! (time$ (check-both 100))) (value-triple (clear-memoize-tables)) (memoize 'f1) (memoize 'f2 :condition '(not (equal x -1/3))) (memoize 'f3) (memoize 'f4 :condition '(not (equal x -1/3))) (memoize 'f5) (memoize 'f6 :condition '(not (equal x -1/3))) ;; Timings on compute-1-1: ;; - ACL2(hp): memoization, lock contention: 242 seconds (many gc messages) ;; - ACL2(h): memoization, no lock contention: 61 seconds (many gc messages) (assert! (time$ (check-both 100)))
true
; Memoize Sanity Checking ; Copyright (C) 2011-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> ; ; Modified 8/2014 by PI:NAME:<NAME>END_PI to make functions tail recursive, to avoid ; errors in LispWorks and Allegro CL (at least). (in-package "ACL2") ; Added by PI:NAME:<NAME>END_PI., May 2015. Improvement observed when certification used ; the :delay strategy: ; 92.53 sec. vs. 314.30 sec. (value-triple (set-gc-strategy :delay)) (include-book "std/testing/assert-bang" :dir :system) (include-book "std/lists/flatten" :dir :system) (include-book "std/util/bstar" :dir :system) ; cert_param: (hons-only) ; This file does nothing useful and should never be included in another ; book. We just do some very basic computations to make sure the memoize ; system seems to be working right. (defun f1 (x) (declare (xargs :guard t)) x) (defun f1-list-tailrec (x acc) (declare (xargs :guard (true-listp acc))) (if (atom x) (reverse acc) (f1-list-tailrec (cdr x) (cons (f1 (car x)) acc)))) (defun f1-list (x) (declare (xargs :guard t)) (f1-list-tailrec x nil)) (defun f2 (x) (declare (xargs :guard t)) (cons x x)) (defun f2-list-tailrec (x acc) (declare (xargs :guard (true-listp acc))) (if (atom x) (reverse acc) (f2-list-tailrec (cdr x) (cons (f2 (car x)) acc)))) (defun f2-list (x) (declare (xargs :guard t)) (f2-list-tailrec x nil)) (defun f3 (x) (declare (xargs :guard t)) (mv x (cons 1 x))) (defun f3-list-tailrec (x acc) (declare (xargs :guard (true-listp acc))) (if (atom x) (reverse acc) (mv-let (a b) (f3 (car x)) (f3-list-tailrec (cdr x) (list* b a acc))))) (defun f3-list (x) (declare (xargs :guard t)) (f3-list-tailrec x nil)) (defun f4 (x y) (declare (xargs :guard t)) (cons 1/2 (cons x y))) (defun f4-list-tailrec (x acc) (declare (xargs :guard (true-listp acc))) (if (atom x) (reverse acc) (if (atom (cdr x)) (reverse acc) (f4-list-tailrec (cdr x) (cons (f4 (first x) (second x)) acc))))) (defun f4-list (x) (declare (xargs :guard t)) (f4-list-tailrec x nil)) (defun f5 (x y) (declare (xargs :guard t)) (mv x y)) (defun f5-list-tailrec (x acc) (declare (xargs :guard (true-listp acc))) (if (atom x) (reverse acc) (if (atom (cdr x)) (reverse acc) (mv-let (a b) (f5 (first x) (second x)) (f5-list-tailrec (cdr x) (list* b a acc)))))) (defun f5-list (x) (declare (xargs :guard t)) (f5-list-tailrec x nil)) (defun f6 (x y z) (declare (xargs :guard t)) (list x y z)) (defun f6-list-tailrec (x acc) (declare (xargs :guard (true-listp acc))) (if (atom x) (reverse acc) (if (atom (cdr x)) (reverse acc) (if (atom (cddr x)) (reverse acc) (f6-list-tailrec (cdr x) (cons (f6 (first x) (second x) (third x)) acc)))))) (defun f6-list (x) (declare (xargs :guard t)) (f6-list-tailrec x nil)) (defconst *stuff* ;; A list with lots of different kinds of objects '(0 1 2 3 4 nil t a b c d 1/2 1/3 1/5 -1 -2 -3 -4 -1/2 -1/3 -1/4 #c(0 1) #c(0 2) #c(1 2) #c(-1 -2) #c(-2 -3) #c(-1 -3) #c(1 0) #c(3 0) #c(-1 0) #c(0 0) #\a #\b #\c #\d "foo" "bar" "baz" (1 . 2) (1 . 3) (a b c d))) (defun nats (n) (if (zp n) nil (cons n (nats (1- n))))) (comp t) ; needed for GCL (and maybe other Lisps) (defconst *data* (flatten (append (make-list 1000 :initial-element *stuff*) (hons-copy (make-list 1000 :initial-element *stuff*))))) (defconst *f1-test* (f1-list *data*)) (defconst *f2-test* (f2-list *data*)) (defconst *f3-test* (f3-list *data*)) (defconst *f4-test* (f4-list *data*)) (defconst *f5-test* (f5-list *data*)) (defconst *f6-test* (f6-list *data*)) (memoize 'f1) (memoize 'f2) (memoize 'f3) (memoize 'f4) (memoize 'f5) (memoize 'f6) (assert! (equal *f1-test* (f1-list *data*))) (assert! (equal *f2-test* (f2-list *data*))) (assert! (equal *f3-test* (f3-list *data*))) (assert! (equal *f4-test* (f4-list *data*))) (assert! (equal *f5-test* (f5-list *data*))) (assert! (equal *f6-test* (f6-list *data*))) (value-triple (memsum)) (unmemoize 'f1) (unmemoize 'f2) (unmemoize 'f3) (unmemoize 'f4) (unmemoize 'f5) (unmemoize 'f6) (memoize 'f1 :condition '(not (equal x -1/3))) (memoize 'f2 :condition '(not (equal x -1/3))) (memoize 'f3 :condition '(not (equal x -1/3))) (memoize 'f4 :condition '(not (equal x -1/3))) (memoize 'f5 :condition '(not (equal x -1/3))) (memoize 'f6 :condition '(not (equal x -1/3))) (assert! (equal *f1-test* (f1-list *data*))) (assert! (equal *f2-test* (f2-list *data*))) (assert! (equal *f3-test* (f3-list *data*))) (assert! (equal *f4-test* (f4-list *data*))) (assert! (equal *f5-test* (f5-list *data*))) (assert! (equal *f6-test* (f6-list *data*))) (value-triple (memsum)) (unmemoize 'f1) (unmemoize 'f2) (unmemoize 'f3) (unmemoize 'f4) (unmemoize 'f5) (unmemoize 'f6) ;; (defun show-me-default-hons-space (from) ;; (declare (xargs :guard t) ;; (ignorable from)) ;; (er hard? 'show-me-default-hons-space ;; "Raw lisp definition not installed")) ;; (defttag :show-me-default-hons-space) ;; (progn! ;; (set-raw-mode t) ;; (defun show-me-default-hons-space (from) ;; (format t "~S: Default-hs is ~S~%" ;; from ;; (funcall (intern "%ADDRESS-OF" "CCL") *default-hs*)) ;; nil)) (defun test-simultaneously-acons () ; We may need to verify guards to execute the raw Lisp (parallelized) version ; of pand. (declare (xargs :verify-guards t)) (pand (progn$ ;; (show-me-default-hons-space 'thread-1-pre) ;; (hons-summary) (hons-acons 1 2 nil) ;; (show-me-default-hons-space 'thread-1-post) ;; (hons-summary) t) (progn$ ;; (show-me-default-hons-space 'thread-2-pre) ;; (hons-summary) (hons-acons 2 3 nil) ;; (show-me-default-hons-space 'thread-2-post) ;; (hons-summary) t))) (assert! (test-simultaneously-acons)) (defun test-simultaneously-acons-with-spec-mv-let () ; We must verify guards to execute the raw Lisp (parallelized) version of ; spec-mv-let. (declare (xargs :verify-guards t)) (spec-mv-let (x) (hons-acons 1 2 nil) (mv-let (y z) (mv (hons-acons 3 4 nil) 6) (if t (+ (caar x) (cdar x) (caar y) (cdar y) z) (+ (caar y) (cadr y) z))))) (assert! (test-simultaneously-acons-with-spec-mv-let)) (defun test-simultaneously-hons () ; We may need to verify guards to execute the raw Lisp (parallelized) version ; of pand. (declare (xargs :verify-guards t)) (pand (hons 1 2) (hons 3 4))) (assert! (test-simultaneously-hons)) (defun test-simultaneously-hons-with-spec-mv-let () ; We must verify guards to execute the raw Lisp (parallelized) version of ; spec-mv-let. (declare (xargs :verify-guards t)) (spec-mv-let (x) (hons 7 8) (mv-let (y z) (mv (hons 9 10) 11) (if t (+ (car x) (cdr x) (car y) (cdr y) z) (+ (car y) (cdr y) z))))) (assert! (test-simultaneously-hons-with-spec-mv-let)) (defun make-memoized-alist (x) (declare (xargs :guard t)) (make-fast-alist (cons (cons 'x x) '(("a" . 1) (b . 2) (c . 3))))) (memoize 'make-memoized-alist) (defun do-stuff-to-fast-alist (n alist) (declare (xargs :guard (natp n))) (b* (((when (zp n)) alist) (?a (hons-get 'a alist)) (?b (hons-get 'b alist)) (?c (hons-get 'c alist)) (alist (hons-acons n n alist))) (do-stuff-to-fast-alist (- n 1) alist))) (comp t) (defconst *spec* (do-stuff-to-fast-alist 1000 (make-memoized-alist 5))) (defun check-both-with-pand (n) (declare (xargs :guard (natp n))) (pand (equal (do-stuff-to-fast-alist n (make-fast-alist (make-memoized-alist 5))) *spec*) (equal (do-stuff-to-fast-alist n (make-fast-alist (make-memoized-alist 5))) *spec*))) (assert! (check-both-with-pand 1000)) ;; Basic check to try to see if threads will interfere with one another (defun add-some-honses (x acc) (declare (xargs :guard t)) (if (atom x) acc (add-some-honses (cdr x) (list* (hons-copy (car x)) (hons (car x) (car x)) acc)))) (defun thread1 (x) (declare (xargs :guard t)) (let ((x (add-some-honses x x))) (list (f1-list x) (f2-list x) (f3-list x) (f4-list x) (f5-list x) (f6-list x)))) (defun thread2 (x) (declare (xargs :guard t)) (let ((x (add-some-honses x x))) (list (f2-list x) (f4-list x) (f6-list x) (f1-list x) (f3-list x) (f5-list x)))) (comp t) ;; so gcl will compile add-some-honses instead of stack overflowing (defconst *thread1-spec* (thread1 *data*)) (defconst *thread2-spec* (thread2 *data*)) (defun check-thread1 (n) (declare (xargs :guard (natp n))) (if (zp n) t (and (equal *thread1-spec* (thread1 *data*)) (check-thread1 (- n 1))))) (defun check-thread2 (n) (declare (xargs :guard (natp n))) (if (zp n) t (and (equal *thread2-spec* (thread2 *data*)) (check-thread2 (- n 1))))) (defun check-both (n) (declare (xargs :guard (natp n))) (pand (check-thread1 n) (check-thread2 n))) ;; Timings on compute-1-1: ;; - ACL2(hp): no memoization: 12.33 seconds (many GC messages) ;; - ACL2(h): no memoization: 15.54 seconds (many GC messages) (assert! (time$ (check-both 100))) (value-triple (clear-memoize-tables)) (memoize 'f1) (memoize 'f2 :condition '(not (equal x -1/3))) (memoize 'f3) (memoize 'f4 :condition '(not (equal x -1/3))) (memoize 'f5) (memoize 'f6 :condition '(not (equal x -1/3))) ;; Timings on compute-1-1: ;; - ACL2(hp): memoization, lock contention: 242 seconds (many gc messages) ;; - ACL2(h): memoization, no lock contention: 61 seconds (many gc messages) (assert! (time$ (check-both 100)))
[ { "context": ";;;; complex-double-float.lisp\n;;;;\n;;;; Author: Cole Scott\n\n(in-package #:magicl)\n\n(deftensor tensor/complex", "end": 59, "score": 0.9997994899749756, "start": 49, "tag": "NAME", "value": "Cole Scott" } ]
src/high-level/types/complex-double-float.lisp
macdavid313/magicl
103
;;;; complex-double-float.lisp ;;;; ;;;; Author: Cole Scott (in-package #:magicl) (deftensor tensor/complex-double-float (complex double-float)) (defmatrix matrix/complex-double-float (complex double-float) tensor/complex-double-float) (defvector vector/complex-double-float (complex double-float) tensor/complex-double-float) (defcompatible (lambda (tensor) (case (order tensor) (1 '(vector/complex-double-float tensor/complex-double-float)) (2 '(matrix/complex-double-float tensor/complex-double-float)) (t '(tensor/complex-double-float)))) tensor/complex-double-float matrix/complex-double-float vector/complex-double-float) (defmethod dot ((vector1 vector/complex-double-float) (vector2 vector/complex-double-float)) (assert (cl:= (size vector1) (size vector2)) () "Vectors must have the same size. The first vector is size ~a and the second vector is size ~a." (size vector1) (size vector2)) (loop :for i :below (size vector1) :sum (* (tref vector1 i) (conjugate (tref vector2 i))))) (defmethod =-lisp ((tensor1 tensor/complex-double-float) (tensor2 tensor/complex-double-float) &optional (epsilon *double-comparison-threshold*)) (unless (equal (shape tensor1) (shape tensor2)) (return-from =-lisp nil)) (map-indexes (shape tensor1) (lambda (&rest pos) (unless (and (<= (abs (- (realpart (apply #'tref tensor1 pos)) (realpart (apply #'tref tensor2 pos)))) epsilon) (<= (abs (- (imagpart (apply #'tref tensor1 pos)) (imagpart (apply #'tref tensor2 pos)))) epsilon)) (return-from =-lisp nil)))) t) (defmethod =-lisp ((tensor1 matrix/complex-double-float) (tensor2 matrix/complex-double-float) &optional (epsilon *double-comparison-threshold*)) (unless (equal (shape tensor1) (shape tensor2)) (return-from =-lisp nil)) (map-indexes (shape tensor1) (lambda (&rest pos) (unless (and (<= (abs (- (realpart (apply #'tref tensor1 pos)) (realpart (apply #'tref tensor2 pos)))) epsilon) (<= (abs (- (imagpart (apply #'tref tensor1 pos)) (imagpart (apply #'tref tensor2 pos)))) epsilon)) (return-from =-lisp nil)))) t) (defmethod =-lisp ((tensor1 vector/complex-double-float) (tensor2 vector/complex-double-float) &optional (epsilon *double-comparison-threshold*)) (unless (equal (shape tensor1) (shape tensor2)) (return-from =-lisp nil)) (map-indexes (shape tensor1) (lambda (&rest pos) (unless (and (<= (abs (- (realpart (apply #'tref tensor1 pos)) (realpart (apply #'tref tensor2 pos)))) epsilon) (<= (abs (- (imagpart (apply #'tref tensor1 pos)) (imagpart (apply #'tref tensor2 pos)))) epsilon)) (return-from =-lisp nil)))) t)
51546
;;;; complex-double-float.lisp ;;;; ;;;; Author: <NAME> (in-package #:magicl) (deftensor tensor/complex-double-float (complex double-float)) (defmatrix matrix/complex-double-float (complex double-float) tensor/complex-double-float) (defvector vector/complex-double-float (complex double-float) tensor/complex-double-float) (defcompatible (lambda (tensor) (case (order tensor) (1 '(vector/complex-double-float tensor/complex-double-float)) (2 '(matrix/complex-double-float tensor/complex-double-float)) (t '(tensor/complex-double-float)))) tensor/complex-double-float matrix/complex-double-float vector/complex-double-float) (defmethod dot ((vector1 vector/complex-double-float) (vector2 vector/complex-double-float)) (assert (cl:= (size vector1) (size vector2)) () "Vectors must have the same size. The first vector is size ~a and the second vector is size ~a." (size vector1) (size vector2)) (loop :for i :below (size vector1) :sum (* (tref vector1 i) (conjugate (tref vector2 i))))) (defmethod =-lisp ((tensor1 tensor/complex-double-float) (tensor2 tensor/complex-double-float) &optional (epsilon *double-comparison-threshold*)) (unless (equal (shape tensor1) (shape tensor2)) (return-from =-lisp nil)) (map-indexes (shape tensor1) (lambda (&rest pos) (unless (and (<= (abs (- (realpart (apply #'tref tensor1 pos)) (realpart (apply #'tref tensor2 pos)))) epsilon) (<= (abs (- (imagpart (apply #'tref tensor1 pos)) (imagpart (apply #'tref tensor2 pos)))) epsilon)) (return-from =-lisp nil)))) t) (defmethod =-lisp ((tensor1 matrix/complex-double-float) (tensor2 matrix/complex-double-float) &optional (epsilon *double-comparison-threshold*)) (unless (equal (shape tensor1) (shape tensor2)) (return-from =-lisp nil)) (map-indexes (shape tensor1) (lambda (&rest pos) (unless (and (<= (abs (- (realpart (apply #'tref tensor1 pos)) (realpart (apply #'tref tensor2 pos)))) epsilon) (<= (abs (- (imagpart (apply #'tref tensor1 pos)) (imagpart (apply #'tref tensor2 pos)))) epsilon)) (return-from =-lisp nil)))) t) (defmethod =-lisp ((tensor1 vector/complex-double-float) (tensor2 vector/complex-double-float) &optional (epsilon *double-comparison-threshold*)) (unless (equal (shape tensor1) (shape tensor2)) (return-from =-lisp nil)) (map-indexes (shape tensor1) (lambda (&rest pos) (unless (and (<= (abs (- (realpart (apply #'tref tensor1 pos)) (realpart (apply #'tref tensor2 pos)))) epsilon) (<= (abs (- (imagpart (apply #'tref tensor1 pos)) (imagpart (apply #'tref tensor2 pos)))) epsilon)) (return-from =-lisp nil)))) t)
true
;;;; complex-double-float.lisp ;;;; ;;;; Author: PI:NAME:<NAME>END_PI (in-package #:magicl) (deftensor tensor/complex-double-float (complex double-float)) (defmatrix matrix/complex-double-float (complex double-float) tensor/complex-double-float) (defvector vector/complex-double-float (complex double-float) tensor/complex-double-float) (defcompatible (lambda (tensor) (case (order tensor) (1 '(vector/complex-double-float tensor/complex-double-float)) (2 '(matrix/complex-double-float tensor/complex-double-float)) (t '(tensor/complex-double-float)))) tensor/complex-double-float matrix/complex-double-float vector/complex-double-float) (defmethod dot ((vector1 vector/complex-double-float) (vector2 vector/complex-double-float)) (assert (cl:= (size vector1) (size vector2)) () "Vectors must have the same size. The first vector is size ~a and the second vector is size ~a." (size vector1) (size vector2)) (loop :for i :below (size vector1) :sum (* (tref vector1 i) (conjugate (tref vector2 i))))) (defmethod =-lisp ((tensor1 tensor/complex-double-float) (tensor2 tensor/complex-double-float) &optional (epsilon *double-comparison-threshold*)) (unless (equal (shape tensor1) (shape tensor2)) (return-from =-lisp nil)) (map-indexes (shape tensor1) (lambda (&rest pos) (unless (and (<= (abs (- (realpart (apply #'tref tensor1 pos)) (realpart (apply #'tref tensor2 pos)))) epsilon) (<= (abs (- (imagpart (apply #'tref tensor1 pos)) (imagpart (apply #'tref tensor2 pos)))) epsilon)) (return-from =-lisp nil)))) t) (defmethod =-lisp ((tensor1 matrix/complex-double-float) (tensor2 matrix/complex-double-float) &optional (epsilon *double-comparison-threshold*)) (unless (equal (shape tensor1) (shape tensor2)) (return-from =-lisp nil)) (map-indexes (shape tensor1) (lambda (&rest pos) (unless (and (<= (abs (- (realpart (apply #'tref tensor1 pos)) (realpart (apply #'tref tensor2 pos)))) epsilon) (<= (abs (- (imagpart (apply #'tref tensor1 pos)) (imagpart (apply #'tref tensor2 pos)))) epsilon)) (return-from =-lisp nil)))) t) (defmethod =-lisp ((tensor1 vector/complex-double-float) (tensor2 vector/complex-double-float) &optional (epsilon *double-comparison-threshold*)) (unless (equal (shape tensor1) (shape tensor2)) (return-from =-lisp nil)) (map-indexes (shape tensor1) (lambda (&rest pos) (unless (and (<= (abs (- (realpart (apply #'tref tensor1 pos)) (realpart (apply #'tref tensor2 pos)))) epsilon) (<= (abs (- (imagpart (apply #'tref tensor1 pos)) (imagpart (apply #'tref tensor2 pos)))) epsilon)) (return-from =-lisp nil)))) t)
[ { "context": "; package: cl-user -*-\n;;; Copyright (c) 2004-2005 Tiago Maduro-Dias. All Rights Reserved.\n;;;\n;;; This code is free s", "end": 86, "score": 0.9998981356620789, "start": 69, "tag": "NAME", "value": "Tiago Maduro-Dias" }, { "context": "utility library.\"\n :version \"0.6\"\n :author \"Tiago Maduro-Dias <[email protected]>\"\n :components ((:file \"utils", "end": 1409, "score": 0.9998953938484192, "start": 1392, "tag": "NAME", "value": "Tiago Maduro-Dias" }, { "context": " :version \"0.6\"\n :author \"Tiago Maduro-Dias <[email protected]>\"\n :components ((:file \"utils\")\n ", "end": 1426, "score": 0.9999312162399292, "start": 1411, "tag": "EMAIL", "value": "[email protected]" } ]
platform/site-lisp/jnil/support/jnil-support.asd
TeamSPoon/CYC_JRTL_with_CommonLisp_OLD
10
;;; -*- mode: lisp; package: cl-user -*- ;;; Copyright (c) 2004-2005 Tiago Maduro-Dias. All Rights Reserved. ;;; ;;; This code is free software; you can redistribute it and/or ;;; modify it under the terms of the version 2.1 of ;;; the GNU Lesser General Public License as published by ;;; the Free Software Foundation, as clarified by the preamble ;;; found in license-llgpl.txt. ;;; ;;; This code 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 General Public License for more details. ;;; ;;; Version 2.1 of the GNU Lesser General Public License is in the file ;;; license-lgpl.txt that was distributed with this file. ;;; If it is not present, you can access it from ;;; http://www.gnu.org/copyleft/lesser.txt (until superseded by a newer ;;; version) or write to the Free Software Foundation, Inc., 59 Temple Place, ;;; Suite 330, Boston, MA 02111-1307 USA ;;; ;;; $Id: jnil-support.asd,v 1.1.1.1 2006/04/23 17:11:48 tdias Exp $ ;;; ;;; Description: System definition for Jnil's support facilities. ;;; ;;; -- start of jnil-support.asd -- ;;;;;;;;;;;;;;;;;;;;;;;;; ;;; system definition ;;; ;;;;;;;;;;;;;;;;;;;;;;;;; (asdf:defsystem :jnil-support :description "Jnil's support utility library." :version "0.6" :author "Tiago Maduro-Dias <[email protected]>" :components ((:file "utils") (:file "foreigns" :depends-on ("utils")))) ;;; -- end of jnil-support.asd --
94037
;;; -*- mode: lisp; package: cl-user -*- ;;; Copyright (c) 2004-2005 <NAME>. All Rights Reserved. ;;; ;;; This code is free software; you can redistribute it and/or ;;; modify it under the terms of the version 2.1 of ;;; the GNU Lesser General Public License as published by ;;; the Free Software Foundation, as clarified by the preamble ;;; found in license-llgpl.txt. ;;; ;;; This code 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 General Public License for more details. ;;; ;;; Version 2.1 of the GNU Lesser General Public License is in the file ;;; license-lgpl.txt that was distributed with this file. ;;; If it is not present, you can access it from ;;; http://www.gnu.org/copyleft/lesser.txt (until superseded by a newer ;;; version) or write to the Free Software Foundation, Inc., 59 Temple Place, ;;; Suite 330, Boston, MA 02111-1307 USA ;;; ;;; $Id: jnil-support.asd,v 1.1.1.1 2006/04/23 17:11:48 tdias Exp $ ;;; ;;; Description: System definition for Jnil's support facilities. ;;; ;;; -- start of jnil-support.asd -- ;;;;;;;;;;;;;;;;;;;;;;;;; ;;; system definition ;;; ;;;;;;;;;;;;;;;;;;;;;;;;; (asdf:defsystem :jnil-support :description "Jnil's support utility library." :version "0.6" :author "<NAME> <<EMAIL>>" :components ((:file "utils") (:file "foreigns" :depends-on ("utils")))) ;;; -- end of jnil-support.asd --
true
;;; -*- mode: lisp; package: cl-user -*- ;;; Copyright (c) 2004-2005 PI:NAME:<NAME>END_PI. All Rights Reserved. ;;; ;;; This code is free software; you can redistribute it and/or ;;; modify it under the terms of the version 2.1 of ;;; the GNU Lesser General Public License as published by ;;; the Free Software Foundation, as clarified by the preamble ;;; found in license-llgpl.txt. ;;; ;;; This code 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 General Public License for more details. ;;; ;;; Version 2.1 of the GNU Lesser General Public License is in the file ;;; license-lgpl.txt that was distributed with this file. ;;; If it is not present, you can access it from ;;; http://www.gnu.org/copyleft/lesser.txt (until superseded by a newer ;;; version) or write to the Free Software Foundation, Inc., 59 Temple Place, ;;; Suite 330, Boston, MA 02111-1307 USA ;;; ;;; $Id: jnil-support.asd,v 1.1.1.1 2006/04/23 17:11:48 tdias Exp $ ;;; ;;; Description: System definition for Jnil's support facilities. ;;; ;;; -- start of jnil-support.asd -- ;;;;;;;;;;;;;;;;;;;;;;;;; ;;; system definition ;;; ;;;;;;;;;;;;;;;;;;;;;;;;; (asdf:defsystem :jnil-support :description "Jnil's support utility library." :version "0.6" :author "PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>" :components ((:file "utils") (:file "foreigns" :depends-on ("utils")))) ;;; -- end of jnil-support.asd --
[ { "context": "ommon-lisp-style: poem -*-\n\n;;; Copyright (c) 2013 Matthias Hölzl\n;;;\n;;; This file is licensed under the MIT licen", "end": 86, "score": 0.9998577237129211, "start": 72, "tag": "NAME", "value": "Matthias Hölzl" } ]
Core/package-utils.lisp
hoelzl/Iliad
2
;;; -*- Mode: Lisp; common-lisp-style: poem -*- ;;; Copyright (c) 2013 Matthias Hölzl ;;; ;;; This file is licensed under the MIT license; see the file LICENSE in the root directory for ;;; further information. (in-package #:poem-bootstrap) (defun get-package-external-symbols (package-name &optional (ignored-symbols '())) (let ((result '()) (package (find-package package-name))) (assert package (package) "No package named ~A." package-name) (do-external-symbols (symbol package) (unless (member symbol ignored-symbols :test (lambda (s1 s2) (string-equal (symbol-name s1) (symbol-name s2)))) (push symbol result))) result)) (defun as-strings (symbols) (mapcar (lambda (symbol) (symbol-name symbol)) symbols)) (defun as-uninterned-symbols (strings) (mapcar (lambda (string) (make-symbol string)) strings)) (defun package-external-symbol-names (package-name &optional (ignored-symbols '())) (sort (as-strings (get-package-external-symbols package-name ignored-symbols)) #'string-lessp)) (defun package-external-symbols (package-name &optional (ignored-symbols '())) (as-uninterned-symbols (package-external-symbol-names package-name ignored-symbols))) (defun package-exports-name (package-name) (assert (symbolp package-name) () "Package name must be a symbol, is ~A" package-name) (intern (format nil "*~A-~A*" package-name '#:package-exports))) (defmacro define-package-exports (package-name &rest ignored-symbols) `(defparameter ,(package-exports-name package-name) ',(package-external-symbol-names package-name ignored-symbols)))
29845
;;; -*- Mode: Lisp; common-lisp-style: poem -*- ;;; Copyright (c) 2013 <NAME> ;;; ;;; This file is licensed under the MIT license; see the file LICENSE in the root directory for ;;; further information. (in-package #:poem-bootstrap) (defun get-package-external-symbols (package-name &optional (ignored-symbols '())) (let ((result '()) (package (find-package package-name))) (assert package (package) "No package named ~A." package-name) (do-external-symbols (symbol package) (unless (member symbol ignored-symbols :test (lambda (s1 s2) (string-equal (symbol-name s1) (symbol-name s2)))) (push symbol result))) result)) (defun as-strings (symbols) (mapcar (lambda (symbol) (symbol-name symbol)) symbols)) (defun as-uninterned-symbols (strings) (mapcar (lambda (string) (make-symbol string)) strings)) (defun package-external-symbol-names (package-name &optional (ignored-symbols '())) (sort (as-strings (get-package-external-symbols package-name ignored-symbols)) #'string-lessp)) (defun package-external-symbols (package-name &optional (ignored-symbols '())) (as-uninterned-symbols (package-external-symbol-names package-name ignored-symbols))) (defun package-exports-name (package-name) (assert (symbolp package-name) () "Package name must be a symbol, is ~A" package-name) (intern (format nil "*~A-~A*" package-name '#:package-exports))) (defmacro define-package-exports (package-name &rest ignored-symbols) `(defparameter ,(package-exports-name package-name) ',(package-external-symbol-names package-name ignored-symbols)))
true
;;; -*- Mode: Lisp; common-lisp-style: poem -*- ;;; Copyright (c) 2013 PI:NAME:<NAME>END_PI ;;; ;;; This file is licensed under the MIT license; see the file LICENSE in the root directory for ;;; further information. (in-package #:poem-bootstrap) (defun get-package-external-symbols (package-name &optional (ignored-symbols '())) (let ((result '()) (package (find-package package-name))) (assert package (package) "No package named ~A." package-name) (do-external-symbols (symbol package) (unless (member symbol ignored-symbols :test (lambda (s1 s2) (string-equal (symbol-name s1) (symbol-name s2)))) (push symbol result))) result)) (defun as-strings (symbols) (mapcar (lambda (symbol) (symbol-name symbol)) symbols)) (defun as-uninterned-symbols (strings) (mapcar (lambda (string) (make-symbol string)) strings)) (defun package-external-symbol-names (package-name &optional (ignored-symbols '())) (sort (as-strings (get-package-external-symbols package-name ignored-symbols)) #'string-lessp)) (defun package-external-symbols (package-name &optional (ignored-symbols '())) (as-uninterned-symbols (package-external-symbol-names package-name ignored-symbols))) (defun package-exports-name (package-name) (assert (symbolp package-name) () "Package name must be a symbol, is ~A" package-name) (intern (format nil "*~A-~A*" package-name '#:package-exports))) (defmacro define-package-exports (package-name &rest ignored-symbols) `(defparameter ,(package-exports-name package-name) ',(package-external-symbol-names package-name ignored-symbols)))
[ { "context": ";;;; pkg.lisp\n\n;;;; Copyright (C) 2016, 2017 Takahiro Ishikawa\n;;;;\n;;;; Permission is hereby granted, free of c", "end": 62, "score": 0.9998291730880737, "start": 45, "tag": "NAME", "value": "Takahiro Ishikawa" } ]
pkg.lisp
takahish/cl-gsl
1
;;;; pkg.lisp ;;;; Copyright (C) 2016, 2017 Takahiro Ishikawa ;;;; ;;;; 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. (cl:defpackage "TENSOR" (:use "CL") (:export ;; util.lisp "LAST1" "FLATTEN" "RANGE" "WHILE" "WITH-GENSYMS" ;; vector-type.lisp "MAKE-VECTOR" "SHARED-VECTOR" ; accessor of vector-view ;; vector.lisp "VECTOR-COERCE" "VECTOR-GET" "VECTOR-SET" "VECTOR-SET-ALL" "VECTOR-SET-ZERO" "VECTOR-SET-BASIS" "VECTOR-SUBVECTOR" "VECTOR-VIEW-ARRAY" "VECTOR-COPY" "VECTOR-SWAP-ELEMENTS" "VECTOR-REVERSE" "VECTOR-ADD" "VECTOR-SUB" "VECTOR-MUL" "VECTOR-DIV" "VECTOR-SCALE" "VECTOR-ADD-CONSTANT" "VECTOR-MAX" "VECTOR-MIN" "VECTOR-MINMAX" "VECTOR-MAX-INDEX" "VECTOR-MIN-INDEX" "VECTOR-MINMAX-INDEX" "VECTOR-ISNULL" "VECTOR-ISPOS" "VECTOR-ISNEG" "VECTOR-ISNONNEG" "VECTOR-EQUAL" "VECTOR-READ" "VECTOR-WRITE" "VECTOR-MAP" "VECTOR-REDUCE" "VECTOR-COUNT-IF" "VECTOR-REMOVE-IF" ;; matrix-type.lisp "MAKE-MATRIX" "SHARED-MATRIX" ; accessor of matrix-view ;; matrix.lisp "MATRIX-COERCE" "MATRIX-GET" "MATRIX-SET" "MATRIX-SET-ALL" "MATRIX-SET-ZERO" "MATRIX-SET-IDENTITY" "MATRIX-SUBMATRIX" "MATRIX-VIEW-VECTOR" "MATRIX-VIEW-ARRAY" "MATRIX-ROW" "MATRIX-COLUMN" "MATRIX-SUBROW" "MATRIX-SUBCOLUMN" "MATRIX-DIAGONAL" "MATRIX-SUBDIAGONAL" "MATRIX-SUPERDIAGONAL" "MATRIX-COPY" "MATRIX-GET-ROW" "MATRIX-SET-ROW" "MATRIX-GET-COL" "MATRIX-SET-COL" "MATRIX-SWAP-ROWS" "MATRIX-SWAP-COLUMNS" "MATRIX-TRANSPOSE" "MATRIX-ADD" "MATRIX-SUB" "MATRIX-MUL-ELEMENTS" "MATRIX-DIV-ELEMENTS" "MATRIX-SCALE" "MATRIX-ADD-CONSTANT" "MATRIX-MAX" "MATRIX-MIN" "MATRIX-MINMAX" "MATRIX-MAX-INDEX" "MATRIX-MIN-INDEX" "MATRIX-MINMAX-INDEX" "MATRIX-ISNULL" "MATRIX-ISPOS" "MATRIX-ISNEG" "MATRIX-ISNONNEG" "MATRIX-EQUAL" "MATRIX-READ" "MATRIX-WRITE" ;; permutation-type.lisp "MAKE-PERMUTATION" "PERMUTATION-INIT" ;; permutation.lisp "PERMUTATION-COPY" "PERMUTATION-GET" "PERMUTATION-SWAP" "PERMUTATION-VALID" "PERMUTATION-REVERSE" "PERMUTATION-INVERSE" "PERMUTATION-NEXT" "PERMUTATION-PREV" "PERMUTATION-MUL" "PERMUTE-VECTOR" "PERMUTE-VECTOR-INVERSE" "PERMUTE-MATRIX" "PERMUTATION-LINEAR-TO-CANONICAL" "PERMUTATION-CANONICAL-TO-LINEAR" "PERMUTATION-INVERSIONS" "PERMUTATION-LINEAR-CYCLES" "PERMUTATION-CANONICAL-CYCLES" ;; blas/blas.lisp "BLAS-DOT" "BLAS-NRM2" "BLAS-ASUM" "BLAS-IAMAX" "BLAS-SWAP" "BLAS-COPY" "BLAS-AXPY" "BLAS-SCAL" "BLAS-ROTG" "BLAS-ROT" "BLAS-ROTMG" "BLAS-ROTM" "BLAS-GEMV" "BLAS-TRMV" "BLAS-SYMV" "BLAS-GER" "BLAS-SYR" "BLAS-SYR2" "BLAS-GEMM" "BLAS-SYMM" "BLAS-TRMM" "BLAS-TRSM" "BLAS-SYRK" "BLAS-SYR2K")) (cl:in-package "TENSOR") (cffi:define-foreign-library libcblas (:darwin "libcblas.dylib") (:unix "libcblas.so") (t (:default "libcblas"))) (cffi:use-foreign-library libcblas)
38794
;;;; pkg.lisp ;;;; Copyright (C) 2016, 2017 <NAME> ;;;; ;;;; Permission is hereby granted, free of charge, to any person ;;;; obtaining a copy of this software and associated documentation ;;;; files (the "Software"), to deal in the Software without ;;;; restriction, including without limitation the rights to use, ;;;; copy, modify, merge, publish, distribute, sublicense, and/or sell ;;;; copies of the Software, and to permit persons to whom the ;;;; Software is furnished to do so, subject to the following ;;;; conditions: ;;;; ;;;; The above copyright notice and this permission notice shall be ;;;; included in all copies or substantial portions of the Software. ;;;; ;;;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, ;;;; EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES ;;;; OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND ;;;; NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT ;;;; HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, ;;;; WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING ;;;; FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR ;;;; OTHER DEALINGS IN THE SOFTWARE. (cl:defpackage "TENSOR" (:use "CL") (:export ;; util.lisp "LAST1" "FLATTEN" "RANGE" "WHILE" "WITH-GENSYMS" ;; vector-type.lisp "MAKE-VECTOR" "SHARED-VECTOR" ; accessor of vector-view ;; vector.lisp "VECTOR-COERCE" "VECTOR-GET" "VECTOR-SET" "VECTOR-SET-ALL" "VECTOR-SET-ZERO" "VECTOR-SET-BASIS" "VECTOR-SUBVECTOR" "VECTOR-VIEW-ARRAY" "VECTOR-COPY" "VECTOR-SWAP-ELEMENTS" "VECTOR-REVERSE" "VECTOR-ADD" "VECTOR-SUB" "VECTOR-MUL" "VECTOR-DIV" "VECTOR-SCALE" "VECTOR-ADD-CONSTANT" "VECTOR-MAX" "VECTOR-MIN" "VECTOR-MINMAX" "VECTOR-MAX-INDEX" "VECTOR-MIN-INDEX" "VECTOR-MINMAX-INDEX" "VECTOR-ISNULL" "VECTOR-ISPOS" "VECTOR-ISNEG" "VECTOR-ISNONNEG" "VECTOR-EQUAL" "VECTOR-READ" "VECTOR-WRITE" "VECTOR-MAP" "VECTOR-REDUCE" "VECTOR-COUNT-IF" "VECTOR-REMOVE-IF" ;; matrix-type.lisp "MAKE-MATRIX" "SHARED-MATRIX" ; accessor of matrix-view ;; matrix.lisp "MATRIX-COERCE" "MATRIX-GET" "MATRIX-SET" "MATRIX-SET-ALL" "MATRIX-SET-ZERO" "MATRIX-SET-IDENTITY" "MATRIX-SUBMATRIX" "MATRIX-VIEW-VECTOR" "MATRIX-VIEW-ARRAY" "MATRIX-ROW" "MATRIX-COLUMN" "MATRIX-SUBROW" "MATRIX-SUBCOLUMN" "MATRIX-DIAGONAL" "MATRIX-SUBDIAGONAL" "MATRIX-SUPERDIAGONAL" "MATRIX-COPY" "MATRIX-GET-ROW" "MATRIX-SET-ROW" "MATRIX-GET-COL" "MATRIX-SET-COL" "MATRIX-SWAP-ROWS" "MATRIX-SWAP-COLUMNS" "MATRIX-TRANSPOSE" "MATRIX-ADD" "MATRIX-SUB" "MATRIX-MUL-ELEMENTS" "MATRIX-DIV-ELEMENTS" "MATRIX-SCALE" "MATRIX-ADD-CONSTANT" "MATRIX-MAX" "MATRIX-MIN" "MATRIX-MINMAX" "MATRIX-MAX-INDEX" "MATRIX-MIN-INDEX" "MATRIX-MINMAX-INDEX" "MATRIX-ISNULL" "MATRIX-ISPOS" "MATRIX-ISNEG" "MATRIX-ISNONNEG" "MATRIX-EQUAL" "MATRIX-READ" "MATRIX-WRITE" ;; permutation-type.lisp "MAKE-PERMUTATION" "PERMUTATION-INIT" ;; permutation.lisp "PERMUTATION-COPY" "PERMUTATION-GET" "PERMUTATION-SWAP" "PERMUTATION-VALID" "PERMUTATION-REVERSE" "PERMUTATION-INVERSE" "PERMUTATION-NEXT" "PERMUTATION-PREV" "PERMUTATION-MUL" "PERMUTE-VECTOR" "PERMUTE-VECTOR-INVERSE" "PERMUTE-MATRIX" "PERMUTATION-LINEAR-TO-CANONICAL" "PERMUTATION-CANONICAL-TO-LINEAR" "PERMUTATION-INVERSIONS" "PERMUTATION-LINEAR-CYCLES" "PERMUTATION-CANONICAL-CYCLES" ;; blas/blas.lisp "BLAS-DOT" "BLAS-NRM2" "BLAS-ASUM" "BLAS-IAMAX" "BLAS-SWAP" "BLAS-COPY" "BLAS-AXPY" "BLAS-SCAL" "BLAS-ROTG" "BLAS-ROT" "BLAS-ROTMG" "BLAS-ROTM" "BLAS-GEMV" "BLAS-TRMV" "BLAS-SYMV" "BLAS-GER" "BLAS-SYR" "BLAS-SYR2" "BLAS-GEMM" "BLAS-SYMM" "BLAS-TRMM" "BLAS-TRSM" "BLAS-SYRK" "BLAS-SYR2K")) (cl:in-package "TENSOR") (cffi:define-foreign-library libcblas (:darwin "libcblas.dylib") (:unix "libcblas.so") (t (:default "libcblas"))) (cffi:use-foreign-library libcblas)
true
;;;; pkg.lisp ;;;; Copyright (C) 2016, 2017 PI:NAME:<NAME>END_PI ;;;; ;;;; Permission is hereby granted, free of charge, to any person ;;;; obtaining a copy of this software and associated documentation ;;;; files (the "Software"), to deal in the Software without ;;;; restriction, including without limitation the rights to use, ;;;; copy, modify, merge, publish, distribute, sublicense, and/or sell ;;;; copies of the Software, and to permit persons to whom the ;;;; Software is furnished to do so, subject to the following ;;;; conditions: ;;;; ;;;; The above copyright notice and this permission notice shall be ;;;; included in all copies or substantial portions of the Software. ;;;; ;;;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, ;;;; EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES ;;;; OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND ;;;; NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT ;;;; HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, ;;;; WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING ;;;; FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR ;;;; OTHER DEALINGS IN THE SOFTWARE. (cl:defpackage "TENSOR" (:use "CL") (:export ;; util.lisp "LAST1" "FLATTEN" "RANGE" "WHILE" "WITH-GENSYMS" ;; vector-type.lisp "MAKE-VECTOR" "SHARED-VECTOR" ; accessor of vector-view ;; vector.lisp "VECTOR-COERCE" "VECTOR-GET" "VECTOR-SET" "VECTOR-SET-ALL" "VECTOR-SET-ZERO" "VECTOR-SET-BASIS" "VECTOR-SUBVECTOR" "VECTOR-VIEW-ARRAY" "VECTOR-COPY" "VECTOR-SWAP-ELEMENTS" "VECTOR-REVERSE" "VECTOR-ADD" "VECTOR-SUB" "VECTOR-MUL" "VECTOR-DIV" "VECTOR-SCALE" "VECTOR-ADD-CONSTANT" "VECTOR-MAX" "VECTOR-MIN" "VECTOR-MINMAX" "VECTOR-MAX-INDEX" "VECTOR-MIN-INDEX" "VECTOR-MINMAX-INDEX" "VECTOR-ISNULL" "VECTOR-ISPOS" "VECTOR-ISNEG" "VECTOR-ISNONNEG" "VECTOR-EQUAL" "VECTOR-READ" "VECTOR-WRITE" "VECTOR-MAP" "VECTOR-REDUCE" "VECTOR-COUNT-IF" "VECTOR-REMOVE-IF" ;; matrix-type.lisp "MAKE-MATRIX" "SHARED-MATRIX" ; accessor of matrix-view ;; matrix.lisp "MATRIX-COERCE" "MATRIX-GET" "MATRIX-SET" "MATRIX-SET-ALL" "MATRIX-SET-ZERO" "MATRIX-SET-IDENTITY" "MATRIX-SUBMATRIX" "MATRIX-VIEW-VECTOR" "MATRIX-VIEW-ARRAY" "MATRIX-ROW" "MATRIX-COLUMN" "MATRIX-SUBROW" "MATRIX-SUBCOLUMN" "MATRIX-DIAGONAL" "MATRIX-SUBDIAGONAL" "MATRIX-SUPERDIAGONAL" "MATRIX-COPY" "MATRIX-GET-ROW" "MATRIX-SET-ROW" "MATRIX-GET-COL" "MATRIX-SET-COL" "MATRIX-SWAP-ROWS" "MATRIX-SWAP-COLUMNS" "MATRIX-TRANSPOSE" "MATRIX-ADD" "MATRIX-SUB" "MATRIX-MUL-ELEMENTS" "MATRIX-DIV-ELEMENTS" "MATRIX-SCALE" "MATRIX-ADD-CONSTANT" "MATRIX-MAX" "MATRIX-MIN" "MATRIX-MINMAX" "MATRIX-MAX-INDEX" "MATRIX-MIN-INDEX" "MATRIX-MINMAX-INDEX" "MATRIX-ISNULL" "MATRIX-ISPOS" "MATRIX-ISNEG" "MATRIX-ISNONNEG" "MATRIX-EQUAL" "MATRIX-READ" "MATRIX-WRITE" ;; permutation-type.lisp "MAKE-PERMUTATION" "PERMUTATION-INIT" ;; permutation.lisp "PERMUTATION-COPY" "PERMUTATION-GET" "PERMUTATION-SWAP" "PERMUTATION-VALID" "PERMUTATION-REVERSE" "PERMUTATION-INVERSE" "PERMUTATION-NEXT" "PERMUTATION-PREV" "PERMUTATION-MUL" "PERMUTE-VECTOR" "PERMUTE-VECTOR-INVERSE" "PERMUTE-MATRIX" "PERMUTATION-LINEAR-TO-CANONICAL" "PERMUTATION-CANONICAL-TO-LINEAR" "PERMUTATION-INVERSIONS" "PERMUTATION-LINEAR-CYCLES" "PERMUTATION-CANONICAL-CYCLES" ;; blas/blas.lisp "BLAS-DOT" "BLAS-NRM2" "BLAS-ASUM" "BLAS-IAMAX" "BLAS-SWAP" "BLAS-COPY" "BLAS-AXPY" "BLAS-SCAL" "BLAS-ROTG" "BLAS-ROT" "BLAS-ROTMG" "BLAS-ROTM" "BLAS-GEMV" "BLAS-TRMV" "BLAS-SYMV" "BLAS-GER" "BLAS-SYR" "BLAS-SYR2" "BLAS-GEMM" "BLAS-SYMM" "BLAS-TRMM" "BLAS-TRSM" "BLAS-SYRK" "BLAS-SYR2K")) (cl:in-package "TENSOR") (cffi:define-foreign-library libcblas (:darwin "libcblas.dylib") (:unix "libcblas.so") (t (:default "libcblas"))) (cffi:use-foreign-library libcblas)
[ { "context": "2015, University of British Columbia\n;; Written by Yan Peng (August 2nd 2016)\n;;\n;; License: A 3-clause BSD l", "end": 76, "score": 0.9996035695075989, "start": 68, "tag": "NAME", "value": "Yan Peng" } ]
books/projects/smtlink/verified/basics.lisp
MattKaufmann/acl2
305
;; Copyright (C) 2015, University of British Columbia ;; Written by Yan Peng (August 2nd 2016) ;; ;; License: A 3-clause BSD license. ;; See the LICENSE file distributed with ACL2 ;; (in-package "SMT") (include-book "xdoc/top" :dir :system) (include-book "std/util/defval" :dir :system) (include-book "std/strings/decimal" :dir :system) (include-book "std/strings/case-conversion" :dir :system) (defxdoc SMT-basics :parents (verified) :short "Basic functions and types in Smtlink.") (defval *SMT-basics* :parents (SMT-basics) :short "Basic ACL2 functions supported in Smtlink." (append '(magic-fix) '(rationalp realp booleanp integerp symbolp) '(binary-+ binary-* unary-/ unary-- equal < implies if not lambda))) (defval *SMT-functions* :parents (SMT-functions) :short "ACL2 functions and their corresponding Z3 functions." ;;(ACL2 function . (SMT function Least # of arguments)) `((binary-+ . ("_SMT_.plus" . 1)) (binary-* . ("_SMT_.times" . 1)) (unary-/ . ("_SMT_.reciprocal" . 1)) (unary-- . ("_SMT_.negate" . 1)) (equal . ("_SMT_.equal" . 2)) (< . ("_SMT_.lt" . 2)) (if . ("_SMT_.ifx" . 3)) (not . ("_SMT_.notx" . 1)) (lambda . ("lambda" . 2)) (implies . ("_SMT_.implies" . 2)) ;; (hint-please . ("_SMT_.hint_okay" . 0)) ;; This doesn't work right now because Z3's definition is different from ACL2 ;; when using types as hypotheses. If X is rationalp in Z3, then it can not ;; be an integerp. We need to first grab a definition in Z3 that can fully ;; capture its ACL2 meaning. ;; (integerp . ("_SMT_.integerp" . 1)) ;; (rationalp . ("_SMT_.rationalp" . 1)) ;; (booleanp . ("_SMT_.booleanp" . 1)) )) (defval *SMT-types* :parents (SMT-basics) :short "ACL2 type functions and their corresponding Z3 type declarations." ;;(ACL2 type . SMT type) `((realp . "_SMT_.RealSort()") (rationalp . "_SMT_.RealSort()") (integerp . "_SMT_.IntSort()") (booleanp . "_SMT_.BoolSort()") (symbolp . "Symbol_z3.z3Sym"))) (defval *SMT-uninterpreted-types* :parents (SMT-basics) :short "ACL2 type functions and their corresponding Z3 uninterpreted function type declarations." `((realp . "_SMT_.RealSort()") (rationalp . "_SMT_.RealSort()") (real/rationalp . "_SMT_.RealSort()") (integerp . "_SMT_.IntSort()") (booleanp . "_SMT_.BoolSort()") (symbolp . "Symbol_z3.z3Sym"))) ;; current tag . next computed-hint (defval *SMT-architecture* '((process-hint . add-hypo-cp) (add-hypo . expand-cp) (expand . type-extract-cp) (type-extract . uninterpreted-fn-cp) (uninterpreted . smt-trusted-cp) (uninterpreted-custom . smt-trusted-cp-custom))) ;;---------------------------------------------------------------- (encapsulate () (local (defun falist-to-xdoc-aux (falist acc) ;; collects a reversed list of strings (b* (((when (atom falist)) acc) ((cons facl2 (cons fsmt nargs)) (car falist)) (facl2-str (if (equal facl2 'hint-please) (list (downcase-string (symbol-name facl2))) `("@(see " ,(symbol-name facl2) ")"))) (entry `("<tr><td>" ,@facl2-str "</td><td>" ,fsmt "</td><td>" ,(natstr nargs) "</td></tr> "))) (falist-to-xdoc-aux (cdr falist) (revappend entry acc))))) (local (defun falist-to-xdoc () (declare (xargs :mode :program)) (str::string-append-lst `("<p></p> <table> <tr><th>ACL2 function</th><th>Z3 function</th><th>Nargs</th></tr> " ,@(reverse (falist-to-xdoc-aux *SMT-functions* nil)) "</table>")))) (make-event `(defxdoc SMT-functions :parents (SMT-basics) :short "SMT functions" :long ,(falist-to-xdoc)))) (encapsulate () (local (defun alist-to-xdoc-aux (alist acc) ;; collects a reversed list of strings (b* (((when (atom alist)) acc) ((cons facl2 fsmt) (car alist)) (facl2-str (if (equal facl2 'realp) (list (downcase-string (symbol-name facl2))) `("@(see " ,(symbol-name facl2) ")"))) (entry `("<tr><td>" ,@facl2-str "</td><td>" ,fsmt "</td></tr> "))) (alist-to-xdoc-aux (cdr alist) (revappend entry acc))))) (local (defun talist-to-xdoc () (declare (xargs :mode :program)) (str::string-append-lst `("<p></p> <table> <tr><th>ACL2 type functions</th><th>Z3 type declarations</th></tr> " ,@(reverse (alist-to-xdoc-aux *SMT-types* nil)) "</table>")))) (make-event `(defxdoc SMT-types :parents (SMT-basics) :short "SMT types" :long ,(talist-to-xdoc))) (local (defun ualist-to-xdoc () (declare (xargs :mode :program)) (str::string-append-lst `("<p></p> <table> <tr><th>ACL2 type functions</th><th>Z3 uninterpreted function type declarations</th></tr> " ,@(reverse (alist-to-xdoc-aux *SMT-uninterpreted-types* nil)) "</table>")))) (make-event `(defxdoc SMT-uninterpreted-types :parents (SMT-basics) :short "SMT uninterpreted function types" :long ,(ualist-to-xdoc))) )
80530
;; Copyright (C) 2015, University of British Columbia ;; Written by <NAME> (August 2nd 2016) ;; ;; License: A 3-clause BSD license. ;; See the LICENSE file distributed with ACL2 ;; (in-package "SMT") (include-book "xdoc/top" :dir :system) (include-book "std/util/defval" :dir :system) (include-book "std/strings/decimal" :dir :system) (include-book "std/strings/case-conversion" :dir :system) (defxdoc SMT-basics :parents (verified) :short "Basic functions and types in Smtlink.") (defval *SMT-basics* :parents (SMT-basics) :short "Basic ACL2 functions supported in Smtlink." (append '(magic-fix) '(rationalp realp booleanp integerp symbolp) '(binary-+ binary-* unary-/ unary-- equal < implies if not lambda))) (defval *SMT-functions* :parents (SMT-functions) :short "ACL2 functions and their corresponding Z3 functions." ;;(ACL2 function . (SMT function Least # of arguments)) `((binary-+ . ("_SMT_.plus" . 1)) (binary-* . ("_SMT_.times" . 1)) (unary-/ . ("_SMT_.reciprocal" . 1)) (unary-- . ("_SMT_.negate" . 1)) (equal . ("_SMT_.equal" . 2)) (< . ("_SMT_.lt" . 2)) (if . ("_SMT_.ifx" . 3)) (not . ("_SMT_.notx" . 1)) (lambda . ("lambda" . 2)) (implies . ("_SMT_.implies" . 2)) ;; (hint-please . ("_SMT_.hint_okay" . 0)) ;; This doesn't work right now because Z3's definition is different from ACL2 ;; when using types as hypotheses. If X is rationalp in Z3, then it can not ;; be an integerp. We need to first grab a definition in Z3 that can fully ;; capture its ACL2 meaning. ;; (integerp . ("_SMT_.integerp" . 1)) ;; (rationalp . ("_SMT_.rationalp" . 1)) ;; (booleanp . ("_SMT_.booleanp" . 1)) )) (defval *SMT-types* :parents (SMT-basics) :short "ACL2 type functions and their corresponding Z3 type declarations." ;;(ACL2 type . SMT type) `((realp . "_SMT_.RealSort()") (rationalp . "_SMT_.RealSort()") (integerp . "_SMT_.IntSort()") (booleanp . "_SMT_.BoolSort()") (symbolp . "Symbol_z3.z3Sym"))) (defval *SMT-uninterpreted-types* :parents (SMT-basics) :short "ACL2 type functions and their corresponding Z3 uninterpreted function type declarations." `((realp . "_SMT_.RealSort()") (rationalp . "_SMT_.RealSort()") (real/rationalp . "_SMT_.RealSort()") (integerp . "_SMT_.IntSort()") (booleanp . "_SMT_.BoolSort()") (symbolp . "Symbol_z3.z3Sym"))) ;; current tag . next computed-hint (defval *SMT-architecture* '((process-hint . add-hypo-cp) (add-hypo . expand-cp) (expand . type-extract-cp) (type-extract . uninterpreted-fn-cp) (uninterpreted . smt-trusted-cp) (uninterpreted-custom . smt-trusted-cp-custom))) ;;---------------------------------------------------------------- (encapsulate () (local (defun falist-to-xdoc-aux (falist acc) ;; collects a reversed list of strings (b* (((when (atom falist)) acc) ((cons facl2 (cons fsmt nargs)) (car falist)) (facl2-str (if (equal facl2 'hint-please) (list (downcase-string (symbol-name facl2))) `("@(see " ,(symbol-name facl2) ")"))) (entry `("<tr><td>" ,@facl2-str "</td><td>" ,fsmt "</td><td>" ,(natstr nargs) "</td></tr> "))) (falist-to-xdoc-aux (cdr falist) (revappend entry acc))))) (local (defun falist-to-xdoc () (declare (xargs :mode :program)) (str::string-append-lst `("<p></p> <table> <tr><th>ACL2 function</th><th>Z3 function</th><th>Nargs</th></tr> " ,@(reverse (falist-to-xdoc-aux *SMT-functions* nil)) "</table>")))) (make-event `(defxdoc SMT-functions :parents (SMT-basics) :short "SMT functions" :long ,(falist-to-xdoc)))) (encapsulate () (local (defun alist-to-xdoc-aux (alist acc) ;; collects a reversed list of strings (b* (((when (atom alist)) acc) ((cons facl2 fsmt) (car alist)) (facl2-str (if (equal facl2 'realp) (list (downcase-string (symbol-name facl2))) `("@(see " ,(symbol-name facl2) ")"))) (entry `("<tr><td>" ,@facl2-str "</td><td>" ,fsmt "</td></tr> "))) (alist-to-xdoc-aux (cdr alist) (revappend entry acc))))) (local (defun talist-to-xdoc () (declare (xargs :mode :program)) (str::string-append-lst `("<p></p> <table> <tr><th>ACL2 type functions</th><th>Z3 type declarations</th></tr> " ,@(reverse (alist-to-xdoc-aux *SMT-types* nil)) "</table>")))) (make-event `(defxdoc SMT-types :parents (SMT-basics) :short "SMT types" :long ,(talist-to-xdoc))) (local (defun ualist-to-xdoc () (declare (xargs :mode :program)) (str::string-append-lst `("<p></p> <table> <tr><th>ACL2 type functions</th><th>Z3 uninterpreted function type declarations</th></tr> " ,@(reverse (alist-to-xdoc-aux *SMT-uninterpreted-types* nil)) "</table>")))) (make-event `(defxdoc SMT-uninterpreted-types :parents (SMT-basics) :short "SMT uninterpreted function types" :long ,(ualist-to-xdoc))) )
true
;; Copyright (C) 2015, University of British Columbia ;; Written by PI:NAME:<NAME>END_PI (August 2nd 2016) ;; ;; License: A 3-clause BSD license. ;; See the LICENSE file distributed with ACL2 ;; (in-package "SMT") (include-book "xdoc/top" :dir :system) (include-book "std/util/defval" :dir :system) (include-book "std/strings/decimal" :dir :system) (include-book "std/strings/case-conversion" :dir :system) (defxdoc SMT-basics :parents (verified) :short "Basic functions and types in Smtlink.") (defval *SMT-basics* :parents (SMT-basics) :short "Basic ACL2 functions supported in Smtlink." (append '(magic-fix) '(rationalp realp booleanp integerp symbolp) '(binary-+ binary-* unary-/ unary-- equal < implies if not lambda))) (defval *SMT-functions* :parents (SMT-functions) :short "ACL2 functions and their corresponding Z3 functions." ;;(ACL2 function . (SMT function Least # of arguments)) `((binary-+ . ("_SMT_.plus" . 1)) (binary-* . ("_SMT_.times" . 1)) (unary-/ . ("_SMT_.reciprocal" . 1)) (unary-- . ("_SMT_.negate" . 1)) (equal . ("_SMT_.equal" . 2)) (< . ("_SMT_.lt" . 2)) (if . ("_SMT_.ifx" . 3)) (not . ("_SMT_.notx" . 1)) (lambda . ("lambda" . 2)) (implies . ("_SMT_.implies" . 2)) ;; (hint-please . ("_SMT_.hint_okay" . 0)) ;; This doesn't work right now because Z3's definition is different from ACL2 ;; when using types as hypotheses. If X is rationalp in Z3, then it can not ;; be an integerp. We need to first grab a definition in Z3 that can fully ;; capture its ACL2 meaning. ;; (integerp . ("_SMT_.integerp" . 1)) ;; (rationalp . ("_SMT_.rationalp" . 1)) ;; (booleanp . ("_SMT_.booleanp" . 1)) )) (defval *SMT-types* :parents (SMT-basics) :short "ACL2 type functions and their corresponding Z3 type declarations." ;;(ACL2 type . SMT type) `((realp . "_SMT_.RealSort()") (rationalp . "_SMT_.RealSort()") (integerp . "_SMT_.IntSort()") (booleanp . "_SMT_.BoolSort()") (symbolp . "Symbol_z3.z3Sym"))) (defval *SMT-uninterpreted-types* :parents (SMT-basics) :short "ACL2 type functions and their corresponding Z3 uninterpreted function type declarations." `((realp . "_SMT_.RealSort()") (rationalp . "_SMT_.RealSort()") (real/rationalp . "_SMT_.RealSort()") (integerp . "_SMT_.IntSort()") (booleanp . "_SMT_.BoolSort()") (symbolp . "Symbol_z3.z3Sym"))) ;; current tag . next computed-hint (defval *SMT-architecture* '((process-hint . add-hypo-cp) (add-hypo . expand-cp) (expand . type-extract-cp) (type-extract . uninterpreted-fn-cp) (uninterpreted . smt-trusted-cp) (uninterpreted-custom . smt-trusted-cp-custom))) ;;---------------------------------------------------------------- (encapsulate () (local (defun falist-to-xdoc-aux (falist acc) ;; collects a reversed list of strings (b* (((when (atom falist)) acc) ((cons facl2 (cons fsmt nargs)) (car falist)) (facl2-str (if (equal facl2 'hint-please) (list (downcase-string (symbol-name facl2))) `("@(see " ,(symbol-name facl2) ")"))) (entry `("<tr><td>" ,@facl2-str "</td><td>" ,fsmt "</td><td>" ,(natstr nargs) "</td></tr> "))) (falist-to-xdoc-aux (cdr falist) (revappend entry acc))))) (local (defun falist-to-xdoc () (declare (xargs :mode :program)) (str::string-append-lst `("<p></p> <table> <tr><th>ACL2 function</th><th>Z3 function</th><th>Nargs</th></tr> " ,@(reverse (falist-to-xdoc-aux *SMT-functions* nil)) "</table>")))) (make-event `(defxdoc SMT-functions :parents (SMT-basics) :short "SMT functions" :long ,(falist-to-xdoc)))) (encapsulate () (local (defun alist-to-xdoc-aux (alist acc) ;; collects a reversed list of strings (b* (((when (atom alist)) acc) ((cons facl2 fsmt) (car alist)) (facl2-str (if (equal facl2 'realp) (list (downcase-string (symbol-name facl2))) `("@(see " ,(symbol-name facl2) ")"))) (entry `("<tr><td>" ,@facl2-str "</td><td>" ,fsmt "</td></tr> "))) (alist-to-xdoc-aux (cdr alist) (revappend entry acc))))) (local (defun talist-to-xdoc () (declare (xargs :mode :program)) (str::string-append-lst `("<p></p> <table> <tr><th>ACL2 type functions</th><th>Z3 type declarations</th></tr> " ,@(reverse (alist-to-xdoc-aux *SMT-types* nil)) "</table>")))) (make-event `(defxdoc SMT-types :parents (SMT-basics) :short "SMT types" :long ,(talist-to-xdoc))) (local (defun ualist-to-xdoc () (declare (xargs :mode :program)) (str::string-append-lst `("<p></p> <table> <tr><th>ACL2 type functions</th><th>Z3 uninterpreted function type declarations</th></tr> " ,@(reverse (alist-to-xdoc-aux *SMT-uninterpreted-types* nil)) "</table>")))) (make-event `(defxdoc SMT-uninterpreted-types :parents (SMT-basics) :short "SMT uninterpreted function types" :long ,(ualist-to-xdoc))) )
[ { "context": "tils.lisp\n\n#|\nThe MIT license.\n\nCopyright (c) 2010 Paul L. Krueger\n\nPermission is hereby granted, free of charge, to", "end": 78, "score": 0.9998793601989746, "start": 63, "tag": "NAME", "value": "Paul L. Krueger" } ]
Utilities/binding-utils.lisp
plkrueger/CocoaInterface
34
;; binding-utils.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 :lc-classes) (require :coerce-obj) (require :nslog-utils) (require :kvo-slot) (require :selector-utils)) (defgeneric lc::modified-bound-value (controller edited-obj key old-val new-val)) (in-package :iu) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Miscellaneous utility functions ;; Given a window and another object, find all the subviews of the window that link to that object ;; for their value and the key paths that they use (returned as a string). (defmethod linking-views ((win ns:ns-window) (obj ns:ns-object)) (let* ((cview (#/contentView win)) (subviews (ns-to-lisp-list (#/subviews cview) :element-class ns:ns-object))) (mapcan #'(lambda (v) (multiple-value-bind (bound-p path) (bound-to v obj #@"value") (when bound-p (list (cons v path))))) subviews))) ;; This looks old and I think assumes a conversion to symbols in ns-to-lisp-assoc ;; that doesn't really happen ... (defmethod bound-to ((view ns::ns-view) (bound-to-obj ns::ns-object) binding-ns-string) (let* ((objc-info (#/infoForBinding: view binding-ns-string)) (info (and (not (eql objc-info (%null-ptr))) (ns-to-lisp-assoc objc-info :element-class ns::ns-object))) (proxy (cdr (assoc 'CL-USER::NSOBSERVEDOBJECT info))) (proxy-desc (and proxy (ns-to-lisp-string (#/description proxy)))) (bound-to-desc (ns-to-lisp-string (#/description bound-to-obj))) (path (and info (ns-to-lisp-string (cdr (assoc 'CL-USER::NSOBSERVEDKEYPATH info)))))) (if (and info (find-substring bound-to-desc proxy-desc)) (values t path) (values nil nil)))) (defun link-path-components (path-str) (if (zerop (length path-str)) nil (do* ((begin 0 (1+ end)) (end (or (position #\. path-str :start (1+ begin)) (length path-str)) (or (position #\. path-str :start (1+ begin)) (length path-str))) (words (list (subseq path-str begin end)) (push (subseq path-str begin end) words))) ((>= end (length path-str)) (mapcar #'objc-to-lisp-keypathname (nreverse words)))))) (defun convert-binding-option (bind-key) (ecase bind-key (:allows-editing-multiple-values-selection #$NSAllowsEditingMultipleValuesSelectionBindingOption) (:allows-null-argument #$NSAllowsNullArgumentBindingOption) (:always-presents-application-modal-alerts #$NSAlwaysPresentsApplicationModalAlertsBindingOption) (:conditionally-sets-editable #$NSConditionallySetsEditableBindingOption) (:conditionally-sets-enabled #$NSConditionallySetsEnabledBindingOption) (:conditionally-sets-hidden #$NSConditionallySetsHiddenBindingOption) (:continuously-updates-value #$NSContinuouslyUpdatesValueBindingOption) (:creates-sort-descriptor #$NSCreatesSortDescriptorBindingOption) (:deletes-objects-on-remove #$NSDeletesObjectsOnRemoveBindingsOption) (:display-name #$NSDisplayNameBindingOption) (:display-pattern #$NSDisplayPatternBindingOption) (:content-placement-tag #$NSContentPlacementTagBindingOption) (:handles-content-as-compound-value #$NSHandlesContentAsCompoundValueBindingOption) (:inserts-null-placeholder #$NSInsertsNullPlaceholderBindingOption) (:invokes-separately-with-array-objects #$NSInvokesSeparatelyWithArrayObjectsBindingOption) (:multiple-vlaues-placeholder #$NSMultipleValuesPlaceholderBindingOption) (:no-selection-placeholder #$NSNoSelectionPlaceholderBindingOption) (:not-applicable-placeholder #$NSNotApplicablePlaceholderBindingOption) (:null-placeholder #$NSNullPlaceholderBindingOption) (:raises-for-not-applicable-keys #$NSRaisesForNotApplicableKeysBindingOption) (:predicate-format #$NSPredicateFormatBindingOption) (:selector-name #$NSSelectorNameBindingOption) (:selects-all-when-setting-content #$NSSelectsAllWhenSettingContentBindingOption) (:validates-immediately #$NSValidatesImmediatelyBindingOption) (:transformer-name #$NSValueTransformerNameBindingOption) (:value-transformer #$NSValueTransformerBindingOption))) (defun convert-key-val-options (olist) ;; olist should be a list of keyword-value pairs where keywords are from the table above ;; note that the coerce-obj to ns-dictionary automatically converts values to appropriate ;; objective-C objects if needed. (do* ((assoc-list nil) (lst olist (cddr lst)) (key (convert-binding-option (first lst)) (convert-binding-option (first lst))) (val (second lst) (second lst))) ((null key) (coerce-obj assoc-list 'ns:ns-dictionary)) (push (cons key val) assoc-list))) #| Constants NSAllowsEditingMultipleValuesSelectionBindingOption An NSNumber object containing a Boolean value that determines if the binding allows editing when the value represents a multiple selection. NSAlwaysPresentsApplicationModalAlertsBindingOption An NSNumber object containing a Boolean value that determines if validation and error alert panels displayed as a result of this binding are displayed as application modal alerts. If YES, then the alerts are displayed application model, otherwise they are displayed as sheets. NSAllowsNullArgumentBindingOption An NSNumber object containing a Boolean value that determines if the argument bindings allows passing argument values of nil. NSConditionallySetsEditableBindingOption An NSNumber object containing a Boolean value that determines if the editable state of the user interface item is automatically configured based on the controller's selection. NSConditionallySetsEnabledBindingOption An NSNumber object containing a Boolean value that determines if the enabled state of the user interface item is automatically configured based on the controller's selection. NSConditionallySetsHiddenBindingOption An NSNumber object containing a Boolean value that determines if the hidden state of the user interface item is automatically configured based on the controller's selection. NSContentPlacementTagBindingOption An NSNumber object specifying the tag id of the popup menu item to replace with the content of the array. This allows you to use a popup menu that contains both static and bindings generated items. NSContinuouslyUpdatesValueBindingOption An NSNumber object containing a Boolean value that determines whether the value of the binding is updated as edits are made to the user interface item or is updated only when the user interface item resigns as the responder. NSCreatesSortDescriptorBindingOption An NSNumber object containing a Boolean value that determines if a sort descriptor is created for a table column. If this value is NO, then the table column does not allow sorting. NSDeletesObjectsOnRemoveBindingsOption An NSNumber object containing a Boolean value that determines if an object is deleted from the managed context immediately upon being removed from a relationship. NSDisplayNameBindingOption An NSString object containing a human readable string to be displayed for a predicate. NSDisplayPatternBindingOption An NSString object that specifies a format string used to construct the final value of a string. NSHandlesContentAsCompoundValueBindingOption An NSNumber object containing a Boolean value that determines if the content is treated as a compound value. NSInsertsNullPlaceholderBindingOption An NSNumber object containing a Boolean value that determines if an additional item which represents nil is inserted into a matrix or pop-up menu before the items in the content array. NSInvokesSeparatelyWithArrayObjectsBindingOption An NSNumber object containing a Boolean value that determines whether the specified selector is invoked with the array as the argument or is invoked repeatedly with each array item as an argument. NSMultipleValuesPlaceholderBindingOption An object that is used as a placeholder when the key path of the bound controller returns the NSMultipleValuesMarker marker for a binding. NSNoSelectionPlaceholderBindingOption An object that is used as a placeholder when the key path of the bound controller returns the NSNoSelectionMarker marker for a binding. NSNotApplicablePlaceholderBindingOption An object that is used as a placeholder when the key path of the bound controller returns the NSNotApplicableMarker marker for a binding. NSNullPlaceholderBindingOption An object that is used as a placeholder when the key path of the bound controller returns nil for a binding. NSPredicateFormatBindingOption An NSString object containing the predicate pattern string for the predicate bindings. Use $value to refer to the value in the search field. NSRaisesForNotApplicableKeysBindingOption An NSNumber object containing a Boolean value that specifies if an exception is raised when the binding is bound to a key that is not applicable—for example when an object is not key-value coding compliant for a key. NSSelectorNameBindingOption An NSString object that specifies the method selector invoked by the target binding when the user interface item is clicked. NSSelectsAllWhenSettingContentBindingOption An NSNumber object containing a Boolean value that specifies if all the items in the array controller are selected when the content is set. NSValidatesImmediatelyBindingOption An NSNumber object containing a Boolean value that determines if the contents of the binding are validated immediately. NSValueTransformerNameBindingOption The value for this key is an identifier of a registered NSValueTransformer instance that is applied to the bound value. NSValueTransformerBindingOption An NSValueTransformer instance that is applied to the bound value. |# ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Methods used to determine what slots are exposed for binding (defun make-proto (class) (let ((pr (#/alloc class))) ;; some classes require initialization to avoid uncatchable errors when getting their #/exposedBindings ;; I suspect that they have exposedBindings methods that query related objects or otherwise test the ;; state of the object and without initialization they fail. We can't just call #/init for every class ;; because that isn't always valid either. (when (some #'(lambda (cl) (ccl::subclassp class cl)) (list ns:ns-cell ns:ns-text)) (setf pr (#/init pr))) pr)) (let ((proto-hash (make-hash-table))) (defmethod proto-for-class ((self objc::objc-class)) (or (gethash self proto-hash) (handler-case (setf (gethash self proto-hash) (make-proto self)) (condition (c) (declare (ignore c)) (setf (gethash self proto-hash) (proto-for-class ns:ns-object))))))) (defmethod valid-bindings ((self ns:ns-object)) (coerce-obj (handler-case (#/exposedBindings self) (condition (c) (declare (ignore c)) (ns-log-format "Error trying to get #/exposedBings for ~s" self) nil)) 'list)) (defmethod valid-bindings ((self objc::objc-class)) (coerce-obj (handler-case (#/exposedBindings (proto-for-class self)) (condition (c) (declare (ignore c)) (ns-log-format "Error trying to get #/exposedBings for ~s" self) nil)) 'list)) (defmethod valid-bindings (non-class) (declare (ignore non-class)) nil) (defmethod valid-binding-p ((self ns:ns-object) property-key-path) (find property-key-path (valid-bindings self) :test #'string=)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Methods used to add Objective-C methods to Objectiv-C objects that have :kvo slot declarations (let ((kvc-hash (make-hash-table))) (defmethod define-kvc-methods ((self class)) ;; do nothing for non objective-c classes ) (defmethod define-kvc-methods ((self objc:objc-class-object)) (unless (gethash self kvc-hash nil) (setf (gethash self kvc-hash) t) (eval `(objc:defmethod (#/valueForUndefinedKey: :id) ((self ,(class-name self)) (key :id)) (let* ((lisp-key (coerce-obj key 'string)) (slot (kvo-slot-for self lisp-key))) (if slot (convert-new-val self (slot-value self (slot-definition-name slot)) lisp-key) (call-next-method key))))) (eval `(objc:defmethod (#/setValue:forUndefinedKey: :void) ((self ,(class-name self)) (new-val :id) (key :id)) (if (kvo-slot-for self (coerce-obj key 'string)) (set-value-for-key self new-val key) (call-next-method new-val key)))) (eval `(objc:defmethod (#/addObserver:forKeyPath:options:context: :void) ((self ,(class-name self)) (obs :id) (key-path :id) (options #>NSUInteger) (context :address)) (set-observer-format self obs key-path) (call-next-method obs key-path options context))))) (defun assure-kvc-methods-defined () (dolist (c (new-kvo-classes)) (define-kvc-methods c))) (defun redefine-all-kvc-methods () (setf kvc-hash (make-hash-table)) (dolist (c (kvo-classes)) (define-kvc-methods c))) ) ;; end of methods using kvc-hash ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; The main Lisp bind method (defmethod bind ((self ns:ns-object) property-key-path target-obj key-path &rest key-val-options) ;; target-obj must be an objective-c object. property-key-path and key-path are defined as: ;; key-path ::= <path-string> | ( <path-object>*) ;; path-object ::= <path-string> | <lisp-function> ;; path-string ::= "<path-elt-string>{.<path-string>}* ;; path-elt-string ::= any legal string for Objective-C keypaths ;; Before binding anything, make sure that all Objective-C classes with KVO slots have some methods ;; defined for them. (assure-kvc-methods-defined) (if (valid-binding-p self property-key-path) (progn (#/bind:toObject:withKeyPath:options: self (convert-path-list property-key-path) (if (typep target-obj 'ns:ns-object) target-obj (wrapper-for target-obj)) (convert-path-list key-path) (if key-val-options (convert-key-val-options key-val-options) (%null-ptr))) t) (progn (ns-log-format "Property path ~s is not a valid bind path for ~s" property-key-path self) nil))) #| (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) ) ;; end of definitions with access to kvc-observed assoc-array |# (defun reader-selector (str) (ccl::%get-selector (ccl::load-objc-selector str))) (defun writer-selector (str) (ccl::%get-selector (ccl::load-objc-selector (concatenate 'string "set" (string-capitalize str :end 1) ":")))) (defmethod bound-slot-will-be-modified ((self standard-object) slot-name) (declare (ignore slot-name)) ;; do nothing by default ) (defmethod bound-slot-modified ((self standard-object) slot-name) (declare (ignore slot-name)) ;; do nothing by default ) (defmethod real-observer (observer) ;; observer will be an instance of one of server types of non-public Apple Classes. Examples include ;; NSSelectionBinder, NSValueBinder, NSTextValueBinder ;; All we want is a pointer to the original observer extracted from that object, but without ;; a public API that is a little tricky. But we are trickier. ;; We can see from (#/description ...) results for these objects that they all seem to respond to ;; the #/object message which returns the original observer. So we test for the object's response ;; to that selector and use it to return the original observer. (when *log-bindings* (ns-log-format "Observer description is: ~a" (coerce-obj (#/description observer) 'string))) (if (responds-to-selector observer "object") (#/object observer) observer)) #| This is an old method that worked in previous OSX versions I'm leaving it around in case something like this is ever useful in the future ;; We use the #/description of that ;; object which provides a substring of the form "Observer: 0x<whatever>" which points to ;; possibly another non-public object of type NSSelectionBinder. We extract the address and ;; create a pointer to the NSSelectionbinder. We now use its description to extract its ;; "object" slot address, which hopefully points to the original view object that we bound ;; to our lisp object. We use that to create a macptr and return it. (let* ((desc (ns-to-lisp-string (#/description nskvo))) (obs-start (search "Observer: " desc)) (hex-start (and obs-start (position #\x desc :start (+ obs-start 9)))) (hex-end (and hex-start (position #\, desc :start hex-start))) (hex-val (and hex-end (read-from-string (concatenate 'string "#" (subseq desc hex-start hex-end)) nil 0))) (nssb-ptr (and hex-val (ccl::%int-to-ptr hex-val))) (nssb-desc (and nssb-ptr (ns-to-lisp-string (#/description nssb-ptr)))) (obj-start (search "object:" nssb-desc)) (obj-class-end (and obj-start (position #\: nssb-desc :start (+ obj-start 8)))) (obj-hex-start (and obj-class-end (position #\x nssb-desc :start obj-class-end))) (obj-hex-end (and obj-hex-start (position #\> nssb-desc :start obj-hex-start))) (obj-hex-val (and obj-hex-end (read-from-string (concatenate 'string "#" (subseq nssb-desc obj-hex-start obj-hex-end)) nil 0)))) (when obj-hex-val (ccl::%int-to-ptr obj-hex-val)))) |# (defun more-specific-format (fmt1 fmt2) (cond ((null fmt2) t) ((eq fmt1 fmt2) nil) ((eq fmt2 :rich-text) t) ((eq fmt1 :rich-text) nil) ((listp fmt1) ;; only ns-decimal t) ((listp fmt2) nil) (t ;; ?? t))) (let ((format-assoc (make-instance 'assoc-array :rank 2 :tests (list #'eql #'equal)))) ;; used to hold needed Objective-C format information for slots that are observed by ;; Objective-C objects that have associated formatter objects from which we can take hints. (defun set-format-assoc (path-obj path format) (let ((existing-format (format-for path-obj path))) (when (more-specific-format format existing-format) (setf (assoc-aref format-assoc path-obj path) format)))) (defun format-for (path-obj path) (assoc-aref format-assoc path-obj path)) ) (defmethod convert-new-val ((self lisp-ptr-wrapper) value key-str) ;; converts the value to an appropriate Objective-C value depending on the key used to access it (let ((kr (key-return key-str))) (cond ((eql value (%null-ptr)) value) ((null value) (%null-ptr)) ((member value (list #$NSNoSelectionMarker #$NSNullPlaceholderBindingOption #$NSNotApplicablePlaceholderBindingOption) :test #'eql) value) ((eq kr :convert) (coerce-obj value 'ns:ns-object :ns-format (format-for (lpw-lisp-ptr self) key-str))) ((eq kr :path) (if (typep value 'ns:ns-object) value (wrapper-for value))) ((typep value 'lisp-ptr-wrapper) value) ((eq kr :path) (wrapper-for value :controller (lpw-controller self) :parent (lpw-lisp-ptr self))) ;; Cases below should only occur if binding was made using native objective-c methods ((typep value 'ns:ns-object) value) ((typep value 'objc-displayable) (coerce-obj value 'ns:ns-object :ns-format (format-for (lpw-lisp-ptr self) key-str))) (t (wrapper-for value :controller (lpw-controller self) :parent (lpw-lisp-ptr self)))))) (defmethod convert-new-val ((self ns:ns-object) value key-str) ;; converts the value to an appropriate Objective-C value depending on the key used to access it ;; If bindings are made using the lisp bind function, then we will know whether the value should ;; be converted to some sort of objective-c type for display or is just an intermediate value on ;; a binding path and should be left alone. We make a best guess for bindings made using native ;; objective-c calls depending on the type of the object returned. If it can be displayed, we ;; convert it. Otherwise we leave it alone (or wrap it, if it's a lisp object). (let ((kr (key-return key-str))) (cond ((eql value (%null-ptr)) value) ((null value) (%null-ptr)) ((member value (list #$NSNoSelectionMarker #$NSNullPlaceholderBindingOption #$NSNotApplicablePlaceholderBindingOption) :test #'eql) value) ;; Above cases apply whether value is a path element or end value ((eq kr :convert) (coerce-obj value 'ns:ns-object :ns-format (format-for self key-str))) ((eq kr :path) (if (typep value 'ns:ns-object) value (wrapper-for value))) ;; Cases below should only occur if binding was made using native objective-c methods ((typep value 'ns:ns-object) value) ((typep value 'objc-displayable) (coerce-obj value 'ns:ns-object :ns-format (format-for self key-str))) (t (wrapper-for value))))) (defun set-observer-format (self obs key-path) ;; We use the ns-format as a hint about how the lisp field is ;; formatted and convert accordingly when that value is retrieved. (let ((observer (real-observer obs)) (ns-format nil)) (cond ((typep observer 'ns:ns-control) (let* ((cell (#/cell observer)) (formatter (#/formatter cell))) (cond ((or (typep cell 'ns:ns-date-picker-cell) (typep formatter 'ns:ns-date-formatter)) (setf ns-format :date)) ((typep formatter 'ns:ns-number-formatter) (cond ((#/generatesDecimalNumbers formatter) (let ((dec-digits (#/maximumFractionDigits formatter))) (setf ns-format (list :decimal dec-digits)))) (t (setf ns-format :number)))) (t ;; NSControls can always accept NSAttributedStrings (setf ns-format :rich-text))))) ((typep observer 'ns:ns-text) ;; This is a little tricky becasue NSText objects can bind to either ;; an NSAttributedString or to an NSString via separate bindings. ;; But we have no real way of knowing which they bound to in IB, so ;; we guess based on the value returned by #/isRichText. Also the ;; developer gives us a hint by what sort of object is in the slot that ;; the interface object is bound to. If that slot has a lisp attributed-string ;; object and the field allows rich-text, we'll pass it an NSMutableAttributedString. ;; Otherwise it will just get an NSString. (setf ns-format (if (#/isRichText observer) :rich-text :text))) ((typep observer 'lc::lisp-controller) ;; We generally don't want to convert from some lisp format to an Objective-C form and then back. ;; Rather we'd like to get a pointer to the original Lisp object. So just create a wrapper for ;; the value. (setf ns-format :wrapper))) (when ns-format (set-format-assoc self (ns-to-lisp-string key-path) ns-format)))) (objc:defmethod (#/addObserver:forKeyPath:options:context: :void) ((self lisp-ptr-wrapper) (obs :id) (key-path :id) (options #>NSUInteger) (context :address)) (multiple-value-bind (observer ns-format) (set-observer-format (lpw-lisp-ptr self) obs key-path) (when *log-bindings* (ns-log-format "~s observed by ~s" (lpw-lisp-ptr self) observer) (ns-log-format "Observer data format: ~s" ns-format)) ;; Any controls that previously observed this field might have ;; received misformatted data, so indicate that the data changed ;; so they will go get it again. This primarily occurs when a new ;; window is open and controls are first observing the field. (#/willChangeValueForKey: self key-path) (#/didChangeValueForKey: self key-path)) (call-next-method obs key-path options context)) (objc:defmethod (#/valueForKey: :id) ((self lisp-ptr-wrapper) (path :id)) ;; Treat path as a lisp path as long as it works. ;; If it is not valid and the next target is an Objective-C object ;; then treat the path as a normal Objective-C Key and return the results ;; of calling #/valueForKey: on the target using path as the key. (let* ((lisp-str (ns-to-lisp-string path)) (lisp-path (objc-to-lisp-keypathname lisp-str)) (func (func-for-keypath lisp-str)) (ptr-obj (lpw-lisp-ptr self)) ;; to set next-obj we try 4 ways: ;; 1. If the path is one that we generated to represent a Lisp function use it ;; 2. If the path is a valid lisp function name use it to access the slot ;; 3. If the object is an Objective-C object try calling its #/valueForKey method ;; 4. Look for any KVO slots defined for the object with path specified as the KVO ;; accessor and use the lisp function value-for-kvo-key to access that slot (next-obj (cond ((and func (compute-applicable-methods func (list ptr-obj))) (funcall func ptr-obj)) ((and (typep lisp-path 'function-name) (fboundp lisp-path) (compute-applicable-methods lisp-path (list ptr-obj))) (funcall lisp-path ptr-obj)) ((and (typep ptr-obj 'objc:objc-object) (#/respondsToSelector: ptr-obj (reader-selector lisp-str))) (#/valueForKey: ptr-obj path)) ((and (typep ptr-obj 'ccl::kvo-object) (compute-applicable-methods #'ccl::value-for-kvo-key (list ptr-obj lisp-str)) (ccl::value-for-kvo-key ptr-obj lisp-str))) (t (%null-ptr))))) ;; First track that the path is being observed by somebody (note-kvc-observed self (lpw-lisp-ptr self) lisp-path) (note-kvc-observed self (lpw-lisp-ptr self) lisp-str) (when func (note-kvc-observed self (lpw-lisp-ptr self) func)) (when *log-bindings* (ns-log-format "(~s ~s) returned ~s" lisp-path (lpw-lisp-ptr self) next-obj)) (convert-new-val self next-obj lisp-str))) (defmethod set-value-for-key (self new-value (path ns:ns-object)) (let* ((lisp-str (coerce-obj path 'string)) (lisp-path (objc-to-lisp-keypathname lisp-str)) (prev-obj (cond ((and (typep lisp-path 'function-name) (fboundp lisp-path)) (funcall lisp-path self)) ((and (typep self 'objc:objc-object) (#/respondsToSelector: self (reader-selector lisp-str))) (#/valueForKey: self path)) (t (ccl::value-for-kvo-key self lisp-str)))) (prev-class (class-of prev-obj)) (new-lisp-obj (ns-to-lisp-object new-value :lisp-class prev-class :ns-format (format-for self lisp-str))) (setf-func (fboundp (list 'setf lisp-path)))) (when *log-bindings* (ns-log-format "Prev Class: ~s" prev-class)) (cond (setf-func (funcall setf-func new-lisp-obj self)) ((and (typep self 'objc:objc-object) (typep new-lisp-obj 'objc:objc-object) (#/respondsToSelector: self (writer-selector lisp-str))) (#/setValue:forKey: self new-lisp-obj path)) (t (let* ((found-slot (ccl::kvo-slot-for self lisp-str)) (slot-name (and found-slot (ccl::slot-definition-name found-slot)))) (if found-slot (progn (bound-slot-will-be-modified self slot-name) (setf (ccl::value-for-kvo-key self lisp-str) new-lisp-obj) (bound-slot-modified self (ccl::slot-definition-name found-slot))) ;; If the setf failed, log the original condition (error "No way to setValue: ~s forKey: ~s for lisp-ptr ~s" new-lisp-obj lisp-str self))))) (values new-lisp-obj prev-obj))) (objc:defmethod (#/setValue:forKey: :void) ((self lisp-ptr-wrapper) (new-value :id) (path :id)) (let ((ptr-obj (lpw-lisp-ptr self)) (ctrl (lpw-controller self)) (lisp-path (objc-to-lisp-keypathname (coerce-obj path 'string)))) (when ptr-obj (multiple-value-bind (new-lisp-obj prev-obj) (set-value-for-key ptr-obj new-value path) (when ctrl (lc::modified-bound-value ctrl (lpw-lisp-ptr self) lisp-path prev-obj new-lisp-obj)) new-lisp-obj)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Methods to observe kvo-compliant paths through and to either Objective-C or Lisp instances #| (defclass kvo-observer (ns:ns-object) ((observed-instance :accessor observed-instance :initarg :obj) (observe-path :accessor observe-path :initarg :path) (when-observed-func :accessor when-observed-func :initarg :func) (convert-type :accessor convert-type :initarg :convert-type)) (:default-initargs :obj nil :path nil :func nil :convert-type nil) (:metaclass ns:+ns-object)) |# (defmethod added-class-key-values ((self (eql (find-class 'kvo-observer)))) ;; provide documenation for keywords '((:obj "An ns:ns-object to be observed by the kvo-observer being created") (:path "A list of lisp forms that provides a path within the observed object") (:func "A function called when the object is observed to have changed") (:convert-type "A data type to which new observations will be converted"))) (defmethod initialize-instance :after ((self kvo-observer) &key (obj nil) (path nil) (func nil)) (assure-kvc-methods-defined) (when (and obj path func) (let ((observed-obj (if (typep obj 'ns:ns-object) obj (wrapper-for obj)))) (#/addObserver:forKeyPath:options:context: observed-obj self (convert-path-list path) 0 (%null-ptr))))) (objc:defmethod (#/dealloc :void) ((self kvo-observer)) (when (and (observed-instance self) (observe-path self)) (let ((observed-obj (if (typep (observed-instance self) 'ns:ns-object) (observed-instance self) (wrapper-for (observed-instance self))))) (when *log-bindings* (ns-log-format "about to remove observer of ~s via path ~s" observed-obj (convert-path-list (observe-path self)))) (#/removeObserver:forKeyPath:context: observed-obj self (convert-path-list (observe-path self)) (%null-ptr)))) (call-next-method) (objc:remove-lisp-slots self)) (objc::defmethod (#/observeValueForKeyPath:ofObject:change:context: :void) ((self kvo-observer) (key-path :id) (observed-obj :id) (change-dict :id) (context :address)) (declare (ignore key-path observed-obj change-dict context)) (when (functionp (when-observed-func self)) (funcall (when-observed-func self) (coerce-obj (#/valueForKeyPath: (observed-instance self) (coerce-obj (observe-path self) 'ns:ns-string)) (convert-type self))))) (defmacro when-observed ((object path new-value-decl) &rest forms) (let ((new-value-var (if (listp new-value-decl) (first new-value-decl) new-value-decl)) (new-value-type (if (listp new-value-decl) (second new-value-decl) t))) `(make-instance 'kvo-observer :obj ,object :path ,path :convert-type ',new-value-type :func #'(lambda (,new-value-var) ,@forms)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; methods to support access to Lisp lists and arrays as if they were NSArrays (objc:defmethod (#/count #>NSUInteger) ((self lisp-ptr-wrapper)) (let ((ptr-obj (lpw-lisp-ptr self))) (typecase ptr-obj (list (list-length ptr-obj)) (vector (length ptr-obj)) (t 0)))) (objc:defmethod (#/objectAtIndex: :id) ((self lisp-ptr-wrapper) (indx #>NSUInteger)) (let* ((ptr-obj (lpw-lisp-ptr self)) (next-obj (typecase ptr-obj (list (nth indx ptr-obj)) (vector (elt ptr-obj indx)) (t (%null-ptr))))) (cond ((eql next-obj (%null-ptr)) next-obj) ((null next-obj) (%null-ptr)) ((and (typep next-obj 'ns:ns-object) (not (typep next-obj 'ccl::kvo-object))) ;; any kvo-objects will be encapsulated in a lisp-ptr-wrapper ;; so that subsequent accesses through this method will try to ;; use ccl::value-for-kvo-key next-obj) ((typep next-obj 'objc-displayable) (lisp-to-ns-object next-obj)) (t (wrapper-for next-obj :controller (lpw-controller self) :parent (lpw-lisp-ptr self)))))) (provide :binding-utils)
96481
;; binding-utils.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 :lc-classes) (require :coerce-obj) (require :nslog-utils) (require :kvo-slot) (require :selector-utils)) (defgeneric lc::modified-bound-value (controller edited-obj key old-val new-val)) (in-package :iu) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Miscellaneous utility functions ;; Given a window and another object, find all the subviews of the window that link to that object ;; for their value and the key paths that they use (returned as a string). (defmethod linking-views ((win ns:ns-window) (obj ns:ns-object)) (let* ((cview (#/contentView win)) (subviews (ns-to-lisp-list (#/subviews cview) :element-class ns:ns-object))) (mapcan #'(lambda (v) (multiple-value-bind (bound-p path) (bound-to v obj #@"value") (when bound-p (list (cons v path))))) subviews))) ;; This looks old and I think assumes a conversion to symbols in ns-to-lisp-assoc ;; that doesn't really happen ... (defmethod bound-to ((view ns::ns-view) (bound-to-obj ns::ns-object) binding-ns-string) (let* ((objc-info (#/infoForBinding: view binding-ns-string)) (info (and (not (eql objc-info (%null-ptr))) (ns-to-lisp-assoc objc-info :element-class ns::ns-object))) (proxy (cdr (assoc 'CL-USER::NSOBSERVEDOBJECT info))) (proxy-desc (and proxy (ns-to-lisp-string (#/description proxy)))) (bound-to-desc (ns-to-lisp-string (#/description bound-to-obj))) (path (and info (ns-to-lisp-string (cdr (assoc 'CL-USER::NSOBSERVEDKEYPATH info)))))) (if (and info (find-substring bound-to-desc proxy-desc)) (values t path) (values nil nil)))) (defun link-path-components (path-str) (if (zerop (length path-str)) nil (do* ((begin 0 (1+ end)) (end (or (position #\. path-str :start (1+ begin)) (length path-str)) (or (position #\. path-str :start (1+ begin)) (length path-str))) (words (list (subseq path-str begin end)) (push (subseq path-str begin end) words))) ((>= end (length path-str)) (mapcar #'objc-to-lisp-keypathname (nreverse words)))))) (defun convert-binding-option (bind-key) (ecase bind-key (:allows-editing-multiple-values-selection #$NSAllowsEditingMultipleValuesSelectionBindingOption) (:allows-null-argument #$NSAllowsNullArgumentBindingOption) (:always-presents-application-modal-alerts #$NSAlwaysPresentsApplicationModalAlertsBindingOption) (:conditionally-sets-editable #$NSConditionallySetsEditableBindingOption) (:conditionally-sets-enabled #$NSConditionallySetsEnabledBindingOption) (:conditionally-sets-hidden #$NSConditionallySetsHiddenBindingOption) (:continuously-updates-value #$NSContinuouslyUpdatesValueBindingOption) (:creates-sort-descriptor #$NSCreatesSortDescriptorBindingOption) (:deletes-objects-on-remove #$NSDeletesObjectsOnRemoveBindingsOption) (:display-name #$NSDisplayNameBindingOption) (:display-pattern #$NSDisplayPatternBindingOption) (:content-placement-tag #$NSContentPlacementTagBindingOption) (:handles-content-as-compound-value #$NSHandlesContentAsCompoundValueBindingOption) (:inserts-null-placeholder #$NSInsertsNullPlaceholderBindingOption) (:invokes-separately-with-array-objects #$NSInvokesSeparatelyWithArrayObjectsBindingOption) (:multiple-vlaues-placeholder #$NSMultipleValuesPlaceholderBindingOption) (:no-selection-placeholder #$NSNoSelectionPlaceholderBindingOption) (:not-applicable-placeholder #$NSNotApplicablePlaceholderBindingOption) (:null-placeholder #$NSNullPlaceholderBindingOption) (:raises-for-not-applicable-keys #$NSRaisesForNotApplicableKeysBindingOption) (:predicate-format #$NSPredicateFormatBindingOption) (:selector-name #$NSSelectorNameBindingOption) (:selects-all-when-setting-content #$NSSelectsAllWhenSettingContentBindingOption) (:validates-immediately #$NSValidatesImmediatelyBindingOption) (:transformer-name #$NSValueTransformerNameBindingOption) (:value-transformer #$NSValueTransformerBindingOption))) (defun convert-key-val-options (olist) ;; olist should be a list of keyword-value pairs where keywords are from the table above ;; note that the coerce-obj to ns-dictionary automatically converts values to appropriate ;; objective-C objects if needed. (do* ((assoc-list nil) (lst olist (cddr lst)) (key (convert-binding-option (first lst)) (convert-binding-option (first lst))) (val (second lst) (second lst))) ((null key) (coerce-obj assoc-list 'ns:ns-dictionary)) (push (cons key val) assoc-list))) #| Constants NSAllowsEditingMultipleValuesSelectionBindingOption An NSNumber object containing a Boolean value that determines if the binding allows editing when the value represents a multiple selection. NSAlwaysPresentsApplicationModalAlertsBindingOption An NSNumber object containing a Boolean value that determines if validation and error alert panels displayed as a result of this binding are displayed as application modal alerts. If YES, then the alerts are displayed application model, otherwise they are displayed as sheets. NSAllowsNullArgumentBindingOption An NSNumber object containing a Boolean value that determines if the argument bindings allows passing argument values of nil. NSConditionallySetsEditableBindingOption An NSNumber object containing a Boolean value that determines if the editable state of the user interface item is automatically configured based on the controller's selection. NSConditionallySetsEnabledBindingOption An NSNumber object containing a Boolean value that determines if the enabled state of the user interface item is automatically configured based on the controller's selection. NSConditionallySetsHiddenBindingOption An NSNumber object containing a Boolean value that determines if the hidden state of the user interface item is automatically configured based on the controller's selection. NSContentPlacementTagBindingOption An NSNumber object specifying the tag id of the popup menu item to replace with the content of the array. This allows you to use a popup menu that contains both static and bindings generated items. NSContinuouslyUpdatesValueBindingOption An NSNumber object containing a Boolean value that determines whether the value of the binding is updated as edits are made to the user interface item or is updated only when the user interface item resigns as the responder. NSCreatesSortDescriptorBindingOption An NSNumber object containing a Boolean value that determines if a sort descriptor is created for a table column. If this value is NO, then the table column does not allow sorting. NSDeletesObjectsOnRemoveBindingsOption An NSNumber object containing a Boolean value that determines if an object is deleted from the managed context immediately upon being removed from a relationship. NSDisplayNameBindingOption An NSString object containing a human readable string to be displayed for a predicate. NSDisplayPatternBindingOption An NSString object that specifies a format string used to construct the final value of a string. NSHandlesContentAsCompoundValueBindingOption An NSNumber object containing a Boolean value that determines if the content is treated as a compound value. NSInsertsNullPlaceholderBindingOption An NSNumber object containing a Boolean value that determines if an additional item which represents nil is inserted into a matrix or pop-up menu before the items in the content array. NSInvokesSeparatelyWithArrayObjectsBindingOption An NSNumber object containing a Boolean value that determines whether the specified selector is invoked with the array as the argument or is invoked repeatedly with each array item as an argument. NSMultipleValuesPlaceholderBindingOption An object that is used as a placeholder when the key path of the bound controller returns the NSMultipleValuesMarker marker for a binding. NSNoSelectionPlaceholderBindingOption An object that is used as a placeholder when the key path of the bound controller returns the NSNoSelectionMarker marker for a binding. NSNotApplicablePlaceholderBindingOption An object that is used as a placeholder when the key path of the bound controller returns the NSNotApplicableMarker marker for a binding. NSNullPlaceholderBindingOption An object that is used as a placeholder when the key path of the bound controller returns nil for a binding. NSPredicateFormatBindingOption An NSString object containing the predicate pattern string for the predicate bindings. Use $value to refer to the value in the search field. NSRaisesForNotApplicableKeysBindingOption An NSNumber object containing a Boolean value that specifies if an exception is raised when the binding is bound to a key that is not applicable—for example when an object is not key-value coding compliant for a key. NSSelectorNameBindingOption An NSString object that specifies the method selector invoked by the target binding when the user interface item is clicked. NSSelectsAllWhenSettingContentBindingOption An NSNumber object containing a Boolean value that specifies if all the items in the array controller are selected when the content is set. NSValidatesImmediatelyBindingOption An NSNumber object containing a Boolean value that determines if the contents of the binding are validated immediately. NSValueTransformerNameBindingOption The value for this key is an identifier of a registered NSValueTransformer instance that is applied to the bound value. NSValueTransformerBindingOption An NSValueTransformer instance that is applied to the bound value. |# ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Methods used to determine what slots are exposed for binding (defun make-proto (class) (let ((pr (#/alloc class))) ;; some classes require initialization to avoid uncatchable errors when getting their #/exposedBindings ;; I suspect that they have exposedBindings methods that query related objects or otherwise test the ;; state of the object and without initialization they fail. We can't just call #/init for every class ;; because that isn't always valid either. (when (some #'(lambda (cl) (ccl::subclassp class cl)) (list ns:ns-cell ns:ns-text)) (setf pr (#/init pr))) pr)) (let ((proto-hash (make-hash-table))) (defmethod proto-for-class ((self objc::objc-class)) (or (gethash self proto-hash) (handler-case (setf (gethash self proto-hash) (make-proto self)) (condition (c) (declare (ignore c)) (setf (gethash self proto-hash) (proto-for-class ns:ns-object))))))) (defmethod valid-bindings ((self ns:ns-object)) (coerce-obj (handler-case (#/exposedBindings self) (condition (c) (declare (ignore c)) (ns-log-format "Error trying to get #/exposedBings for ~s" self) nil)) 'list)) (defmethod valid-bindings ((self objc::objc-class)) (coerce-obj (handler-case (#/exposedBindings (proto-for-class self)) (condition (c) (declare (ignore c)) (ns-log-format "Error trying to get #/exposedBings for ~s" self) nil)) 'list)) (defmethod valid-bindings (non-class) (declare (ignore non-class)) nil) (defmethod valid-binding-p ((self ns:ns-object) property-key-path) (find property-key-path (valid-bindings self) :test #'string=)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Methods used to add Objective-C methods to Objectiv-C objects that have :kvo slot declarations (let ((kvc-hash (make-hash-table))) (defmethod define-kvc-methods ((self class)) ;; do nothing for non objective-c classes ) (defmethod define-kvc-methods ((self objc:objc-class-object)) (unless (gethash self kvc-hash nil) (setf (gethash self kvc-hash) t) (eval `(objc:defmethod (#/valueForUndefinedKey: :id) ((self ,(class-name self)) (key :id)) (let* ((lisp-key (coerce-obj key 'string)) (slot (kvo-slot-for self lisp-key))) (if slot (convert-new-val self (slot-value self (slot-definition-name slot)) lisp-key) (call-next-method key))))) (eval `(objc:defmethod (#/setValue:forUndefinedKey: :void) ((self ,(class-name self)) (new-val :id) (key :id)) (if (kvo-slot-for self (coerce-obj key 'string)) (set-value-for-key self new-val key) (call-next-method new-val key)))) (eval `(objc:defmethod (#/addObserver:forKeyPath:options:context: :void) ((self ,(class-name self)) (obs :id) (key-path :id) (options #>NSUInteger) (context :address)) (set-observer-format self obs key-path) (call-next-method obs key-path options context))))) (defun assure-kvc-methods-defined () (dolist (c (new-kvo-classes)) (define-kvc-methods c))) (defun redefine-all-kvc-methods () (setf kvc-hash (make-hash-table)) (dolist (c (kvo-classes)) (define-kvc-methods c))) ) ;; end of methods using kvc-hash ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; The main Lisp bind method (defmethod bind ((self ns:ns-object) property-key-path target-obj key-path &rest key-val-options) ;; target-obj must be an objective-c object. property-key-path and key-path are defined as: ;; key-path ::= <path-string> | ( <path-object>*) ;; path-object ::= <path-string> | <lisp-function> ;; path-string ::= "<path-elt-string>{.<path-string>}* ;; path-elt-string ::= any legal string for Objective-C keypaths ;; Before binding anything, make sure that all Objective-C classes with KVO slots have some methods ;; defined for them. (assure-kvc-methods-defined) (if (valid-binding-p self property-key-path) (progn (#/bind:toObject:withKeyPath:options: self (convert-path-list property-key-path) (if (typep target-obj 'ns:ns-object) target-obj (wrapper-for target-obj)) (convert-path-list key-path) (if key-val-options (convert-key-val-options key-val-options) (%null-ptr))) t) (progn (ns-log-format "Property path ~s is not a valid bind path for ~s" property-key-path self) nil))) #| (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) ) ;; end of definitions with access to kvc-observed assoc-array |# (defun reader-selector (str) (ccl::%get-selector (ccl::load-objc-selector str))) (defun writer-selector (str) (ccl::%get-selector (ccl::load-objc-selector (concatenate 'string "set" (string-capitalize str :end 1) ":")))) (defmethod bound-slot-will-be-modified ((self standard-object) slot-name) (declare (ignore slot-name)) ;; do nothing by default ) (defmethod bound-slot-modified ((self standard-object) slot-name) (declare (ignore slot-name)) ;; do nothing by default ) (defmethod real-observer (observer) ;; observer will be an instance of one of server types of non-public Apple Classes. Examples include ;; NSSelectionBinder, NSValueBinder, NSTextValueBinder ;; All we want is a pointer to the original observer extracted from that object, but without ;; a public API that is a little tricky. But we are trickier. ;; We can see from (#/description ...) results for these objects that they all seem to respond to ;; the #/object message which returns the original observer. So we test for the object's response ;; to that selector and use it to return the original observer. (when *log-bindings* (ns-log-format "Observer description is: ~a" (coerce-obj (#/description observer) 'string))) (if (responds-to-selector observer "object") (#/object observer) observer)) #| This is an old method that worked in previous OSX versions I'm leaving it around in case something like this is ever useful in the future ;; We use the #/description of that ;; object which provides a substring of the form "Observer: 0x<whatever>" which points to ;; possibly another non-public object of type NSSelectionBinder. We extract the address and ;; create a pointer to the NSSelectionbinder. We now use its description to extract its ;; "object" slot address, which hopefully points to the original view object that we bound ;; to our lisp object. We use that to create a macptr and return it. (let* ((desc (ns-to-lisp-string (#/description nskvo))) (obs-start (search "Observer: " desc)) (hex-start (and obs-start (position #\x desc :start (+ obs-start 9)))) (hex-end (and hex-start (position #\, desc :start hex-start))) (hex-val (and hex-end (read-from-string (concatenate 'string "#" (subseq desc hex-start hex-end)) nil 0))) (nssb-ptr (and hex-val (ccl::%int-to-ptr hex-val))) (nssb-desc (and nssb-ptr (ns-to-lisp-string (#/description nssb-ptr)))) (obj-start (search "object:" nssb-desc)) (obj-class-end (and obj-start (position #\: nssb-desc :start (+ obj-start 8)))) (obj-hex-start (and obj-class-end (position #\x nssb-desc :start obj-class-end))) (obj-hex-end (and obj-hex-start (position #\> nssb-desc :start obj-hex-start))) (obj-hex-val (and obj-hex-end (read-from-string (concatenate 'string "#" (subseq nssb-desc obj-hex-start obj-hex-end)) nil 0)))) (when obj-hex-val (ccl::%int-to-ptr obj-hex-val)))) |# (defun more-specific-format (fmt1 fmt2) (cond ((null fmt2) t) ((eq fmt1 fmt2) nil) ((eq fmt2 :rich-text) t) ((eq fmt1 :rich-text) nil) ((listp fmt1) ;; only ns-decimal t) ((listp fmt2) nil) (t ;; ?? t))) (let ((format-assoc (make-instance 'assoc-array :rank 2 :tests (list #'eql #'equal)))) ;; used to hold needed Objective-C format information for slots that are observed by ;; Objective-C objects that have associated formatter objects from which we can take hints. (defun set-format-assoc (path-obj path format) (let ((existing-format (format-for path-obj path))) (when (more-specific-format format existing-format) (setf (assoc-aref format-assoc path-obj path) format)))) (defun format-for (path-obj path) (assoc-aref format-assoc path-obj path)) ) (defmethod convert-new-val ((self lisp-ptr-wrapper) value key-str) ;; converts the value to an appropriate Objective-C value depending on the key used to access it (let ((kr (key-return key-str))) (cond ((eql value (%null-ptr)) value) ((null value) (%null-ptr)) ((member value (list #$NSNoSelectionMarker #$NSNullPlaceholderBindingOption #$NSNotApplicablePlaceholderBindingOption) :test #'eql) value) ((eq kr :convert) (coerce-obj value 'ns:ns-object :ns-format (format-for (lpw-lisp-ptr self) key-str))) ((eq kr :path) (if (typep value 'ns:ns-object) value (wrapper-for value))) ((typep value 'lisp-ptr-wrapper) value) ((eq kr :path) (wrapper-for value :controller (lpw-controller self) :parent (lpw-lisp-ptr self))) ;; Cases below should only occur if binding was made using native objective-c methods ((typep value 'ns:ns-object) value) ((typep value 'objc-displayable) (coerce-obj value 'ns:ns-object :ns-format (format-for (lpw-lisp-ptr self) key-str))) (t (wrapper-for value :controller (lpw-controller self) :parent (lpw-lisp-ptr self)))))) (defmethod convert-new-val ((self ns:ns-object) value key-str) ;; converts the value to an appropriate Objective-C value depending on the key used to access it ;; If bindings are made using the lisp bind function, then we will know whether the value should ;; be converted to some sort of objective-c type for display or is just an intermediate value on ;; a binding path and should be left alone. We make a best guess for bindings made using native ;; objective-c calls depending on the type of the object returned. If it can be displayed, we ;; convert it. Otherwise we leave it alone (or wrap it, if it's a lisp object). (let ((kr (key-return key-str))) (cond ((eql value (%null-ptr)) value) ((null value) (%null-ptr)) ((member value (list #$NSNoSelectionMarker #$NSNullPlaceholderBindingOption #$NSNotApplicablePlaceholderBindingOption) :test #'eql) value) ;; Above cases apply whether value is a path element or end value ((eq kr :convert) (coerce-obj value 'ns:ns-object :ns-format (format-for self key-str))) ((eq kr :path) (if (typep value 'ns:ns-object) value (wrapper-for value))) ;; Cases below should only occur if binding was made using native objective-c methods ((typep value 'ns:ns-object) value) ((typep value 'objc-displayable) (coerce-obj value 'ns:ns-object :ns-format (format-for self key-str))) (t (wrapper-for value))))) (defun set-observer-format (self obs key-path) ;; We use the ns-format as a hint about how the lisp field is ;; formatted and convert accordingly when that value is retrieved. (let ((observer (real-observer obs)) (ns-format nil)) (cond ((typep observer 'ns:ns-control) (let* ((cell (#/cell observer)) (formatter (#/formatter cell))) (cond ((or (typep cell 'ns:ns-date-picker-cell) (typep formatter 'ns:ns-date-formatter)) (setf ns-format :date)) ((typep formatter 'ns:ns-number-formatter) (cond ((#/generatesDecimalNumbers formatter) (let ((dec-digits (#/maximumFractionDigits formatter))) (setf ns-format (list :decimal dec-digits)))) (t (setf ns-format :number)))) (t ;; NSControls can always accept NSAttributedStrings (setf ns-format :rich-text))))) ((typep observer 'ns:ns-text) ;; This is a little tricky becasue NSText objects can bind to either ;; an NSAttributedString or to an NSString via separate bindings. ;; But we have no real way of knowing which they bound to in IB, so ;; we guess based on the value returned by #/isRichText. Also the ;; developer gives us a hint by what sort of object is in the slot that ;; the interface object is bound to. If that slot has a lisp attributed-string ;; object and the field allows rich-text, we'll pass it an NSMutableAttributedString. ;; Otherwise it will just get an NSString. (setf ns-format (if (#/isRichText observer) :rich-text :text))) ((typep observer 'lc::lisp-controller) ;; We generally don't want to convert from some lisp format to an Objective-C form and then back. ;; Rather we'd like to get a pointer to the original Lisp object. So just create a wrapper for ;; the value. (setf ns-format :wrapper))) (when ns-format (set-format-assoc self (ns-to-lisp-string key-path) ns-format)))) (objc:defmethod (#/addObserver:forKeyPath:options:context: :void) ((self lisp-ptr-wrapper) (obs :id) (key-path :id) (options #>NSUInteger) (context :address)) (multiple-value-bind (observer ns-format) (set-observer-format (lpw-lisp-ptr self) obs key-path) (when *log-bindings* (ns-log-format "~s observed by ~s" (lpw-lisp-ptr self) observer) (ns-log-format "Observer data format: ~s" ns-format)) ;; Any controls that previously observed this field might have ;; received misformatted data, so indicate that the data changed ;; so they will go get it again. This primarily occurs when a new ;; window is open and controls are first observing the field. (#/willChangeValueForKey: self key-path) (#/didChangeValueForKey: self key-path)) (call-next-method obs key-path options context)) (objc:defmethod (#/valueForKey: :id) ((self lisp-ptr-wrapper) (path :id)) ;; Treat path as a lisp path as long as it works. ;; If it is not valid and the next target is an Objective-C object ;; then treat the path as a normal Objective-C Key and return the results ;; of calling #/valueForKey: on the target using path as the key. (let* ((lisp-str (ns-to-lisp-string path)) (lisp-path (objc-to-lisp-keypathname lisp-str)) (func (func-for-keypath lisp-str)) (ptr-obj (lpw-lisp-ptr self)) ;; to set next-obj we try 4 ways: ;; 1. If the path is one that we generated to represent a Lisp function use it ;; 2. If the path is a valid lisp function name use it to access the slot ;; 3. If the object is an Objective-C object try calling its #/valueForKey method ;; 4. Look for any KVO slots defined for the object with path specified as the KVO ;; accessor and use the lisp function value-for-kvo-key to access that slot (next-obj (cond ((and func (compute-applicable-methods func (list ptr-obj))) (funcall func ptr-obj)) ((and (typep lisp-path 'function-name) (fboundp lisp-path) (compute-applicable-methods lisp-path (list ptr-obj))) (funcall lisp-path ptr-obj)) ((and (typep ptr-obj 'objc:objc-object) (#/respondsToSelector: ptr-obj (reader-selector lisp-str))) (#/valueForKey: ptr-obj path)) ((and (typep ptr-obj 'ccl::kvo-object) (compute-applicable-methods #'ccl::value-for-kvo-key (list ptr-obj lisp-str)) (ccl::value-for-kvo-key ptr-obj lisp-str))) (t (%null-ptr))))) ;; First track that the path is being observed by somebody (note-kvc-observed self (lpw-lisp-ptr self) lisp-path) (note-kvc-observed self (lpw-lisp-ptr self) lisp-str) (when func (note-kvc-observed self (lpw-lisp-ptr self) func)) (when *log-bindings* (ns-log-format "(~s ~s) returned ~s" lisp-path (lpw-lisp-ptr self) next-obj)) (convert-new-val self next-obj lisp-str))) (defmethod set-value-for-key (self new-value (path ns:ns-object)) (let* ((lisp-str (coerce-obj path 'string)) (lisp-path (objc-to-lisp-keypathname lisp-str)) (prev-obj (cond ((and (typep lisp-path 'function-name) (fboundp lisp-path)) (funcall lisp-path self)) ((and (typep self 'objc:objc-object) (#/respondsToSelector: self (reader-selector lisp-str))) (#/valueForKey: self path)) (t (ccl::value-for-kvo-key self lisp-str)))) (prev-class (class-of prev-obj)) (new-lisp-obj (ns-to-lisp-object new-value :lisp-class prev-class :ns-format (format-for self lisp-str))) (setf-func (fboundp (list 'setf lisp-path)))) (when *log-bindings* (ns-log-format "Prev Class: ~s" prev-class)) (cond (setf-func (funcall setf-func new-lisp-obj self)) ((and (typep self 'objc:objc-object) (typep new-lisp-obj 'objc:objc-object) (#/respondsToSelector: self (writer-selector lisp-str))) (#/setValue:forKey: self new-lisp-obj path)) (t (let* ((found-slot (ccl::kvo-slot-for self lisp-str)) (slot-name (and found-slot (ccl::slot-definition-name found-slot)))) (if found-slot (progn (bound-slot-will-be-modified self slot-name) (setf (ccl::value-for-kvo-key self lisp-str) new-lisp-obj) (bound-slot-modified self (ccl::slot-definition-name found-slot))) ;; If the setf failed, log the original condition (error "No way to setValue: ~s forKey: ~s for lisp-ptr ~s" new-lisp-obj lisp-str self))))) (values new-lisp-obj prev-obj))) (objc:defmethod (#/setValue:forKey: :void) ((self lisp-ptr-wrapper) (new-value :id) (path :id)) (let ((ptr-obj (lpw-lisp-ptr self)) (ctrl (lpw-controller self)) (lisp-path (objc-to-lisp-keypathname (coerce-obj path 'string)))) (when ptr-obj (multiple-value-bind (new-lisp-obj prev-obj) (set-value-for-key ptr-obj new-value path) (when ctrl (lc::modified-bound-value ctrl (lpw-lisp-ptr self) lisp-path prev-obj new-lisp-obj)) new-lisp-obj)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Methods to observe kvo-compliant paths through and to either Objective-C or Lisp instances #| (defclass kvo-observer (ns:ns-object) ((observed-instance :accessor observed-instance :initarg :obj) (observe-path :accessor observe-path :initarg :path) (when-observed-func :accessor when-observed-func :initarg :func) (convert-type :accessor convert-type :initarg :convert-type)) (:default-initargs :obj nil :path nil :func nil :convert-type nil) (:metaclass ns:+ns-object)) |# (defmethod added-class-key-values ((self (eql (find-class 'kvo-observer)))) ;; provide documenation for keywords '((:obj "An ns:ns-object to be observed by the kvo-observer being created") (:path "A list of lisp forms that provides a path within the observed object") (:func "A function called when the object is observed to have changed") (:convert-type "A data type to which new observations will be converted"))) (defmethod initialize-instance :after ((self kvo-observer) &key (obj nil) (path nil) (func nil)) (assure-kvc-methods-defined) (when (and obj path func) (let ((observed-obj (if (typep obj 'ns:ns-object) obj (wrapper-for obj)))) (#/addObserver:forKeyPath:options:context: observed-obj self (convert-path-list path) 0 (%null-ptr))))) (objc:defmethod (#/dealloc :void) ((self kvo-observer)) (when (and (observed-instance self) (observe-path self)) (let ((observed-obj (if (typep (observed-instance self) 'ns:ns-object) (observed-instance self) (wrapper-for (observed-instance self))))) (when *log-bindings* (ns-log-format "about to remove observer of ~s via path ~s" observed-obj (convert-path-list (observe-path self)))) (#/removeObserver:forKeyPath:context: observed-obj self (convert-path-list (observe-path self)) (%null-ptr)))) (call-next-method) (objc:remove-lisp-slots self)) (objc::defmethod (#/observeValueForKeyPath:ofObject:change:context: :void) ((self kvo-observer) (key-path :id) (observed-obj :id) (change-dict :id) (context :address)) (declare (ignore key-path observed-obj change-dict context)) (when (functionp (when-observed-func self)) (funcall (when-observed-func self) (coerce-obj (#/valueForKeyPath: (observed-instance self) (coerce-obj (observe-path self) 'ns:ns-string)) (convert-type self))))) (defmacro when-observed ((object path new-value-decl) &rest forms) (let ((new-value-var (if (listp new-value-decl) (first new-value-decl) new-value-decl)) (new-value-type (if (listp new-value-decl) (second new-value-decl) t))) `(make-instance 'kvo-observer :obj ,object :path ,path :convert-type ',new-value-type :func #'(lambda (,new-value-var) ,@forms)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; methods to support access to Lisp lists and arrays as if they were NSArrays (objc:defmethod (#/count #>NSUInteger) ((self lisp-ptr-wrapper)) (let ((ptr-obj (lpw-lisp-ptr self))) (typecase ptr-obj (list (list-length ptr-obj)) (vector (length ptr-obj)) (t 0)))) (objc:defmethod (#/objectAtIndex: :id) ((self lisp-ptr-wrapper) (indx #>NSUInteger)) (let* ((ptr-obj (lpw-lisp-ptr self)) (next-obj (typecase ptr-obj (list (nth indx ptr-obj)) (vector (elt ptr-obj indx)) (t (%null-ptr))))) (cond ((eql next-obj (%null-ptr)) next-obj) ((null next-obj) (%null-ptr)) ((and (typep next-obj 'ns:ns-object) (not (typep next-obj 'ccl::kvo-object))) ;; any kvo-objects will be encapsulated in a lisp-ptr-wrapper ;; so that subsequent accesses through this method will try to ;; use ccl::value-for-kvo-key next-obj) ((typep next-obj 'objc-displayable) (lisp-to-ns-object next-obj)) (t (wrapper-for next-obj :controller (lpw-controller self) :parent (lpw-lisp-ptr self)))))) (provide :binding-utils)
true
;; binding-utils.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 :lc-classes) (require :coerce-obj) (require :nslog-utils) (require :kvo-slot) (require :selector-utils)) (defgeneric lc::modified-bound-value (controller edited-obj key old-val new-val)) (in-package :iu) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Miscellaneous utility functions ;; Given a window and another object, find all the subviews of the window that link to that object ;; for their value and the key paths that they use (returned as a string). (defmethod linking-views ((win ns:ns-window) (obj ns:ns-object)) (let* ((cview (#/contentView win)) (subviews (ns-to-lisp-list (#/subviews cview) :element-class ns:ns-object))) (mapcan #'(lambda (v) (multiple-value-bind (bound-p path) (bound-to v obj #@"value") (when bound-p (list (cons v path))))) subviews))) ;; This looks old and I think assumes a conversion to symbols in ns-to-lisp-assoc ;; that doesn't really happen ... (defmethod bound-to ((view ns::ns-view) (bound-to-obj ns::ns-object) binding-ns-string) (let* ((objc-info (#/infoForBinding: view binding-ns-string)) (info (and (not (eql objc-info (%null-ptr))) (ns-to-lisp-assoc objc-info :element-class ns::ns-object))) (proxy (cdr (assoc 'CL-USER::NSOBSERVEDOBJECT info))) (proxy-desc (and proxy (ns-to-lisp-string (#/description proxy)))) (bound-to-desc (ns-to-lisp-string (#/description bound-to-obj))) (path (and info (ns-to-lisp-string (cdr (assoc 'CL-USER::NSOBSERVEDKEYPATH info)))))) (if (and info (find-substring bound-to-desc proxy-desc)) (values t path) (values nil nil)))) (defun link-path-components (path-str) (if (zerop (length path-str)) nil (do* ((begin 0 (1+ end)) (end (or (position #\. path-str :start (1+ begin)) (length path-str)) (or (position #\. path-str :start (1+ begin)) (length path-str))) (words (list (subseq path-str begin end)) (push (subseq path-str begin end) words))) ((>= end (length path-str)) (mapcar #'objc-to-lisp-keypathname (nreverse words)))))) (defun convert-binding-option (bind-key) (ecase bind-key (:allows-editing-multiple-values-selection #$NSAllowsEditingMultipleValuesSelectionBindingOption) (:allows-null-argument #$NSAllowsNullArgumentBindingOption) (:always-presents-application-modal-alerts #$NSAlwaysPresentsApplicationModalAlertsBindingOption) (:conditionally-sets-editable #$NSConditionallySetsEditableBindingOption) (:conditionally-sets-enabled #$NSConditionallySetsEnabledBindingOption) (:conditionally-sets-hidden #$NSConditionallySetsHiddenBindingOption) (:continuously-updates-value #$NSContinuouslyUpdatesValueBindingOption) (:creates-sort-descriptor #$NSCreatesSortDescriptorBindingOption) (:deletes-objects-on-remove #$NSDeletesObjectsOnRemoveBindingsOption) (:display-name #$NSDisplayNameBindingOption) (:display-pattern #$NSDisplayPatternBindingOption) (:content-placement-tag #$NSContentPlacementTagBindingOption) (:handles-content-as-compound-value #$NSHandlesContentAsCompoundValueBindingOption) (:inserts-null-placeholder #$NSInsertsNullPlaceholderBindingOption) (:invokes-separately-with-array-objects #$NSInvokesSeparatelyWithArrayObjectsBindingOption) (:multiple-vlaues-placeholder #$NSMultipleValuesPlaceholderBindingOption) (:no-selection-placeholder #$NSNoSelectionPlaceholderBindingOption) (:not-applicable-placeholder #$NSNotApplicablePlaceholderBindingOption) (:null-placeholder #$NSNullPlaceholderBindingOption) (:raises-for-not-applicable-keys #$NSRaisesForNotApplicableKeysBindingOption) (:predicate-format #$NSPredicateFormatBindingOption) (:selector-name #$NSSelectorNameBindingOption) (:selects-all-when-setting-content #$NSSelectsAllWhenSettingContentBindingOption) (:validates-immediately #$NSValidatesImmediatelyBindingOption) (:transformer-name #$NSValueTransformerNameBindingOption) (:value-transformer #$NSValueTransformerBindingOption))) (defun convert-key-val-options (olist) ;; olist should be a list of keyword-value pairs where keywords are from the table above ;; note that the coerce-obj to ns-dictionary automatically converts values to appropriate ;; objective-C objects if needed. (do* ((assoc-list nil) (lst olist (cddr lst)) (key (convert-binding-option (first lst)) (convert-binding-option (first lst))) (val (second lst) (second lst))) ((null key) (coerce-obj assoc-list 'ns:ns-dictionary)) (push (cons key val) assoc-list))) #| Constants NSAllowsEditingMultipleValuesSelectionBindingOption An NSNumber object containing a Boolean value that determines if the binding allows editing when the value represents a multiple selection. NSAlwaysPresentsApplicationModalAlertsBindingOption An NSNumber object containing a Boolean value that determines if validation and error alert panels displayed as a result of this binding are displayed as application modal alerts. If YES, then the alerts are displayed application model, otherwise they are displayed as sheets. NSAllowsNullArgumentBindingOption An NSNumber object containing a Boolean value that determines if the argument bindings allows passing argument values of nil. NSConditionallySetsEditableBindingOption An NSNumber object containing a Boolean value that determines if the editable state of the user interface item is automatically configured based on the controller's selection. NSConditionallySetsEnabledBindingOption An NSNumber object containing a Boolean value that determines if the enabled state of the user interface item is automatically configured based on the controller's selection. NSConditionallySetsHiddenBindingOption An NSNumber object containing a Boolean value that determines if the hidden state of the user interface item is automatically configured based on the controller's selection. NSContentPlacementTagBindingOption An NSNumber object specifying the tag id of the popup menu item to replace with the content of the array. This allows you to use a popup menu that contains both static and bindings generated items. NSContinuouslyUpdatesValueBindingOption An NSNumber object containing a Boolean value that determines whether the value of the binding is updated as edits are made to the user interface item or is updated only when the user interface item resigns as the responder. NSCreatesSortDescriptorBindingOption An NSNumber object containing a Boolean value that determines if a sort descriptor is created for a table column. If this value is NO, then the table column does not allow sorting. NSDeletesObjectsOnRemoveBindingsOption An NSNumber object containing a Boolean value that determines if an object is deleted from the managed context immediately upon being removed from a relationship. NSDisplayNameBindingOption An NSString object containing a human readable string to be displayed for a predicate. NSDisplayPatternBindingOption An NSString object that specifies a format string used to construct the final value of a string. NSHandlesContentAsCompoundValueBindingOption An NSNumber object containing a Boolean value that determines if the content is treated as a compound value. NSInsertsNullPlaceholderBindingOption An NSNumber object containing a Boolean value that determines if an additional item which represents nil is inserted into a matrix or pop-up menu before the items in the content array. NSInvokesSeparatelyWithArrayObjectsBindingOption An NSNumber object containing a Boolean value that determines whether the specified selector is invoked with the array as the argument or is invoked repeatedly with each array item as an argument. NSMultipleValuesPlaceholderBindingOption An object that is used as a placeholder when the key path of the bound controller returns the NSMultipleValuesMarker marker for a binding. NSNoSelectionPlaceholderBindingOption An object that is used as a placeholder when the key path of the bound controller returns the NSNoSelectionMarker marker for a binding. NSNotApplicablePlaceholderBindingOption An object that is used as a placeholder when the key path of the bound controller returns the NSNotApplicableMarker marker for a binding. NSNullPlaceholderBindingOption An object that is used as a placeholder when the key path of the bound controller returns nil for a binding. NSPredicateFormatBindingOption An NSString object containing the predicate pattern string for the predicate bindings. Use $value to refer to the value in the search field. NSRaisesForNotApplicableKeysBindingOption An NSNumber object containing a Boolean value that specifies if an exception is raised when the binding is bound to a key that is not applicable—for example when an object is not key-value coding compliant for a key. NSSelectorNameBindingOption An NSString object that specifies the method selector invoked by the target binding when the user interface item is clicked. NSSelectsAllWhenSettingContentBindingOption An NSNumber object containing a Boolean value that specifies if all the items in the array controller are selected when the content is set. NSValidatesImmediatelyBindingOption An NSNumber object containing a Boolean value that determines if the contents of the binding are validated immediately. NSValueTransformerNameBindingOption The value for this key is an identifier of a registered NSValueTransformer instance that is applied to the bound value. NSValueTransformerBindingOption An NSValueTransformer instance that is applied to the bound value. |# ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Methods used to determine what slots are exposed for binding (defun make-proto (class) (let ((pr (#/alloc class))) ;; some classes require initialization to avoid uncatchable errors when getting their #/exposedBindings ;; I suspect that they have exposedBindings methods that query related objects or otherwise test the ;; state of the object and without initialization they fail. We can't just call #/init for every class ;; because that isn't always valid either. (when (some #'(lambda (cl) (ccl::subclassp class cl)) (list ns:ns-cell ns:ns-text)) (setf pr (#/init pr))) pr)) (let ((proto-hash (make-hash-table))) (defmethod proto-for-class ((self objc::objc-class)) (or (gethash self proto-hash) (handler-case (setf (gethash self proto-hash) (make-proto self)) (condition (c) (declare (ignore c)) (setf (gethash self proto-hash) (proto-for-class ns:ns-object))))))) (defmethod valid-bindings ((self ns:ns-object)) (coerce-obj (handler-case (#/exposedBindings self) (condition (c) (declare (ignore c)) (ns-log-format "Error trying to get #/exposedBings for ~s" self) nil)) 'list)) (defmethod valid-bindings ((self objc::objc-class)) (coerce-obj (handler-case (#/exposedBindings (proto-for-class self)) (condition (c) (declare (ignore c)) (ns-log-format "Error trying to get #/exposedBings for ~s" self) nil)) 'list)) (defmethod valid-bindings (non-class) (declare (ignore non-class)) nil) (defmethod valid-binding-p ((self ns:ns-object) property-key-path) (find property-key-path (valid-bindings self) :test #'string=)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Methods used to add Objective-C methods to Objectiv-C objects that have :kvo slot declarations (let ((kvc-hash (make-hash-table))) (defmethod define-kvc-methods ((self class)) ;; do nothing for non objective-c classes ) (defmethod define-kvc-methods ((self objc:objc-class-object)) (unless (gethash self kvc-hash nil) (setf (gethash self kvc-hash) t) (eval `(objc:defmethod (#/valueForUndefinedKey: :id) ((self ,(class-name self)) (key :id)) (let* ((lisp-key (coerce-obj key 'string)) (slot (kvo-slot-for self lisp-key))) (if slot (convert-new-val self (slot-value self (slot-definition-name slot)) lisp-key) (call-next-method key))))) (eval `(objc:defmethod (#/setValue:forUndefinedKey: :void) ((self ,(class-name self)) (new-val :id) (key :id)) (if (kvo-slot-for self (coerce-obj key 'string)) (set-value-for-key self new-val key) (call-next-method new-val key)))) (eval `(objc:defmethod (#/addObserver:forKeyPath:options:context: :void) ((self ,(class-name self)) (obs :id) (key-path :id) (options #>NSUInteger) (context :address)) (set-observer-format self obs key-path) (call-next-method obs key-path options context))))) (defun assure-kvc-methods-defined () (dolist (c (new-kvo-classes)) (define-kvc-methods c))) (defun redefine-all-kvc-methods () (setf kvc-hash (make-hash-table)) (dolist (c (kvo-classes)) (define-kvc-methods c))) ) ;; end of methods using kvc-hash ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; The main Lisp bind method (defmethod bind ((self ns:ns-object) property-key-path target-obj key-path &rest key-val-options) ;; target-obj must be an objective-c object. property-key-path and key-path are defined as: ;; key-path ::= <path-string> | ( <path-object>*) ;; path-object ::= <path-string> | <lisp-function> ;; path-string ::= "<path-elt-string>{.<path-string>}* ;; path-elt-string ::= any legal string for Objective-C keypaths ;; Before binding anything, make sure that all Objective-C classes with KVO slots have some methods ;; defined for them. (assure-kvc-methods-defined) (if (valid-binding-p self property-key-path) (progn (#/bind:toObject:withKeyPath:options: self (convert-path-list property-key-path) (if (typep target-obj 'ns:ns-object) target-obj (wrapper-for target-obj)) (convert-path-list key-path) (if key-val-options (convert-key-val-options key-val-options) (%null-ptr))) t) (progn (ns-log-format "Property path ~s is not a valid bind path for ~s" property-key-path self) nil))) #| (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) ) ;; end of definitions with access to kvc-observed assoc-array |# (defun reader-selector (str) (ccl::%get-selector (ccl::load-objc-selector str))) (defun writer-selector (str) (ccl::%get-selector (ccl::load-objc-selector (concatenate 'string "set" (string-capitalize str :end 1) ":")))) (defmethod bound-slot-will-be-modified ((self standard-object) slot-name) (declare (ignore slot-name)) ;; do nothing by default ) (defmethod bound-slot-modified ((self standard-object) slot-name) (declare (ignore slot-name)) ;; do nothing by default ) (defmethod real-observer (observer) ;; observer will be an instance of one of server types of non-public Apple Classes. Examples include ;; NSSelectionBinder, NSValueBinder, NSTextValueBinder ;; All we want is a pointer to the original observer extracted from that object, but without ;; a public API that is a little tricky. But we are trickier. ;; We can see from (#/description ...) results for these objects that they all seem to respond to ;; the #/object message which returns the original observer. So we test for the object's response ;; to that selector and use it to return the original observer. (when *log-bindings* (ns-log-format "Observer description is: ~a" (coerce-obj (#/description observer) 'string))) (if (responds-to-selector observer "object") (#/object observer) observer)) #| This is an old method that worked in previous OSX versions I'm leaving it around in case something like this is ever useful in the future ;; We use the #/description of that ;; object which provides a substring of the form "Observer: 0x<whatever>" which points to ;; possibly another non-public object of type NSSelectionBinder. We extract the address and ;; create a pointer to the NSSelectionbinder. We now use its description to extract its ;; "object" slot address, which hopefully points to the original view object that we bound ;; to our lisp object. We use that to create a macptr and return it. (let* ((desc (ns-to-lisp-string (#/description nskvo))) (obs-start (search "Observer: " desc)) (hex-start (and obs-start (position #\x desc :start (+ obs-start 9)))) (hex-end (and hex-start (position #\, desc :start hex-start))) (hex-val (and hex-end (read-from-string (concatenate 'string "#" (subseq desc hex-start hex-end)) nil 0))) (nssb-ptr (and hex-val (ccl::%int-to-ptr hex-val))) (nssb-desc (and nssb-ptr (ns-to-lisp-string (#/description nssb-ptr)))) (obj-start (search "object:" nssb-desc)) (obj-class-end (and obj-start (position #\: nssb-desc :start (+ obj-start 8)))) (obj-hex-start (and obj-class-end (position #\x nssb-desc :start obj-class-end))) (obj-hex-end (and obj-hex-start (position #\> nssb-desc :start obj-hex-start))) (obj-hex-val (and obj-hex-end (read-from-string (concatenate 'string "#" (subseq nssb-desc obj-hex-start obj-hex-end)) nil 0)))) (when obj-hex-val (ccl::%int-to-ptr obj-hex-val)))) |# (defun more-specific-format (fmt1 fmt2) (cond ((null fmt2) t) ((eq fmt1 fmt2) nil) ((eq fmt2 :rich-text) t) ((eq fmt1 :rich-text) nil) ((listp fmt1) ;; only ns-decimal t) ((listp fmt2) nil) (t ;; ?? t))) (let ((format-assoc (make-instance 'assoc-array :rank 2 :tests (list #'eql #'equal)))) ;; used to hold needed Objective-C format information for slots that are observed by ;; Objective-C objects that have associated formatter objects from which we can take hints. (defun set-format-assoc (path-obj path format) (let ((existing-format (format-for path-obj path))) (when (more-specific-format format existing-format) (setf (assoc-aref format-assoc path-obj path) format)))) (defun format-for (path-obj path) (assoc-aref format-assoc path-obj path)) ) (defmethod convert-new-val ((self lisp-ptr-wrapper) value key-str) ;; converts the value to an appropriate Objective-C value depending on the key used to access it (let ((kr (key-return key-str))) (cond ((eql value (%null-ptr)) value) ((null value) (%null-ptr)) ((member value (list #$NSNoSelectionMarker #$NSNullPlaceholderBindingOption #$NSNotApplicablePlaceholderBindingOption) :test #'eql) value) ((eq kr :convert) (coerce-obj value 'ns:ns-object :ns-format (format-for (lpw-lisp-ptr self) key-str))) ((eq kr :path) (if (typep value 'ns:ns-object) value (wrapper-for value))) ((typep value 'lisp-ptr-wrapper) value) ((eq kr :path) (wrapper-for value :controller (lpw-controller self) :parent (lpw-lisp-ptr self))) ;; Cases below should only occur if binding was made using native objective-c methods ((typep value 'ns:ns-object) value) ((typep value 'objc-displayable) (coerce-obj value 'ns:ns-object :ns-format (format-for (lpw-lisp-ptr self) key-str))) (t (wrapper-for value :controller (lpw-controller self) :parent (lpw-lisp-ptr self)))))) (defmethod convert-new-val ((self ns:ns-object) value key-str) ;; converts the value to an appropriate Objective-C value depending on the key used to access it ;; If bindings are made using the lisp bind function, then we will know whether the value should ;; be converted to some sort of objective-c type for display or is just an intermediate value on ;; a binding path and should be left alone. We make a best guess for bindings made using native ;; objective-c calls depending on the type of the object returned. If it can be displayed, we ;; convert it. Otherwise we leave it alone (or wrap it, if it's a lisp object). (let ((kr (key-return key-str))) (cond ((eql value (%null-ptr)) value) ((null value) (%null-ptr)) ((member value (list #$NSNoSelectionMarker #$NSNullPlaceholderBindingOption #$NSNotApplicablePlaceholderBindingOption) :test #'eql) value) ;; Above cases apply whether value is a path element or end value ((eq kr :convert) (coerce-obj value 'ns:ns-object :ns-format (format-for self key-str))) ((eq kr :path) (if (typep value 'ns:ns-object) value (wrapper-for value))) ;; Cases below should only occur if binding was made using native objective-c methods ((typep value 'ns:ns-object) value) ((typep value 'objc-displayable) (coerce-obj value 'ns:ns-object :ns-format (format-for self key-str))) (t (wrapper-for value))))) (defun set-observer-format (self obs key-path) ;; We use the ns-format as a hint about how the lisp field is ;; formatted and convert accordingly when that value is retrieved. (let ((observer (real-observer obs)) (ns-format nil)) (cond ((typep observer 'ns:ns-control) (let* ((cell (#/cell observer)) (formatter (#/formatter cell))) (cond ((or (typep cell 'ns:ns-date-picker-cell) (typep formatter 'ns:ns-date-formatter)) (setf ns-format :date)) ((typep formatter 'ns:ns-number-formatter) (cond ((#/generatesDecimalNumbers formatter) (let ((dec-digits (#/maximumFractionDigits formatter))) (setf ns-format (list :decimal dec-digits)))) (t (setf ns-format :number)))) (t ;; NSControls can always accept NSAttributedStrings (setf ns-format :rich-text))))) ((typep observer 'ns:ns-text) ;; This is a little tricky becasue NSText objects can bind to either ;; an NSAttributedString or to an NSString via separate bindings. ;; But we have no real way of knowing which they bound to in IB, so ;; we guess based on the value returned by #/isRichText. Also the ;; developer gives us a hint by what sort of object is in the slot that ;; the interface object is bound to. If that slot has a lisp attributed-string ;; object and the field allows rich-text, we'll pass it an NSMutableAttributedString. ;; Otherwise it will just get an NSString. (setf ns-format (if (#/isRichText observer) :rich-text :text))) ((typep observer 'lc::lisp-controller) ;; We generally don't want to convert from some lisp format to an Objective-C form and then back. ;; Rather we'd like to get a pointer to the original Lisp object. So just create a wrapper for ;; the value. (setf ns-format :wrapper))) (when ns-format (set-format-assoc self (ns-to-lisp-string key-path) ns-format)))) (objc:defmethod (#/addObserver:forKeyPath:options:context: :void) ((self lisp-ptr-wrapper) (obs :id) (key-path :id) (options #>NSUInteger) (context :address)) (multiple-value-bind (observer ns-format) (set-observer-format (lpw-lisp-ptr self) obs key-path) (when *log-bindings* (ns-log-format "~s observed by ~s" (lpw-lisp-ptr self) observer) (ns-log-format "Observer data format: ~s" ns-format)) ;; Any controls that previously observed this field might have ;; received misformatted data, so indicate that the data changed ;; so they will go get it again. This primarily occurs when a new ;; window is open and controls are first observing the field. (#/willChangeValueForKey: self key-path) (#/didChangeValueForKey: self key-path)) (call-next-method obs key-path options context)) (objc:defmethod (#/valueForKey: :id) ((self lisp-ptr-wrapper) (path :id)) ;; Treat path as a lisp path as long as it works. ;; If it is not valid and the next target is an Objective-C object ;; then treat the path as a normal Objective-C Key and return the results ;; of calling #/valueForKey: on the target using path as the key. (let* ((lisp-str (ns-to-lisp-string path)) (lisp-path (objc-to-lisp-keypathname lisp-str)) (func (func-for-keypath lisp-str)) (ptr-obj (lpw-lisp-ptr self)) ;; to set next-obj we try 4 ways: ;; 1. If the path is one that we generated to represent a Lisp function use it ;; 2. If the path is a valid lisp function name use it to access the slot ;; 3. If the object is an Objective-C object try calling its #/valueForKey method ;; 4. Look for any KVO slots defined for the object with path specified as the KVO ;; accessor and use the lisp function value-for-kvo-key to access that slot (next-obj (cond ((and func (compute-applicable-methods func (list ptr-obj))) (funcall func ptr-obj)) ((and (typep lisp-path 'function-name) (fboundp lisp-path) (compute-applicable-methods lisp-path (list ptr-obj))) (funcall lisp-path ptr-obj)) ((and (typep ptr-obj 'objc:objc-object) (#/respondsToSelector: ptr-obj (reader-selector lisp-str))) (#/valueForKey: ptr-obj path)) ((and (typep ptr-obj 'ccl::kvo-object) (compute-applicable-methods #'ccl::value-for-kvo-key (list ptr-obj lisp-str)) (ccl::value-for-kvo-key ptr-obj lisp-str))) (t (%null-ptr))))) ;; First track that the path is being observed by somebody (note-kvc-observed self (lpw-lisp-ptr self) lisp-path) (note-kvc-observed self (lpw-lisp-ptr self) lisp-str) (when func (note-kvc-observed self (lpw-lisp-ptr self) func)) (when *log-bindings* (ns-log-format "(~s ~s) returned ~s" lisp-path (lpw-lisp-ptr self) next-obj)) (convert-new-val self next-obj lisp-str))) (defmethod set-value-for-key (self new-value (path ns:ns-object)) (let* ((lisp-str (coerce-obj path 'string)) (lisp-path (objc-to-lisp-keypathname lisp-str)) (prev-obj (cond ((and (typep lisp-path 'function-name) (fboundp lisp-path)) (funcall lisp-path self)) ((and (typep self 'objc:objc-object) (#/respondsToSelector: self (reader-selector lisp-str))) (#/valueForKey: self path)) (t (ccl::value-for-kvo-key self lisp-str)))) (prev-class (class-of prev-obj)) (new-lisp-obj (ns-to-lisp-object new-value :lisp-class prev-class :ns-format (format-for self lisp-str))) (setf-func (fboundp (list 'setf lisp-path)))) (when *log-bindings* (ns-log-format "Prev Class: ~s" prev-class)) (cond (setf-func (funcall setf-func new-lisp-obj self)) ((and (typep self 'objc:objc-object) (typep new-lisp-obj 'objc:objc-object) (#/respondsToSelector: self (writer-selector lisp-str))) (#/setValue:forKey: self new-lisp-obj path)) (t (let* ((found-slot (ccl::kvo-slot-for self lisp-str)) (slot-name (and found-slot (ccl::slot-definition-name found-slot)))) (if found-slot (progn (bound-slot-will-be-modified self slot-name) (setf (ccl::value-for-kvo-key self lisp-str) new-lisp-obj) (bound-slot-modified self (ccl::slot-definition-name found-slot))) ;; If the setf failed, log the original condition (error "No way to setValue: ~s forKey: ~s for lisp-ptr ~s" new-lisp-obj lisp-str self))))) (values new-lisp-obj prev-obj))) (objc:defmethod (#/setValue:forKey: :void) ((self lisp-ptr-wrapper) (new-value :id) (path :id)) (let ((ptr-obj (lpw-lisp-ptr self)) (ctrl (lpw-controller self)) (lisp-path (objc-to-lisp-keypathname (coerce-obj path 'string)))) (when ptr-obj (multiple-value-bind (new-lisp-obj prev-obj) (set-value-for-key ptr-obj new-value path) (when ctrl (lc::modified-bound-value ctrl (lpw-lisp-ptr self) lisp-path prev-obj new-lisp-obj)) new-lisp-obj)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Methods to observe kvo-compliant paths through and to either Objective-C or Lisp instances #| (defclass kvo-observer (ns:ns-object) ((observed-instance :accessor observed-instance :initarg :obj) (observe-path :accessor observe-path :initarg :path) (when-observed-func :accessor when-observed-func :initarg :func) (convert-type :accessor convert-type :initarg :convert-type)) (:default-initargs :obj nil :path nil :func nil :convert-type nil) (:metaclass ns:+ns-object)) |# (defmethod added-class-key-values ((self (eql (find-class 'kvo-observer)))) ;; provide documenation for keywords '((:obj "An ns:ns-object to be observed by the kvo-observer being created") (:path "A list of lisp forms that provides a path within the observed object") (:func "A function called when the object is observed to have changed") (:convert-type "A data type to which new observations will be converted"))) (defmethod initialize-instance :after ((self kvo-observer) &key (obj nil) (path nil) (func nil)) (assure-kvc-methods-defined) (when (and obj path func) (let ((observed-obj (if (typep obj 'ns:ns-object) obj (wrapper-for obj)))) (#/addObserver:forKeyPath:options:context: observed-obj self (convert-path-list path) 0 (%null-ptr))))) (objc:defmethod (#/dealloc :void) ((self kvo-observer)) (when (and (observed-instance self) (observe-path self)) (let ((observed-obj (if (typep (observed-instance self) 'ns:ns-object) (observed-instance self) (wrapper-for (observed-instance self))))) (when *log-bindings* (ns-log-format "about to remove observer of ~s via path ~s" observed-obj (convert-path-list (observe-path self)))) (#/removeObserver:forKeyPath:context: observed-obj self (convert-path-list (observe-path self)) (%null-ptr)))) (call-next-method) (objc:remove-lisp-slots self)) (objc::defmethod (#/observeValueForKeyPath:ofObject:change:context: :void) ((self kvo-observer) (key-path :id) (observed-obj :id) (change-dict :id) (context :address)) (declare (ignore key-path observed-obj change-dict context)) (when (functionp (when-observed-func self)) (funcall (when-observed-func self) (coerce-obj (#/valueForKeyPath: (observed-instance self) (coerce-obj (observe-path self) 'ns:ns-string)) (convert-type self))))) (defmacro when-observed ((object path new-value-decl) &rest forms) (let ((new-value-var (if (listp new-value-decl) (first new-value-decl) new-value-decl)) (new-value-type (if (listp new-value-decl) (second new-value-decl) t))) `(make-instance 'kvo-observer :obj ,object :path ,path :convert-type ',new-value-type :func #'(lambda (,new-value-var) ,@forms)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; methods to support access to Lisp lists and arrays as if they were NSArrays (objc:defmethod (#/count #>NSUInteger) ((self lisp-ptr-wrapper)) (let ((ptr-obj (lpw-lisp-ptr self))) (typecase ptr-obj (list (list-length ptr-obj)) (vector (length ptr-obj)) (t 0)))) (objc:defmethod (#/objectAtIndex: :id) ((self lisp-ptr-wrapper) (indx #>NSUInteger)) (let* ((ptr-obj (lpw-lisp-ptr self)) (next-obj (typecase ptr-obj (list (nth indx ptr-obj)) (vector (elt ptr-obj indx)) (t (%null-ptr))))) (cond ((eql next-obj (%null-ptr)) next-obj) ((null next-obj) (%null-ptr)) ((and (typep next-obj 'ns:ns-object) (not (typep next-obj 'ccl::kvo-object))) ;; any kvo-objects will be encapsulated in a lisp-ptr-wrapper ;; so that subsequent accesses through this method will try to ;; use ccl::value-for-kvo-key next-obj) ((typep next-obj 'objc-displayable) (lisp-to-ns-object next-obj)) (t (wrapper-for next-obj :controller (lpw-controller self) :parent (lpw-lisp-ptr self)))))) (provide :binding-utils)
[ { "context": "valuated in the correct lexical context.\r\n;;; From JP Massar.\r\n;;;\r\n(defmacro cl::multiple-value-bind (vars va", "end": 46502, "score": 0.9380801916122437, "start": 46493, "tag": "NAME", "value": "JP Massar" } ]
Sys/ffi.lisp
foss-santanu/cormanlisp
608
;;;; ------------------------------- ;;;; Copyright (c) Corman Technologies Inc. ;;;; See LICENSE.txt for license information. ;;;; ------------------------------- ;;;; ;;;; File: ffi.lisp ;;;; Contents: Foreign function interface. ;;;; History: 2/13/97 RGC Created. ;;;; (defpackage "C-TYPES" (:export "DEFUN-DLL" "DEFUN-COM-METHOD" "DEFUN-THISCALL" "DEFUN-POINTER" "DEFUN-KERNEL" "DEFCSTRUCT" "DEFCTYPE" "CREATE-FOREIGN-PTR" "SIZEOF" "OFFSETOF" "CPOINTER-VALUE" "CPOINTERP" "DEFUN-CALLBACK" "DEFUN-C-CALLBACK" "DEFUN-DIRECT-CALLBACK" "DEFUN-DIRECT-C-CALLBACK" "DEFUN-DLL-EXPORT-FUNCTION" "DEFUN-DLL-EXPORT-C-FUNCTION" "GET-CALLBACK-PROCINST" "CREF" "CREATE-C-STRING" "C-STRING-LENGTH" "CPOINTER=" "CPOINTER-NULL" "MEMCMP" "MEMCPY" "MALLOC" "FREE" "FOREIGN-PTR-TO-INT" "INT-TO-FOREIGN-PTR" "UNICODE-TO-LISP-STRING" "LISP-STRING-TO-UNICODE" "C-STRING-TO-LISP-STRING" "LISP-STRING-TO-C-STRING" "WITH-C-STRUCT" "WITH-FRESH-FOREIGN-BLOCK" "FOREIGN-STACK-P" "ALLOCA" "*COLLECT-EXPORTED-FUNCTIONS*" "DUMP-C-STRUCT" "FOREIGN-HEAP-LENGTH" "LISP-BYTES-TO-C-BYTES" "C-BYTES-TO-LISP-BYTES" ) (:nicknames :ct)) (in-package "C-TYPES") (setq cl::*compiler-warn-on-undefined-function* nil) ;;; examples of valid C type descriptors: ;;; :void ;;; :char ;;; :unsigned-char ;;; :short ;;; :unsigned-short ;;; :wide-char ;;; :long ;;; :unsigned-long ;;; :short-bool ;;; :long-bool ;;; :single-float ;;; :double-float ;;; :handle ;;; (:long 5) ; array of 5 longs ;;; (:long *) ; pointer to long ;;; ((:long *) *) ; pointer to pointer to long ;;; (:struct f1 :short f2 :long) ; struct containing a short and a long (defstruct foreign-function-record dll-name foreign-name lisp-sym foreign-address jump-table-address) (defstruct dll-record name handle (function-records nil)) (defvar *dlls-loaded* nil) #| (defun pl::peek-dword (addr) (+ (pl::peek-byte addr) (ash (pl::peek-byte (+ addr 1)) 8) (ash (pl::peek-byte (+ addr 2)) 16) (ash (pl::peek-byte (+ addr 3)) 24))) |# (defun foreign-jump-table-capacity () (pl::peek-dword (+ (cl::sys-globals-address) 12))) (defun foreign-jump-table-num-entries () (pl::peek-dword (+ (cl::sys-globals-address) 8))) ;; ;; forward references ;; (declaim (ftype (function (t) t) ctype-lookup-alias)) (declaim (ftype (function (t) fixnum) determine-c-struct-size)) (declaim (ftype (function (t) t) valid-c-struct-definition)) (defun foreign-type-error (obj) (error "Not a foreign pointer: ~A" obj)) (defun determine-c-type-size (definition) (if (symbolp definition) (let ((typedef (ctype-lookup-alias definition))) (if typedef (setq definition typedef)))) (cond ((symbolp definition) (ecase definition (:void 0) ((:char :unsigned-char) 1) ((:short :unsigned-short :short-bool :wide-char) 2) ((:long :unsigned-long :single-float :long-bool :handle) 4) ((:double-float :int64 :uint64) 8))) ((not (listp definition)) (error "Invalid C Type descriptor: ~S" definition)) ((eq (car definition) ':struct) (determine-c-struct-size definition)) ((eq (cadr definition) '*) 4) ;; pointer type ((integerp (cadr definition)) (* (determine-c-type-size (car definition)) (cadr definition))) ((and (constantp (cadr definition)) (fixnump (symbol-value (cadr definition)))) (* (determine-c-type-size (car definition)) (symbol-value (cadr definition)))) (t (error "Invalid C Type descriptor: ~S" definition)))) (defconstant simple-c-types '(:void :char :unsigned-char :short :unsigned-short :long :unsigned-long :short-bool :long-bool :single-float :double-float :handle :wide-char :int64 :uint64)) (defun valid-c-type-definition (definition) (cond ((symbolp definition) (let ((typedef (ctype-lookup-alias definition))) (if typedef t (if (member definition simple-c-types) t)))) ((not (listp definition)) nil) ((eq (car definition) ':struct) (valid-c-struct-definition definition)) ((eq (cadr definition) '*) (valid-c-type-definition (car definition))) ((or (fixnump (cadr definition)) (and (constantp (cadr definition)) (fixnump (symbol-value (cadr definition))))) (valid-c-type-definition (car definition))) (t nil))) (defun valid-c-struct-definition (definition) (unless (eq (car definition) ':struct) (return-from valid-c-struct-definition nil)) (do ((p (cdr definition)(cddr p))) ((null p) t) (unless (valid-c-type-definition (cadr p)) (return nil)))) (defun determine-c-struct-size (definition) (do ((size 0) (p (cdr definition)(cddr p))) ((null p) size) (incf size (determine-c-type-size (cadr p))))) (defun cstruct-definition-equal-p (def1 def2) (equal def1 def2)) (defasm set-foreign-func-address (func cptr) { push ebp mov ebp, esp mov eax, [ebp + (+ ARGS_OFFSET 4)] ;eax = func mov edx, [ebp + ARGS_OFFSET] ;edx = cptr mov edx, [edx + (uvector-offset cl::foreign-heap-ptr-offset)] mov [eax + (uvector-offset cl::function-code-buffer-offset)], edx mov ecx, 1 pop ebp ret }) (defun foreign-ptr-to-function (cptr) (let ((func (alloc-uvector cl::function-size cl::uvector-kfunction-tag))) (setf (uref func cl::function-environment-offset) nil) (set-foreign-func-address func cptr) func)) (defun get-dll-record (dll-name) (dolist (rec *dlls-loaded*) (if (string-equal (dll-record-name rec) dll-name) (return-from get-dll-record rec))) (let* ((handle (load-dll dll-name)) (rec (make-dll-record :name dll-name :handle handle))) (push rec *dlls-loaded*) rec)) ;;; ;;; GET-DLL-HANDLE dll-name ;;; Returns handle of the DLL if it is already loaded, ;;; otherwise returns it loads the DLL and returns the handle. ;;; (defun get-dll-handle (dll-name) (let ((rec (get-dll-record dll-name))) (if rec (dll-record-handle rec) nil))) ;;; ;;; GET-DLL-FUNCTION-ADDRESS dll-name dll-function-name ;;; (defun get-dll-function-address (dll-name dll-function-name) (let ((dll-handle (get-dll-handle dll-name))) (if dll-handle (let ((addr (get-dll-proc-address dll-function-name dll-handle))) (if addr (return-from get-dll-function-address addr) (error "Could not find function ~S in library ~S" dll-function-name dll-name))) (error "Could not open library ~S" dll-name)))) ;;; ;;; INSTALL-DLL-FUNCTION dll-name dll-function-name lisp-symbol ;;; ;;; ;;; INSTALL-DLL-FUNCTION dll-name dll-function-name lisp-symbol ;;; (defun install-dll-function (dll-name dll-function-name lisp-symbol) (let* ((func-address (get-dll-function-address dll-name dll-function-name)) (dll-rec (get-dll-record dll-name)) (jump-address (cl::allocate-foreign-jump-table-entry func-address)) (func-rec (make-foreign-function-record :dll-name dll-name :foreign-name dll-function-name :lisp-sym lisp-symbol :foreign-address func-address :jump-table-address jump-address))) (setf (symbol-function lisp-symbol) (foreign-ptr-to-function jump-address)) (push func-rec (dll-record-function-records dll-rec)) lisp-symbol)) ;;; ;;; GENERATE-DYNAMIC-FUNCTION ;;; This generates a function which is used as a stub for a dynamically linked ;;; function. When this executes, it loads the actual function, and calls it ;;; with the arguments which were passed to it. ;;; #| (defun generate-dynamic-function (dll-name dll-function-name lisp-symbol) #'(lambda (&rest args) (install-dll-function dll-name dll-function-name lisp-symbol) (apply lisp-symbol args))) |# (defun generate-dynamic-function (dll_name dll_function_name lisp_symbol) (defasm dynamic-func-instance () { push ebp mov ebp, esp push edi ;; push lisp stack context--enter lisp mode foreign-call-lisp push ecx push ct::dll_name push ct::dll_function_name push ct::lisp_symbol mov ecx, 3 callf ct::install-dll-function add esp, 12 pop ecx ;; pop lisp stack context--back to foreign code lisp-return-to-foreign pop edi mov eax, ct::lisp_symbol mov eax, [eax + (uvector-offset cl::symbol-jump-table-offset)] shr eax, 1 pop ebp jmp near [esi + eax + 4] ret }) #'dynamic-func-instance) #| (defun generate-dynamic-function (dll_name dll_function_name lisp_symbol) (defasm dynamic-func-instance () { push ebp mov ebp, esp push edi ;; pop foreign stack context--return to lisp mode begin-atomic mov edx, [esi + (* stack-marker-index-qv-offset 4)] cmp edx, 0 jg :t1 end-atomic push "Tried to pop foreign stack context but none exist!" mov ecx, 1 callf error :t1 sub edx, 4 mov [esi + (* stack-marker-index-qv-offset 4)], edx end-atomic push ecx push ct::dll_name push ct::dll_function_name push ct::lisp_symbol mov ecx, 3 callf ct::install-dll-function add esp, 12 pop ecx ;; push foreign stack context--back to foreign code begin-atomic mov eax, [esi + (* stack-marker-index-qv-offset 4)] cmp eax, stack-markers-max jl :t2 end-atomic push "Ran out of stack markers!" mov ecx, 1 callf error :t2 push eax ;; just to get esp - 4 mov [esi + eax*2 + (* stack-markers-qv-offset 4)], esp lea edi, [esi + eax*2 + (* (+ stack-markers-qv-offset 1) 4)] pop eax ;; just to get esp - 4 add eax, 4 mov [esi + (* stack-marker-index-qv-offset 4)], eax end-atomic pop edi mov eax, ct::lisp_symbol mov eax, [eax + (uvector-offset cl::symbol-jump-table-offset)] shr eax, 1 pop ebp jmp near [esi + eax + 4] ret }) #'dynamic-func-instance) |# (defun install-dynamic-foreign-function (dll-name dll-function-name lisp-symbol) (setf (symbol-function lisp-symbol) (generate-dynamic-function dll-name dll-function-name lisp-symbol)) lisp-symbol) (defun create-foreign-function-name (dll-function-name) (intern (concatenate 'string "%FOREIGN-" dll-function-name))) (defun stack-frame-bytes (arg-type-list) (let ((bytes 0)) (dolist (i arg-type-list bytes) (incf bytes (case i (:long 4) (:double-float 8) (:int64 8) (:uint64 8) (otherwise 4)))))) (defstruct foreign-call-params-info push-forms local-vars lambda-list frame-cells pointer-p) (defun generate-call-params-info (param-list frame-cells &optional (func-ptr nil)) (let ((push-forms '()) (local-vars '()) (num-cells (- frame-cells)) (lambda-list '()) (pointer-p nil)) ;; special case for defun-pointer--skip past the pointer (when func-ptr ;; start with foreign func ptr (push `(x86::compile-foreign-arg ,func-ptr (:void *) ,num-cells) push-forms) (incf num-cells 1) (setf pointer-p t)) (dolist (i param-list) (let ((var (first i)) (ctype (second i))) (setq ctype (ctypeexpand-all ctype)) (if (stringp var) (setf var (if (equalp var "") (gensym) (intern (string-upcase var))))) (push var lambda-list) (cond ((equal ctype '(:char *)) (let ((t3 (gensym))) (push `(,t3 (ct::create-c-string ,var)) local-vars) (push `(x86::compile-foreign-arg ,t3 ,ctype ,num-cells) push-forms))) (t (push `(x86::compile-foreign-arg ,var ,ctype ,num-cells) push-forms))) (if (member ctype '(:double-float :int64 :uint64)) (incf num-cells 2) (incf num-cells 1)))) (make-foreign-call-params-info :push-forms push-forms :local-vars local-vars :lambda-list lambda-list :frame-cells frame-cells :pointer-p pointer-p))) (defun foreign-defun-stub (name info stack-cleanup-forms return-type call-form &optional call-setup-form) (let ((num-cells (foreign-call-params-info-frame-cells info))) `(defun ,name ,(nreverse (foreign-call-params-info-lambda-list info)) (let (,@(foreign-call-params-info-local-vars info)) (x86::save-lisp-registers) ,@(foreign-call-params-info-push-forms info) ,@call-setup-form (x86::push-foreign-stack-context) (x86::push-foreign-args-length ,(if (foreign-call-params-info-pointer-p info) (- num-cells 1) num-cells)) ;; if called by DEFUN-POINTER, the args length is one fewer because pointer is ;; popped as part of function call (x86::copy-foreign-args ,(foreign-call-params-info-frame-cells info)) ,call-form (x86::pop-foreign-args-length) (x86::copy-return-value ,return-type) ,@stack-cleanup-forms (x86::pop-foreign-stack-context) (x86::restore-lisp-registers) (x86::wrap-foreign-return-value ,return-type))))) (defmacro defun-dll (name param-list &key (return-type :long) library-name entry-name (linkage-type :c)) (unless entry-name (setq entry-name (symbol-name name))) (unless library-name (error "You must specify a DLL name in the declaration of ~A" name)) (setq return-type (ctypeexpand-all return-type)) (let* ((arg-type-list (mapcar #'cadr param-list)) (stack-cleanup-forms nil) (lisp-symbol (create-foreign-function-name entry-name)) (frame-cells (/ (stack-frame-bytes arg-type-list) 4)) (info (generate-call-params-info param-list frame-cells))) ;side effect--allocates a jump table entry (cl::%create-func-table-entry lisp-symbol) (if (eq linkage-type :c) (setq stack-cleanup-forms `((x86::popargs ,arg-type-list)))) `(progn (install-dynamic-foreign-function ,library-name ,entry-name ',lisp-symbol) ,(foreign-defun-stub name info stack-cleanup-forms return-type `(x86::call-foreign-proc ,lisp-symbol))))) (defmacro defun-com-method (name param-list vtable-index &key (return-type :unsigned-long)) (setq return-type (ctypeexpand-all return-type)) (let* ((arg-type-list (mapcar #'cadr param-list)) (frame-cells (/ (stack-frame-bytes arg-type-list) 4)) (info (generate-call-params-info param-list frame-cells))) `(progn ,(foreign-defun-stub name info nil return-type `(x86::call-com-method ,vtable-index) `((x86::compile-com-method-address ,vtable-index)))))) ;;; ;;; Like DEFUN-DLL, but passes first argument in ECX. Used for interfacing ;;; to C++, functions which are defined with thiscall (any non-static ;;; member-function which does not take a variable number of arguments). ;;; (defmacro defun-thiscall (name param-list &key (return-type :long) library-name entry-name) (unless entry-name (setq entry-name (symbol-name name))) (unless library-name (error "You must specify a DLL name in the declaration of ~A" name)) (setq return-type (ctypeexpand-all return-type)) (let* ((arg-type-list (mapcar #'cadr param-list)) (lisp-symbol (create-foreign-function-name entry-name)) (frame-cells (/ (stack-frame-bytes arg-type-list) 4)) (info (generate-call-params-info param-list frame-cells))) ;side effect--allocates a jump table entry (cl::%create-func-table-entry lisp-symbol) `(progn (install-dynamic-foreign-function ,library-name ,entry-name ',lisp-symbol) ,(foreign-defun-stub name info nil return-type `(progn {{ pop ecx ;; move first argument into ECX register }} (x86::call-foreign-proc ,lisp-symbol)))))) ;;; ;;; Corman Lisp DEFUN-POINTER ;;; Similar to defun-dll, but allow the foreign function pointer to be passed ;;; as the first argument to the defined function. This should be a foreign ;;; pointer. ;;; #| Example: (setf module (cl::load-dll "msvcrt.dll")) (setf proc (cl::get-dll-proc-address "strlen" module)) (ct::defun-pointer strlen-ptr ((str (:char *))) :return-type :long :linkage-type :c) (strlen-ptr proc "corman lisp") |# (defmacro defun-pointer (name param-list &key (return-type :long) (linkage-type :c)) (setq return-type (ctypeexpand-all return-type)) (let* ((arg-type-list (mapcar #'cadr param-list)) (stack-cleanup-forms nil) (func-ptr (gensym)) (frame-cells (+ (/ (stack-frame-bytes arg-type-list) 4) 1)) ;; add 1 for func ptr (info (generate-call-params-info param-list frame-cells func-ptr))) (if (eq linkage-type :c) (setq stack-cleanup-forms `((x86::popargs ,arg-type-list)))) ;; add function pointer on as first arg (this means adding it to the end as it will get reversed) (setf (foreign-call-params-info-lambda-list info) (append (foreign-call-params-info-lambda-list info) (list func-ptr))) `(progn ,(foreign-defun-stub name info stack-cleanup-forms return-type `(x86::call-foreign-pointer))))) ;;; ;;; DEFUN-KERNEL macro is used to call kernel functions via the FFI. ;;; This protects the foreign kernel code from negatively affecting ;;; garbage collection, at the cost of thunking between lisp and foreign code. ;;; The called function is assumed to be defined in the kernel, as a foreign ;;; function. These will typically be in the common-lisp package, internal, with ;;; names beginning with '%'. ;;; (defmacro defun-kernel (name param-list &key (return-type :long) kernel-name ;; a symbol (linkage-type :c)) (setq return-type (ctypeexpand-all return-type)) (let* ((arg-type-list (mapcar #'cadr param-list)) (stack-cleanup-forms nil) (frame-cells (/ (stack-frame-bytes arg-type-list) 4)) (info (generate-call-params-info param-list frame-cells))) (if (eq linkage-type :c) (setq stack-cleanup-forms `((x86::popargs ,arg-type-list)))) `(progn ,(foreign-defun-stub name info stack-cleanup-forms return-type `(x86::call-foreign-proc ,kernel-name))))) (defun uvector-offset (index) (- (* 4 index) x86::uvector-tag)) (defconstant uvector-foreign-ptr-size 1) (defun create-foreign-ptr () (let ((p (cl::alloc-uvector uvector-foreign-ptr-size cl::uvector-foreign-tag))) (setf (uref p cl::foreign-heap-ptr-offset) 0) p)) ;;; Override kernel function (defun cl::%foreignnode () (ct:create-foreign-ptr)) (defasm %create-c-string (string) { push ebp mov ebp, esp push [esi] ; allocate temp variable push ebx push edi mov edx, [ebp + ARGS_OFFSET] ;edx = string push edx mov ecx, 1 callf length add esp, 4 ;eax = length of string mov [ebp - 4], eax ; save length in [ebp - 4] mov ecx, eax add ecx, 8 ;ecx = string-length + 1 push ecx mov ecx, 1 callf allocate-c-heap ;eax = c-string handle add esp, 4 push eax mov edi, [eax + (uvector-offset foreign-heap-ptr-offset)] ;edi = actual c-string mov edx, [ebp + ARGS_OFFSET] ; edx = string mov eax, [edx + (uvector-offset 0)] shr al, 3 cmp al, uvector-simple-char-vector-tag je :t2 mov edx, [edx + (uvector-offset cl::adjustable-array-vector-offset)] :t2 mov ecx, [ebp - 4] ; get string length ;; add ecx, (* 3 8) shr ecx, 3 ;ecx = number of chars to copy ;; unicode mod ;; shr ecx, 5 ;ecx = number of words to copy xor ebx, ebx xor eax, eax jmp :t1 :loop mov ax, [edx + ebx*2 + (uvector-offset 2)] ;; unicode mod ;; mov eax, [edx + ebx*4 + (uvector-offset 2)] mov [edi + ebx], al ;; unicode mod ;; mov [edi + ebx*4], eax inc ebx :t1 dec ecx jge :loop ;; null terminate the c string mov ecx, [ebp - 4] ; get string length shr ecx, 3 xor eax, eax mov [edi + ecx], al pop eax ; eax = c-string handle mov ecx, 1 pop edi pop ebx add esp, 4 pop ebp ret }) (defun create-c-string (string) (if (or (foreignp string)(cl::foreign-heap-p string)) string (if (stringp string) (%create-c-string string) (error "Cannot convert ~A to a C string" string)))) (defasm c-string-to-lisp-string (c-string) { push ebp mov ebp, esp mov eax, [ebp + ARGS_OFFSET] push [eax + (uvector-offset foreign-heap-ptr-offset)] callp cl::%stringNode add esp, 4 mov ecx, 1 pop ebp ret }) (defasm create-c-long (fixnum) { push ebp mov ebp, esp push ebx push edi push 32 mov ecx, 1 callf allocate-c-heap ;eax = c-string handle add esp, 4 push eax mov edi, [eax + (uvector-offset foreign-heap-ptr-offset)] ;edi = pointer to c-long address mov edx, [ebp + ARGS_OFFSET] ;edx = integer mov [edi], edx pop eax ; eax = c-string handle mov ecx, 1 pop edi pop ebx pop ebp ret }) (defasm c-string-length (c-string) { push ebp mov ebp, esp cmp ecx, 1 jz short :t1 callp _wrong-number-of-args-error :t1 mov edx, [ebp + ARGS_OFFSET] ;; edx = argument mov edx, [edx - 1] ;; edx = foreign pointer xor eax, eax and edx, edx jz :done xor ecx, ecx :t2 cmp [edx], cl jz short :done inc eax inc edx jmp short :t2 :done shl eax, 3 inc ecx pop ebp ret }) ;;;; ;;;; Corman Lisp kernel FOREIGNP function. ;;;; (defasm foreignp (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 mov eax, [esi] jne short :next2 mov edx, [edx - uvector-tag] cmp dl, (tag-byte uvector-foreign-tag) jne short :next2 mov eax, [esi + t-offset] :next2 pop ebp ret }) ;;;; ;;;; Corman Lisp kernel FOREIGN-HEAP-P function. ;;;; (defasm foreign-heap-p (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 mov eax, [esi] jne short :next2 mov edx, [edx - uvector-tag] cmp dl, (tag-byte uvector-foreign-heap-tag) jne short :next2 mov eax, [esi + t-offset] :next2 pop ebp ret }) (defun foreign-heap-length (x) (unless (cl::foreign-heap-p x) (cl::signal-type-error x 'cl::foreign-heap)) (uref x cl::foreign-heap-length-offset)) (defun unlink-dll-function (dll-func-rec) (install-dynamic-foreign-function (foreign-function-record-dll-name dll-func-rec) (foreign-function-record-foreign-name dll-func-rec) (foreign-function-record-lisp-sym dll-func-rec))) (defun unlink-dll (dll-rec) (let ((func-recs (dll-record-function-records dll-rec))) (dolist (r func-recs) (unlink-dll-function r)) (unload-dll (dll-record-handle dll-rec)) (setq *dlls-loaded* (remove dll-rec *dlls-loaded*)))) (defun unlink-all-dll-functions () (dolist (rec *dlls-loaded*) (unlink-dll rec)) (cl::clear-foreign-jump-table)) (cl::register-save-image-cleanup-func #'unlink-all-dll-functions) (let ((ctype-table (make-hash-table))) (defun ctype-install-alias (name ctype) (setf (gethash name ctype-table) ctype)) (defun ctype-lookup-alias (name) (gethash name ctype-table))) (defmacro defctype (name ctype) (let ((sym (gensym))) `(progn (unless (valid-c-type-definition ',ctype) (error "Invalid C type specifier: ~S" ',ctype)) (let ((,sym (ctypeexpand-all ',ctype))) (unless ,sym (error "Invalid C type: ~S" ',ctype)) (ctype-install-alias ',name ,sym)) ',name))) (defun ctypeexpand (x) (if (symbolp x) (let ((type (ctype-lookup-alias x))) (if type type x)) x)) (defun ctypeexpand-all (x) (if (symbolp x) (let ((type (ctype-lookup-alias x))) (return-from ctypeexpand-all (if type type x)))) (unless (consp x) (return-from ctypeexpand-all x)) (if (eq (car x) ':struct) (do ((p (cdr x)(cddr p))) ((null p) x) (setf (cadr p) (ctypeexpand-all (cadr p)))) (if (or (eq (cadr x) '*) (fixnump (cadr x)) (and (constantp (cadr x)) (fixnump (symbol-value (cadr x))))) (setf (car x) (ctypeexpand-all (car x))) (error "Invalid C type specifier: ~S" x))) x) (defun determine-coerce-type (specifier) (if (symbolp specifier) (ecase specifier ((:short :long :char) :integer) ((:unsigned-short :unsigned-long :unsigned-char) :unsigned-integer) ((:single-float) :single-float) ((:double-float) :double-float) ((:short-bool :long-bool) :bool) ((:wide-char) :wide-char) (:handle :pointer)) (if (eq (cadr specifier) '*) :pointer :reference))) ;;; ;;; cstruct-slot-info ;;; Returns 3 values: ;;; offset into c-struct ;;; size in bytes of result ;;; how to interpret the result (:integer, ;;; :unsigned-integer, :float, :bool, ;;; :pointer, :reference or :wide-char) ;;; (defun cstruct-slot-info (specifier access) (let ((position 0) slot-type size coerce) (do ((p (cdr specifier)(cddr p))) ((null p)(error "Cannot access C type ~A with access ~A" specifier access)) (when (eq (car p) access) (setq slot-type (cadr p)) (return)) (incf position (determine-c-type-size (cadr p)))) (setq coerce (determine-coerce-type slot-type)) (setq size (determine-c-type-size slot-type)) (values position size coerce))) (defun cstruct-definition-p (descriptor) (and (consp descriptor) (eq (car descriptor) ':struct))) (defun carray-definition-p (descriptor) (and (consp descriptor) (or (fixnump (cadr descriptor)) (and (constantp (cadr descriptor)) (fixnump (symbol-value (cadr descriptor))))))) (defun cpointer-definition-p (descriptor) (and (consp descriptor) (eq (cadr descriptor) '*))) (defun struct-cref-expand (ctype object access value-object value-type) (unless (symbolp access) (error "Cannot access C structure with access ~A" access)) (multiple-value-bind (offset size coerce) (cstruct-slot-info ctype access) `(%cref ,object ,offset ,size ,coerce ,value-object ,value-type))) (defun struct-set-cref-expand (value ctype object access) (unless (symbolp access) (error "Cannot access C structure with access ~A" access)) (multiple-value-bind (offset size coerce) (cstruct-slot-info ctype access) `(%set-cref ,object ,offset ,size ,coerce ,value))) (defun array-cref-expand (ctype object access value-object value-type) (if (eq access '*) (setq access 0)) (let ((size (determine-c-type-size (car ctype)))) `(%cref ,object (* ,access ,size) ,size ,(determine-coerce-type (car ctype)) ,value-object ,value-type))) (defun array-set-cref-expand (value ctype object access) (if (eq access '*) (setq access 0)) (let ((size (determine-c-type-size (car ctype)))) `(%set-cref ,object (* ,access ,size) ,size ,(determine-coerce-type (car ctype)) ,value))) (defmacro cref (ctype object access &optional value-object value-type alt-value-object) (declare (ignore alt-value-object)) (setq ctype (ctypeexpand-all ctype)) (unless (valid-c-type-definition ctype) (error "Invalid C type specifier: ~S" ctype)) (cond ((cstruct-definition-p ctype) (struct-cref-expand ctype object access value-object value-type)) ((carray-definition-p ctype) (array-cref-expand ctype object access value-object value-type)) ((cpointer-definition-p ctype) (array-cref-expand ctype object access value-object value-type)) (t (error "Cannot access C type ~A using CREF" ctype)))) (defmacro (setf cref) (value ctype object access) (setq ctype (ctypeexpand-all ctype)) (unless (valid-c-type-definition ctype) (error "Invalid C type specifier: ~S" ctype)) (cond ((cstruct-definition-p ctype) (struct-set-cref-expand value ctype object access)) ((carray-definition-p ctype) (array-set-cref-expand value ctype object access)) ((cpointer-definition-p ctype) (array-set-cref-expand value ctype object access)) (t (error "Cannot access C type ~A using CREF" ctype)))) (defmacro defcstruct (name params) (let ((args nil)) (dolist (p params) (unless (and (= (length p) 2) (symbolp (car p))) (error "Invalid C structure definition: ~S" params)) (push (car p) args) (push (cadr p) args)) `(defctype ,name ,(cons ':struct (nreverse args))))) (in-package :x86) ;; the arguments should each be fixnums < #x10000, tagged (defasm %create-positive-bignum (low-16 high-16) { push ebp mov ebp, esp push 8 ;; tagged fixnum 1 mov ecx, 1 callp cl::alloc-bignum add esp, 4 mov edx, [ebp + (+ ARGS_OFFSET 4)] shr edx, 3 mov [eax + (uvector-offset cl::bignum-first-cell-offset)], edx mov edx, [ebp + (+ ARGS_OFFSET 0)] shl edx, 13 or [eax + (uvector-offset cl::bignum-first-cell-offset)], edx mov ecx, 1 pop ebp ret }) (defasm %create-negative-bignum (low-16 high-16) { push ebp mov ebp, esp push 8 ;; tagged fixnum 1 mov ecx, 1 callp cl::alloc-bignum add esp, 4 mov edx, [ebp + (+ ARGS_OFFSET 4)] begin-atomic shr edx, 3 mov ecx, [ebp + (+ ARGS_OFFSET 0)] shl ecx, 13 or edx, ecx neg edx mov [eax + (uvector-offset cl::bignum-first-cell-offset)], edx mov edx, [eax + (uvector-offset 1)] end-atomic or edx, 8 ;; set sign bit mov [eax + (uvector-offset 1)], edx mov ecx, 1 pop ebp ret }) (defcodegen ct::%cref (form dest) (let ((obj (second form)) (position (third form)) (bytes (fourth form)) (coerce (fifth form)) (value-object (sixth form)) (value-type (seventh form))) (declare (ignore value-object value-type)) (cl::compile-sub-form obj :dest-stack t) (cl::compile-sub-form position :dest-eax-operand t) ;; make sure the offset is a fixnum (parse-assembler { test al, 7 jz short :t1 push "Invalid index, expected a fixnum: ~A" push eax mov ecx, 2 callf error :t1 mov ecx, eax pop edx mov edx, [edx + (uvector-offset foreign-heap-ptr-offset)] }) (x86::offset-stack 4) ;; at this point ecx is the tagged offset (in bytes) and ;; edx is the untagged pointer into a foreign heap. EDX is not tagged but ;; this should not matter, as it should not be a pointer into the lisp heap. ;; (ecase coerce (:integer (case bytes (1 (parse-assembler { xor eax, eax begin-atomic sar ecx, 3 mov al, [edx + ecx] xor ecx, ecx end-atomic shl eax, 24 sar eax, 21 })) (2 (parse-assembler { xor eax, eax begin-atomic sar ecx, 3 mov ax, [edx + ecx] xor ecx, ecx end-atomic shl eax, 16 sar eax, 13 })) (4 (parse-assembler { begin-atomic sar ecx, 3 mov eax, [edx + ecx] xor ecx, ecx cmp eax, most-positive-fixnum jg :pos-bignum cmp eax, most-negative-fixnum jl :neg-bignum shl eax, 3 end-atomic jmp short :next :pos-bignum mov ecx, eax shr ecx, 16 shl ecx, 3 shl eax, 16 shr eax, 13 ;; eax = low 16 bits, ecx = high 16 bits end-atomic push eax push ecx callp %create-positive-bignum add esp, 8 jmp short :next :neg-bignum mov ecx, eax shr ecx, 16 shl ecx, 3 shl eax, 16 shr eax, 13 ;; eax = low 16 bits, ecx = high 16 bits end-atomic push eax push ecx callp %create-negative-bignum add esp, 8 :next })))) (:unsigned-integer (case bytes (1 (parse-assembler { xor eax, eax begin-atomic sar ecx, 3 mov al, [edx + ecx] xor ecx, ecx end-atomic shl eax, 24 shr eax, 21 })) (2 (parse-assembler { xor eax, eax begin-atomic sar ecx, 3 mov ax, [edx + ecx] xor ecx, ecx end-atomic shl eax, 16 shr eax, 13 })) (4 (parse-assembler { begin-atomic sar ecx, 3 mov eax, [edx + ecx] xor ecx, ecx cmp eax, most-positive-fixnum ja :bignum shl eax, 3 end-atomic jmp short :next :bignum mov ecx, eax shr ecx, 16 shl ecx, 3 shl eax, 16 shr eax, 13 ;; eax = low 16 bits, ecx = high 16 bits end-atomic push eax push ecx callp %create-positive-bignum add esp, 8 :next })))) (:pointer (parse-assembler { push ecx push edx xor ecx, ecx callp ct:create-foreign-ptr pop edx pop ecx begin-atomic sar ecx, 3 mov edx, [edx + ecx] mov [eax + (uvector-offset cl::foreign-heap-ptr-offset)], edx xor ecx, ecx xor edx, edx end-atomic })) (:single-float (parse-assembler { begin-atomic shr ecx, 3 fld.single [edx + ecx] xor ecx, ecx end-atomic push 0 push 0 callp cl::%single-float-node add esp, 8 fstp.single [eax + (uvector-offset cl::single-float-offset)] })) (:double-float (parse-assembler { begin-atomic shr ecx, 3 fld [edx + ecx] xor ecx, ecx end-atomic push 0 push 0 callp cl::%double-float-node add esp, 8 fstp [eax + (uvector-offset cl::double-float-offset)] })) (:wide-char (parse-assembler { xor eax, eax begin-atomic shr ecx, 3 mov ax, [edx + ecx] xor ecx, ecx end-atomic shl eax, 8 inc eax })) (:reference (parse-assembler { push ecx push edx xor ecx, ecx callp ct:create-foreign-ptr pop edx pop ecx begin-atomic shr ecx, 3 lea edx, [edx + ecx] mov [eax + (uvector-offset cl::foreign-heap-ptr-offset)], edx xor ecx, ecx end-atomic }))) (if (eq dest :dest-stack) (progn (parse-assembler { push eax }) (x86::offset-stack -4)) (parse-assembler { mov ecx, 1 }))) t) (defcodegen ct::%set-cref (form dest) (let ((obj (second form)) (position (third form)) (bytes (fourth form)) (coerce (fifth form)) (value (sixth form))) (cl::compile-sub-form value :dest-stack t) (cl::compile-sub-form obj :dest-stack t) (cl::compile-sub-form position :dest-eax-operand t) ;; make sure the offset is a fixnum (parse-assembler { test al, 7 jz short :t1 push "Invalid index, expected a fixnum: ~A" push eax mov ecx, 2 callf error :t1 shr eax, 3 pop edx ;; edx = obj mov edx, [edx + (uvector-offset foreign-heap-ptr-offset)] ;; edx = c object address add edx, eax ;; edx = target address of store operation pop eax ;; eax = value push eax ;; save value }) (x86::offset-stack 4) (ecase coerce (:integer (case bytes (1 (parse-assembler { push edx callp %get-long-safe ;; get low 16 bits in ax pop edx mov [edx], al })) (2 (parse-assembler { push edx callp %get-long-safe ;; get low 16 bits in ax pop edx mov [edx], ax })) (4 (parse-assembler { push edx callp %get-long-safe ;; get low 16 bits in ax, high bits in dx mov ecx, edx pop edx mov [edx], ax mov [edx + 2], cx })))) (:unsigned-integer (case bytes (1 (parse-assembler { push edx callp %get-unsigned-long-safe ;; get low 16 bits in ax pop edx mov [edx], al })) (2 (parse-assembler { push edx callp %get-unsigned-long-safe ;; get low 16 bits in ax pop edx mov [edx], ax })) (4 (parse-assembler { push edx callp %get-unsigned-long-safe ;; get low 16 bits in ax mov ecx, edx pop edx mov [edx], ax mov [edx + 2], cx })))) (:single-float (parse-assembler { push edx mov edx, eax and edx, 7 cmp edx, uvector-tag je short :t1 :err push "Not a :single-float: ~S" push eax mov ecx, 2 callf error :t1 mov edx, [eax - uvector-tag] shr dl, 3 cmp dl, cl::uvector-single-float-tag jne :err :t2 fld.single [eax + (uvector-offset cl::single-float-offset)] pop edx fstp.single [edx] })) (:double-float (parse-assembler { push edx mov edx, eax and edx, 7 cmp edx, uvector-tag je short :t1 :err push "Not a :double-float: ~S" push eax mov ecx, 2 callf error :t1 mov edx, [eax - uvector-tag] shr dl, 3 cmp dl, cl::uvector-double-float-tag jne :err :t2 pop edx fld [eax + (uvector-offset cl::double-float-offset)] fstp [edx] })) (:wide-char (parse-assembler { cmp al, 1 je short :t1 :err push "Not a character: ~S" push eax mov ecx, 2 callf error :t1 shl eax, 8 shr eax, 16 mov [edx], ax })) (:pointer (parse-assembler { mov eax, [eax + (uvector-offset cl::foreign-heap-ptr-offset)] mov [edx], eax }))) (unless (eq dest :dest-stack) (progn (parse-assembler { pop eax mov ecx, 1 }) (x86::offset-stack 4)))) t) (in-package :c-types) (pl:defasm cpointer-value (cpointer) { push ebp mov ebp, esp cmp ecx, 1 jz short :t1 callp _wrong-number-of-args-error :t1 mov edx, [ebp + ARGS_OFFSET] ;; edx = argument ;; check type mov eax, edx and eax, 7 cmp eax, uvector-tag jne short :type-error mov eax, [edx - uvector-tag] cmp al, (tag-byte uvector-foreign-tag) je :next1 cmp al, (tag-byte uvector-foreign-heap-tag) je :next1 :type-error push edx callp ct::foreign-type-error :next1 begin-atomic mov eax, [edx + (uvector-offset cl::foreign-heap-ptr-offset)] ;; untagged pointer in eax ;; probably safe, but we'll be careful anyway cmp eax, most-positive-fixnum ja :bignum shl eax, 3 end-atomic jmp short :next :bignum mov ecx, eax shr ecx, 16 shl ecx, 3 shl eax, 16 shr eax, 13 ;; eax = low 16 bits, ecx = high 16 bits end-atomic push eax push ecx callp %create-positive-bignum add esp, 8 :next mov ecx, 1 pop ebp ret }) (pl:defasm |SETF CPOINTER-VALUE| (value cpointer) { push ebp mov ebp, esp cmp ecx, 2 jz short :t1 callp _wrong-number-of-args-error :t1 mov edx, [ebp + ARGS_OFFSET] ;; edx = cpointer ;; check type mov eax, edx and eax, 7 cmp eax, uvector-tag jne short :type-error mov eax, [edx - uvector-tag] cmp al, (tag-byte uvector-foreign-tag) je :next1 cmp al, (tag-byte uvector-foreign-heap-tag) je :next1 :type-error push edx callp ct::foreign-type-error :next1 mov eax, [ebp + (+ ARGS_OFFSET 4)] ;; eax = number test eax, 7 jnz short :t2 mov ecx, eax shr ecx, 3 mov [edx + (uvector-offset cl::foreign-heap-ptr-offset)], ecx jmp short :t4 :t2 mov ecx, eax and ecx, 7 cmp ecx, uvector-tag jne short :err mov ecx, [eax - uvector-tag] shr cl, 3 cmp cl, uvector-bignum-tag jne short :err mov ecx, [eax + (uvector-offset cl::bignum-first-cell-offset)] mov [edx + (uvector-offset cl::foreign-heap-ptr-offset)], ecx jmp short :t4 :err push "Invalid cpointer value: ~A" push eax mov ecx, 2 callf error :t4 mov ecx, 1 pop ebp ret }) (cl::register-setf-function 'cpointer-value '|SETF CPOINTER-VALUE|) (defun cpointer= (cp1 cp2) (= (cpointer-value cp1)(cpointer-value cp2))) (defun cpointer-null (cp) (declare (special ct:null)) (cpointer= cp ct:null)) ;;; ;;; CormanLisp FOREIGN-PTR-TO-INT function. ;;; (defun foreign-ptr-to-int (p) (cpointer-value p)) ;;; ;;; CormanLisp INT-TO-FOREIGN-PTR function. ;;; (defun int-to-foreign-ptr (i) (if (< i 0) (setf i (+ i #x100000000))) (let ((p (create-foreign-ptr))) (setf (cpointer-value p) i) p)) (defun sizeof (c-type-specifier) (determine-c-type-size c-type-specifier)) (defun offsetof (c-type-specifier struct-field) (values (ct::cstruct-slot-info (ct::ctypeexpand-all c-type-specifier) struct-field))) (defun valid-callback-arg-type (ctype) (setq ctype (ctypeexpand-all ctype)) (if (member ctype simple-c-types) t (and (consp ctype) (consp (cdr ctype)) (valid-callback-arg-type (first ctype)) (or (integerp (second ctype))(eq (second ctype) '*))))) ;;; We only execute the following macro for its side effects (defmacro ensure-func-table-entry (symbol) (if (zerop (uref symbol cl::symbol-jump-table-offset)) (cl::%create-func-table-entry symbol)) nil) ;;; ;;; Redefine Common Lisp MULTIPLE-VALUE-BIND macro to ;;; make the VALUE-FORM be evaluated in the correct lexical context. ;;; From JP Massar. ;;; (defmacro cl::multiple-value-bind (vars value-form &rest forms) (let ((declarations nil)) ;; look for declarations (do* ((f forms (cdr f))) ((null f) (setq forms f)) (if (and (consp (car f)) (eq (caar f) 'declare)) (push (car f) declarations) (progn (setq forms f) (return)))) (let* ((gensyms (mapcar #'(lambda (x) (gensym (symbol-name x))) vars)) (bindings (mapcar #'list vars gensyms))) `(let ,gensyms (multiple-value-setq ,gensyms ,value-form) (let ,bindings ,@(nreverse declarations) ,@forms))))) (defmacro define-callback-func (name arg-list body &key (linkage :c) (create-heap-handler nil)) (declare (ignore create-heap-handler)) (let* ((syms nil) (lisp-func nil) (foreign-func nil) (arg-conversion-forms nil) internal-name (docstring nil) (num-args (length arg-list)) (sym-t1 (gensym))) (dolist (x arg-list) (unless (and (listp x) (= (length x) 2) (valid-callback-arg-type (second x))) (error "Invalid argument specification in DEFUN-CALLBACK form: ~A" x)) (push (first x) syms)) (setq syms (nreverse syms)) (setq internal-name (intern (concatenate 'string "%" (symbol-name name) "-internal"))) (multiple-value-bind (doc decls body bad-decls) (cl::parse-doc-decls-body body) (declare (ignore doc)) (when bad-decls (error "Declarations found in body of callback")) (setq lisp-func `(defun ,internal-name ,syms (let () (cl::%safecall #'(lambda () ,@decls (block ,name ,@body)))))) (setq docstring doc)) (let ((param-offset 0)) (dolist (x arg-list) (let ((arg-type (ctypeexpand-all (second x)))) (cond ((eq arg-type :char) (push `(x86::push-signed-char-lisp-arg ,param-offset) arg-conversion-forms)) ((eq arg-type :unsigned-char) (push `(x86::push-unsigned-char-lisp-arg ,param-offset) arg-conversion-forms)) ((eq arg-type :short) (push `(x86::push-signed-short-lisp-arg ,param-offset) arg-conversion-forms)) ((eq arg-type :unsigned-short) (push `(x86::push-unsigned-short-lisp-arg ,param-offset) arg-conversion-forms)) ((eq arg-type :wide-char) (push `(x86::push-wide-char-lisp-arg ,param-offset) arg-conversion-forms)) ((eq arg-type :long) (push `(x86::push-signed-long-lisp-arg ,param-offset) arg-conversion-forms)) ((eq arg-type :unsigned-long) (push `(x86::push-unsigned-long-lisp-arg ,param-offset) arg-conversion-forms)) ((eq arg-type :short-bool) (push `(x86::push-short-bool-lisp-arg ,param-offset) arg-conversion-forms)) ((eq arg-type :long-bool) (push `(x86::push-long-bool-lisp-arg ,param-offset) arg-conversion-forms)) ; ((eq arg-type :handle) ; (push `(x86::push-long-handle-lisp-arg ,param-offset) arg-conversion-forms)) ((eq arg-type :single-float) (push `(x86::push-single-float-lisp-arg ,param-offset) arg-conversion-forms)) ((eq arg-type :double-float) (push `(x86::push-double-float-lisp-arg ,param-offset) arg-conversion-forms) (incf param-offset 4)) ((eq arg-type :int64) (push `(x86::push-int64-lisp-arg ,param-offset) arg-conversion-forms) (incf param-offset 4)) ((eq arg-type :uint64) (push `(x86::push-uint64-lisp-arg ,param-offset) arg-conversion-forms) (incf param-offset 4)) (t (push `(x86::push-pointer-lisp-arg ,param-offset) arg-conversion-forms)))) (incf param-offset 4)) (setq foreign-func `(defun ,name ,syms ,@(when docstring (list docstring)) (declare (optimize (speed 3)(safety 0))) ; disable arg checking (declare (ignore ,@syms)) ; disable "unused variable" warnings (x86::setup-lisp-registers) (x86::push-lisp-stack-context) (x86::link-heap-handler) ;,@(if create-heap-handler ; `((x86::link-heap-handler))) ,@(nreverse arg-conversion-forms) (x86::mov-ecx-num ,num-args) (x86::call-lisp-proc ,internal-name) (x86::pop-lisp-args ,num-args) (x86::return-lisp-val-as-c) (x86::unlink-heap-handler) ;,@(if create-heap-handler ; `((x86::unlink-heap-handler))) (x86::pop-lisp-stack-context) (x86::copy-foreign-return-val-to-eax) (x86::restore-c-registers) ,@(if (eq linkage :pascal) `((x86::return-from-pascal ,num-args))))) `(let ((,sym-t1 (cl::create-callback-thunk ',name))) (setf (get ',name 'ct::callback-thunk) ,sym-t1) (ensure-func-table-entry ,internal-name) ;; make sure there is a jump entry ,lisp-func ;; define lisp function ,foreign-func)))) ;; define foreign function (defvar *collect-exported-functions* nil) ;; used by COMPILE-FILE and COMPILE-DLL (defvar *callback-registry* (make-hash-table :test #'equal :synchronized t)) ;; maps strings to callback symbols (defmacro defun-callback (name arg-list &rest body) `(define-callback-func ,name ,arg-list ,body :linkage :pascal)) (defmacro defun-c-callback (name arg-list &rest body) `(define-callback-func ,name ,arg-list ,body :linkage :c)) (defmacro defun-direct-callback (name arg-list &rest body) `(define-callback-func ,name ,arg-list ,body :linkage :pascal :create-heap-handler t)) (defmacro defun-direct-c-callback (name arg-list &rest body) `(define-callback-func ,name ,arg-list ,body :linkage :c :create-heap-handler t)) (defun defun-dll-export-body (name arg-list body linkage) (let ((prototype nil) (sym name)) (when (stringp (first body)) (setf prototype (first body)) (setf body (cdr body))) (when (consp name) ;; map export string name to symbol (setf (gethash (cadr name) *callback-registry*) (car name)) (setf sym (car name))) `(eval-when (:execute :load-toplevel :compile-toplevel) ,@(if (consp name) `((setf (gethash ',(cadr name) *callback-registry*) ',(car name))) nil) (if *collect-exported-functions* (vector-push-extend ',(list name prototype) *collect-exported-functions*)) (define-callback-func ,sym ,arg-list ,body :linkage ,linkage :create-heap-handler t)))) (defmacro defun-dll-export-function (name arg-list &rest body) (defun-dll-export-body name arg-list body ':pascal)) (defmacro defun-dll-export-c-function (name arg-list &rest body) (defun-dll-export-body name arg-list body ':c)) ;;; support code generation operators for defun-callback macro (in-package :x86) (defcodegen setup-lisp-registers (form dest) (declare (ignore form dest)) (parse-assembler { push esi push edi push ebx mov eax, 'cl::%load-qv-reg mov eax, [eax + (uvector-offset symbol-function-offset)] ; get function binding mov eax, [eax - cons-tag] call [eax + (uvector-offset function-code-buffer-offset)] }) t) (defcodegen restore-c-registers (form dest) (declare (ignore form dest)) (parse-assembler { pop ebx pop edi pop esi }) t) (defcodegen call-lisp-proc (form dest) (declare (ignore dest)) (let* ((sym (second form)) (env-offset (* (uref sym symbol-jump-table-offset) 4)) (jump-offset (+ env-offset 4))) (if (zerop env-offset) (error "The function ~A does not have a jump table offset and cannot be called" sym)) (parse-assembler { mov edi, [esi + env-offset] add-env-table-ref sym call [esi + jump-offset] add-jump-table-ref sym })) t) (defcodegen pop-lisp-args (form dest) (declare (ignore dest)) (let* ((numargs (second form)) (bytes (* 4 numargs))) (parse-assembler { add esp, bytes })) t) (defcodegen return-lisp-val-as-c (form dest) (declare (ignore form dest)) (parse-assembler { mov ecx, eax and ecx, 7 ;; if fixnum, return that jnz short :t2 cmp eax, 0 jl short :neg-integer mov ecx, -1 callp x86::%get-foreign-unsigned-long jmp :exit :neg-integer mov ecx, -1 callp x86::%get-foreign-long jmp :exit :t2 cmp al, 1 je :char cmp ecx, uvector-tag jne :t3 ;; not handling return of short floats from callback yet mov cl, [eax - uvector-tag] shr cl, 3 cmp cl, uvector-bignum-tag jne short :t7 mov cl, [eax + (uvector-offset 1)] and cl, 8 ;; negative bignum? jnz short :neg-bignum mov ecx, -1 callp x86::%get-foreign-unsigned-long jmp short :exit :neg-bignum mov ecx, -1 callp x86::%get-foreign-long jmp short :exit :t7 cmp cl, uvector-foreign-tag jne short :t4 begin-atomic mov eax, [eax + (uvector-offset foreign-heap-ptr-offset)] mov [esi + (- (* foreign-cells-qv-tos 4) 4)], eax xor eax, eax end-atomic jmp short :exit :t4 cmp cl, uvector-foreign-heap-tag jne short :t5 begin-atomic mov eax, [eax + (uvector-offset foreign-heap-ptr-offset)] mov [esi + (- (* foreign-cells-qv-tos 4) 4)], eax xor eax, eax end-atomic jmp short :exit :t5 cmp cl, uvector-double-float-tag jne short :t6 fld [eax + (uvector-offset cl::double-float-offset)] ;; store 0 in eax, in case caller is not expecting a float they will get that mov eax, 0 mov [esi + (- (* foreign-cells-qv-tos 4) 4)], eax jmp short :exit :t6 cmp cl, uvector-single-float-tag jne short :t3 fld.single [eax + (uvector-offset cl::single-float-offset)] ;; store 0 in eax, in case caller is not expecting a float they will get that mov eax, 0 mov [esi + (- (* foreign-cells-qv-tos 4) 4)], eax jmp short :exit :char shl eax, 8 shr eax, 16 jmp short :exit :t3 xor eax, eax :exit }) t) (defcodegen copy-foreign-return-val-to-eax (form dest) (declare (ignore form dest)) (parse-assembler { mov eax, [esi + (- (* foreign-cells-qv-tos 4) 4)] }) t) (defcodegen push-signed-char-lisp-arg (form dest) (declare (ignore dest)) (let ((offset (+ ARGS_OFFSET (second form)))) (parse-assembler { xor eax, eax mov al, [ebp + offset] shl eax, 24 sar eax, 21 push eax })) t) (defcodegen push-unsigned-char-lisp-arg (form dest) (declare (ignore dest)) (let ((offset (+ ARGS_OFFSET (second form)))) (parse-assembler { xor eax, eax mov al, [ebp + offset] shl eax, 24 shr eax, 21 push eax })) t) (defcodegen push-signed-short-lisp-arg (form dest) (declare (ignore dest)) (let ((offset (+ ARGS_OFFSET (second form)))) (parse-assembler { xor eax, eax mov ax, [ebp + offset] shl eax, 16 sar eax, 13 push eax })) t) (defcodegen push-unsigned-short-lisp-arg (form dest) (declare (ignore dest)) (let ((offset (+ ARGS_OFFSET (second form)))) (parse-assembler { xor eax, eax mov ax, [ebp + offset] shl eax, 16 shr eax, 13 push eax })) t) (defcodegen push-wide-char-lisp-arg (form dest) (declare (ignore dest)) (let ((offset (+ ARGS_OFFSET (second form)))) (parse-assembler { xor eax, eax mov ax, [ebp + offset] shl eax, 8 inc eax push eax })) t) (defcodegen push-signed-long-lisp-arg (form dest) (declare (ignore dest)) (let ((offset (+ ARGS_OFFSET (second form)))) (parse-assembler { ;; top cell gets converted into Lisp integer in eax begin-atomic mov eax, [ebp + offset] cmp eax, cl::most-positive-fixnum jg short :bignum cmp eax, cl::most-negative-fixnum jl short :bignum shl eax, 3 jmp short :done :bignum xor eax, eax end-atomic push (* 8 1) ;; wrapped integer 1 callp cl::alloc-bignum add esp, 4 begin-atomic mov edx, [ebp + offset] cmp edx, 0 jge :next1 neg edx mov [eax + (uvector-offset 2)], edx mov edx, [eax + (uvector-offset 1)] xor edx, 8 mov [eax + (uvector-offset 1)], edx jmp short :done :next1 mov [eax + (uvector-offset 2)], edx :done end-atomic push eax })) t) (defcodegen push-unsigned-long-lisp-arg (form dest) (declare (ignore dest)) (let ((offset (+ ARGS_OFFSET (second form)))) (parse-assembler { ;; carefully copy DWORD to foreign region of QV (top cell) begin-atomic mov eax, [ebp + offset] mov [esi + (- (* foreign-cells-qv-tos 4) 4)], eax xor eax, eax end-atomic ;; top cell gets converted into Lisp integer in eax push (* 8 -1) callp x86::create-foreign-lisp-unsigned-integer add esp, 4 push eax })) t) (defcodegen push-int64-lisp-arg (form dest) (declare (ignore dest)) (let ((offset (+ ARGS_OFFSET (second form)))) (parse-assembler { ;; carefully copy Int64 to foreign region of QV (top cell) begin-atomic mov eax, [ebp + offset] mov [esi + (- (* foreign-cells-qv-tos 4) 8)], eax mov eax, [ebp + (+ offset 4)] mov [esi + (- (* foreign-cells-qv-tos 4) 4)], eax xor eax, eax end-atomic ;; top 2 cells gets converted into Lisp integer in eax push (* 8 -2) callp x86::create-foreign-lisp-int64 add esp, 4 push eax })) t) (defcodegen push-uint64-lisp-arg (form dest) (declare (ignore dest)) (let ((offset (+ ARGS_OFFSET (second form)))) (parse-assembler { ;; carefully copy UInt64 to foreign region of QV (top cell) begin-atomic mov eax, [ebp + offset] mov [esi + (- (* foreign-cells-qv-tos 4) 8)], eax mov eax, [ebp + (+ offset 4)] mov [esi + (- (* foreign-cells-qv-tos 4) 4)], eax xor eax, eax end-atomic ;; top cell gets converted into Lisp integer in eax push (* 8 -2) callp x86::create-foreign-lisp-uint64 add esp, 4 push eax })) t) (defcodegen push-single-float-lisp-arg (form dest) (declare (ignore dest)) (let ((offset (+ ARGS_OFFSET (second form)))) (parse-assembler { mov ecx, 0 callf cl::alloc-single-float fld.single [ebp + offset] fstp.single [eax + (uvector-offset cl::single-float-offset)] push eax })) t) (defcodegen push-double-float-lisp-arg (form dest) (declare (ignore dest)) (let ((offset (+ ARGS_OFFSET (second form)))) (parse-assembler { mov ecx, 0 callf cl::alloc-double-float fld [ebp + offset] fstp [eax + (uvector-offset cl::double-float-offset)] push eax })) t) (defcodegen push-pointer-lisp-arg (form dest) (declare (ignore dest)) (let ((offset (+ ARGS_OFFSET (second form)))) (parse-assembler { xor ecx, ecx callf ct::create-foreign-ptr begin-atomic mov ecx, [ebp + offset] mov [eax + (uvector-offset cl::foreign-heap-ptr-offset)], ecx xor ecx, ecx end-atomic push eax })) t) (defcodegen return-from-pascal (form dest) (declare (ignore dest)) (let ((numbytes (* (second form) 4))) (parse-assembler { mov esp, ebp pop ebp ret numbytes })) t) (ct::ensure-func-table-entry create-foreign-ptr) (defun ct::get-callback-procinst (callback-func-sym) (when (stringp callback-func-sym) (setf callback-func-sym (gethash callback-func-sym ct::*callback-registry*))) (if (null callback-func-sym) (return-from ct::get-callback-procinst nil)) (get callback-func-sym 'ct::callback-thunk)) ;; This function gets accessed via the COM interface from ;; foreign threads. (defun cl::get-callback (name) (ct::get-callback-procinst name)) ;;; ;;; CormanLisp CPOINTERP function. ;;; (defasm ct::cpointerp (p) { push ebp mov ebp, esp cmp ecx, 1 jz short :t1 callp _wrong-number-of-args-error :t1 mov eax, [ebp + ARGS_OFFSET] ;eax = p mov edx, eax and edx, 7 cmp edx, uvector-tag jne short :not-foreign mov dl, [eax - uvector-tag] shr dl, 3 cmp dl, uvector-foreign-tag je short :is-foreign cmp dl, uvector-foreign-heap-tag je short :is-foreign cmp dl, uvector-foreign-stack-tag je short :is-foreign jmp short :not-foreign :is-foreign mov eax, [esi + t-offset] jmp short :exit :not-foreign mov eax, [esi] :exit pop ebp ret }) (defun ct::foreign-stack-p (x) (and (uvectorp x)(eq (cl::uvector-type-bits x) uvector-foreign-stack-tag))) (defasm ct::%memcmp (cp1 cp2 count) { push ebp mov ebp, esp push esi push edi mov esi, [ebp + (+ ARGS_OFFSET 8)] ;; esi = cp1 mov edi, [ebp + (+ ARGS_OFFSET 4)] ;; edi = cp2 mov ecx, [ebp + (+ ARGS_OFFSET 0)] ;; ecx = count shr ecx, 3 ;; ecx = unwrapped count :loop1 cmp ecx, 3 jle short :loop2 mov eax, [esi] cmp eax, [edi] jne :diff add esi, 4 add edi, 4 sub ecx, 4 jmp short :loop1 :loop2 cmp ecx, 0 je short :same mov al, [esi] cmp al, [edi] jne :diff inc esi inc edi dec ecx jmp short :loop2 :diff jl :less :greater mov eax, 8 ;; eax = 1 jmp short :exit :less mov eax, -8 jmp short :exit :same mov eax, 0 :exit mov ecx, 1 pop edi pop esi mov esp, ebp pop ebp ret }) (in-package :ct) (defun ct:memcmp (buf1 buf2 count) (unless (ct:cpointerp buf1) (error "Not a foreign pointer: ~A" buf1)) (unless (ct:cpointerp buf2) (error "Not a foreign pointer: ~A" buf2)) (unless (fixnump count) (error "Third argument to memcmp must be a fixnum, got ~A" count)) (%memcmp (uref buf1 1)(uref buf2 1) count)) (ct:defun-dll memcpy ((dest (:void *))(src (:void *))(count :unsigned-long)) :return-type (:void *) :library-name "msvcrt.dll" :entry-name "memcpy" :linkage-type :c) (defun malloc (size) (cl::allocate-c-heap size)) (defun free (cptr) (cl::deallocate-c-heap cptr)) (defun unicode-to-lisp-string (buf) (let ((x (make-array 0 :element-type 'character :fill-pointer t :adjustable t))) (do* ((index 0 (+ index 1)) (c (ct:cref (:wide-char *) buf index) (ct:cref (:wide-char *) buf index))) ((char= c #\nul) x) (vector-push-extend c x)))) (defun lisp-string-to-unicode (str &optional (buf nil)) (let ((strlength (length str))) (unless buf (setf buf (ct:malloc (* (+ strlength 1) 2)))) (do* ((i 0 (+ i 1))) ((= i strlength) (setf (ct:cref (:wide-char *) buf i) #\nul) buf) (setf (ct:cref (:wide-char *) buf i) (elt str i))))) (defun lisp-string-to-c-string (str &optional (cstr nil)) (let ((strlength (length str))) (unless cstr (setf cstr (ct:malloc (+ strlength 1)))) (dotimes (i strlength) (setf (ct:cref (:unsigned-char *) cstr i) (char-int (elt str i)))) (setf (ct:cref (:unsigned-char *) cstr strlength) 0) cstr)) ;; Copy a lisp array of bytes to a C byte array. ;; If the optional parameter cbuf is not supplied (or is nil) then a new C byte ;; array of the same length is allocated with ct:malloc. The resulting C array is returned. ;; (defun lisp-bytes-to-c-bytes (buf &optional (cbuf nil)) (let ((length (length buf))) (unless cbuf (setf cbuf (ct:malloc length))) (dotimes (i length) (setf (ct:cref (:unsigned-char *) cbuf i) (aref buf i))) cbuf)) ;; Copy a C array of bytes to a Lisp array of bytes. ;; If the optional parameter lisp-buf is supplied, it should be a Lisp array of 'byte ;; of a length greater or equal to the passed length parameter. ;; The lisp array is returned. (defun c-bytes-to-lisp-bytes (cbuf length &optional (lisp-buf nil)) (unless lisp-buf (setf lisp-buf (make-array length :element-type 'byte))) (dotimes (i length) (setf (aref lisp-buf i) (ct:cref (:unsigned-char *) cbuf i))) lisp-buf) (defmacro with-c-struct ((var expr structure-type) &body body) (declare (ignore var)) (let ((struct-def (ct::ctypeexpand-all structure-type))) (unless (and (listp struct-def) (eq (car struct-def) ':struct)) (error "Not a C structure definition: ~S" struct-def)) (let ((fields (let ((j 0) (ret nil)) (dolist (i (rest struct-def)(nreverse ret)) (if (evenp j) (push i ret)) (incf j))))) (unless (every #'symbolp fields) (error "Invalid structure definition, names are not all symbols: ~A" fields)) `(symbol-macrolet ,(mapcar #'(lambda (sym) `(,sym (ct:cref ,structure-type ,expr ,sym))) fields) ,@body)))) (defmacro with-fresh-foreign-block ((sym type) &rest forms) `(let ((,sym (ct:malloc (ct:sizeof ,type)))) (unwind-protect (progn ,@forms)(ct:free ,sym)))) ;;; ;;; Output the contents of a C structure. ;;; The structure and the optional stream are evaluated, but the C structure name is not. ;;; Example: (dump-c-struct s WNDCLASSEX) ;;; (defmacro dump-c-struct (struct type &optional (stream t)) (let ((exptype (ct::ctypeexpand-all type))) (unless (ct::valid-c-type-definition exptype) (error "Invalid C type specifier: ~S" type)) (let ((forms '())) (do* ((x (cdr exptype) (cddr x)) (name (car x) (car x)) (field-type (cadr x) (cadr x))) ((null x)) (push `(format ,stream "~4T~A[~A]:~40T~S~%" ',name ',field-type (ct:cref ,type ,struct ,name)) forms)) `(progn (format ,stream "~A:~%" ',type) ,@forms (format ,stream "~%") (values))))) (defconstant x86::foreign-stack-start-marker (+ (* cl::uvector-foreign-stack-tag 8) x86::uvector-header-tag)) (defconstant x86::foreign-stack-end-marker (+ (* cl::uvector-foreign-stack-end-tag 8) x86::uvector-header-tag)) (defasm alloca (size) { begin-atomic pop edx ; edx = return address pop eax ; eax = size in bytes shr eax, 3 ; untag test esp, 4 ; are we at an 8-byte stack boundary jnz :t1 push 0 ; if so, push a pad word :t1 add eax, 7 and eax, -8 ; should be multiple of 8 mov ecx, eax shr ecx, 3 add ecx, 2 ; 4 word header shl ecx, 8 or ecx, x86::foreign-stack-end-marker push ecx ; push end marker sub esp, eax ; allocate foreign block push 0 ; pad shl eax, 3 ; tag byte count push eax ; number of bytes lea eax, [esp + 8] ; start of foreign block push eax and ecx, #xffffff7 or ecx, x86::foreign-stack-start-marker push ecx mov eax, esp or eax, uvector-tag push 0 ; dummy arg push edx ; push return address mov ecx, 1 end-atomic ret }) ;; redefine kernel function (defasm cl::lisp-object-id (obj) { push ebp mov ebp, esp mov eax, [ebp + ARGS_OFFSET] cmp eax, most-positive-fixnum ja :bignum shl eax, 3 jmp short :next :bignum mov ecx, eax shr ecx, 16 shl ecx, 3 shl eax, 16 shr eax, 13 ;; eax = low 16 bits, ecx = high 16 bits push eax push ecx callp %create-positive-bignum add esp, 8 :next mov ecx, 1 pop ebp ret }) ;;; ;;; Redefine kernel LOAD-DLL function ;;; (ct:defun-kernel cl::loadlibrary ((filename (:unsigned-char *))) :return-type :handle :kernel-name cl::%LoadLibrary :linkage-type :pascal) ;(defun cl::load-dll (filename) ; (ct:foreign-ptr-to-int (cl::loadlibrary (ct:lisp-string-to-c-string filename)))) (make-package :temp-package) (in-package :temp-package) ;; avoid interning these exported symbols (defpackage :win32 (:export ) (:nicknames :win)) (in-package :win) (use-package :ct) (in-package :cl) (setq cl::*compiler-warn-on-undefined-function* t)
26038
;;;; ------------------------------- ;;;; Copyright (c) Corman Technologies Inc. ;;;; See LICENSE.txt for license information. ;;;; ------------------------------- ;;;; ;;;; File: ffi.lisp ;;;; Contents: Foreign function interface. ;;;; History: 2/13/97 RGC Created. ;;;; (defpackage "C-TYPES" (:export "DEFUN-DLL" "DEFUN-COM-METHOD" "DEFUN-THISCALL" "DEFUN-POINTER" "DEFUN-KERNEL" "DEFCSTRUCT" "DEFCTYPE" "CREATE-FOREIGN-PTR" "SIZEOF" "OFFSETOF" "CPOINTER-VALUE" "CPOINTERP" "DEFUN-CALLBACK" "DEFUN-C-CALLBACK" "DEFUN-DIRECT-CALLBACK" "DEFUN-DIRECT-C-CALLBACK" "DEFUN-DLL-EXPORT-FUNCTION" "DEFUN-DLL-EXPORT-C-FUNCTION" "GET-CALLBACK-PROCINST" "CREF" "CREATE-C-STRING" "C-STRING-LENGTH" "CPOINTER=" "CPOINTER-NULL" "MEMCMP" "MEMCPY" "MALLOC" "FREE" "FOREIGN-PTR-TO-INT" "INT-TO-FOREIGN-PTR" "UNICODE-TO-LISP-STRING" "LISP-STRING-TO-UNICODE" "C-STRING-TO-LISP-STRING" "LISP-STRING-TO-C-STRING" "WITH-C-STRUCT" "WITH-FRESH-FOREIGN-BLOCK" "FOREIGN-STACK-P" "ALLOCA" "*COLLECT-EXPORTED-FUNCTIONS*" "DUMP-C-STRUCT" "FOREIGN-HEAP-LENGTH" "LISP-BYTES-TO-C-BYTES" "C-BYTES-TO-LISP-BYTES" ) (:nicknames :ct)) (in-package "C-TYPES") (setq cl::*compiler-warn-on-undefined-function* nil) ;;; examples of valid C type descriptors: ;;; :void ;;; :char ;;; :unsigned-char ;;; :short ;;; :unsigned-short ;;; :wide-char ;;; :long ;;; :unsigned-long ;;; :short-bool ;;; :long-bool ;;; :single-float ;;; :double-float ;;; :handle ;;; (:long 5) ; array of 5 longs ;;; (:long *) ; pointer to long ;;; ((:long *) *) ; pointer to pointer to long ;;; (:struct f1 :short f2 :long) ; struct containing a short and a long (defstruct foreign-function-record dll-name foreign-name lisp-sym foreign-address jump-table-address) (defstruct dll-record name handle (function-records nil)) (defvar *dlls-loaded* nil) #| (defun pl::peek-dword (addr) (+ (pl::peek-byte addr) (ash (pl::peek-byte (+ addr 1)) 8) (ash (pl::peek-byte (+ addr 2)) 16) (ash (pl::peek-byte (+ addr 3)) 24))) |# (defun foreign-jump-table-capacity () (pl::peek-dword (+ (cl::sys-globals-address) 12))) (defun foreign-jump-table-num-entries () (pl::peek-dword (+ (cl::sys-globals-address) 8))) ;; ;; forward references ;; (declaim (ftype (function (t) t) ctype-lookup-alias)) (declaim (ftype (function (t) fixnum) determine-c-struct-size)) (declaim (ftype (function (t) t) valid-c-struct-definition)) (defun foreign-type-error (obj) (error "Not a foreign pointer: ~A" obj)) (defun determine-c-type-size (definition) (if (symbolp definition) (let ((typedef (ctype-lookup-alias definition))) (if typedef (setq definition typedef)))) (cond ((symbolp definition) (ecase definition (:void 0) ((:char :unsigned-char) 1) ((:short :unsigned-short :short-bool :wide-char) 2) ((:long :unsigned-long :single-float :long-bool :handle) 4) ((:double-float :int64 :uint64) 8))) ((not (listp definition)) (error "Invalid C Type descriptor: ~S" definition)) ((eq (car definition) ':struct) (determine-c-struct-size definition)) ((eq (cadr definition) '*) 4) ;; pointer type ((integerp (cadr definition)) (* (determine-c-type-size (car definition)) (cadr definition))) ((and (constantp (cadr definition)) (fixnump (symbol-value (cadr definition)))) (* (determine-c-type-size (car definition)) (symbol-value (cadr definition)))) (t (error "Invalid C Type descriptor: ~S" definition)))) (defconstant simple-c-types '(:void :char :unsigned-char :short :unsigned-short :long :unsigned-long :short-bool :long-bool :single-float :double-float :handle :wide-char :int64 :uint64)) (defun valid-c-type-definition (definition) (cond ((symbolp definition) (let ((typedef (ctype-lookup-alias definition))) (if typedef t (if (member definition simple-c-types) t)))) ((not (listp definition)) nil) ((eq (car definition) ':struct) (valid-c-struct-definition definition)) ((eq (cadr definition) '*) (valid-c-type-definition (car definition))) ((or (fixnump (cadr definition)) (and (constantp (cadr definition)) (fixnump (symbol-value (cadr definition))))) (valid-c-type-definition (car definition))) (t nil))) (defun valid-c-struct-definition (definition) (unless (eq (car definition) ':struct) (return-from valid-c-struct-definition nil)) (do ((p (cdr definition)(cddr p))) ((null p) t) (unless (valid-c-type-definition (cadr p)) (return nil)))) (defun determine-c-struct-size (definition) (do ((size 0) (p (cdr definition)(cddr p))) ((null p) size) (incf size (determine-c-type-size (cadr p))))) (defun cstruct-definition-equal-p (def1 def2) (equal def1 def2)) (defasm set-foreign-func-address (func cptr) { push ebp mov ebp, esp mov eax, [ebp + (+ ARGS_OFFSET 4)] ;eax = func mov edx, [ebp + ARGS_OFFSET] ;edx = cptr mov edx, [edx + (uvector-offset cl::foreign-heap-ptr-offset)] mov [eax + (uvector-offset cl::function-code-buffer-offset)], edx mov ecx, 1 pop ebp ret }) (defun foreign-ptr-to-function (cptr) (let ((func (alloc-uvector cl::function-size cl::uvector-kfunction-tag))) (setf (uref func cl::function-environment-offset) nil) (set-foreign-func-address func cptr) func)) (defun get-dll-record (dll-name) (dolist (rec *dlls-loaded*) (if (string-equal (dll-record-name rec) dll-name) (return-from get-dll-record rec))) (let* ((handle (load-dll dll-name)) (rec (make-dll-record :name dll-name :handle handle))) (push rec *dlls-loaded*) rec)) ;;; ;;; GET-DLL-HANDLE dll-name ;;; Returns handle of the DLL if it is already loaded, ;;; otherwise returns it loads the DLL and returns the handle. ;;; (defun get-dll-handle (dll-name) (let ((rec (get-dll-record dll-name))) (if rec (dll-record-handle rec) nil))) ;;; ;;; GET-DLL-FUNCTION-ADDRESS dll-name dll-function-name ;;; (defun get-dll-function-address (dll-name dll-function-name) (let ((dll-handle (get-dll-handle dll-name))) (if dll-handle (let ((addr (get-dll-proc-address dll-function-name dll-handle))) (if addr (return-from get-dll-function-address addr) (error "Could not find function ~S in library ~S" dll-function-name dll-name))) (error "Could not open library ~S" dll-name)))) ;;; ;;; INSTALL-DLL-FUNCTION dll-name dll-function-name lisp-symbol ;;; ;;; ;;; INSTALL-DLL-FUNCTION dll-name dll-function-name lisp-symbol ;;; (defun install-dll-function (dll-name dll-function-name lisp-symbol) (let* ((func-address (get-dll-function-address dll-name dll-function-name)) (dll-rec (get-dll-record dll-name)) (jump-address (cl::allocate-foreign-jump-table-entry func-address)) (func-rec (make-foreign-function-record :dll-name dll-name :foreign-name dll-function-name :lisp-sym lisp-symbol :foreign-address func-address :jump-table-address jump-address))) (setf (symbol-function lisp-symbol) (foreign-ptr-to-function jump-address)) (push func-rec (dll-record-function-records dll-rec)) lisp-symbol)) ;;; ;;; GENERATE-DYNAMIC-FUNCTION ;;; This generates a function which is used as a stub for a dynamically linked ;;; function. When this executes, it loads the actual function, and calls it ;;; with the arguments which were passed to it. ;;; #| (defun generate-dynamic-function (dll-name dll-function-name lisp-symbol) #'(lambda (&rest args) (install-dll-function dll-name dll-function-name lisp-symbol) (apply lisp-symbol args))) |# (defun generate-dynamic-function (dll_name dll_function_name lisp_symbol) (defasm dynamic-func-instance () { push ebp mov ebp, esp push edi ;; push lisp stack context--enter lisp mode foreign-call-lisp push ecx push ct::dll_name push ct::dll_function_name push ct::lisp_symbol mov ecx, 3 callf ct::install-dll-function add esp, 12 pop ecx ;; pop lisp stack context--back to foreign code lisp-return-to-foreign pop edi mov eax, ct::lisp_symbol mov eax, [eax + (uvector-offset cl::symbol-jump-table-offset)] shr eax, 1 pop ebp jmp near [esi + eax + 4] ret }) #'dynamic-func-instance) #| (defun generate-dynamic-function (dll_name dll_function_name lisp_symbol) (defasm dynamic-func-instance () { push ebp mov ebp, esp push edi ;; pop foreign stack context--return to lisp mode begin-atomic mov edx, [esi + (* stack-marker-index-qv-offset 4)] cmp edx, 0 jg :t1 end-atomic push "Tried to pop foreign stack context but none exist!" mov ecx, 1 callf error :t1 sub edx, 4 mov [esi + (* stack-marker-index-qv-offset 4)], edx end-atomic push ecx push ct::dll_name push ct::dll_function_name push ct::lisp_symbol mov ecx, 3 callf ct::install-dll-function add esp, 12 pop ecx ;; push foreign stack context--back to foreign code begin-atomic mov eax, [esi + (* stack-marker-index-qv-offset 4)] cmp eax, stack-markers-max jl :t2 end-atomic push "Ran out of stack markers!" mov ecx, 1 callf error :t2 push eax ;; just to get esp - 4 mov [esi + eax*2 + (* stack-markers-qv-offset 4)], esp lea edi, [esi + eax*2 + (* (+ stack-markers-qv-offset 1) 4)] pop eax ;; just to get esp - 4 add eax, 4 mov [esi + (* stack-marker-index-qv-offset 4)], eax end-atomic pop edi mov eax, ct::lisp_symbol mov eax, [eax + (uvector-offset cl::symbol-jump-table-offset)] shr eax, 1 pop ebp jmp near [esi + eax + 4] ret }) #'dynamic-func-instance) |# (defun install-dynamic-foreign-function (dll-name dll-function-name lisp-symbol) (setf (symbol-function lisp-symbol) (generate-dynamic-function dll-name dll-function-name lisp-symbol)) lisp-symbol) (defun create-foreign-function-name (dll-function-name) (intern (concatenate 'string "%FOREIGN-" dll-function-name))) (defun stack-frame-bytes (arg-type-list) (let ((bytes 0)) (dolist (i arg-type-list bytes) (incf bytes (case i (:long 4) (:double-float 8) (:int64 8) (:uint64 8) (otherwise 4)))))) (defstruct foreign-call-params-info push-forms local-vars lambda-list frame-cells pointer-p) (defun generate-call-params-info (param-list frame-cells &optional (func-ptr nil)) (let ((push-forms '()) (local-vars '()) (num-cells (- frame-cells)) (lambda-list '()) (pointer-p nil)) ;; special case for defun-pointer--skip past the pointer (when func-ptr ;; start with foreign func ptr (push `(x86::compile-foreign-arg ,func-ptr (:void *) ,num-cells) push-forms) (incf num-cells 1) (setf pointer-p t)) (dolist (i param-list) (let ((var (first i)) (ctype (second i))) (setq ctype (ctypeexpand-all ctype)) (if (stringp var) (setf var (if (equalp var "") (gensym) (intern (string-upcase var))))) (push var lambda-list) (cond ((equal ctype '(:char *)) (let ((t3 (gensym))) (push `(,t3 (ct::create-c-string ,var)) local-vars) (push `(x86::compile-foreign-arg ,t3 ,ctype ,num-cells) push-forms))) (t (push `(x86::compile-foreign-arg ,var ,ctype ,num-cells) push-forms))) (if (member ctype '(:double-float :int64 :uint64)) (incf num-cells 2) (incf num-cells 1)))) (make-foreign-call-params-info :push-forms push-forms :local-vars local-vars :lambda-list lambda-list :frame-cells frame-cells :pointer-p pointer-p))) (defun foreign-defun-stub (name info stack-cleanup-forms return-type call-form &optional call-setup-form) (let ((num-cells (foreign-call-params-info-frame-cells info))) `(defun ,name ,(nreverse (foreign-call-params-info-lambda-list info)) (let (,@(foreign-call-params-info-local-vars info)) (x86::save-lisp-registers) ,@(foreign-call-params-info-push-forms info) ,@call-setup-form (x86::push-foreign-stack-context) (x86::push-foreign-args-length ,(if (foreign-call-params-info-pointer-p info) (- num-cells 1) num-cells)) ;; if called by DEFUN-POINTER, the args length is one fewer because pointer is ;; popped as part of function call (x86::copy-foreign-args ,(foreign-call-params-info-frame-cells info)) ,call-form (x86::pop-foreign-args-length) (x86::copy-return-value ,return-type) ,@stack-cleanup-forms (x86::pop-foreign-stack-context) (x86::restore-lisp-registers) (x86::wrap-foreign-return-value ,return-type))))) (defmacro defun-dll (name param-list &key (return-type :long) library-name entry-name (linkage-type :c)) (unless entry-name (setq entry-name (symbol-name name))) (unless library-name (error "You must specify a DLL name in the declaration of ~A" name)) (setq return-type (ctypeexpand-all return-type)) (let* ((arg-type-list (mapcar #'cadr param-list)) (stack-cleanup-forms nil) (lisp-symbol (create-foreign-function-name entry-name)) (frame-cells (/ (stack-frame-bytes arg-type-list) 4)) (info (generate-call-params-info param-list frame-cells))) ;side effect--allocates a jump table entry (cl::%create-func-table-entry lisp-symbol) (if (eq linkage-type :c) (setq stack-cleanup-forms `((x86::popargs ,arg-type-list)))) `(progn (install-dynamic-foreign-function ,library-name ,entry-name ',lisp-symbol) ,(foreign-defun-stub name info stack-cleanup-forms return-type `(x86::call-foreign-proc ,lisp-symbol))))) (defmacro defun-com-method (name param-list vtable-index &key (return-type :unsigned-long)) (setq return-type (ctypeexpand-all return-type)) (let* ((arg-type-list (mapcar #'cadr param-list)) (frame-cells (/ (stack-frame-bytes arg-type-list) 4)) (info (generate-call-params-info param-list frame-cells))) `(progn ,(foreign-defun-stub name info nil return-type `(x86::call-com-method ,vtable-index) `((x86::compile-com-method-address ,vtable-index)))))) ;;; ;;; Like DEFUN-DLL, but passes first argument in ECX. Used for interfacing ;;; to C++, functions which are defined with thiscall (any non-static ;;; member-function which does not take a variable number of arguments). ;;; (defmacro defun-thiscall (name param-list &key (return-type :long) library-name entry-name) (unless entry-name (setq entry-name (symbol-name name))) (unless library-name (error "You must specify a DLL name in the declaration of ~A" name)) (setq return-type (ctypeexpand-all return-type)) (let* ((arg-type-list (mapcar #'cadr param-list)) (lisp-symbol (create-foreign-function-name entry-name)) (frame-cells (/ (stack-frame-bytes arg-type-list) 4)) (info (generate-call-params-info param-list frame-cells))) ;side effect--allocates a jump table entry (cl::%create-func-table-entry lisp-symbol) `(progn (install-dynamic-foreign-function ,library-name ,entry-name ',lisp-symbol) ,(foreign-defun-stub name info nil return-type `(progn {{ pop ecx ;; move first argument into ECX register }} (x86::call-foreign-proc ,lisp-symbol)))))) ;;; ;;; Corman Lisp DEFUN-POINTER ;;; Similar to defun-dll, but allow the foreign function pointer to be passed ;;; as the first argument to the defined function. This should be a foreign ;;; pointer. ;;; #| Example: (setf module (cl::load-dll "msvcrt.dll")) (setf proc (cl::get-dll-proc-address "strlen" module)) (ct::defun-pointer strlen-ptr ((str (:char *))) :return-type :long :linkage-type :c) (strlen-ptr proc "corman lisp") |# (defmacro defun-pointer (name param-list &key (return-type :long) (linkage-type :c)) (setq return-type (ctypeexpand-all return-type)) (let* ((arg-type-list (mapcar #'cadr param-list)) (stack-cleanup-forms nil) (func-ptr (gensym)) (frame-cells (+ (/ (stack-frame-bytes arg-type-list) 4) 1)) ;; add 1 for func ptr (info (generate-call-params-info param-list frame-cells func-ptr))) (if (eq linkage-type :c) (setq stack-cleanup-forms `((x86::popargs ,arg-type-list)))) ;; add function pointer on as first arg (this means adding it to the end as it will get reversed) (setf (foreign-call-params-info-lambda-list info) (append (foreign-call-params-info-lambda-list info) (list func-ptr))) `(progn ,(foreign-defun-stub name info stack-cleanup-forms return-type `(x86::call-foreign-pointer))))) ;;; ;;; DEFUN-KERNEL macro is used to call kernel functions via the FFI. ;;; This protects the foreign kernel code from negatively affecting ;;; garbage collection, at the cost of thunking between lisp and foreign code. ;;; The called function is assumed to be defined in the kernel, as a foreign ;;; function. These will typically be in the common-lisp package, internal, with ;;; names beginning with '%'. ;;; (defmacro defun-kernel (name param-list &key (return-type :long) kernel-name ;; a symbol (linkage-type :c)) (setq return-type (ctypeexpand-all return-type)) (let* ((arg-type-list (mapcar #'cadr param-list)) (stack-cleanup-forms nil) (frame-cells (/ (stack-frame-bytes arg-type-list) 4)) (info (generate-call-params-info param-list frame-cells))) (if (eq linkage-type :c) (setq stack-cleanup-forms `((x86::popargs ,arg-type-list)))) `(progn ,(foreign-defun-stub name info stack-cleanup-forms return-type `(x86::call-foreign-proc ,kernel-name))))) (defun uvector-offset (index) (- (* 4 index) x86::uvector-tag)) (defconstant uvector-foreign-ptr-size 1) (defun create-foreign-ptr () (let ((p (cl::alloc-uvector uvector-foreign-ptr-size cl::uvector-foreign-tag))) (setf (uref p cl::foreign-heap-ptr-offset) 0) p)) ;;; Override kernel function (defun cl::%foreignnode () (ct:create-foreign-ptr)) (defasm %create-c-string (string) { push ebp mov ebp, esp push [esi] ; allocate temp variable push ebx push edi mov edx, [ebp + ARGS_OFFSET] ;edx = string push edx mov ecx, 1 callf length add esp, 4 ;eax = length of string mov [ebp - 4], eax ; save length in [ebp - 4] mov ecx, eax add ecx, 8 ;ecx = string-length + 1 push ecx mov ecx, 1 callf allocate-c-heap ;eax = c-string handle add esp, 4 push eax mov edi, [eax + (uvector-offset foreign-heap-ptr-offset)] ;edi = actual c-string mov edx, [ebp + ARGS_OFFSET] ; edx = string mov eax, [edx + (uvector-offset 0)] shr al, 3 cmp al, uvector-simple-char-vector-tag je :t2 mov edx, [edx + (uvector-offset cl::adjustable-array-vector-offset)] :t2 mov ecx, [ebp - 4] ; get string length ;; add ecx, (* 3 8) shr ecx, 3 ;ecx = number of chars to copy ;; unicode mod ;; shr ecx, 5 ;ecx = number of words to copy xor ebx, ebx xor eax, eax jmp :t1 :loop mov ax, [edx + ebx*2 + (uvector-offset 2)] ;; unicode mod ;; mov eax, [edx + ebx*4 + (uvector-offset 2)] mov [edi + ebx], al ;; unicode mod ;; mov [edi + ebx*4], eax inc ebx :t1 dec ecx jge :loop ;; null terminate the c string mov ecx, [ebp - 4] ; get string length shr ecx, 3 xor eax, eax mov [edi + ecx], al pop eax ; eax = c-string handle mov ecx, 1 pop edi pop ebx add esp, 4 pop ebp ret }) (defun create-c-string (string) (if (or (foreignp string)(cl::foreign-heap-p string)) string (if (stringp string) (%create-c-string string) (error "Cannot convert ~A to a C string" string)))) (defasm c-string-to-lisp-string (c-string) { push ebp mov ebp, esp mov eax, [ebp + ARGS_OFFSET] push [eax + (uvector-offset foreign-heap-ptr-offset)] callp cl::%stringNode add esp, 4 mov ecx, 1 pop ebp ret }) (defasm create-c-long (fixnum) { push ebp mov ebp, esp push ebx push edi push 32 mov ecx, 1 callf allocate-c-heap ;eax = c-string handle add esp, 4 push eax mov edi, [eax + (uvector-offset foreign-heap-ptr-offset)] ;edi = pointer to c-long address mov edx, [ebp + ARGS_OFFSET] ;edx = integer mov [edi], edx pop eax ; eax = c-string handle mov ecx, 1 pop edi pop ebx pop ebp ret }) (defasm c-string-length (c-string) { push ebp mov ebp, esp cmp ecx, 1 jz short :t1 callp _wrong-number-of-args-error :t1 mov edx, [ebp + ARGS_OFFSET] ;; edx = argument mov edx, [edx - 1] ;; edx = foreign pointer xor eax, eax and edx, edx jz :done xor ecx, ecx :t2 cmp [edx], cl jz short :done inc eax inc edx jmp short :t2 :done shl eax, 3 inc ecx pop ebp ret }) ;;;; ;;;; Corman Lisp kernel FOREIGNP function. ;;;; (defasm foreignp (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 mov eax, [esi] jne short :next2 mov edx, [edx - uvector-tag] cmp dl, (tag-byte uvector-foreign-tag) jne short :next2 mov eax, [esi + t-offset] :next2 pop ebp ret }) ;;;; ;;;; Corman Lisp kernel FOREIGN-HEAP-P function. ;;;; (defasm foreign-heap-p (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 mov eax, [esi] jne short :next2 mov edx, [edx - uvector-tag] cmp dl, (tag-byte uvector-foreign-heap-tag) jne short :next2 mov eax, [esi + t-offset] :next2 pop ebp ret }) (defun foreign-heap-length (x) (unless (cl::foreign-heap-p x) (cl::signal-type-error x 'cl::foreign-heap)) (uref x cl::foreign-heap-length-offset)) (defun unlink-dll-function (dll-func-rec) (install-dynamic-foreign-function (foreign-function-record-dll-name dll-func-rec) (foreign-function-record-foreign-name dll-func-rec) (foreign-function-record-lisp-sym dll-func-rec))) (defun unlink-dll (dll-rec) (let ((func-recs (dll-record-function-records dll-rec))) (dolist (r func-recs) (unlink-dll-function r)) (unload-dll (dll-record-handle dll-rec)) (setq *dlls-loaded* (remove dll-rec *dlls-loaded*)))) (defun unlink-all-dll-functions () (dolist (rec *dlls-loaded*) (unlink-dll rec)) (cl::clear-foreign-jump-table)) (cl::register-save-image-cleanup-func #'unlink-all-dll-functions) (let ((ctype-table (make-hash-table))) (defun ctype-install-alias (name ctype) (setf (gethash name ctype-table) ctype)) (defun ctype-lookup-alias (name) (gethash name ctype-table))) (defmacro defctype (name ctype) (let ((sym (gensym))) `(progn (unless (valid-c-type-definition ',ctype) (error "Invalid C type specifier: ~S" ',ctype)) (let ((,sym (ctypeexpand-all ',ctype))) (unless ,sym (error "Invalid C type: ~S" ',ctype)) (ctype-install-alias ',name ,sym)) ',name))) (defun ctypeexpand (x) (if (symbolp x) (let ((type (ctype-lookup-alias x))) (if type type x)) x)) (defun ctypeexpand-all (x) (if (symbolp x) (let ((type (ctype-lookup-alias x))) (return-from ctypeexpand-all (if type type x)))) (unless (consp x) (return-from ctypeexpand-all x)) (if (eq (car x) ':struct) (do ((p (cdr x)(cddr p))) ((null p) x) (setf (cadr p) (ctypeexpand-all (cadr p)))) (if (or (eq (cadr x) '*) (fixnump (cadr x)) (and (constantp (cadr x)) (fixnump (symbol-value (cadr x))))) (setf (car x) (ctypeexpand-all (car x))) (error "Invalid C type specifier: ~S" x))) x) (defun determine-coerce-type (specifier) (if (symbolp specifier) (ecase specifier ((:short :long :char) :integer) ((:unsigned-short :unsigned-long :unsigned-char) :unsigned-integer) ((:single-float) :single-float) ((:double-float) :double-float) ((:short-bool :long-bool) :bool) ((:wide-char) :wide-char) (:handle :pointer)) (if (eq (cadr specifier) '*) :pointer :reference))) ;;; ;;; cstruct-slot-info ;;; Returns 3 values: ;;; offset into c-struct ;;; size in bytes of result ;;; how to interpret the result (:integer, ;;; :unsigned-integer, :float, :bool, ;;; :pointer, :reference or :wide-char) ;;; (defun cstruct-slot-info (specifier access) (let ((position 0) slot-type size coerce) (do ((p (cdr specifier)(cddr p))) ((null p)(error "Cannot access C type ~A with access ~A" specifier access)) (when (eq (car p) access) (setq slot-type (cadr p)) (return)) (incf position (determine-c-type-size (cadr p)))) (setq coerce (determine-coerce-type slot-type)) (setq size (determine-c-type-size slot-type)) (values position size coerce))) (defun cstruct-definition-p (descriptor) (and (consp descriptor) (eq (car descriptor) ':struct))) (defun carray-definition-p (descriptor) (and (consp descriptor) (or (fixnump (cadr descriptor)) (and (constantp (cadr descriptor)) (fixnump (symbol-value (cadr descriptor))))))) (defun cpointer-definition-p (descriptor) (and (consp descriptor) (eq (cadr descriptor) '*))) (defun struct-cref-expand (ctype object access value-object value-type) (unless (symbolp access) (error "Cannot access C structure with access ~A" access)) (multiple-value-bind (offset size coerce) (cstruct-slot-info ctype access) `(%cref ,object ,offset ,size ,coerce ,value-object ,value-type))) (defun struct-set-cref-expand (value ctype object access) (unless (symbolp access) (error "Cannot access C structure with access ~A" access)) (multiple-value-bind (offset size coerce) (cstruct-slot-info ctype access) `(%set-cref ,object ,offset ,size ,coerce ,value))) (defun array-cref-expand (ctype object access value-object value-type) (if (eq access '*) (setq access 0)) (let ((size (determine-c-type-size (car ctype)))) `(%cref ,object (* ,access ,size) ,size ,(determine-coerce-type (car ctype)) ,value-object ,value-type))) (defun array-set-cref-expand (value ctype object access) (if (eq access '*) (setq access 0)) (let ((size (determine-c-type-size (car ctype)))) `(%set-cref ,object (* ,access ,size) ,size ,(determine-coerce-type (car ctype)) ,value))) (defmacro cref (ctype object access &optional value-object value-type alt-value-object) (declare (ignore alt-value-object)) (setq ctype (ctypeexpand-all ctype)) (unless (valid-c-type-definition ctype) (error "Invalid C type specifier: ~S" ctype)) (cond ((cstruct-definition-p ctype) (struct-cref-expand ctype object access value-object value-type)) ((carray-definition-p ctype) (array-cref-expand ctype object access value-object value-type)) ((cpointer-definition-p ctype) (array-cref-expand ctype object access value-object value-type)) (t (error "Cannot access C type ~A using CREF" ctype)))) (defmacro (setf cref) (value ctype object access) (setq ctype (ctypeexpand-all ctype)) (unless (valid-c-type-definition ctype) (error "Invalid C type specifier: ~S" ctype)) (cond ((cstruct-definition-p ctype) (struct-set-cref-expand value ctype object access)) ((carray-definition-p ctype) (array-set-cref-expand value ctype object access)) ((cpointer-definition-p ctype) (array-set-cref-expand value ctype object access)) (t (error "Cannot access C type ~A using CREF" ctype)))) (defmacro defcstruct (name params) (let ((args nil)) (dolist (p params) (unless (and (= (length p) 2) (symbolp (car p))) (error "Invalid C structure definition: ~S" params)) (push (car p) args) (push (cadr p) args)) `(defctype ,name ,(cons ':struct (nreverse args))))) (in-package :x86) ;; the arguments should each be fixnums < #x10000, tagged (defasm %create-positive-bignum (low-16 high-16) { push ebp mov ebp, esp push 8 ;; tagged fixnum 1 mov ecx, 1 callp cl::alloc-bignum add esp, 4 mov edx, [ebp + (+ ARGS_OFFSET 4)] shr edx, 3 mov [eax + (uvector-offset cl::bignum-first-cell-offset)], edx mov edx, [ebp + (+ ARGS_OFFSET 0)] shl edx, 13 or [eax + (uvector-offset cl::bignum-first-cell-offset)], edx mov ecx, 1 pop ebp ret }) (defasm %create-negative-bignum (low-16 high-16) { push ebp mov ebp, esp push 8 ;; tagged fixnum 1 mov ecx, 1 callp cl::alloc-bignum add esp, 4 mov edx, [ebp + (+ ARGS_OFFSET 4)] begin-atomic shr edx, 3 mov ecx, [ebp + (+ ARGS_OFFSET 0)] shl ecx, 13 or edx, ecx neg edx mov [eax + (uvector-offset cl::bignum-first-cell-offset)], edx mov edx, [eax + (uvector-offset 1)] end-atomic or edx, 8 ;; set sign bit mov [eax + (uvector-offset 1)], edx mov ecx, 1 pop ebp ret }) (defcodegen ct::%cref (form dest) (let ((obj (second form)) (position (third form)) (bytes (fourth form)) (coerce (fifth form)) (value-object (sixth form)) (value-type (seventh form))) (declare (ignore value-object value-type)) (cl::compile-sub-form obj :dest-stack t) (cl::compile-sub-form position :dest-eax-operand t) ;; make sure the offset is a fixnum (parse-assembler { test al, 7 jz short :t1 push "Invalid index, expected a fixnum: ~A" push eax mov ecx, 2 callf error :t1 mov ecx, eax pop edx mov edx, [edx + (uvector-offset foreign-heap-ptr-offset)] }) (x86::offset-stack 4) ;; at this point ecx is the tagged offset (in bytes) and ;; edx is the untagged pointer into a foreign heap. EDX is not tagged but ;; this should not matter, as it should not be a pointer into the lisp heap. ;; (ecase coerce (:integer (case bytes (1 (parse-assembler { xor eax, eax begin-atomic sar ecx, 3 mov al, [edx + ecx] xor ecx, ecx end-atomic shl eax, 24 sar eax, 21 })) (2 (parse-assembler { xor eax, eax begin-atomic sar ecx, 3 mov ax, [edx + ecx] xor ecx, ecx end-atomic shl eax, 16 sar eax, 13 })) (4 (parse-assembler { begin-atomic sar ecx, 3 mov eax, [edx + ecx] xor ecx, ecx cmp eax, most-positive-fixnum jg :pos-bignum cmp eax, most-negative-fixnum jl :neg-bignum shl eax, 3 end-atomic jmp short :next :pos-bignum mov ecx, eax shr ecx, 16 shl ecx, 3 shl eax, 16 shr eax, 13 ;; eax = low 16 bits, ecx = high 16 bits end-atomic push eax push ecx callp %create-positive-bignum add esp, 8 jmp short :next :neg-bignum mov ecx, eax shr ecx, 16 shl ecx, 3 shl eax, 16 shr eax, 13 ;; eax = low 16 bits, ecx = high 16 bits end-atomic push eax push ecx callp %create-negative-bignum add esp, 8 :next })))) (:unsigned-integer (case bytes (1 (parse-assembler { xor eax, eax begin-atomic sar ecx, 3 mov al, [edx + ecx] xor ecx, ecx end-atomic shl eax, 24 shr eax, 21 })) (2 (parse-assembler { xor eax, eax begin-atomic sar ecx, 3 mov ax, [edx + ecx] xor ecx, ecx end-atomic shl eax, 16 shr eax, 13 })) (4 (parse-assembler { begin-atomic sar ecx, 3 mov eax, [edx + ecx] xor ecx, ecx cmp eax, most-positive-fixnum ja :bignum shl eax, 3 end-atomic jmp short :next :bignum mov ecx, eax shr ecx, 16 shl ecx, 3 shl eax, 16 shr eax, 13 ;; eax = low 16 bits, ecx = high 16 bits end-atomic push eax push ecx callp %create-positive-bignum add esp, 8 :next })))) (:pointer (parse-assembler { push ecx push edx xor ecx, ecx callp ct:create-foreign-ptr pop edx pop ecx begin-atomic sar ecx, 3 mov edx, [edx + ecx] mov [eax + (uvector-offset cl::foreign-heap-ptr-offset)], edx xor ecx, ecx xor edx, edx end-atomic })) (:single-float (parse-assembler { begin-atomic shr ecx, 3 fld.single [edx + ecx] xor ecx, ecx end-atomic push 0 push 0 callp cl::%single-float-node add esp, 8 fstp.single [eax + (uvector-offset cl::single-float-offset)] })) (:double-float (parse-assembler { begin-atomic shr ecx, 3 fld [edx + ecx] xor ecx, ecx end-atomic push 0 push 0 callp cl::%double-float-node add esp, 8 fstp [eax + (uvector-offset cl::double-float-offset)] })) (:wide-char (parse-assembler { xor eax, eax begin-atomic shr ecx, 3 mov ax, [edx + ecx] xor ecx, ecx end-atomic shl eax, 8 inc eax })) (:reference (parse-assembler { push ecx push edx xor ecx, ecx callp ct:create-foreign-ptr pop edx pop ecx begin-atomic shr ecx, 3 lea edx, [edx + ecx] mov [eax + (uvector-offset cl::foreign-heap-ptr-offset)], edx xor ecx, ecx end-atomic }))) (if (eq dest :dest-stack) (progn (parse-assembler { push eax }) (x86::offset-stack -4)) (parse-assembler { mov ecx, 1 }))) t) (defcodegen ct::%set-cref (form dest) (let ((obj (second form)) (position (third form)) (bytes (fourth form)) (coerce (fifth form)) (value (sixth form))) (cl::compile-sub-form value :dest-stack t) (cl::compile-sub-form obj :dest-stack t) (cl::compile-sub-form position :dest-eax-operand t) ;; make sure the offset is a fixnum (parse-assembler { test al, 7 jz short :t1 push "Invalid index, expected a fixnum: ~A" push eax mov ecx, 2 callf error :t1 shr eax, 3 pop edx ;; edx = obj mov edx, [edx + (uvector-offset foreign-heap-ptr-offset)] ;; edx = c object address add edx, eax ;; edx = target address of store operation pop eax ;; eax = value push eax ;; save value }) (x86::offset-stack 4) (ecase coerce (:integer (case bytes (1 (parse-assembler { push edx callp %get-long-safe ;; get low 16 bits in ax pop edx mov [edx], al })) (2 (parse-assembler { push edx callp %get-long-safe ;; get low 16 bits in ax pop edx mov [edx], ax })) (4 (parse-assembler { push edx callp %get-long-safe ;; get low 16 bits in ax, high bits in dx mov ecx, edx pop edx mov [edx], ax mov [edx + 2], cx })))) (:unsigned-integer (case bytes (1 (parse-assembler { push edx callp %get-unsigned-long-safe ;; get low 16 bits in ax pop edx mov [edx], al })) (2 (parse-assembler { push edx callp %get-unsigned-long-safe ;; get low 16 bits in ax pop edx mov [edx], ax })) (4 (parse-assembler { push edx callp %get-unsigned-long-safe ;; get low 16 bits in ax mov ecx, edx pop edx mov [edx], ax mov [edx + 2], cx })))) (:single-float (parse-assembler { push edx mov edx, eax and edx, 7 cmp edx, uvector-tag je short :t1 :err push "Not a :single-float: ~S" push eax mov ecx, 2 callf error :t1 mov edx, [eax - uvector-tag] shr dl, 3 cmp dl, cl::uvector-single-float-tag jne :err :t2 fld.single [eax + (uvector-offset cl::single-float-offset)] pop edx fstp.single [edx] })) (:double-float (parse-assembler { push edx mov edx, eax and edx, 7 cmp edx, uvector-tag je short :t1 :err push "Not a :double-float: ~S" push eax mov ecx, 2 callf error :t1 mov edx, [eax - uvector-tag] shr dl, 3 cmp dl, cl::uvector-double-float-tag jne :err :t2 pop edx fld [eax + (uvector-offset cl::double-float-offset)] fstp [edx] })) (:wide-char (parse-assembler { cmp al, 1 je short :t1 :err push "Not a character: ~S" push eax mov ecx, 2 callf error :t1 shl eax, 8 shr eax, 16 mov [edx], ax })) (:pointer (parse-assembler { mov eax, [eax + (uvector-offset cl::foreign-heap-ptr-offset)] mov [edx], eax }))) (unless (eq dest :dest-stack) (progn (parse-assembler { pop eax mov ecx, 1 }) (x86::offset-stack 4)))) t) (in-package :c-types) (pl:defasm cpointer-value (cpointer) { push ebp mov ebp, esp cmp ecx, 1 jz short :t1 callp _wrong-number-of-args-error :t1 mov edx, [ebp + ARGS_OFFSET] ;; edx = argument ;; check type mov eax, edx and eax, 7 cmp eax, uvector-tag jne short :type-error mov eax, [edx - uvector-tag] cmp al, (tag-byte uvector-foreign-tag) je :next1 cmp al, (tag-byte uvector-foreign-heap-tag) je :next1 :type-error push edx callp ct::foreign-type-error :next1 begin-atomic mov eax, [edx + (uvector-offset cl::foreign-heap-ptr-offset)] ;; untagged pointer in eax ;; probably safe, but we'll be careful anyway cmp eax, most-positive-fixnum ja :bignum shl eax, 3 end-atomic jmp short :next :bignum mov ecx, eax shr ecx, 16 shl ecx, 3 shl eax, 16 shr eax, 13 ;; eax = low 16 bits, ecx = high 16 bits end-atomic push eax push ecx callp %create-positive-bignum add esp, 8 :next mov ecx, 1 pop ebp ret }) (pl:defasm |SETF CPOINTER-VALUE| (value cpointer) { push ebp mov ebp, esp cmp ecx, 2 jz short :t1 callp _wrong-number-of-args-error :t1 mov edx, [ebp + ARGS_OFFSET] ;; edx = cpointer ;; check type mov eax, edx and eax, 7 cmp eax, uvector-tag jne short :type-error mov eax, [edx - uvector-tag] cmp al, (tag-byte uvector-foreign-tag) je :next1 cmp al, (tag-byte uvector-foreign-heap-tag) je :next1 :type-error push edx callp ct::foreign-type-error :next1 mov eax, [ebp + (+ ARGS_OFFSET 4)] ;; eax = number test eax, 7 jnz short :t2 mov ecx, eax shr ecx, 3 mov [edx + (uvector-offset cl::foreign-heap-ptr-offset)], ecx jmp short :t4 :t2 mov ecx, eax and ecx, 7 cmp ecx, uvector-tag jne short :err mov ecx, [eax - uvector-tag] shr cl, 3 cmp cl, uvector-bignum-tag jne short :err mov ecx, [eax + (uvector-offset cl::bignum-first-cell-offset)] mov [edx + (uvector-offset cl::foreign-heap-ptr-offset)], ecx jmp short :t4 :err push "Invalid cpointer value: ~A" push eax mov ecx, 2 callf error :t4 mov ecx, 1 pop ebp ret }) (cl::register-setf-function 'cpointer-value '|SETF CPOINTER-VALUE|) (defun cpointer= (cp1 cp2) (= (cpointer-value cp1)(cpointer-value cp2))) (defun cpointer-null (cp) (declare (special ct:null)) (cpointer= cp ct:null)) ;;; ;;; CormanLisp FOREIGN-PTR-TO-INT function. ;;; (defun foreign-ptr-to-int (p) (cpointer-value p)) ;;; ;;; CormanLisp INT-TO-FOREIGN-PTR function. ;;; (defun int-to-foreign-ptr (i) (if (< i 0) (setf i (+ i #x100000000))) (let ((p (create-foreign-ptr))) (setf (cpointer-value p) i) p)) (defun sizeof (c-type-specifier) (determine-c-type-size c-type-specifier)) (defun offsetof (c-type-specifier struct-field) (values (ct::cstruct-slot-info (ct::ctypeexpand-all c-type-specifier) struct-field))) (defun valid-callback-arg-type (ctype) (setq ctype (ctypeexpand-all ctype)) (if (member ctype simple-c-types) t (and (consp ctype) (consp (cdr ctype)) (valid-callback-arg-type (first ctype)) (or (integerp (second ctype))(eq (second ctype) '*))))) ;;; We only execute the following macro for its side effects (defmacro ensure-func-table-entry (symbol) (if (zerop (uref symbol cl::symbol-jump-table-offset)) (cl::%create-func-table-entry symbol)) nil) ;;; ;;; Redefine Common Lisp MULTIPLE-VALUE-BIND macro to ;;; make the VALUE-FORM be evaluated in the correct lexical context. ;;; From <NAME>. ;;; (defmacro cl::multiple-value-bind (vars value-form &rest forms) (let ((declarations nil)) ;; look for declarations (do* ((f forms (cdr f))) ((null f) (setq forms f)) (if (and (consp (car f)) (eq (caar f) 'declare)) (push (car f) declarations) (progn (setq forms f) (return)))) (let* ((gensyms (mapcar #'(lambda (x) (gensym (symbol-name x))) vars)) (bindings (mapcar #'list vars gensyms))) `(let ,gensyms (multiple-value-setq ,gensyms ,value-form) (let ,bindings ,@(nreverse declarations) ,@forms))))) (defmacro define-callback-func (name arg-list body &key (linkage :c) (create-heap-handler nil)) (declare (ignore create-heap-handler)) (let* ((syms nil) (lisp-func nil) (foreign-func nil) (arg-conversion-forms nil) internal-name (docstring nil) (num-args (length arg-list)) (sym-t1 (gensym))) (dolist (x arg-list) (unless (and (listp x) (= (length x) 2) (valid-callback-arg-type (second x))) (error "Invalid argument specification in DEFUN-CALLBACK form: ~A" x)) (push (first x) syms)) (setq syms (nreverse syms)) (setq internal-name (intern (concatenate 'string "%" (symbol-name name) "-internal"))) (multiple-value-bind (doc decls body bad-decls) (cl::parse-doc-decls-body body) (declare (ignore doc)) (when bad-decls (error "Declarations found in body of callback")) (setq lisp-func `(defun ,internal-name ,syms (let () (cl::%safecall #'(lambda () ,@decls (block ,name ,@body)))))) (setq docstring doc)) (let ((param-offset 0)) (dolist (x arg-list) (let ((arg-type (ctypeexpand-all (second x)))) (cond ((eq arg-type :char) (push `(x86::push-signed-char-lisp-arg ,param-offset) arg-conversion-forms)) ((eq arg-type :unsigned-char) (push `(x86::push-unsigned-char-lisp-arg ,param-offset) arg-conversion-forms)) ((eq arg-type :short) (push `(x86::push-signed-short-lisp-arg ,param-offset) arg-conversion-forms)) ((eq arg-type :unsigned-short) (push `(x86::push-unsigned-short-lisp-arg ,param-offset) arg-conversion-forms)) ((eq arg-type :wide-char) (push `(x86::push-wide-char-lisp-arg ,param-offset) arg-conversion-forms)) ((eq arg-type :long) (push `(x86::push-signed-long-lisp-arg ,param-offset) arg-conversion-forms)) ((eq arg-type :unsigned-long) (push `(x86::push-unsigned-long-lisp-arg ,param-offset) arg-conversion-forms)) ((eq arg-type :short-bool) (push `(x86::push-short-bool-lisp-arg ,param-offset) arg-conversion-forms)) ((eq arg-type :long-bool) (push `(x86::push-long-bool-lisp-arg ,param-offset) arg-conversion-forms)) ; ((eq arg-type :handle) ; (push `(x86::push-long-handle-lisp-arg ,param-offset) arg-conversion-forms)) ((eq arg-type :single-float) (push `(x86::push-single-float-lisp-arg ,param-offset) arg-conversion-forms)) ((eq arg-type :double-float) (push `(x86::push-double-float-lisp-arg ,param-offset) arg-conversion-forms) (incf param-offset 4)) ((eq arg-type :int64) (push `(x86::push-int64-lisp-arg ,param-offset) arg-conversion-forms) (incf param-offset 4)) ((eq arg-type :uint64) (push `(x86::push-uint64-lisp-arg ,param-offset) arg-conversion-forms) (incf param-offset 4)) (t (push `(x86::push-pointer-lisp-arg ,param-offset) arg-conversion-forms)))) (incf param-offset 4)) (setq foreign-func `(defun ,name ,syms ,@(when docstring (list docstring)) (declare (optimize (speed 3)(safety 0))) ; disable arg checking (declare (ignore ,@syms)) ; disable "unused variable" warnings (x86::setup-lisp-registers) (x86::push-lisp-stack-context) (x86::link-heap-handler) ;,@(if create-heap-handler ; `((x86::link-heap-handler))) ,@(nreverse arg-conversion-forms) (x86::mov-ecx-num ,num-args) (x86::call-lisp-proc ,internal-name) (x86::pop-lisp-args ,num-args) (x86::return-lisp-val-as-c) (x86::unlink-heap-handler) ;,@(if create-heap-handler ; `((x86::unlink-heap-handler))) (x86::pop-lisp-stack-context) (x86::copy-foreign-return-val-to-eax) (x86::restore-c-registers) ,@(if (eq linkage :pascal) `((x86::return-from-pascal ,num-args))))) `(let ((,sym-t1 (cl::create-callback-thunk ',name))) (setf (get ',name 'ct::callback-thunk) ,sym-t1) (ensure-func-table-entry ,internal-name) ;; make sure there is a jump entry ,lisp-func ;; define lisp function ,foreign-func)))) ;; define foreign function (defvar *collect-exported-functions* nil) ;; used by COMPILE-FILE and COMPILE-DLL (defvar *callback-registry* (make-hash-table :test #'equal :synchronized t)) ;; maps strings to callback symbols (defmacro defun-callback (name arg-list &rest body) `(define-callback-func ,name ,arg-list ,body :linkage :pascal)) (defmacro defun-c-callback (name arg-list &rest body) `(define-callback-func ,name ,arg-list ,body :linkage :c)) (defmacro defun-direct-callback (name arg-list &rest body) `(define-callback-func ,name ,arg-list ,body :linkage :pascal :create-heap-handler t)) (defmacro defun-direct-c-callback (name arg-list &rest body) `(define-callback-func ,name ,arg-list ,body :linkage :c :create-heap-handler t)) (defun defun-dll-export-body (name arg-list body linkage) (let ((prototype nil) (sym name)) (when (stringp (first body)) (setf prototype (first body)) (setf body (cdr body))) (when (consp name) ;; map export string name to symbol (setf (gethash (cadr name) *callback-registry*) (car name)) (setf sym (car name))) `(eval-when (:execute :load-toplevel :compile-toplevel) ,@(if (consp name) `((setf (gethash ',(cadr name) *callback-registry*) ',(car name))) nil) (if *collect-exported-functions* (vector-push-extend ',(list name prototype) *collect-exported-functions*)) (define-callback-func ,sym ,arg-list ,body :linkage ,linkage :create-heap-handler t)))) (defmacro defun-dll-export-function (name arg-list &rest body) (defun-dll-export-body name arg-list body ':pascal)) (defmacro defun-dll-export-c-function (name arg-list &rest body) (defun-dll-export-body name arg-list body ':c)) ;;; support code generation operators for defun-callback macro (in-package :x86) (defcodegen setup-lisp-registers (form dest) (declare (ignore form dest)) (parse-assembler { push esi push edi push ebx mov eax, 'cl::%load-qv-reg mov eax, [eax + (uvector-offset symbol-function-offset)] ; get function binding mov eax, [eax - cons-tag] call [eax + (uvector-offset function-code-buffer-offset)] }) t) (defcodegen restore-c-registers (form dest) (declare (ignore form dest)) (parse-assembler { pop ebx pop edi pop esi }) t) (defcodegen call-lisp-proc (form dest) (declare (ignore dest)) (let* ((sym (second form)) (env-offset (* (uref sym symbol-jump-table-offset) 4)) (jump-offset (+ env-offset 4))) (if (zerop env-offset) (error "The function ~A does not have a jump table offset and cannot be called" sym)) (parse-assembler { mov edi, [esi + env-offset] add-env-table-ref sym call [esi + jump-offset] add-jump-table-ref sym })) t) (defcodegen pop-lisp-args (form dest) (declare (ignore dest)) (let* ((numargs (second form)) (bytes (* 4 numargs))) (parse-assembler { add esp, bytes })) t) (defcodegen return-lisp-val-as-c (form dest) (declare (ignore form dest)) (parse-assembler { mov ecx, eax and ecx, 7 ;; if fixnum, return that jnz short :t2 cmp eax, 0 jl short :neg-integer mov ecx, -1 callp x86::%get-foreign-unsigned-long jmp :exit :neg-integer mov ecx, -1 callp x86::%get-foreign-long jmp :exit :t2 cmp al, 1 je :char cmp ecx, uvector-tag jne :t3 ;; not handling return of short floats from callback yet mov cl, [eax - uvector-tag] shr cl, 3 cmp cl, uvector-bignum-tag jne short :t7 mov cl, [eax + (uvector-offset 1)] and cl, 8 ;; negative bignum? jnz short :neg-bignum mov ecx, -1 callp x86::%get-foreign-unsigned-long jmp short :exit :neg-bignum mov ecx, -1 callp x86::%get-foreign-long jmp short :exit :t7 cmp cl, uvector-foreign-tag jne short :t4 begin-atomic mov eax, [eax + (uvector-offset foreign-heap-ptr-offset)] mov [esi + (- (* foreign-cells-qv-tos 4) 4)], eax xor eax, eax end-atomic jmp short :exit :t4 cmp cl, uvector-foreign-heap-tag jne short :t5 begin-atomic mov eax, [eax + (uvector-offset foreign-heap-ptr-offset)] mov [esi + (- (* foreign-cells-qv-tos 4) 4)], eax xor eax, eax end-atomic jmp short :exit :t5 cmp cl, uvector-double-float-tag jne short :t6 fld [eax + (uvector-offset cl::double-float-offset)] ;; store 0 in eax, in case caller is not expecting a float they will get that mov eax, 0 mov [esi + (- (* foreign-cells-qv-tos 4) 4)], eax jmp short :exit :t6 cmp cl, uvector-single-float-tag jne short :t3 fld.single [eax + (uvector-offset cl::single-float-offset)] ;; store 0 in eax, in case caller is not expecting a float they will get that mov eax, 0 mov [esi + (- (* foreign-cells-qv-tos 4) 4)], eax jmp short :exit :char shl eax, 8 shr eax, 16 jmp short :exit :t3 xor eax, eax :exit }) t) (defcodegen copy-foreign-return-val-to-eax (form dest) (declare (ignore form dest)) (parse-assembler { mov eax, [esi + (- (* foreign-cells-qv-tos 4) 4)] }) t) (defcodegen push-signed-char-lisp-arg (form dest) (declare (ignore dest)) (let ((offset (+ ARGS_OFFSET (second form)))) (parse-assembler { xor eax, eax mov al, [ebp + offset] shl eax, 24 sar eax, 21 push eax })) t) (defcodegen push-unsigned-char-lisp-arg (form dest) (declare (ignore dest)) (let ((offset (+ ARGS_OFFSET (second form)))) (parse-assembler { xor eax, eax mov al, [ebp + offset] shl eax, 24 shr eax, 21 push eax })) t) (defcodegen push-signed-short-lisp-arg (form dest) (declare (ignore dest)) (let ((offset (+ ARGS_OFFSET (second form)))) (parse-assembler { xor eax, eax mov ax, [ebp + offset] shl eax, 16 sar eax, 13 push eax })) t) (defcodegen push-unsigned-short-lisp-arg (form dest) (declare (ignore dest)) (let ((offset (+ ARGS_OFFSET (second form)))) (parse-assembler { xor eax, eax mov ax, [ebp + offset] shl eax, 16 shr eax, 13 push eax })) t) (defcodegen push-wide-char-lisp-arg (form dest) (declare (ignore dest)) (let ((offset (+ ARGS_OFFSET (second form)))) (parse-assembler { xor eax, eax mov ax, [ebp + offset] shl eax, 8 inc eax push eax })) t) (defcodegen push-signed-long-lisp-arg (form dest) (declare (ignore dest)) (let ((offset (+ ARGS_OFFSET (second form)))) (parse-assembler { ;; top cell gets converted into Lisp integer in eax begin-atomic mov eax, [ebp + offset] cmp eax, cl::most-positive-fixnum jg short :bignum cmp eax, cl::most-negative-fixnum jl short :bignum shl eax, 3 jmp short :done :bignum xor eax, eax end-atomic push (* 8 1) ;; wrapped integer 1 callp cl::alloc-bignum add esp, 4 begin-atomic mov edx, [ebp + offset] cmp edx, 0 jge :next1 neg edx mov [eax + (uvector-offset 2)], edx mov edx, [eax + (uvector-offset 1)] xor edx, 8 mov [eax + (uvector-offset 1)], edx jmp short :done :next1 mov [eax + (uvector-offset 2)], edx :done end-atomic push eax })) t) (defcodegen push-unsigned-long-lisp-arg (form dest) (declare (ignore dest)) (let ((offset (+ ARGS_OFFSET (second form)))) (parse-assembler { ;; carefully copy DWORD to foreign region of QV (top cell) begin-atomic mov eax, [ebp + offset] mov [esi + (- (* foreign-cells-qv-tos 4) 4)], eax xor eax, eax end-atomic ;; top cell gets converted into Lisp integer in eax push (* 8 -1) callp x86::create-foreign-lisp-unsigned-integer add esp, 4 push eax })) t) (defcodegen push-int64-lisp-arg (form dest) (declare (ignore dest)) (let ((offset (+ ARGS_OFFSET (second form)))) (parse-assembler { ;; carefully copy Int64 to foreign region of QV (top cell) begin-atomic mov eax, [ebp + offset] mov [esi + (- (* foreign-cells-qv-tos 4) 8)], eax mov eax, [ebp + (+ offset 4)] mov [esi + (- (* foreign-cells-qv-tos 4) 4)], eax xor eax, eax end-atomic ;; top 2 cells gets converted into Lisp integer in eax push (* 8 -2) callp x86::create-foreign-lisp-int64 add esp, 4 push eax })) t) (defcodegen push-uint64-lisp-arg (form dest) (declare (ignore dest)) (let ((offset (+ ARGS_OFFSET (second form)))) (parse-assembler { ;; carefully copy UInt64 to foreign region of QV (top cell) begin-atomic mov eax, [ebp + offset] mov [esi + (- (* foreign-cells-qv-tos 4) 8)], eax mov eax, [ebp + (+ offset 4)] mov [esi + (- (* foreign-cells-qv-tos 4) 4)], eax xor eax, eax end-atomic ;; top cell gets converted into Lisp integer in eax push (* 8 -2) callp x86::create-foreign-lisp-uint64 add esp, 4 push eax })) t) (defcodegen push-single-float-lisp-arg (form dest) (declare (ignore dest)) (let ((offset (+ ARGS_OFFSET (second form)))) (parse-assembler { mov ecx, 0 callf cl::alloc-single-float fld.single [ebp + offset] fstp.single [eax + (uvector-offset cl::single-float-offset)] push eax })) t) (defcodegen push-double-float-lisp-arg (form dest) (declare (ignore dest)) (let ((offset (+ ARGS_OFFSET (second form)))) (parse-assembler { mov ecx, 0 callf cl::alloc-double-float fld [ebp + offset] fstp [eax + (uvector-offset cl::double-float-offset)] push eax })) t) (defcodegen push-pointer-lisp-arg (form dest) (declare (ignore dest)) (let ((offset (+ ARGS_OFFSET (second form)))) (parse-assembler { xor ecx, ecx callf ct::create-foreign-ptr begin-atomic mov ecx, [ebp + offset] mov [eax + (uvector-offset cl::foreign-heap-ptr-offset)], ecx xor ecx, ecx end-atomic push eax })) t) (defcodegen return-from-pascal (form dest) (declare (ignore dest)) (let ((numbytes (* (second form) 4))) (parse-assembler { mov esp, ebp pop ebp ret numbytes })) t) (ct::ensure-func-table-entry create-foreign-ptr) (defun ct::get-callback-procinst (callback-func-sym) (when (stringp callback-func-sym) (setf callback-func-sym (gethash callback-func-sym ct::*callback-registry*))) (if (null callback-func-sym) (return-from ct::get-callback-procinst nil)) (get callback-func-sym 'ct::callback-thunk)) ;; This function gets accessed via the COM interface from ;; foreign threads. (defun cl::get-callback (name) (ct::get-callback-procinst name)) ;;; ;;; CormanLisp CPOINTERP function. ;;; (defasm ct::cpointerp (p) { push ebp mov ebp, esp cmp ecx, 1 jz short :t1 callp _wrong-number-of-args-error :t1 mov eax, [ebp + ARGS_OFFSET] ;eax = p mov edx, eax and edx, 7 cmp edx, uvector-tag jne short :not-foreign mov dl, [eax - uvector-tag] shr dl, 3 cmp dl, uvector-foreign-tag je short :is-foreign cmp dl, uvector-foreign-heap-tag je short :is-foreign cmp dl, uvector-foreign-stack-tag je short :is-foreign jmp short :not-foreign :is-foreign mov eax, [esi + t-offset] jmp short :exit :not-foreign mov eax, [esi] :exit pop ebp ret }) (defun ct::foreign-stack-p (x) (and (uvectorp x)(eq (cl::uvector-type-bits x) uvector-foreign-stack-tag))) (defasm ct::%memcmp (cp1 cp2 count) { push ebp mov ebp, esp push esi push edi mov esi, [ebp + (+ ARGS_OFFSET 8)] ;; esi = cp1 mov edi, [ebp + (+ ARGS_OFFSET 4)] ;; edi = cp2 mov ecx, [ebp + (+ ARGS_OFFSET 0)] ;; ecx = count shr ecx, 3 ;; ecx = unwrapped count :loop1 cmp ecx, 3 jle short :loop2 mov eax, [esi] cmp eax, [edi] jne :diff add esi, 4 add edi, 4 sub ecx, 4 jmp short :loop1 :loop2 cmp ecx, 0 je short :same mov al, [esi] cmp al, [edi] jne :diff inc esi inc edi dec ecx jmp short :loop2 :diff jl :less :greater mov eax, 8 ;; eax = 1 jmp short :exit :less mov eax, -8 jmp short :exit :same mov eax, 0 :exit mov ecx, 1 pop edi pop esi mov esp, ebp pop ebp ret }) (in-package :ct) (defun ct:memcmp (buf1 buf2 count) (unless (ct:cpointerp buf1) (error "Not a foreign pointer: ~A" buf1)) (unless (ct:cpointerp buf2) (error "Not a foreign pointer: ~A" buf2)) (unless (fixnump count) (error "Third argument to memcmp must be a fixnum, got ~A" count)) (%memcmp (uref buf1 1)(uref buf2 1) count)) (ct:defun-dll memcpy ((dest (:void *))(src (:void *))(count :unsigned-long)) :return-type (:void *) :library-name "msvcrt.dll" :entry-name "memcpy" :linkage-type :c) (defun malloc (size) (cl::allocate-c-heap size)) (defun free (cptr) (cl::deallocate-c-heap cptr)) (defun unicode-to-lisp-string (buf) (let ((x (make-array 0 :element-type 'character :fill-pointer t :adjustable t))) (do* ((index 0 (+ index 1)) (c (ct:cref (:wide-char *) buf index) (ct:cref (:wide-char *) buf index))) ((char= c #\nul) x) (vector-push-extend c x)))) (defun lisp-string-to-unicode (str &optional (buf nil)) (let ((strlength (length str))) (unless buf (setf buf (ct:malloc (* (+ strlength 1) 2)))) (do* ((i 0 (+ i 1))) ((= i strlength) (setf (ct:cref (:wide-char *) buf i) #\nul) buf) (setf (ct:cref (:wide-char *) buf i) (elt str i))))) (defun lisp-string-to-c-string (str &optional (cstr nil)) (let ((strlength (length str))) (unless cstr (setf cstr (ct:malloc (+ strlength 1)))) (dotimes (i strlength) (setf (ct:cref (:unsigned-char *) cstr i) (char-int (elt str i)))) (setf (ct:cref (:unsigned-char *) cstr strlength) 0) cstr)) ;; Copy a lisp array of bytes to a C byte array. ;; If the optional parameter cbuf is not supplied (or is nil) then a new C byte ;; array of the same length is allocated with ct:malloc. The resulting C array is returned. ;; (defun lisp-bytes-to-c-bytes (buf &optional (cbuf nil)) (let ((length (length buf))) (unless cbuf (setf cbuf (ct:malloc length))) (dotimes (i length) (setf (ct:cref (:unsigned-char *) cbuf i) (aref buf i))) cbuf)) ;; Copy a C array of bytes to a Lisp array of bytes. ;; If the optional parameter lisp-buf is supplied, it should be a Lisp array of 'byte ;; of a length greater or equal to the passed length parameter. ;; The lisp array is returned. (defun c-bytes-to-lisp-bytes (cbuf length &optional (lisp-buf nil)) (unless lisp-buf (setf lisp-buf (make-array length :element-type 'byte))) (dotimes (i length) (setf (aref lisp-buf i) (ct:cref (:unsigned-char *) cbuf i))) lisp-buf) (defmacro with-c-struct ((var expr structure-type) &body body) (declare (ignore var)) (let ((struct-def (ct::ctypeexpand-all structure-type))) (unless (and (listp struct-def) (eq (car struct-def) ':struct)) (error "Not a C structure definition: ~S" struct-def)) (let ((fields (let ((j 0) (ret nil)) (dolist (i (rest struct-def)(nreverse ret)) (if (evenp j) (push i ret)) (incf j))))) (unless (every #'symbolp fields) (error "Invalid structure definition, names are not all symbols: ~A" fields)) `(symbol-macrolet ,(mapcar #'(lambda (sym) `(,sym (ct:cref ,structure-type ,expr ,sym))) fields) ,@body)))) (defmacro with-fresh-foreign-block ((sym type) &rest forms) `(let ((,sym (ct:malloc (ct:sizeof ,type)))) (unwind-protect (progn ,@forms)(ct:free ,sym)))) ;;; ;;; Output the contents of a C structure. ;;; The structure and the optional stream are evaluated, but the C structure name is not. ;;; Example: (dump-c-struct s WNDCLASSEX) ;;; (defmacro dump-c-struct (struct type &optional (stream t)) (let ((exptype (ct::ctypeexpand-all type))) (unless (ct::valid-c-type-definition exptype) (error "Invalid C type specifier: ~S" type)) (let ((forms '())) (do* ((x (cdr exptype) (cddr x)) (name (car x) (car x)) (field-type (cadr x) (cadr x))) ((null x)) (push `(format ,stream "~4T~A[~A]:~40T~S~%" ',name ',field-type (ct:cref ,type ,struct ,name)) forms)) `(progn (format ,stream "~A:~%" ',type) ,@forms (format ,stream "~%") (values))))) (defconstant x86::foreign-stack-start-marker (+ (* cl::uvector-foreign-stack-tag 8) x86::uvector-header-tag)) (defconstant x86::foreign-stack-end-marker (+ (* cl::uvector-foreign-stack-end-tag 8) x86::uvector-header-tag)) (defasm alloca (size) { begin-atomic pop edx ; edx = return address pop eax ; eax = size in bytes shr eax, 3 ; untag test esp, 4 ; are we at an 8-byte stack boundary jnz :t1 push 0 ; if so, push a pad word :t1 add eax, 7 and eax, -8 ; should be multiple of 8 mov ecx, eax shr ecx, 3 add ecx, 2 ; 4 word header shl ecx, 8 or ecx, x86::foreign-stack-end-marker push ecx ; push end marker sub esp, eax ; allocate foreign block push 0 ; pad shl eax, 3 ; tag byte count push eax ; number of bytes lea eax, [esp + 8] ; start of foreign block push eax and ecx, #xffffff7 or ecx, x86::foreign-stack-start-marker push ecx mov eax, esp or eax, uvector-tag push 0 ; dummy arg push edx ; push return address mov ecx, 1 end-atomic ret }) ;; redefine kernel function (defasm cl::lisp-object-id (obj) { push ebp mov ebp, esp mov eax, [ebp + ARGS_OFFSET] cmp eax, most-positive-fixnum ja :bignum shl eax, 3 jmp short :next :bignum mov ecx, eax shr ecx, 16 shl ecx, 3 shl eax, 16 shr eax, 13 ;; eax = low 16 bits, ecx = high 16 bits push eax push ecx callp %create-positive-bignum add esp, 8 :next mov ecx, 1 pop ebp ret }) ;;; ;;; Redefine kernel LOAD-DLL function ;;; (ct:defun-kernel cl::loadlibrary ((filename (:unsigned-char *))) :return-type :handle :kernel-name cl::%LoadLibrary :linkage-type :pascal) ;(defun cl::load-dll (filename) ; (ct:foreign-ptr-to-int (cl::loadlibrary (ct:lisp-string-to-c-string filename)))) (make-package :temp-package) (in-package :temp-package) ;; avoid interning these exported symbols (defpackage :win32 (:export ) (:nicknames :win)) (in-package :win) (use-package :ct) (in-package :cl) (setq cl::*compiler-warn-on-undefined-function* t)
true
;;;; ------------------------------- ;;;; Copyright (c) Corman Technologies Inc. ;;;; See LICENSE.txt for license information. ;;;; ------------------------------- ;;;; ;;;; File: ffi.lisp ;;;; Contents: Foreign function interface. ;;;; History: 2/13/97 RGC Created. ;;;; (defpackage "C-TYPES" (:export "DEFUN-DLL" "DEFUN-COM-METHOD" "DEFUN-THISCALL" "DEFUN-POINTER" "DEFUN-KERNEL" "DEFCSTRUCT" "DEFCTYPE" "CREATE-FOREIGN-PTR" "SIZEOF" "OFFSETOF" "CPOINTER-VALUE" "CPOINTERP" "DEFUN-CALLBACK" "DEFUN-C-CALLBACK" "DEFUN-DIRECT-CALLBACK" "DEFUN-DIRECT-C-CALLBACK" "DEFUN-DLL-EXPORT-FUNCTION" "DEFUN-DLL-EXPORT-C-FUNCTION" "GET-CALLBACK-PROCINST" "CREF" "CREATE-C-STRING" "C-STRING-LENGTH" "CPOINTER=" "CPOINTER-NULL" "MEMCMP" "MEMCPY" "MALLOC" "FREE" "FOREIGN-PTR-TO-INT" "INT-TO-FOREIGN-PTR" "UNICODE-TO-LISP-STRING" "LISP-STRING-TO-UNICODE" "C-STRING-TO-LISP-STRING" "LISP-STRING-TO-C-STRING" "WITH-C-STRUCT" "WITH-FRESH-FOREIGN-BLOCK" "FOREIGN-STACK-P" "ALLOCA" "*COLLECT-EXPORTED-FUNCTIONS*" "DUMP-C-STRUCT" "FOREIGN-HEAP-LENGTH" "LISP-BYTES-TO-C-BYTES" "C-BYTES-TO-LISP-BYTES" ) (:nicknames :ct)) (in-package "C-TYPES") (setq cl::*compiler-warn-on-undefined-function* nil) ;;; examples of valid C type descriptors: ;;; :void ;;; :char ;;; :unsigned-char ;;; :short ;;; :unsigned-short ;;; :wide-char ;;; :long ;;; :unsigned-long ;;; :short-bool ;;; :long-bool ;;; :single-float ;;; :double-float ;;; :handle ;;; (:long 5) ; array of 5 longs ;;; (:long *) ; pointer to long ;;; ((:long *) *) ; pointer to pointer to long ;;; (:struct f1 :short f2 :long) ; struct containing a short and a long (defstruct foreign-function-record dll-name foreign-name lisp-sym foreign-address jump-table-address) (defstruct dll-record name handle (function-records nil)) (defvar *dlls-loaded* nil) #| (defun pl::peek-dword (addr) (+ (pl::peek-byte addr) (ash (pl::peek-byte (+ addr 1)) 8) (ash (pl::peek-byte (+ addr 2)) 16) (ash (pl::peek-byte (+ addr 3)) 24))) |# (defun foreign-jump-table-capacity () (pl::peek-dword (+ (cl::sys-globals-address) 12))) (defun foreign-jump-table-num-entries () (pl::peek-dword (+ (cl::sys-globals-address) 8))) ;; ;; forward references ;; (declaim (ftype (function (t) t) ctype-lookup-alias)) (declaim (ftype (function (t) fixnum) determine-c-struct-size)) (declaim (ftype (function (t) t) valid-c-struct-definition)) (defun foreign-type-error (obj) (error "Not a foreign pointer: ~A" obj)) (defun determine-c-type-size (definition) (if (symbolp definition) (let ((typedef (ctype-lookup-alias definition))) (if typedef (setq definition typedef)))) (cond ((symbolp definition) (ecase definition (:void 0) ((:char :unsigned-char) 1) ((:short :unsigned-short :short-bool :wide-char) 2) ((:long :unsigned-long :single-float :long-bool :handle) 4) ((:double-float :int64 :uint64) 8))) ((not (listp definition)) (error "Invalid C Type descriptor: ~S" definition)) ((eq (car definition) ':struct) (determine-c-struct-size definition)) ((eq (cadr definition) '*) 4) ;; pointer type ((integerp (cadr definition)) (* (determine-c-type-size (car definition)) (cadr definition))) ((and (constantp (cadr definition)) (fixnump (symbol-value (cadr definition)))) (* (determine-c-type-size (car definition)) (symbol-value (cadr definition)))) (t (error "Invalid C Type descriptor: ~S" definition)))) (defconstant simple-c-types '(:void :char :unsigned-char :short :unsigned-short :long :unsigned-long :short-bool :long-bool :single-float :double-float :handle :wide-char :int64 :uint64)) (defun valid-c-type-definition (definition) (cond ((symbolp definition) (let ((typedef (ctype-lookup-alias definition))) (if typedef t (if (member definition simple-c-types) t)))) ((not (listp definition)) nil) ((eq (car definition) ':struct) (valid-c-struct-definition definition)) ((eq (cadr definition) '*) (valid-c-type-definition (car definition))) ((or (fixnump (cadr definition)) (and (constantp (cadr definition)) (fixnump (symbol-value (cadr definition))))) (valid-c-type-definition (car definition))) (t nil))) (defun valid-c-struct-definition (definition) (unless (eq (car definition) ':struct) (return-from valid-c-struct-definition nil)) (do ((p (cdr definition)(cddr p))) ((null p) t) (unless (valid-c-type-definition (cadr p)) (return nil)))) (defun determine-c-struct-size (definition) (do ((size 0) (p (cdr definition)(cddr p))) ((null p) size) (incf size (determine-c-type-size (cadr p))))) (defun cstruct-definition-equal-p (def1 def2) (equal def1 def2)) (defasm set-foreign-func-address (func cptr) { push ebp mov ebp, esp mov eax, [ebp + (+ ARGS_OFFSET 4)] ;eax = func mov edx, [ebp + ARGS_OFFSET] ;edx = cptr mov edx, [edx + (uvector-offset cl::foreign-heap-ptr-offset)] mov [eax + (uvector-offset cl::function-code-buffer-offset)], edx mov ecx, 1 pop ebp ret }) (defun foreign-ptr-to-function (cptr) (let ((func (alloc-uvector cl::function-size cl::uvector-kfunction-tag))) (setf (uref func cl::function-environment-offset) nil) (set-foreign-func-address func cptr) func)) (defun get-dll-record (dll-name) (dolist (rec *dlls-loaded*) (if (string-equal (dll-record-name rec) dll-name) (return-from get-dll-record rec))) (let* ((handle (load-dll dll-name)) (rec (make-dll-record :name dll-name :handle handle))) (push rec *dlls-loaded*) rec)) ;;; ;;; GET-DLL-HANDLE dll-name ;;; Returns handle of the DLL if it is already loaded, ;;; otherwise returns it loads the DLL and returns the handle. ;;; (defun get-dll-handle (dll-name) (let ((rec (get-dll-record dll-name))) (if rec (dll-record-handle rec) nil))) ;;; ;;; GET-DLL-FUNCTION-ADDRESS dll-name dll-function-name ;;; (defun get-dll-function-address (dll-name dll-function-name) (let ((dll-handle (get-dll-handle dll-name))) (if dll-handle (let ((addr (get-dll-proc-address dll-function-name dll-handle))) (if addr (return-from get-dll-function-address addr) (error "Could not find function ~S in library ~S" dll-function-name dll-name))) (error "Could not open library ~S" dll-name)))) ;;; ;;; INSTALL-DLL-FUNCTION dll-name dll-function-name lisp-symbol ;;; ;;; ;;; INSTALL-DLL-FUNCTION dll-name dll-function-name lisp-symbol ;;; (defun install-dll-function (dll-name dll-function-name lisp-symbol) (let* ((func-address (get-dll-function-address dll-name dll-function-name)) (dll-rec (get-dll-record dll-name)) (jump-address (cl::allocate-foreign-jump-table-entry func-address)) (func-rec (make-foreign-function-record :dll-name dll-name :foreign-name dll-function-name :lisp-sym lisp-symbol :foreign-address func-address :jump-table-address jump-address))) (setf (symbol-function lisp-symbol) (foreign-ptr-to-function jump-address)) (push func-rec (dll-record-function-records dll-rec)) lisp-symbol)) ;;; ;;; GENERATE-DYNAMIC-FUNCTION ;;; This generates a function which is used as a stub for a dynamically linked ;;; function. When this executes, it loads the actual function, and calls it ;;; with the arguments which were passed to it. ;;; #| (defun generate-dynamic-function (dll-name dll-function-name lisp-symbol) #'(lambda (&rest args) (install-dll-function dll-name dll-function-name lisp-symbol) (apply lisp-symbol args))) |# (defun generate-dynamic-function (dll_name dll_function_name lisp_symbol) (defasm dynamic-func-instance () { push ebp mov ebp, esp push edi ;; push lisp stack context--enter lisp mode foreign-call-lisp push ecx push ct::dll_name push ct::dll_function_name push ct::lisp_symbol mov ecx, 3 callf ct::install-dll-function add esp, 12 pop ecx ;; pop lisp stack context--back to foreign code lisp-return-to-foreign pop edi mov eax, ct::lisp_symbol mov eax, [eax + (uvector-offset cl::symbol-jump-table-offset)] shr eax, 1 pop ebp jmp near [esi + eax + 4] ret }) #'dynamic-func-instance) #| (defun generate-dynamic-function (dll_name dll_function_name lisp_symbol) (defasm dynamic-func-instance () { push ebp mov ebp, esp push edi ;; pop foreign stack context--return to lisp mode begin-atomic mov edx, [esi + (* stack-marker-index-qv-offset 4)] cmp edx, 0 jg :t1 end-atomic push "Tried to pop foreign stack context but none exist!" mov ecx, 1 callf error :t1 sub edx, 4 mov [esi + (* stack-marker-index-qv-offset 4)], edx end-atomic push ecx push ct::dll_name push ct::dll_function_name push ct::lisp_symbol mov ecx, 3 callf ct::install-dll-function add esp, 12 pop ecx ;; push foreign stack context--back to foreign code begin-atomic mov eax, [esi + (* stack-marker-index-qv-offset 4)] cmp eax, stack-markers-max jl :t2 end-atomic push "Ran out of stack markers!" mov ecx, 1 callf error :t2 push eax ;; just to get esp - 4 mov [esi + eax*2 + (* stack-markers-qv-offset 4)], esp lea edi, [esi + eax*2 + (* (+ stack-markers-qv-offset 1) 4)] pop eax ;; just to get esp - 4 add eax, 4 mov [esi + (* stack-marker-index-qv-offset 4)], eax end-atomic pop edi mov eax, ct::lisp_symbol mov eax, [eax + (uvector-offset cl::symbol-jump-table-offset)] shr eax, 1 pop ebp jmp near [esi + eax + 4] ret }) #'dynamic-func-instance) |# (defun install-dynamic-foreign-function (dll-name dll-function-name lisp-symbol) (setf (symbol-function lisp-symbol) (generate-dynamic-function dll-name dll-function-name lisp-symbol)) lisp-symbol) (defun create-foreign-function-name (dll-function-name) (intern (concatenate 'string "%FOREIGN-" dll-function-name))) (defun stack-frame-bytes (arg-type-list) (let ((bytes 0)) (dolist (i arg-type-list bytes) (incf bytes (case i (:long 4) (:double-float 8) (:int64 8) (:uint64 8) (otherwise 4)))))) (defstruct foreign-call-params-info push-forms local-vars lambda-list frame-cells pointer-p) (defun generate-call-params-info (param-list frame-cells &optional (func-ptr nil)) (let ((push-forms '()) (local-vars '()) (num-cells (- frame-cells)) (lambda-list '()) (pointer-p nil)) ;; special case for defun-pointer--skip past the pointer (when func-ptr ;; start with foreign func ptr (push `(x86::compile-foreign-arg ,func-ptr (:void *) ,num-cells) push-forms) (incf num-cells 1) (setf pointer-p t)) (dolist (i param-list) (let ((var (first i)) (ctype (second i))) (setq ctype (ctypeexpand-all ctype)) (if (stringp var) (setf var (if (equalp var "") (gensym) (intern (string-upcase var))))) (push var lambda-list) (cond ((equal ctype '(:char *)) (let ((t3 (gensym))) (push `(,t3 (ct::create-c-string ,var)) local-vars) (push `(x86::compile-foreign-arg ,t3 ,ctype ,num-cells) push-forms))) (t (push `(x86::compile-foreign-arg ,var ,ctype ,num-cells) push-forms))) (if (member ctype '(:double-float :int64 :uint64)) (incf num-cells 2) (incf num-cells 1)))) (make-foreign-call-params-info :push-forms push-forms :local-vars local-vars :lambda-list lambda-list :frame-cells frame-cells :pointer-p pointer-p))) (defun foreign-defun-stub (name info stack-cleanup-forms return-type call-form &optional call-setup-form) (let ((num-cells (foreign-call-params-info-frame-cells info))) `(defun ,name ,(nreverse (foreign-call-params-info-lambda-list info)) (let (,@(foreign-call-params-info-local-vars info)) (x86::save-lisp-registers) ,@(foreign-call-params-info-push-forms info) ,@call-setup-form (x86::push-foreign-stack-context) (x86::push-foreign-args-length ,(if (foreign-call-params-info-pointer-p info) (- num-cells 1) num-cells)) ;; if called by DEFUN-POINTER, the args length is one fewer because pointer is ;; popped as part of function call (x86::copy-foreign-args ,(foreign-call-params-info-frame-cells info)) ,call-form (x86::pop-foreign-args-length) (x86::copy-return-value ,return-type) ,@stack-cleanup-forms (x86::pop-foreign-stack-context) (x86::restore-lisp-registers) (x86::wrap-foreign-return-value ,return-type))))) (defmacro defun-dll (name param-list &key (return-type :long) library-name entry-name (linkage-type :c)) (unless entry-name (setq entry-name (symbol-name name))) (unless library-name (error "You must specify a DLL name in the declaration of ~A" name)) (setq return-type (ctypeexpand-all return-type)) (let* ((arg-type-list (mapcar #'cadr param-list)) (stack-cleanup-forms nil) (lisp-symbol (create-foreign-function-name entry-name)) (frame-cells (/ (stack-frame-bytes arg-type-list) 4)) (info (generate-call-params-info param-list frame-cells))) ;side effect--allocates a jump table entry (cl::%create-func-table-entry lisp-symbol) (if (eq linkage-type :c) (setq stack-cleanup-forms `((x86::popargs ,arg-type-list)))) `(progn (install-dynamic-foreign-function ,library-name ,entry-name ',lisp-symbol) ,(foreign-defun-stub name info stack-cleanup-forms return-type `(x86::call-foreign-proc ,lisp-symbol))))) (defmacro defun-com-method (name param-list vtable-index &key (return-type :unsigned-long)) (setq return-type (ctypeexpand-all return-type)) (let* ((arg-type-list (mapcar #'cadr param-list)) (frame-cells (/ (stack-frame-bytes arg-type-list) 4)) (info (generate-call-params-info param-list frame-cells))) `(progn ,(foreign-defun-stub name info nil return-type `(x86::call-com-method ,vtable-index) `((x86::compile-com-method-address ,vtable-index)))))) ;;; ;;; Like DEFUN-DLL, but passes first argument in ECX. Used for interfacing ;;; to C++, functions which are defined with thiscall (any non-static ;;; member-function which does not take a variable number of arguments). ;;; (defmacro defun-thiscall (name param-list &key (return-type :long) library-name entry-name) (unless entry-name (setq entry-name (symbol-name name))) (unless library-name (error "You must specify a DLL name in the declaration of ~A" name)) (setq return-type (ctypeexpand-all return-type)) (let* ((arg-type-list (mapcar #'cadr param-list)) (lisp-symbol (create-foreign-function-name entry-name)) (frame-cells (/ (stack-frame-bytes arg-type-list) 4)) (info (generate-call-params-info param-list frame-cells))) ;side effect--allocates a jump table entry (cl::%create-func-table-entry lisp-symbol) `(progn (install-dynamic-foreign-function ,library-name ,entry-name ',lisp-symbol) ,(foreign-defun-stub name info nil return-type `(progn {{ pop ecx ;; move first argument into ECX register }} (x86::call-foreign-proc ,lisp-symbol)))))) ;;; ;;; Corman Lisp DEFUN-POINTER ;;; Similar to defun-dll, but allow the foreign function pointer to be passed ;;; as the first argument to the defined function. This should be a foreign ;;; pointer. ;;; #| Example: (setf module (cl::load-dll "msvcrt.dll")) (setf proc (cl::get-dll-proc-address "strlen" module)) (ct::defun-pointer strlen-ptr ((str (:char *))) :return-type :long :linkage-type :c) (strlen-ptr proc "corman lisp") |# (defmacro defun-pointer (name param-list &key (return-type :long) (linkage-type :c)) (setq return-type (ctypeexpand-all return-type)) (let* ((arg-type-list (mapcar #'cadr param-list)) (stack-cleanup-forms nil) (func-ptr (gensym)) (frame-cells (+ (/ (stack-frame-bytes arg-type-list) 4) 1)) ;; add 1 for func ptr (info (generate-call-params-info param-list frame-cells func-ptr))) (if (eq linkage-type :c) (setq stack-cleanup-forms `((x86::popargs ,arg-type-list)))) ;; add function pointer on as first arg (this means adding it to the end as it will get reversed) (setf (foreign-call-params-info-lambda-list info) (append (foreign-call-params-info-lambda-list info) (list func-ptr))) `(progn ,(foreign-defun-stub name info stack-cleanup-forms return-type `(x86::call-foreign-pointer))))) ;;; ;;; DEFUN-KERNEL macro is used to call kernel functions via the FFI. ;;; This protects the foreign kernel code from negatively affecting ;;; garbage collection, at the cost of thunking between lisp and foreign code. ;;; The called function is assumed to be defined in the kernel, as a foreign ;;; function. These will typically be in the common-lisp package, internal, with ;;; names beginning with '%'. ;;; (defmacro defun-kernel (name param-list &key (return-type :long) kernel-name ;; a symbol (linkage-type :c)) (setq return-type (ctypeexpand-all return-type)) (let* ((arg-type-list (mapcar #'cadr param-list)) (stack-cleanup-forms nil) (frame-cells (/ (stack-frame-bytes arg-type-list) 4)) (info (generate-call-params-info param-list frame-cells))) (if (eq linkage-type :c) (setq stack-cleanup-forms `((x86::popargs ,arg-type-list)))) `(progn ,(foreign-defun-stub name info stack-cleanup-forms return-type `(x86::call-foreign-proc ,kernel-name))))) (defun uvector-offset (index) (- (* 4 index) x86::uvector-tag)) (defconstant uvector-foreign-ptr-size 1) (defun create-foreign-ptr () (let ((p (cl::alloc-uvector uvector-foreign-ptr-size cl::uvector-foreign-tag))) (setf (uref p cl::foreign-heap-ptr-offset) 0) p)) ;;; Override kernel function (defun cl::%foreignnode () (ct:create-foreign-ptr)) (defasm %create-c-string (string) { push ebp mov ebp, esp push [esi] ; allocate temp variable push ebx push edi mov edx, [ebp + ARGS_OFFSET] ;edx = string push edx mov ecx, 1 callf length add esp, 4 ;eax = length of string mov [ebp - 4], eax ; save length in [ebp - 4] mov ecx, eax add ecx, 8 ;ecx = string-length + 1 push ecx mov ecx, 1 callf allocate-c-heap ;eax = c-string handle add esp, 4 push eax mov edi, [eax + (uvector-offset foreign-heap-ptr-offset)] ;edi = actual c-string mov edx, [ebp + ARGS_OFFSET] ; edx = string mov eax, [edx + (uvector-offset 0)] shr al, 3 cmp al, uvector-simple-char-vector-tag je :t2 mov edx, [edx + (uvector-offset cl::adjustable-array-vector-offset)] :t2 mov ecx, [ebp - 4] ; get string length ;; add ecx, (* 3 8) shr ecx, 3 ;ecx = number of chars to copy ;; unicode mod ;; shr ecx, 5 ;ecx = number of words to copy xor ebx, ebx xor eax, eax jmp :t1 :loop mov ax, [edx + ebx*2 + (uvector-offset 2)] ;; unicode mod ;; mov eax, [edx + ebx*4 + (uvector-offset 2)] mov [edi + ebx], al ;; unicode mod ;; mov [edi + ebx*4], eax inc ebx :t1 dec ecx jge :loop ;; null terminate the c string mov ecx, [ebp - 4] ; get string length shr ecx, 3 xor eax, eax mov [edi + ecx], al pop eax ; eax = c-string handle mov ecx, 1 pop edi pop ebx add esp, 4 pop ebp ret }) (defun create-c-string (string) (if (or (foreignp string)(cl::foreign-heap-p string)) string (if (stringp string) (%create-c-string string) (error "Cannot convert ~A to a C string" string)))) (defasm c-string-to-lisp-string (c-string) { push ebp mov ebp, esp mov eax, [ebp + ARGS_OFFSET] push [eax + (uvector-offset foreign-heap-ptr-offset)] callp cl::%stringNode add esp, 4 mov ecx, 1 pop ebp ret }) (defasm create-c-long (fixnum) { push ebp mov ebp, esp push ebx push edi push 32 mov ecx, 1 callf allocate-c-heap ;eax = c-string handle add esp, 4 push eax mov edi, [eax + (uvector-offset foreign-heap-ptr-offset)] ;edi = pointer to c-long address mov edx, [ebp + ARGS_OFFSET] ;edx = integer mov [edi], edx pop eax ; eax = c-string handle mov ecx, 1 pop edi pop ebx pop ebp ret }) (defasm c-string-length (c-string) { push ebp mov ebp, esp cmp ecx, 1 jz short :t1 callp _wrong-number-of-args-error :t1 mov edx, [ebp + ARGS_OFFSET] ;; edx = argument mov edx, [edx - 1] ;; edx = foreign pointer xor eax, eax and edx, edx jz :done xor ecx, ecx :t2 cmp [edx], cl jz short :done inc eax inc edx jmp short :t2 :done shl eax, 3 inc ecx pop ebp ret }) ;;;; ;;;; Corman Lisp kernel FOREIGNP function. ;;;; (defasm foreignp (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 mov eax, [esi] jne short :next2 mov edx, [edx - uvector-tag] cmp dl, (tag-byte uvector-foreign-tag) jne short :next2 mov eax, [esi + t-offset] :next2 pop ebp ret }) ;;;; ;;;; Corman Lisp kernel FOREIGN-HEAP-P function. ;;;; (defasm foreign-heap-p (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 mov eax, [esi] jne short :next2 mov edx, [edx - uvector-tag] cmp dl, (tag-byte uvector-foreign-heap-tag) jne short :next2 mov eax, [esi + t-offset] :next2 pop ebp ret }) (defun foreign-heap-length (x) (unless (cl::foreign-heap-p x) (cl::signal-type-error x 'cl::foreign-heap)) (uref x cl::foreign-heap-length-offset)) (defun unlink-dll-function (dll-func-rec) (install-dynamic-foreign-function (foreign-function-record-dll-name dll-func-rec) (foreign-function-record-foreign-name dll-func-rec) (foreign-function-record-lisp-sym dll-func-rec))) (defun unlink-dll (dll-rec) (let ((func-recs (dll-record-function-records dll-rec))) (dolist (r func-recs) (unlink-dll-function r)) (unload-dll (dll-record-handle dll-rec)) (setq *dlls-loaded* (remove dll-rec *dlls-loaded*)))) (defun unlink-all-dll-functions () (dolist (rec *dlls-loaded*) (unlink-dll rec)) (cl::clear-foreign-jump-table)) (cl::register-save-image-cleanup-func #'unlink-all-dll-functions) (let ((ctype-table (make-hash-table))) (defun ctype-install-alias (name ctype) (setf (gethash name ctype-table) ctype)) (defun ctype-lookup-alias (name) (gethash name ctype-table))) (defmacro defctype (name ctype) (let ((sym (gensym))) `(progn (unless (valid-c-type-definition ',ctype) (error "Invalid C type specifier: ~S" ',ctype)) (let ((,sym (ctypeexpand-all ',ctype))) (unless ,sym (error "Invalid C type: ~S" ',ctype)) (ctype-install-alias ',name ,sym)) ',name))) (defun ctypeexpand (x) (if (symbolp x) (let ((type (ctype-lookup-alias x))) (if type type x)) x)) (defun ctypeexpand-all (x) (if (symbolp x) (let ((type (ctype-lookup-alias x))) (return-from ctypeexpand-all (if type type x)))) (unless (consp x) (return-from ctypeexpand-all x)) (if (eq (car x) ':struct) (do ((p (cdr x)(cddr p))) ((null p) x) (setf (cadr p) (ctypeexpand-all (cadr p)))) (if (or (eq (cadr x) '*) (fixnump (cadr x)) (and (constantp (cadr x)) (fixnump (symbol-value (cadr x))))) (setf (car x) (ctypeexpand-all (car x))) (error "Invalid C type specifier: ~S" x))) x) (defun determine-coerce-type (specifier) (if (symbolp specifier) (ecase specifier ((:short :long :char) :integer) ((:unsigned-short :unsigned-long :unsigned-char) :unsigned-integer) ((:single-float) :single-float) ((:double-float) :double-float) ((:short-bool :long-bool) :bool) ((:wide-char) :wide-char) (:handle :pointer)) (if (eq (cadr specifier) '*) :pointer :reference))) ;;; ;;; cstruct-slot-info ;;; Returns 3 values: ;;; offset into c-struct ;;; size in bytes of result ;;; how to interpret the result (:integer, ;;; :unsigned-integer, :float, :bool, ;;; :pointer, :reference or :wide-char) ;;; (defun cstruct-slot-info (specifier access) (let ((position 0) slot-type size coerce) (do ((p (cdr specifier)(cddr p))) ((null p)(error "Cannot access C type ~A with access ~A" specifier access)) (when (eq (car p) access) (setq slot-type (cadr p)) (return)) (incf position (determine-c-type-size (cadr p)))) (setq coerce (determine-coerce-type slot-type)) (setq size (determine-c-type-size slot-type)) (values position size coerce))) (defun cstruct-definition-p (descriptor) (and (consp descriptor) (eq (car descriptor) ':struct))) (defun carray-definition-p (descriptor) (and (consp descriptor) (or (fixnump (cadr descriptor)) (and (constantp (cadr descriptor)) (fixnump (symbol-value (cadr descriptor))))))) (defun cpointer-definition-p (descriptor) (and (consp descriptor) (eq (cadr descriptor) '*))) (defun struct-cref-expand (ctype object access value-object value-type) (unless (symbolp access) (error "Cannot access C structure with access ~A" access)) (multiple-value-bind (offset size coerce) (cstruct-slot-info ctype access) `(%cref ,object ,offset ,size ,coerce ,value-object ,value-type))) (defun struct-set-cref-expand (value ctype object access) (unless (symbolp access) (error "Cannot access C structure with access ~A" access)) (multiple-value-bind (offset size coerce) (cstruct-slot-info ctype access) `(%set-cref ,object ,offset ,size ,coerce ,value))) (defun array-cref-expand (ctype object access value-object value-type) (if (eq access '*) (setq access 0)) (let ((size (determine-c-type-size (car ctype)))) `(%cref ,object (* ,access ,size) ,size ,(determine-coerce-type (car ctype)) ,value-object ,value-type))) (defun array-set-cref-expand (value ctype object access) (if (eq access '*) (setq access 0)) (let ((size (determine-c-type-size (car ctype)))) `(%set-cref ,object (* ,access ,size) ,size ,(determine-coerce-type (car ctype)) ,value))) (defmacro cref (ctype object access &optional value-object value-type alt-value-object) (declare (ignore alt-value-object)) (setq ctype (ctypeexpand-all ctype)) (unless (valid-c-type-definition ctype) (error "Invalid C type specifier: ~S" ctype)) (cond ((cstruct-definition-p ctype) (struct-cref-expand ctype object access value-object value-type)) ((carray-definition-p ctype) (array-cref-expand ctype object access value-object value-type)) ((cpointer-definition-p ctype) (array-cref-expand ctype object access value-object value-type)) (t (error "Cannot access C type ~A using CREF" ctype)))) (defmacro (setf cref) (value ctype object access) (setq ctype (ctypeexpand-all ctype)) (unless (valid-c-type-definition ctype) (error "Invalid C type specifier: ~S" ctype)) (cond ((cstruct-definition-p ctype) (struct-set-cref-expand value ctype object access)) ((carray-definition-p ctype) (array-set-cref-expand value ctype object access)) ((cpointer-definition-p ctype) (array-set-cref-expand value ctype object access)) (t (error "Cannot access C type ~A using CREF" ctype)))) (defmacro defcstruct (name params) (let ((args nil)) (dolist (p params) (unless (and (= (length p) 2) (symbolp (car p))) (error "Invalid C structure definition: ~S" params)) (push (car p) args) (push (cadr p) args)) `(defctype ,name ,(cons ':struct (nreverse args))))) (in-package :x86) ;; the arguments should each be fixnums < #x10000, tagged (defasm %create-positive-bignum (low-16 high-16) { push ebp mov ebp, esp push 8 ;; tagged fixnum 1 mov ecx, 1 callp cl::alloc-bignum add esp, 4 mov edx, [ebp + (+ ARGS_OFFSET 4)] shr edx, 3 mov [eax + (uvector-offset cl::bignum-first-cell-offset)], edx mov edx, [ebp + (+ ARGS_OFFSET 0)] shl edx, 13 or [eax + (uvector-offset cl::bignum-first-cell-offset)], edx mov ecx, 1 pop ebp ret }) (defasm %create-negative-bignum (low-16 high-16) { push ebp mov ebp, esp push 8 ;; tagged fixnum 1 mov ecx, 1 callp cl::alloc-bignum add esp, 4 mov edx, [ebp + (+ ARGS_OFFSET 4)] begin-atomic shr edx, 3 mov ecx, [ebp + (+ ARGS_OFFSET 0)] shl ecx, 13 or edx, ecx neg edx mov [eax + (uvector-offset cl::bignum-first-cell-offset)], edx mov edx, [eax + (uvector-offset 1)] end-atomic or edx, 8 ;; set sign bit mov [eax + (uvector-offset 1)], edx mov ecx, 1 pop ebp ret }) (defcodegen ct::%cref (form dest) (let ((obj (second form)) (position (third form)) (bytes (fourth form)) (coerce (fifth form)) (value-object (sixth form)) (value-type (seventh form))) (declare (ignore value-object value-type)) (cl::compile-sub-form obj :dest-stack t) (cl::compile-sub-form position :dest-eax-operand t) ;; make sure the offset is a fixnum (parse-assembler { test al, 7 jz short :t1 push "Invalid index, expected a fixnum: ~A" push eax mov ecx, 2 callf error :t1 mov ecx, eax pop edx mov edx, [edx + (uvector-offset foreign-heap-ptr-offset)] }) (x86::offset-stack 4) ;; at this point ecx is the tagged offset (in bytes) and ;; edx is the untagged pointer into a foreign heap. EDX is not tagged but ;; this should not matter, as it should not be a pointer into the lisp heap. ;; (ecase coerce (:integer (case bytes (1 (parse-assembler { xor eax, eax begin-atomic sar ecx, 3 mov al, [edx + ecx] xor ecx, ecx end-atomic shl eax, 24 sar eax, 21 })) (2 (parse-assembler { xor eax, eax begin-atomic sar ecx, 3 mov ax, [edx + ecx] xor ecx, ecx end-atomic shl eax, 16 sar eax, 13 })) (4 (parse-assembler { begin-atomic sar ecx, 3 mov eax, [edx + ecx] xor ecx, ecx cmp eax, most-positive-fixnum jg :pos-bignum cmp eax, most-negative-fixnum jl :neg-bignum shl eax, 3 end-atomic jmp short :next :pos-bignum mov ecx, eax shr ecx, 16 shl ecx, 3 shl eax, 16 shr eax, 13 ;; eax = low 16 bits, ecx = high 16 bits end-atomic push eax push ecx callp %create-positive-bignum add esp, 8 jmp short :next :neg-bignum mov ecx, eax shr ecx, 16 shl ecx, 3 shl eax, 16 shr eax, 13 ;; eax = low 16 bits, ecx = high 16 bits end-atomic push eax push ecx callp %create-negative-bignum add esp, 8 :next })))) (:unsigned-integer (case bytes (1 (parse-assembler { xor eax, eax begin-atomic sar ecx, 3 mov al, [edx + ecx] xor ecx, ecx end-atomic shl eax, 24 shr eax, 21 })) (2 (parse-assembler { xor eax, eax begin-atomic sar ecx, 3 mov ax, [edx + ecx] xor ecx, ecx end-atomic shl eax, 16 shr eax, 13 })) (4 (parse-assembler { begin-atomic sar ecx, 3 mov eax, [edx + ecx] xor ecx, ecx cmp eax, most-positive-fixnum ja :bignum shl eax, 3 end-atomic jmp short :next :bignum mov ecx, eax shr ecx, 16 shl ecx, 3 shl eax, 16 shr eax, 13 ;; eax = low 16 bits, ecx = high 16 bits end-atomic push eax push ecx callp %create-positive-bignum add esp, 8 :next })))) (:pointer (parse-assembler { push ecx push edx xor ecx, ecx callp ct:create-foreign-ptr pop edx pop ecx begin-atomic sar ecx, 3 mov edx, [edx + ecx] mov [eax + (uvector-offset cl::foreign-heap-ptr-offset)], edx xor ecx, ecx xor edx, edx end-atomic })) (:single-float (parse-assembler { begin-atomic shr ecx, 3 fld.single [edx + ecx] xor ecx, ecx end-atomic push 0 push 0 callp cl::%single-float-node add esp, 8 fstp.single [eax + (uvector-offset cl::single-float-offset)] })) (:double-float (parse-assembler { begin-atomic shr ecx, 3 fld [edx + ecx] xor ecx, ecx end-atomic push 0 push 0 callp cl::%double-float-node add esp, 8 fstp [eax + (uvector-offset cl::double-float-offset)] })) (:wide-char (parse-assembler { xor eax, eax begin-atomic shr ecx, 3 mov ax, [edx + ecx] xor ecx, ecx end-atomic shl eax, 8 inc eax })) (:reference (parse-assembler { push ecx push edx xor ecx, ecx callp ct:create-foreign-ptr pop edx pop ecx begin-atomic shr ecx, 3 lea edx, [edx + ecx] mov [eax + (uvector-offset cl::foreign-heap-ptr-offset)], edx xor ecx, ecx end-atomic }))) (if (eq dest :dest-stack) (progn (parse-assembler { push eax }) (x86::offset-stack -4)) (parse-assembler { mov ecx, 1 }))) t) (defcodegen ct::%set-cref (form dest) (let ((obj (second form)) (position (third form)) (bytes (fourth form)) (coerce (fifth form)) (value (sixth form))) (cl::compile-sub-form value :dest-stack t) (cl::compile-sub-form obj :dest-stack t) (cl::compile-sub-form position :dest-eax-operand t) ;; make sure the offset is a fixnum (parse-assembler { test al, 7 jz short :t1 push "Invalid index, expected a fixnum: ~A" push eax mov ecx, 2 callf error :t1 shr eax, 3 pop edx ;; edx = obj mov edx, [edx + (uvector-offset foreign-heap-ptr-offset)] ;; edx = c object address add edx, eax ;; edx = target address of store operation pop eax ;; eax = value push eax ;; save value }) (x86::offset-stack 4) (ecase coerce (:integer (case bytes (1 (parse-assembler { push edx callp %get-long-safe ;; get low 16 bits in ax pop edx mov [edx], al })) (2 (parse-assembler { push edx callp %get-long-safe ;; get low 16 bits in ax pop edx mov [edx], ax })) (4 (parse-assembler { push edx callp %get-long-safe ;; get low 16 bits in ax, high bits in dx mov ecx, edx pop edx mov [edx], ax mov [edx + 2], cx })))) (:unsigned-integer (case bytes (1 (parse-assembler { push edx callp %get-unsigned-long-safe ;; get low 16 bits in ax pop edx mov [edx], al })) (2 (parse-assembler { push edx callp %get-unsigned-long-safe ;; get low 16 bits in ax pop edx mov [edx], ax })) (4 (parse-assembler { push edx callp %get-unsigned-long-safe ;; get low 16 bits in ax mov ecx, edx pop edx mov [edx], ax mov [edx + 2], cx })))) (:single-float (parse-assembler { push edx mov edx, eax and edx, 7 cmp edx, uvector-tag je short :t1 :err push "Not a :single-float: ~S" push eax mov ecx, 2 callf error :t1 mov edx, [eax - uvector-tag] shr dl, 3 cmp dl, cl::uvector-single-float-tag jne :err :t2 fld.single [eax + (uvector-offset cl::single-float-offset)] pop edx fstp.single [edx] })) (:double-float (parse-assembler { push edx mov edx, eax and edx, 7 cmp edx, uvector-tag je short :t1 :err push "Not a :double-float: ~S" push eax mov ecx, 2 callf error :t1 mov edx, [eax - uvector-tag] shr dl, 3 cmp dl, cl::uvector-double-float-tag jne :err :t2 pop edx fld [eax + (uvector-offset cl::double-float-offset)] fstp [edx] })) (:wide-char (parse-assembler { cmp al, 1 je short :t1 :err push "Not a character: ~S" push eax mov ecx, 2 callf error :t1 shl eax, 8 shr eax, 16 mov [edx], ax })) (:pointer (parse-assembler { mov eax, [eax + (uvector-offset cl::foreign-heap-ptr-offset)] mov [edx], eax }))) (unless (eq dest :dest-stack) (progn (parse-assembler { pop eax mov ecx, 1 }) (x86::offset-stack 4)))) t) (in-package :c-types) (pl:defasm cpointer-value (cpointer) { push ebp mov ebp, esp cmp ecx, 1 jz short :t1 callp _wrong-number-of-args-error :t1 mov edx, [ebp + ARGS_OFFSET] ;; edx = argument ;; check type mov eax, edx and eax, 7 cmp eax, uvector-tag jne short :type-error mov eax, [edx - uvector-tag] cmp al, (tag-byte uvector-foreign-tag) je :next1 cmp al, (tag-byte uvector-foreign-heap-tag) je :next1 :type-error push edx callp ct::foreign-type-error :next1 begin-atomic mov eax, [edx + (uvector-offset cl::foreign-heap-ptr-offset)] ;; untagged pointer in eax ;; probably safe, but we'll be careful anyway cmp eax, most-positive-fixnum ja :bignum shl eax, 3 end-atomic jmp short :next :bignum mov ecx, eax shr ecx, 16 shl ecx, 3 shl eax, 16 shr eax, 13 ;; eax = low 16 bits, ecx = high 16 bits end-atomic push eax push ecx callp %create-positive-bignum add esp, 8 :next mov ecx, 1 pop ebp ret }) (pl:defasm |SETF CPOINTER-VALUE| (value cpointer) { push ebp mov ebp, esp cmp ecx, 2 jz short :t1 callp _wrong-number-of-args-error :t1 mov edx, [ebp + ARGS_OFFSET] ;; edx = cpointer ;; check type mov eax, edx and eax, 7 cmp eax, uvector-tag jne short :type-error mov eax, [edx - uvector-tag] cmp al, (tag-byte uvector-foreign-tag) je :next1 cmp al, (tag-byte uvector-foreign-heap-tag) je :next1 :type-error push edx callp ct::foreign-type-error :next1 mov eax, [ebp + (+ ARGS_OFFSET 4)] ;; eax = number test eax, 7 jnz short :t2 mov ecx, eax shr ecx, 3 mov [edx + (uvector-offset cl::foreign-heap-ptr-offset)], ecx jmp short :t4 :t2 mov ecx, eax and ecx, 7 cmp ecx, uvector-tag jne short :err mov ecx, [eax - uvector-tag] shr cl, 3 cmp cl, uvector-bignum-tag jne short :err mov ecx, [eax + (uvector-offset cl::bignum-first-cell-offset)] mov [edx + (uvector-offset cl::foreign-heap-ptr-offset)], ecx jmp short :t4 :err push "Invalid cpointer value: ~A" push eax mov ecx, 2 callf error :t4 mov ecx, 1 pop ebp ret }) (cl::register-setf-function 'cpointer-value '|SETF CPOINTER-VALUE|) (defun cpointer= (cp1 cp2) (= (cpointer-value cp1)(cpointer-value cp2))) (defun cpointer-null (cp) (declare (special ct:null)) (cpointer= cp ct:null)) ;;; ;;; CormanLisp FOREIGN-PTR-TO-INT function. ;;; (defun foreign-ptr-to-int (p) (cpointer-value p)) ;;; ;;; CormanLisp INT-TO-FOREIGN-PTR function. ;;; (defun int-to-foreign-ptr (i) (if (< i 0) (setf i (+ i #x100000000))) (let ((p (create-foreign-ptr))) (setf (cpointer-value p) i) p)) (defun sizeof (c-type-specifier) (determine-c-type-size c-type-specifier)) (defun offsetof (c-type-specifier struct-field) (values (ct::cstruct-slot-info (ct::ctypeexpand-all c-type-specifier) struct-field))) (defun valid-callback-arg-type (ctype) (setq ctype (ctypeexpand-all ctype)) (if (member ctype simple-c-types) t (and (consp ctype) (consp (cdr ctype)) (valid-callback-arg-type (first ctype)) (or (integerp (second ctype))(eq (second ctype) '*))))) ;;; We only execute the following macro for its side effects (defmacro ensure-func-table-entry (symbol) (if (zerop (uref symbol cl::symbol-jump-table-offset)) (cl::%create-func-table-entry symbol)) nil) ;;; ;;; Redefine Common Lisp MULTIPLE-VALUE-BIND macro to ;;; make the VALUE-FORM be evaluated in the correct lexical context. ;;; From PI:NAME:<NAME>END_PI. ;;; (defmacro cl::multiple-value-bind (vars value-form &rest forms) (let ((declarations nil)) ;; look for declarations (do* ((f forms (cdr f))) ((null f) (setq forms f)) (if (and (consp (car f)) (eq (caar f) 'declare)) (push (car f) declarations) (progn (setq forms f) (return)))) (let* ((gensyms (mapcar #'(lambda (x) (gensym (symbol-name x))) vars)) (bindings (mapcar #'list vars gensyms))) `(let ,gensyms (multiple-value-setq ,gensyms ,value-form) (let ,bindings ,@(nreverse declarations) ,@forms))))) (defmacro define-callback-func (name arg-list body &key (linkage :c) (create-heap-handler nil)) (declare (ignore create-heap-handler)) (let* ((syms nil) (lisp-func nil) (foreign-func nil) (arg-conversion-forms nil) internal-name (docstring nil) (num-args (length arg-list)) (sym-t1 (gensym))) (dolist (x arg-list) (unless (and (listp x) (= (length x) 2) (valid-callback-arg-type (second x))) (error "Invalid argument specification in DEFUN-CALLBACK form: ~A" x)) (push (first x) syms)) (setq syms (nreverse syms)) (setq internal-name (intern (concatenate 'string "%" (symbol-name name) "-internal"))) (multiple-value-bind (doc decls body bad-decls) (cl::parse-doc-decls-body body) (declare (ignore doc)) (when bad-decls (error "Declarations found in body of callback")) (setq lisp-func `(defun ,internal-name ,syms (let () (cl::%safecall #'(lambda () ,@decls (block ,name ,@body)))))) (setq docstring doc)) (let ((param-offset 0)) (dolist (x arg-list) (let ((arg-type (ctypeexpand-all (second x)))) (cond ((eq arg-type :char) (push `(x86::push-signed-char-lisp-arg ,param-offset) arg-conversion-forms)) ((eq arg-type :unsigned-char) (push `(x86::push-unsigned-char-lisp-arg ,param-offset) arg-conversion-forms)) ((eq arg-type :short) (push `(x86::push-signed-short-lisp-arg ,param-offset) arg-conversion-forms)) ((eq arg-type :unsigned-short) (push `(x86::push-unsigned-short-lisp-arg ,param-offset) arg-conversion-forms)) ((eq arg-type :wide-char) (push `(x86::push-wide-char-lisp-arg ,param-offset) arg-conversion-forms)) ((eq arg-type :long) (push `(x86::push-signed-long-lisp-arg ,param-offset) arg-conversion-forms)) ((eq arg-type :unsigned-long) (push `(x86::push-unsigned-long-lisp-arg ,param-offset) arg-conversion-forms)) ((eq arg-type :short-bool) (push `(x86::push-short-bool-lisp-arg ,param-offset) arg-conversion-forms)) ((eq arg-type :long-bool) (push `(x86::push-long-bool-lisp-arg ,param-offset) arg-conversion-forms)) ; ((eq arg-type :handle) ; (push `(x86::push-long-handle-lisp-arg ,param-offset) arg-conversion-forms)) ((eq arg-type :single-float) (push `(x86::push-single-float-lisp-arg ,param-offset) arg-conversion-forms)) ((eq arg-type :double-float) (push `(x86::push-double-float-lisp-arg ,param-offset) arg-conversion-forms) (incf param-offset 4)) ((eq arg-type :int64) (push `(x86::push-int64-lisp-arg ,param-offset) arg-conversion-forms) (incf param-offset 4)) ((eq arg-type :uint64) (push `(x86::push-uint64-lisp-arg ,param-offset) arg-conversion-forms) (incf param-offset 4)) (t (push `(x86::push-pointer-lisp-arg ,param-offset) arg-conversion-forms)))) (incf param-offset 4)) (setq foreign-func `(defun ,name ,syms ,@(when docstring (list docstring)) (declare (optimize (speed 3)(safety 0))) ; disable arg checking (declare (ignore ,@syms)) ; disable "unused variable" warnings (x86::setup-lisp-registers) (x86::push-lisp-stack-context) (x86::link-heap-handler) ;,@(if create-heap-handler ; `((x86::link-heap-handler))) ,@(nreverse arg-conversion-forms) (x86::mov-ecx-num ,num-args) (x86::call-lisp-proc ,internal-name) (x86::pop-lisp-args ,num-args) (x86::return-lisp-val-as-c) (x86::unlink-heap-handler) ;,@(if create-heap-handler ; `((x86::unlink-heap-handler))) (x86::pop-lisp-stack-context) (x86::copy-foreign-return-val-to-eax) (x86::restore-c-registers) ,@(if (eq linkage :pascal) `((x86::return-from-pascal ,num-args))))) `(let ((,sym-t1 (cl::create-callback-thunk ',name))) (setf (get ',name 'ct::callback-thunk) ,sym-t1) (ensure-func-table-entry ,internal-name) ;; make sure there is a jump entry ,lisp-func ;; define lisp function ,foreign-func)))) ;; define foreign function (defvar *collect-exported-functions* nil) ;; used by COMPILE-FILE and COMPILE-DLL (defvar *callback-registry* (make-hash-table :test #'equal :synchronized t)) ;; maps strings to callback symbols (defmacro defun-callback (name arg-list &rest body) `(define-callback-func ,name ,arg-list ,body :linkage :pascal)) (defmacro defun-c-callback (name arg-list &rest body) `(define-callback-func ,name ,arg-list ,body :linkage :c)) (defmacro defun-direct-callback (name arg-list &rest body) `(define-callback-func ,name ,arg-list ,body :linkage :pascal :create-heap-handler t)) (defmacro defun-direct-c-callback (name arg-list &rest body) `(define-callback-func ,name ,arg-list ,body :linkage :c :create-heap-handler t)) (defun defun-dll-export-body (name arg-list body linkage) (let ((prototype nil) (sym name)) (when (stringp (first body)) (setf prototype (first body)) (setf body (cdr body))) (when (consp name) ;; map export string name to symbol (setf (gethash (cadr name) *callback-registry*) (car name)) (setf sym (car name))) `(eval-when (:execute :load-toplevel :compile-toplevel) ,@(if (consp name) `((setf (gethash ',(cadr name) *callback-registry*) ',(car name))) nil) (if *collect-exported-functions* (vector-push-extend ',(list name prototype) *collect-exported-functions*)) (define-callback-func ,sym ,arg-list ,body :linkage ,linkage :create-heap-handler t)))) (defmacro defun-dll-export-function (name arg-list &rest body) (defun-dll-export-body name arg-list body ':pascal)) (defmacro defun-dll-export-c-function (name arg-list &rest body) (defun-dll-export-body name arg-list body ':c)) ;;; support code generation operators for defun-callback macro (in-package :x86) (defcodegen setup-lisp-registers (form dest) (declare (ignore form dest)) (parse-assembler { push esi push edi push ebx mov eax, 'cl::%load-qv-reg mov eax, [eax + (uvector-offset symbol-function-offset)] ; get function binding mov eax, [eax - cons-tag] call [eax + (uvector-offset function-code-buffer-offset)] }) t) (defcodegen restore-c-registers (form dest) (declare (ignore form dest)) (parse-assembler { pop ebx pop edi pop esi }) t) (defcodegen call-lisp-proc (form dest) (declare (ignore dest)) (let* ((sym (second form)) (env-offset (* (uref sym symbol-jump-table-offset) 4)) (jump-offset (+ env-offset 4))) (if (zerop env-offset) (error "The function ~A does not have a jump table offset and cannot be called" sym)) (parse-assembler { mov edi, [esi + env-offset] add-env-table-ref sym call [esi + jump-offset] add-jump-table-ref sym })) t) (defcodegen pop-lisp-args (form dest) (declare (ignore dest)) (let* ((numargs (second form)) (bytes (* 4 numargs))) (parse-assembler { add esp, bytes })) t) (defcodegen return-lisp-val-as-c (form dest) (declare (ignore form dest)) (parse-assembler { mov ecx, eax and ecx, 7 ;; if fixnum, return that jnz short :t2 cmp eax, 0 jl short :neg-integer mov ecx, -1 callp x86::%get-foreign-unsigned-long jmp :exit :neg-integer mov ecx, -1 callp x86::%get-foreign-long jmp :exit :t2 cmp al, 1 je :char cmp ecx, uvector-tag jne :t3 ;; not handling return of short floats from callback yet mov cl, [eax - uvector-tag] shr cl, 3 cmp cl, uvector-bignum-tag jne short :t7 mov cl, [eax + (uvector-offset 1)] and cl, 8 ;; negative bignum? jnz short :neg-bignum mov ecx, -1 callp x86::%get-foreign-unsigned-long jmp short :exit :neg-bignum mov ecx, -1 callp x86::%get-foreign-long jmp short :exit :t7 cmp cl, uvector-foreign-tag jne short :t4 begin-atomic mov eax, [eax + (uvector-offset foreign-heap-ptr-offset)] mov [esi + (- (* foreign-cells-qv-tos 4) 4)], eax xor eax, eax end-atomic jmp short :exit :t4 cmp cl, uvector-foreign-heap-tag jne short :t5 begin-atomic mov eax, [eax + (uvector-offset foreign-heap-ptr-offset)] mov [esi + (- (* foreign-cells-qv-tos 4) 4)], eax xor eax, eax end-atomic jmp short :exit :t5 cmp cl, uvector-double-float-tag jne short :t6 fld [eax + (uvector-offset cl::double-float-offset)] ;; store 0 in eax, in case caller is not expecting a float they will get that mov eax, 0 mov [esi + (- (* foreign-cells-qv-tos 4) 4)], eax jmp short :exit :t6 cmp cl, uvector-single-float-tag jne short :t3 fld.single [eax + (uvector-offset cl::single-float-offset)] ;; store 0 in eax, in case caller is not expecting a float they will get that mov eax, 0 mov [esi + (- (* foreign-cells-qv-tos 4) 4)], eax jmp short :exit :char shl eax, 8 shr eax, 16 jmp short :exit :t3 xor eax, eax :exit }) t) (defcodegen copy-foreign-return-val-to-eax (form dest) (declare (ignore form dest)) (parse-assembler { mov eax, [esi + (- (* foreign-cells-qv-tos 4) 4)] }) t) (defcodegen push-signed-char-lisp-arg (form dest) (declare (ignore dest)) (let ((offset (+ ARGS_OFFSET (second form)))) (parse-assembler { xor eax, eax mov al, [ebp + offset] shl eax, 24 sar eax, 21 push eax })) t) (defcodegen push-unsigned-char-lisp-arg (form dest) (declare (ignore dest)) (let ((offset (+ ARGS_OFFSET (second form)))) (parse-assembler { xor eax, eax mov al, [ebp + offset] shl eax, 24 shr eax, 21 push eax })) t) (defcodegen push-signed-short-lisp-arg (form dest) (declare (ignore dest)) (let ((offset (+ ARGS_OFFSET (second form)))) (parse-assembler { xor eax, eax mov ax, [ebp + offset] shl eax, 16 sar eax, 13 push eax })) t) (defcodegen push-unsigned-short-lisp-arg (form dest) (declare (ignore dest)) (let ((offset (+ ARGS_OFFSET (second form)))) (parse-assembler { xor eax, eax mov ax, [ebp + offset] shl eax, 16 shr eax, 13 push eax })) t) (defcodegen push-wide-char-lisp-arg (form dest) (declare (ignore dest)) (let ((offset (+ ARGS_OFFSET (second form)))) (parse-assembler { xor eax, eax mov ax, [ebp + offset] shl eax, 8 inc eax push eax })) t) (defcodegen push-signed-long-lisp-arg (form dest) (declare (ignore dest)) (let ((offset (+ ARGS_OFFSET (second form)))) (parse-assembler { ;; top cell gets converted into Lisp integer in eax begin-atomic mov eax, [ebp + offset] cmp eax, cl::most-positive-fixnum jg short :bignum cmp eax, cl::most-negative-fixnum jl short :bignum shl eax, 3 jmp short :done :bignum xor eax, eax end-atomic push (* 8 1) ;; wrapped integer 1 callp cl::alloc-bignum add esp, 4 begin-atomic mov edx, [ebp + offset] cmp edx, 0 jge :next1 neg edx mov [eax + (uvector-offset 2)], edx mov edx, [eax + (uvector-offset 1)] xor edx, 8 mov [eax + (uvector-offset 1)], edx jmp short :done :next1 mov [eax + (uvector-offset 2)], edx :done end-atomic push eax })) t) (defcodegen push-unsigned-long-lisp-arg (form dest) (declare (ignore dest)) (let ((offset (+ ARGS_OFFSET (second form)))) (parse-assembler { ;; carefully copy DWORD to foreign region of QV (top cell) begin-atomic mov eax, [ebp + offset] mov [esi + (- (* foreign-cells-qv-tos 4) 4)], eax xor eax, eax end-atomic ;; top cell gets converted into Lisp integer in eax push (* 8 -1) callp x86::create-foreign-lisp-unsigned-integer add esp, 4 push eax })) t) (defcodegen push-int64-lisp-arg (form dest) (declare (ignore dest)) (let ((offset (+ ARGS_OFFSET (second form)))) (parse-assembler { ;; carefully copy Int64 to foreign region of QV (top cell) begin-atomic mov eax, [ebp + offset] mov [esi + (- (* foreign-cells-qv-tos 4) 8)], eax mov eax, [ebp + (+ offset 4)] mov [esi + (- (* foreign-cells-qv-tos 4) 4)], eax xor eax, eax end-atomic ;; top 2 cells gets converted into Lisp integer in eax push (* 8 -2) callp x86::create-foreign-lisp-int64 add esp, 4 push eax })) t) (defcodegen push-uint64-lisp-arg (form dest) (declare (ignore dest)) (let ((offset (+ ARGS_OFFSET (second form)))) (parse-assembler { ;; carefully copy UInt64 to foreign region of QV (top cell) begin-atomic mov eax, [ebp + offset] mov [esi + (- (* foreign-cells-qv-tos 4) 8)], eax mov eax, [ebp + (+ offset 4)] mov [esi + (- (* foreign-cells-qv-tos 4) 4)], eax xor eax, eax end-atomic ;; top cell gets converted into Lisp integer in eax push (* 8 -2) callp x86::create-foreign-lisp-uint64 add esp, 4 push eax })) t) (defcodegen push-single-float-lisp-arg (form dest) (declare (ignore dest)) (let ((offset (+ ARGS_OFFSET (second form)))) (parse-assembler { mov ecx, 0 callf cl::alloc-single-float fld.single [ebp + offset] fstp.single [eax + (uvector-offset cl::single-float-offset)] push eax })) t) (defcodegen push-double-float-lisp-arg (form dest) (declare (ignore dest)) (let ((offset (+ ARGS_OFFSET (second form)))) (parse-assembler { mov ecx, 0 callf cl::alloc-double-float fld [ebp + offset] fstp [eax + (uvector-offset cl::double-float-offset)] push eax })) t) (defcodegen push-pointer-lisp-arg (form dest) (declare (ignore dest)) (let ((offset (+ ARGS_OFFSET (second form)))) (parse-assembler { xor ecx, ecx callf ct::create-foreign-ptr begin-atomic mov ecx, [ebp + offset] mov [eax + (uvector-offset cl::foreign-heap-ptr-offset)], ecx xor ecx, ecx end-atomic push eax })) t) (defcodegen return-from-pascal (form dest) (declare (ignore dest)) (let ((numbytes (* (second form) 4))) (parse-assembler { mov esp, ebp pop ebp ret numbytes })) t) (ct::ensure-func-table-entry create-foreign-ptr) (defun ct::get-callback-procinst (callback-func-sym) (when (stringp callback-func-sym) (setf callback-func-sym (gethash callback-func-sym ct::*callback-registry*))) (if (null callback-func-sym) (return-from ct::get-callback-procinst nil)) (get callback-func-sym 'ct::callback-thunk)) ;; This function gets accessed via the COM interface from ;; foreign threads. (defun cl::get-callback (name) (ct::get-callback-procinst name)) ;;; ;;; CormanLisp CPOINTERP function. ;;; (defasm ct::cpointerp (p) { push ebp mov ebp, esp cmp ecx, 1 jz short :t1 callp _wrong-number-of-args-error :t1 mov eax, [ebp + ARGS_OFFSET] ;eax = p mov edx, eax and edx, 7 cmp edx, uvector-tag jne short :not-foreign mov dl, [eax - uvector-tag] shr dl, 3 cmp dl, uvector-foreign-tag je short :is-foreign cmp dl, uvector-foreign-heap-tag je short :is-foreign cmp dl, uvector-foreign-stack-tag je short :is-foreign jmp short :not-foreign :is-foreign mov eax, [esi + t-offset] jmp short :exit :not-foreign mov eax, [esi] :exit pop ebp ret }) (defun ct::foreign-stack-p (x) (and (uvectorp x)(eq (cl::uvector-type-bits x) uvector-foreign-stack-tag))) (defasm ct::%memcmp (cp1 cp2 count) { push ebp mov ebp, esp push esi push edi mov esi, [ebp + (+ ARGS_OFFSET 8)] ;; esi = cp1 mov edi, [ebp + (+ ARGS_OFFSET 4)] ;; edi = cp2 mov ecx, [ebp + (+ ARGS_OFFSET 0)] ;; ecx = count shr ecx, 3 ;; ecx = unwrapped count :loop1 cmp ecx, 3 jle short :loop2 mov eax, [esi] cmp eax, [edi] jne :diff add esi, 4 add edi, 4 sub ecx, 4 jmp short :loop1 :loop2 cmp ecx, 0 je short :same mov al, [esi] cmp al, [edi] jne :diff inc esi inc edi dec ecx jmp short :loop2 :diff jl :less :greater mov eax, 8 ;; eax = 1 jmp short :exit :less mov eax, -8 jmp short :exit :same mov eax, 0 :exit mov ecx, 1 pop edi pop esi mov esp, ebp pop ebp ret }) (in-package :ct) (defun ct:memcmp (buf1 buf2 count) (unless (ct:cpointerp buf1) (error "Not a foreign pointer: ~A" buf1)) (unless (ct:cpointerp buf2) (error "Not a foreign pointer: ~A" buf2)) (unless (fixnump count) (error "Third argument to memcmp must be a fixnum, got ~A" count)) (%memcmp (uref buf1 1)(uref buf2 1) count)) (ct:defun-dll memcpy ((dest (:void *))(src (:void *))(count :unsigned-long)) :return-type (:void *) :library-name "msvcrt.dll" :entry-name "memcpy" :linkage-type :c) (defun malloc (size) (cl::allocate-c-heap size)) (defun free (cptr) (cl::deallocate-c-heap cptr)) (defun unicode-to-lisp-string (buf) (let ((x (make-array 0 :element-type 'character :fill-pointer t :adjustable t))) (do* ((index 0 (+ index 1)) (c (ct:cref (:wide-char *) buf index) (ct:cref (:wide-char *) buf index))) ((char= c #\nul) x) (vector-push-extend c x)))) (defun lisp-string-to-unicode (str &optional (buf nil)) (let ((strlength (length str))) (unless buf (setf buf (ct:malloc (* (+ strlength 1) 2)))) (do* ((i 0 (+ i 1))) ((= i strlength) (setf (ct:cref (:wide-char *) buf i) #\nul) buf) (setf (ct:cref (:wide-char *) buf i) (elt str i))))) (defun lisp-string-to-c-string (str &optional (cstr nil)) (let ((strlength (length str))) (unless cstr (setf cstr (ct:malloc (+ strlength 1)))) (dotimes (i strlength) (setf (ct:cref (:unsigned-char *) cstr i) (char-int (elt str i)))) (setf (ct:cref (:unsigned-char *) cstr strlength) 0) cstr)) ;; Copy a lisp array of bytes to a C byte array. ;; If the optional parameter cbuf is not supplied (or is nil) then a new C byte ;; array of the same length is allocated with ct:malloc. The resulting C array is returned. ;; (defun lisp-bytes-to-c-bytes (buf &optional (cbuf nil)) (let ((length (length buf))) (unless cbuf (setf cbuf (ct:malloc length))) (dotimes (i length) (setf (ct:cref (:unsigned-char *) cbuf i) (aref buf i))) cbuf)) ;; Copy a C array of bytes to a Lisp array of bytes. ;; If the optional parameter lisp-buf is supplied, it should be a Lisp array of 'byte ;; of a length greater or equal to the passed length parameter. ;; The lisp array is returned. (defun c-bytes-to-lisp-bytes (cbuf length &optional (lisp-buf nil)) (unless lisp-buf (setf lisp-buf (make-array length :element-type 'byte))) (dotimes (i length) (setf (aref lisp-buf i) (ct:cref (:unsigned-char *) cbuf i))) lisp-buf) (defmacro with-c-struct ((var expr structure-type) &body body) (declare (ignore var)) (let ((struct-def (ct::ctypeexpand-all structure-type))) (unless (and (listp struct-def) (eq (car struct-def) ':struct)) (error "Not a C structure definition: ~S" struct-def)) (let ((fields (let ((j 0) (ret nil)) (dolist (i (rest struct-def)(nreverse ret)) (if (evenp j) (push i ret)) (incf j))))) (unless (every #'symbolp fields) (error "Invalid structure definition, names are not all symbols: ~A" fields)) `(symbol-macrolet ,(mapcar #'(lambda (sym) `(,sym (ct:cref ,structure-type ,expr ,sym))) fields) ,@body)))) (defmacro with-fresh-foreign-block ((sym type) &rest forms) `(let ((,sym (ct:malloc (ct:sizeof ,type)))) (unwind-protect (progn ,@forms)(ct:free ,sym)))) ;;; ;;; Output the contents of a C structure. ;;; The structure and the optional stream are evaluated, but the C structure name is not. ;;; Example: (dump-c-struct s WNDCLASSEX) ;;; (defmacro dump-c-struct (struct type &optional (stream t)) (let ((exptype (ct::ctypeexpand-all type))) (unless (ct::valid-c-type-definition exptype) (error "Invalid C type specifier: ~S" type)) (let ((forms '())) (do* ((x (cdr exptype) (cddr x)) (name (car x) (car x)) (field-type (cadr x) (cadr x))) ((null x)) (push `(format ,stream "~4T~A[~A]:~40T~S~%" ',name ',field-type (ct:cref ,type ,struct ,name)) forms)) `(progn (format ,stream "~A:~%" ',type) ,@forms (format ,stream "~%") (values))))) (defconstant x86::foreign-stack-start-marker (+ (* cl::uvector-foreign-stack-tag 8) x86::uvector-header-tag)) (defconstant x86::foreign-stack-end-marker (+ (* cl::uvector-foreign-stack-end-tag 8) x86::uvector-header-tag)) (defasm alloca (size) { begin-atomic pop edx ; edx = return address pop eax ; eax = size in bytes shr eax, 3 ; untag test esp, 4 ; are we at an 8-byte stack boundary jnz :t1 push 0 ; if so, push a pad word :t1 add eax, 7 and eax, -8 ; should be multiple of 8 mov ecx, eax shr ecx, 3 add ecx, 2 ; 4 word header shl ecx, 8 or ecx, x86::foreign-stack-end-marker push ecx ; push end marker sub esp, eax ; allocate foreign block push 0 ; pad shl eax, 3 ; tag byte count push eax ; number of bytes lea eax, [esp + 8] ; start of foreign block push eax and ecx, #xffffff7 or ecx, x86::foreign-stack-start-marker push ecx mov eax, esp or eax, uvector-tag push 0 ; dummy arg push edx ; push return address mov ecx, 1 end-atomic ret }) ;; redefine kernel function (defasm cl::lisp-object-id (obj) { push ebp mov ebp, esp mov eax, [ebp + ARGS_OFFSET] cmp eax, most-positive-fixnum ja :bignum shl eax, 3 jmp short :next :bignum mov ecx, eax shr ecx, 16 shl ecx, 3 shl eax, 16 shr eax, 13 ;; eax = low 16 bits, ecx = high 16 bits push eax push ecx callp %create-positive-bignum add esp, 8 :next mov ecx, 1 pop ebp ret }) ;;; ;;; Redefine kernel LOAD-DLL function ;;; (ct:defun-kernel cl::loadlibrary ((filename (:unsigned-char *))) :return-type :handle :kernel-name cl::%LoadLibrary :linkage-type :pascal) ;(defun cl::load-dll (filename) ; (ct:foreign-ptr-to-int (cl::loadlibrary (ct:lisp-string-to-c-string filename)))) (make-package :temp-package) (in-package :temp-package) ;; avoid interning these exported symbols (defpackage :win32 (:export ) (:nicknames :win)) (in-package :win) (use-package :ct) (in-package :cl) (setq cl::*compiler-warn-on-undefined-function* t)
[ { "context": ";;; Copyright (c) 2011-2012, James M. Lawrence. All rights reserved.\n;;;\n;;; Redistribution and ", "end": 46, "score": 0.9997361898422241, "start": 29, "tag": "NAME", "value": "James M. Lawrence" } ]
vendor/quicklisp/dists/quicklisp/software/lparallel-20160825-git/src/util/defmacro.lisp
corpix/clx
151
;;; Copyright (c) 2011-2012, James M. Lawrence. 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 the project 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. (in-package #:lparallel.util) (defmacro defmacro/once (name params &body body) "Like `defmacro' except that params which are immediately preceded by `&once' are passed to a `once-only' call which surrounds `body'." (labels ((once-keyword-p (obj) (and (symbolp obj) (equalp (symbol-name obj) "&once"))) (remove-once-keywords (params) (mapcar (lambda (x) (if (consp x) (remove-once-keywords x) x)) (remove-if #'once-keyword-p params))) (grab-once-param (list) (let ((target (first list))) (when (or (null list) (consp target) (find target lambda-list-keywords) (once-keyword-p target)) (error "`&once' without parameter in ~a" name)) target)) (find-once-params (params) (mapcon (lambda (cell) (destructuring-bind (elem &rest rest) cell (cond ((consp elem) (find-once-params elem)) ((once-keyword-p elem) (list (grab-once-param rest))) (t nil)))) params))) (with-parsed-body (body declares docstring) `(defmacro ,name ,(remove-once-keywords params) ,@(unsplice docstring) ,@declares (once-only ,(find-once-params params) ,@body)))))
92547
;;; Copyright (c) 2011-2012, <NAME>. All rights reserved. ;;; ;;; Redistribution and use in source and binary forms, with or without ;;; modification, are permitted provided that the following conditions ;;; are met: ;;; ;;; * Redistributions of source code must retain the above copyright ;;; notice, this list of conditions and the following disclaimer. ;;; ;;; * Redistributions in binary form must reproduce the above ;;; copyright notice, this list of conditions and the following ;;; disclaimer in the documentation and/or other materials provided ;;; with the distribution. ;;; ;;; * Neither the name of the project 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. (in-package #:lparallel.util) (defmacro defmacro/once (name params &body body) "Like `defmacro' except that params which are immediately preceded by `&once' are passed to a `once-only' call which surrounds `body'." (labels ((once-keyword-p (obj) (and (symbolp obj) (equalp (symbol-name obj) "&once"))) (remove-once-keywords (params) (mapcar (lambda (x) (if (consp x) (remove-once-keywords x) x)) (remove-if #'once-keyword-p params))) (grab-once-param (list) (let ((target (first list))) (when (or (null list) (consp target) (find target lambda-list-keywords) (once-keyword-p target)) (error "`&once' without parameter in ~a" name)) target)) (find-once-params (params) (mapcon (lambda (cell) (destructuring-bind (elem &rest rest) cell (cond ((consp elem) (find-once-params elem)) ((once-keyword-p elem) (list (grab-once-param rest))) (t nil)))) params))) (with-parsed-body (body declares docstring) `(defmacro ,name ,(remove-once-keywords params) ,@(unsplice docstring) ,@declares (once-only ,(find-once-params params) ,@body)))))
true
;;; Copyright (c) 2011-2012, PI:NAME:<NAME>END_PI. All rights reserved. ;;; ;;; Redistribution and use in source and binary forms, with or without ;;; modification, are permitted provided that the following conditions ;;; are met: ;;; ;;; * Redistributions of source code must retain the above copyright ;;; notice, this list of conditions and the following disclaimer. ;;; ;;; * Redistributions in binary form must reproduce the above ;;; copyright notice, this list of conditions and the following ;;; disclaimer in the documentation and/or other materials provided ;;; with the distribution. ;;; ;;; * Neither the name of the project 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. (in-package #:lparallel.util) (defmacro defmacro/once (name params &body body) "Like `defmacro' except that params which are immediately preceded by `&once' are passed to a `once-only' call which surrounds `body'." (labels ((once-keyword-p (obj) (and (symbolp obj) (equalp (symbol-name obj) "&once"))) (remove-once-keywords (params) (mapcar (lambda (x) (if (consp x) (remove-once-keywords x) x)) (remove-if #'once-keyword-p params))) (grab-once-param (list) (let ((target (first list))) (when (or (null list) (consp target) (find target lambda-list-keywords) (once-keyword-p target)) (error "`&once' without parameter in ~a" name)) target)) (find-once-params (params) (mapcon (lambda (cell) (destructuring-bind (elem &rest rest) cell (cond ((consp elem) (find-once-params elem)) ((once-keyword-p elem) (list (grab-once-param rest))) (t nil)))) params))) (with-parsed-body (body declares docstring) `(defmacro ,name ,(remove-once-keywords params) ,@(unsplice docstring) ,@declares (once-only ,(find-once-params params) ,@body)))))
[ { "context": " system for synchronized-hash-tables.\"\n :author \"Johnny Ruiz <[email protected]>\"\n :license \"MIT\"\n :versi", "end": 171, "score": 0.9998898506164551, "start": 160, "tag": "NAME", "value": "Johnny Ruiz" }, { "context": "ynchronized-hash-tables.\"\n :author \"Johnny Ruiz <[email protected]>\"\n :license \"MIT\"\n :version \"0.0.1\"\n :depends", "end": 192, "score": 0.999927282333374, "start": 173, "tag": "EMAIL", "value": "[email protected]" } ]
synchronized-hash-tables-test.asd
jeko2000/synchronized-hash-tables
0
;;;; synchronized-hash-tables-test.asd (asdf:defsystem #:synchronized-hash-tables-test :description "A test system for synchronized-hash-tables." :author "Johnny Ruiz <[email protected]>" :license "MIT" :version "0.0.1" :depends-on (:synchronized-hash-tables :parachute :bordeaux-threads) :components ((:file "test")) :perform (asdf:test-op (op c) (uiop:symbol-call :parachute :test :synchronized-hash-tables-test)))
43867
;;;; synchronized-hash-tables-test.asd (asdf:defsystem #:synchronized-hash-tables-test :description "A test system for synchronized-hash-tables." :author "<NAME> <<EMAIL>>" :license "MIT" :version "0.0.1" :depends-on (:synchronized-hash-tables :parachute :bordeaux-threads) :components ((:file "test")) :perform (asdf:test-op (op c) (uiop:symbol-call :parachute :test :synchronized-hash-tables-test)))
true
;;;; synchronized-hash-tables-test.asd (asdf:defsystem #:synchronized-hash-tables-test :description "A test system for synchronized-hash-tables." :author "PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>" :license "MIT" :version "0.0.1" :depends-on (:synchronized-hash-tables :parachute :bordeaux-threads) :components ((:file "test")) :perform (asdf:test-op (op c) (uiop:symbol-call :parachute :test :synchronized-hash-tables-test)))
[ { "context": "\n #:fast-websocket.error)\n (:import-from :alexandria\n #:named-lambda)\n (:export #:make", "end": 190, "score": 0.6629872918128967, "start": 180, "tag": "NAME", "value": "alexandria" } ]
vendor/quicklisp/dists/quicklisp/software/fast-websocket-20210228-git/src/parser.lisp
corpix/clx
0
(in-package :cl-user) (defpackage fast-websocket.parser (:use :cl #:fast-websocket.constants #:fast-websocket.ws #:fast-websocket.error) (:import-from :alexandria #:named-lambda) (:export #:make-ll-parser)) (in-package :fast-websocket.parser) (deftype octet () '(unsigned-byte 8)) (deftype octets () '(simple-array octet (*))) (defun make-ll-parser (ws &key require-masking (max-length #x3ffffff) payload-callback) (declare (type (or null function) payload-callback) (type fixnum max-length)) (named-lambda parser (data &key (start 0) (end (length data))) (declare (type fixnum start end) (type octets data) (optimize (speed 3) (safety 2))) (when (= start end) (return-from parser start)) (let ((i start)) (declare (type fixnum i)) (tagbody (ecase (ws-stage ws) (0 (go parsing-first-byte)) (1 (go parsing-second-byte)) (2 (go parsing-extended-length)) (3 (go parsing-masking-key)) (4 (go parsing-payload))) parsing-first-byte (let* ((byte (aref data i)) (fin (= (logand byte +fin+) +fin+))) (declare (type octet byte)) (dolist (rsv (list +rsv1+ +rsv2+ +rsv3+)) (when (= (logand byte rsv) rsv) (error 'protocol-error :format-control "Reserved bit is on: ~A" :format-arguments (list rsv)))) (let ((opcode (logand byte +opcode+))) (unless (valid-opcode-p opcode) (error 'protocol-error :format-control "Unrecognized frame opcode: ~A" :format-arguments (list opcode))) (unless (or fin (fragmented-opcode-p opcode)) (error 'protocol-error :format-control "Received fragmented control frame: opcode = ~A" :format-arguments (list opcode))) (when (and (ws-mode ws) (opening-opcode-p opcode)) (error 'protocol-error :format-control "Received new data frame but previous continuous frame is unfinished")) (setf (ws-fin ws) fin (ws-opcode ws) opcode))) (incf i) (setf (ws-stage ws) 1) parsing-second-byte (when (= i end) (go end)) (let ((byte (aref data i))) (declare (type octet byte)) (incf i) (setf (ws-mask ws) (= (logand byte +mask+) +mask+)) (unless (eql require-masking (ws-mask ws)) (error 'unacceptable :require-masking require-masking)) (let ((length (logand byte +length+))) (setf (ws-length ws) length) (cond ((<= 0 length 125) (when (< max-length length) (error 'too-large :length length :max-length max-length)) (if (ws-mask ws) (progn (setf (ws-stage ws) 3) (go parsing-masking-key)) (progn (setf (ws-stage ws) 4) (go parsing-payload)))) (t (setf (ws-length-size ws) (if (= length 126) 2 8)) (setf (ws-stage ws) 2))))) parsing-extended-length (when (< end (+ i (ws-length-size ws))) (return-from parser (values i t))) (let ((length 0)) (declare (type integer length)) (dotimes (j (ws-length-size ws)) (setf length (+ (ash length 8) (aref data i))) (incf i)) (unless (or (fragmented-opcode-p (ws-opcode ws)) (<= length 125)) (error 'protocol-error :format-control "Received control frame having too long payload: ~A" :format-arguments (list length))) (when (< max-length length) (error 'too-large :length length :max-length max-length)) (setf (ws-length ws) length)) (if (ws-mask ws) (setf (ws-stage ws) 3) (progn (setf (ws-stage ws) 4) (go parsing-payload))) parsing-masking-key (when (< end (+ i 4)) (return-from parser (values i t))) (dotimes (j 4) (setf (aref (ws-masking-key ws) j) (aref data i)) (incf i)) (setf (ws-stage ws) 4) parsing-payload (let* ((payload-end (+ i (ws-length ws))) (read-a-part (< end payload-end)) (next-end (if read-a-part end payload-end))) (declare (type integer payload-end)) (case (opcode-name (ws-opcode ws)) (:continuation (unless (ws-mode ws) (error 'protocol-error :format-control "Received unexpected continuation frame"))) (:text (unless (ws-fin ws) (setf (ws-mode ws) :text))) (:binary (unless (ws-fin ws) (setf (ws-mode ws) :binary)))) (when payload-callback (funcall (the function payload-callback) data :start i :end next-end)) (when (and (ws-fin ws) (= (ws-opcode ws) #.(opcode :continuation))) (setf (ws-mode ws) nil)) (if read-a-part (progn (decf (ws-length ws) (- end i)) (setq i next-end)) (progn (setf (ws-stage ws) 0) (setq i next-end) (unless (= i end) (go parsing-first-byte))))) end (return-from parser i)))))
46936
(in-package :cl-user) (defpackage fast-websocket.parser (:use :cl #:fast-websocket.constants #:fast-websocket.ws #:fast-websocket.error) (:import-from :<NAME> #:named-lambda) (:export #:make-ll-parser)) (in-package :fast-websocket.parser) (deftype octet () '(unsigned-byte 8)) (deftype octets () '(simple-array octet (*))) (defun make-ll-parser (ws &key require-masking (max-length #x3ffffff) payload-callback) (declare (type (or null function) payload-callback) (type fixnum max-length)) (named-lambda parser (data &key (start 0) (end (length data))) (declare (type fixnum start end) (type octets data) (optimize (speed 3) (safety 2))) (when (= start end) (return-from parser start)) (let ((i start)) (declare (type fixnum i)) (tagbody (ecase (ws-stage ws) (0 (go parsing-first-byte)) (1 (go parsing-second-byte)) (2 (go parsing-extended-length)) (3 (go parsing-masking-key)) (4 (go parsing-payload))) parsing-first-byte (let* ((byte (aref data i)) (fin (= (logand byte +fin+) +fin+))) (declare (type octet byte)) (dolist (rsv (list +rsv1+ +rsv2+ +rsv3+)) (when (= (logand byte rsv) rsv) (error 'protocol-error :format-control "Reserved bit is on: ~A" :format-arguments (list rsv)))) (let ((opcode (logand byte +opcode+))) (unless (valid-opcode-p opcode) (error 'protocol-error :format-control "Unrecognized frame opcode: ~A" :format-arguments (list opcode))) (unless (or fin (fragmented-opcode-p opcode)) (error 'protocol-error :format-control "Received fragmented control frame: opcode = ~A" :format-arguments (list opcode))) (when (and (ws-mode ws) (opening-opcode-p opcode)) (error 'protocol-error :format-control "Received new data frame but previous continuous frame is unfinished")) (setf (ws-fin ws) fin (ws-opcode ws) opcode))) (incf i) (setf (ws-stage ws) 1) parsing-second-byte (when (= i end) (go end)) (let ((byte (aref data i))) (declare (type octet byte)) (incf i) (setf (ws-mask ws) (= (logand byte +mask+) +mask+)) (unless (eql require-masking (ws-mask ws)) (error 'unacceptable :require-masking require-masking)) (let ((length (logand byte +length+))) (setf (ws-length ws) length) (cond ((<= 0 length 125) (when (< max-length length) (error 'too-large :length length :max-length max-length)) (if (ws-mask ws) (progn (setf (ws-stage ws) 3) (go parsing-masking-key)) (progn (setf (ws-stage ws) 4) (go parsing-payload)))) (t (setf (ws-length-size ws) (if (= length 126) 2 8)) (setf (ws-stage ws) 2))))) parsing-extended-length (when (< end (+ i (ws-length-size ws))) (return-from parser (values i t))) (let ((length 0)) (declare (type integer length)) (dotimes (j (ws-length-size ws)) (setf length (+ (ash length 8) (aref data i))) (incf i)) (unless (or (fragmented-opcode-p (ws-opcode ws)) (<= length 125)) (error 'protocol-error :format-control "Received control frame having too long payload: ~A" :format-arguments (list length))) (when (< max-length length) (error 'too-large :length length :max-length max-length)) (setf (ws-length ws) length)) (if (ws-mask ws) (setf (ws-stage ws) 3) (progn (setf (ws-stage ws) 4) (go parsing-payload))) parsing-masking-key (when (< end (+ i 4)) (return-from parser (values i t))) (dotimes (j 4) (setf (aref (ws-masking-key ws) j) (aref data i)) (incf i)) (setf (ws-stage ws) 4) parsing-payload (let* ((payload-end (+ i (ws-length ws))) (read-a-part (< end payload-end)) (next-end (if read-a-part end payload-end))) (declare (type integer payload-end)) (case (opcode-name (ws-opcode ws)) (:continuation (unless (ws-mode ws) (error 'protocol-error :format-control "Received unexpected continuation frame"))) (:text (unless (ws-fin ws) (setf (ws-mode ws) :text))) (:binary (unless (ws-fin ws) (setf (ws-mode ws) :binary)))) (when payload-callback (funcall (the function payload-callback) data :start i :end next-end)) (when (and (ws-fin ws) (= (ws-opcode ws) #.(opcode :continuation))) (setf (ws-mode ws) nil)) (if read-a-part (progn (decf (ws-length ws) (- end i)) (setq i next-end)) (progn (setf (ws-stage ws) 0) (setq i next-end) (unless (= i end) (go parsing-first-byte))))) end (return-from parser i)))))
true
(in-package :cl-user) (defpackage fast-websocket.parser (:use :cl #:fast-websocket.constants #:fast-websocket.ws #:fast-websocket.error) (:import-from :PI:NAME:<NAME>END_PI #:named-lambda) (:export #:make-ll-parser)) (in-package :fast-websocket.parser) (deftype octet () '(unsigned-byte 8)) (deftype octets () '(simple-array octet (*))) (defun make-ll-parser (ws &key require-masking (max-length #x3ffffff) payload-callback) (declare (type (or null function) payload-callback) (type fixnum max-length)) (named-lambda parser (data &key (start 0) (end (length data))) (declare (type fixnum start end) (type octets data) (optimize (speed 3) (safety 2))) (when (= start end) (return-from parser start)) (let ((i start)) (declare (type fixnum i)) (tagbody (ecase (ws-stage ws) (0 (go parsing-first-byte)) (1 (go parsing-second-byte)) (2 (go parsing-extended-length)) (3 (go parsing-masking-key)) (4 (go parsing-payload))) parsing-first-byte (let* ((byte (aref data i)) (fin (= (logand byte +fin+) +fin+))) (declare (type octet byte)) (dolist (rsv (list +rsv1+ +rsv2+ +rsv3+)) (when (= (logand byte rsv) rsv) (error 'protocol-error :format-control "Reserved bit is on: ~A" :format-arguments (list rsv)))) (let ((opcode (logand byte +opcode+))) (unless (valid-opcode-p opcode) (error 'protocol-error :format-control "Unrecognized frame opcode: ~A" :format-arguments (list opcode))) (unless (or fin (fragmented-opcode-p opcode)) (error 'protocol-error :format-control "Received fragmented control frame: opcode = ~A" :format-arguments (list opcode))) (when (and (ws-mode ws) (opening-opcode-p opcode)) (error 'protocol-error :format-control "Received new data frame but previous continuous frame is unfinished")) (setf (ws-fin ws) fin (ws-opcode ws) opcode))) (incf i) (setf (ws-stage ws) 1) parsing-second-byte (when (= i end) (go end)) (let ((byte (aref data i))) (declare (type octet byte)) (incf i) (setf (ws-mask ws) (= (logand byte +mask+) +mask+)) (unless (eql require-masking (ws-mask ws)) (error 'unacceptable :require-masking require-masking)) (let ((length (logand byte +length+))) (setf (ws-length ws) length) (cond ((<= 0 length 125) (when (< max-length length) (error 'too-large :length length :max-length max-length)) (if (ws-mask ws) (progn (setf (ws-stage ws) 3) (go parsing-masking-key)) (progn (setf (ws-stage ws) 4) (go parsing-payload)))) (t (setf (ws-length-size ws) (if (= length 126) 2 8)) (setf (ws-stage ws) 2))))) parsing-extended-length (when (< end (+ i (ws-length-size ws))) (return-from parser (values i t))) (let ((length 0)) (declare (type integer length)) (dotimes (j (ws-length-size ws)) (setf length (+ (ash length 8) (aref data i))) (incf i)) (unless (or (fragmented-opcode-p (ws-opcode ws)) (<= length 125)) (error 'protocol-error :format-control "Received control frame having too long payload: ~A" :format-arguments (list length))) (when (< max-length length) (error 'too-large :length length :max-length max-length)) (setf (ws-length ws) length)) (if (ws-mask ws) (setf (ws-stage ws) 3) (progn (setf (ws-stage ws) 4) (go parsing-payload))) parsing-masking-key (when (< end (+ i 4)) (return-from parser (values i t))) (dotimes (j 4) (setf (aref (ws-masking-key ws) j) (aref data i)) (incf i)) (setf (ws-stage ws) 4) parsing-payload (let* ((payload-end (+ i (ws-length ws))) (read-a-part (< end payload-end)) (next-end (if read-a-part end payload-end))) (declare (type integer payload-end)) (case (opcode-name (ws-opcode ws)) (:continuation (unless (ws-mode ws) (error 'protocol-error :format-control "Received unexpected continuation frame"))) (:text (unless (ws-fin ws) (setf (ws-mode ws) :text))) (:binary (unless (ws-fin ws) (setf (ws-mode ws) :binary)))) (when payload-callback (funcall (the function payload-callback) data :start i :end next-end)) (when (and (ws-fin ws) (= (ws-opcode ws) #.(opcode :continuation))) (setf (ws-mode ws) nil)) (if read-a-part (progn (decf (ws-length ws) (- end i)) (setq i next-end)) (progn (setf (ws-stage ws) 0) (setq i next-end) (unless (= i end) (go parsing-first-byte))))) end (return-from parser i)))))
[ { "context": " oh - Kate's parents are back!\n;; Kate cannot hide Mark!\n;; Mark is thinking of an excuse...\nI was consul", "end": 4101, "score": 0.8714507818222046, "start": 4097, "tag": "NAME", "value": "Mark" }, { "context": "e's parents are back!\n;; Kate cannot hide Mark!\n;; Mark is thinking of an excuse...\nI was consulting Kate", "end": 4110, "score": 0.8603992462158203, "start": 4106, "tag": "NAME", "value": "Mark" }, { "context": " to buy for my father! ; text input by the user\n;; Mark excuses himself before leaving:\n;; \"I was consult", "end": 4234, "score": 0.8745569586753845, "start": 4230, "tag": "NAME", "value": "Mark" }, { "context": " oh - Kate's parents are back!\n;; Kate cannot hide Mark!\n;; Mark is thinking of an excuse...\n ", "end": 4492, "score": 0.8676835894584656, "start": 4488, "tag": "NAME", "value": "Mark" }, { "context": "e's parents are back!\n;; Kate cannot hide Mark!\n;; Mark is thinking of an excuse...\n ", "end": 4501, "score": 0.790178120136261, "start": 4497, "tag": "NAME", "value": "Mark" }, { "context": " ; empty line provided ; ; ; ; ; ; ; ; ; ; ;\n;; Mark excuses himself before leaving:\n;; \"Kate did not ", "end": 4644, "score": 0.8712711930274963, "start": 4640, "tag": "NAME", "value": "Mark" } ]
Sources - TCLCS/04-restarts/tclcs-30-custom-restart-invoking-functions.lisp
johnhilts/common-lisp-condition-system
88
;;;; clcs-30-custom-restart-invoking-functions.lisp (defpackage #:clcs-30-custom-restart-invoking-functions (:use #:cl) (:export #:test-1 #:test-2 #:test-3 #:test-4)) (in-package #:clcs-30-custom-restart-invoking-functions) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Relevant restarts (defvar *toplevel-restarts* '()) (defun compute-relevant-restarts (&optional condition) (set-difference (compute-restarts condition) *toplevel-restarts*)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Basic environment (defvar *front-door-locked-p* t) (defvar *back-door-locked-p* t) (defun parents-come-back () (format t ";; Uh oh - Kate's parents are back!~%") (call-with-home-restarts (lambda () (try-to-hide-mark) (we do not want to be here))) (format t ";; Whew... We're safe! For now.~%")) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Restart helper functions (defun perform-escape-through-front-door () (format t ";; Escaping through the front door.~%")) (defun escape-through-front-door-p (condition) (declare (ignore condition)) (not *front-door-locked-p*)) (defun perform-escape-through-back-door () (format t ";; Escaping through the back door.~%")) (defun escape-through-back-door-p (condition) (declare (ignore condition)) (not *back-door-locked-p*)) (defvar *excuses* '("Kate did not divide her program into sections properly!" "I was borrowing Kate's books on mainframe programming!" "I had COBOL-related homework and hoped Kate could help me!")) (defun perform-excuse (excuse) (format t ";; Mark excuses himself before leaving:~%;; \"~A\"~%" excuse)) (defun provide-excuse () (format t ";; Mark is thinking of an excuse...~%") (let ((excuse-text (read-line))) (list (if (string/= "" excuse-text) excuse-text (elt *excuses* (random (length *excuses*))))))) (defun escape (&optional condition) (let ((restart (find-restart 'escape condition))) (when restart (invoke-restart restart)))) (defun excuse (&optional excuse-text condition) (if excuse-text (invoke-restart 'excuse excuse-text) (invoke-restart-interactively 'excuse))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Hiding logic (defun try-to-hide-mark () (escape) (format t ";; Kate cannot hide Mark!~%") (excuse)) (defun call-with-home-restarts (thunk) (let ((*toplevel-restarts* (compute-restarts))) (restart-case (funcall thunk) (escape () :test escape-through-back-door-p (perform-escape-through-back-door)) (escape () :test escape-through-front-door-p (perform-escape-through-front-door)) (excuse (reason) :interactive provide-excuse (perform-excuse reason))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Tests (defun test-1 () (call-with-home-restarts (lambda () (let ((*front-door-locked-p* nil) (*back-door-locked-p* nil)) (parents-come-back))))) (defun test-2 () (call-with-home-restarts (lambda () (let ((*front-door-locked-p* nil)) (parents-come-back))))) (defun test-3 () (call-with-home-restarts (lambda () (let ((*back-door-locked-p* nil)) (parents-come-back))))) (defun test-4 () (call-with-home-restarts (lambda () (parents-come-back)))) #| CL-USER> (clcs-30-custom-restart-invoking-functions:test-1) ;; Uh oh - Kate's parents are back! ;; Escaping through the back door. ;; Whew... We're safe! For now. NIL CL-USER> (clcs-30-custom-restart-invoking-functions:test-2) ;; Uh oh - Kate's parents are back! ;; Escaping through the front door. ;; Whew... We're safe! For now. NIL CL-USER> (clcs-30-custom-restart-invoking-functions:test-3) ;; Uh oh - Kate's parents are back! ;; Escaping through the back door. ;; Whew... We're safe! For now. NIL CL-USER> (clcs-30-custom-restart-invoking-functions:test-4) ;; Uh oh - Kate's parents are back! ;; Kate cannot hide Mark! ;; Mark is thinking of an excuse... I was consulting Kate on which mainframe to buy for my father! ; text input by the user ;; Mark excuses himself before leaving: ;; "I was consulting Kate on which mainframe to buy for my father!" ;; Whew... We're safe! For now. NIL CL-USER> (clcs-30-custom-restart-invoking-functions:test-4) ;; Uh oh - Kate's parents are back! ;; Kate cannot hide Mark! ;; Mark is thinking of an excuse... ; empty line provided ; ; ; ; ; ; ; ; ; ; ; ;; Mark excuses himself before leaving: ;; "Kate did not divide her program into sections properly!" ;; Whew... We're safe! For now. NIL |#
75180
;;;; clcs-30-custom-restart-invoking-functions.lisp (defpackage #:clcs-30-custom-restart-invoking-functions (:use #:cl) (:export #:test-1 #:test-2 #:test-3 #:test-4)) (in-package #:clcs-30-custom-restart-invoking-functions) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Relevant restarts (defvar *toplevel-restarts* '()) (defun compute-relevant-restarts (&optional condition) (set-difference (compute-restarts condition) *toplevel-restarts*)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Basic environment (defvar *front-door-locked-p* t) (defvar *back-door-locked-p* t) (defun parents-come-back () (format t ";; Uh oh - Kate's parents are back!~%") (call-with-home-restarts (lambda () (try-to-hide-mark) (we do not want to be here))) (format t ";; Whew... We're safe! For now.~%")) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Restart helper functions (defun perform-escape-through-front-door () (format t ";; Escaping through the front door.~%")) (defun escape-through-front-door-p (condition) (declare (ignore condition)) (not *front-door-locked-p*)) (defun perform-escape-through-back-door () (format t ";; Escaping through the back door.~%")) (defun escape-through-back-door-p (condition) (declare (ignore condition)) (not *back-door-locked-p*)) (defvar *excuses* '("Kate did not divide her program into sections properly!" "I was borrowing Kate's books on mainframe programming!" "I had COBOL-related homework and hoped Kate could help me!")) (defun perform-excuse (excuse) (format t ";; Mark excuses himself before leaving:~%;; \"~A\"~%" excuse)) (defun provide-excuse () (format t ";; Mark is thinking of an excuse...~%") (let ((excuse-text (read-line))) (list (if (string/= "" excuse-text) excuse-text (elt *excuses* (random (length *excuses*))))))) (defun escape (&optional condition) (let ((restart (find-restart 'escape condition))) (when restart (invoke-restart restart)))) (defun excuse (&optional excuse-text condition) (if excuse-text (invoke-restart 'excuse excuse-text) (invoke-restart-interactively 'excuse))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Hiding logic (defun try-to-hide-mark () (escape) (format t ";; Kate cannot hide Mark!~%") (excuse)) (defun call-with-home-restarts (thunk) (let ((*toplevel-restarts* (compute-restarts))) (restart-case (funcall thunk) (escape () :test escape-through-back-door-p (perform-escape-through-back-door)) (escape () :test escape-through-front-door-p (perform-escape-through-front-door)) (excuse (reason) :interactive provide-excuse (perform-excuse reason))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Tests (defun test-1 () (call-with-home-restarts (lambda () (let ((*front-door-locked-p* nil) (*back-door-locked-p* nil)) (parents-come-back))))) (defun test-2 () (call-with-home-restarts (lambda () (let ((*front-door-locked-p* nil)) (parents-come-back))))) (defun test-3 () (call-with-home-restarts (lambda () (let ((*back-door-locked-p* nil)) (parents-come-back))))) (defun test-4 () (call-with-home-restarts (lambda () (parents-come-back)))) #| CL-USER> (clcs-30-custom-restart-invoking-functions:test-1) ;; Uh oh - Kate's parents are back! ;; Escaping through the back door. ;; Whew... We're safe! For now. NIL CL-USER> (clcs-30-custom-restart-invoking-functions:test-2) ;; Uh oh - Kate's parents are back! ;; Escaping through the front door. ;; Whew... We're safe! For now. NIL CL-USER> (clcs-30-custom-restart-invoking-functions:test-3) ;; Uh oh - Kate's parents are back! ;; Escaping through the back door. ;; Whew... We're safe! For now. NIL CL-USER> (clcs-30-custom-restart-invoking-functions:test-4) ;; Uh oh - Kate's parents are back! ;; Kate cannot hide <NAME>! ;; <NAME> is thinking of an excuse... I was consulting Kate on which mainframe to buy for my father! ; text input by the user ;; <NAME> excuses himself before leaving: ;; "I was consulting Kate on which mainframe to buy for my father!" ;; Whew... We're safe! For now. NIL CL-USER> (clcs-30-custom-restart-invoking-functions:test-4) ;; Uh oh - Kate's parents are back! ;; Kate cannot hide <NAME>! ;; <NAME> is thinking of an excuse... ; empty line provided ; ; ; ; ; ; ; ; ; ; ; ;; <NAME> excuses himself before leaving: ;; "Kate did not divide her program into sections properly!" ;; Whew... We're safe! For now. NIL |#
true
;;;; clcs-30-custom-restart-invoking-functions.lisp (defpackage #:clcs-30-custom-restart-invoking-functions (:use #:cl) (:export #:test-1 #:test-2 #:test-3 #:test-4)) (in-package #:clcs-30-custom-restart-invoking-functions) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Relevant restarts (defvar *toplevel-restarts* '()) (defun compute-relevant-restarts (&optional condition) (set-difference (compute-restarts condition) *toplevel-restarts*)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Basic environment (defvar *front-door-locked-p* t) (defvar *back-door-locked-p* t) (defun parents-come-back () (format t ";; Uh oh - Kate's parents are back!~%") (call-with-home-restarts (lambda () (try-to-hide-mark) (we do not want to be here))) (format t ";; Whew... We're safe! For now.~%")) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Restart helper functions (defun perform-escape-through-front-door () (format t ";; Escaping through the front door.~%")) (defun escape-through-front-door-p (condition) (declare (ignore condition)) (not *front-door-locked-p*)) (defun perform-escape-through-back-door () (format t ";; Escaping through the back door.~%")) (defun escape-through-back-door-p (condition) (declare (ignore condition)) (not *back-door-locked-p*)) (defvar *excuses* '("Kate did not divide her program into sections properly!" "I was borrowing Kate's books on mainframe programming!" "I had COBOL-related homework and hoped Kate could help me!")) (defun perform-excuse (excuse) (format t ";; Mark excuses himself before leaving:~%;; \"~A\"~%" excuse)) (defun provide-excuse () (format t ";; Mark is thinking of an excuse...~%") (let ((excuse-text (read-line))) (list (if (string/= "" excuse-text) excuse-text (elt *excuses* (random (length *excuses*))))))) (defun escape (&optional condition) (let ((restart (find-restart 'escape condition))) (when restart (invoke-restart restart)))) (defun excuse (&optional excuse-text condition) (if excuse-text (invoke-restart 'excuse excuse-text) (invoke-restart-interactively 'excuse))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Hiding logic (defun try-to-hide-mark () (escape) (format t ";; Kate cannot hide Mark!~%") (excuse)) (defun call-with-home-restarts (thunk) (let ((*toplevel-restarts* (compute-restarts))) (restart-case (funcall thunk) (escape () :test escape-through-back-door-p (perform-escape-through-back-door)) (escape () :test escape-through-front-door-p (perform-escape-through-front-door)) (excuse (reason) :interactive provide-excuse (perform-excuse reason))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Tests (defun test-1 () (call-with-home-restarts (lambda () (let ((*front-door-locked-p* nil) (*back-door-locked-p* nil)) (parents-come-back))))) (defun test-2 () (call-with-home-restarts (lambda () (let ((*front-door-locked-p* nil)) (parents-come-back))))) (defun test-3 () (call-with-home-restarts (lambda () (let ((*back-door-locked-p* nil)) (parents-come-back))))) (defun test-4 () (call-with-home-restarts (lambda () (parents-come-back)))) #| CL-USER> (clcs-30-custom-restart-invoking-functions:test-1) ;; Uh oh - Kate's parents are back! ;; Escaping through the back door. ;; Whew... We're safe! For now. NIL CL-USER> (clcs-30-custom-restart-invoking-functions:test-2) ;; Uh oh - Kate's parents are back! ;; Escaping through the front door. ;; Whew... We're safe! For now. NIL CL-USER> (clcs-30-custom-restart-invoking-functions:test-3) ;; Uh oh - Kate's parents are back! ;; Escaping through the back door. ;; Whew... We're safe! For now. NIL CL-USER> (clcs-30-custom-restart-invoking-functions:test-4) ;; Uh oh - Kate's parents are back! ;; Kate cannot hide PI:NAME:<NAME>END_PI! ;; PI:NAME:<NAME>END_PI is thinking of an excuse... I was consulting Kate on which mainframe to buy for my father! ; text input by the user ;; PI:NAME:<NAME>END_PI excuses himself before leaving: ;; "I was consulting Kate on which mainframe to buy for my father!" ;; Whew... We're safe! For now. NIL CL-USER> (clcs-30-custom-restart-invoking-functions:test-4) ;; Uh oh - Kate's parents are back! ;; Kate cannot hide PI:NAME:<NAME>END_PI! ;; PI:NAME:<NAME>END_PI is thinking of an excuse... ; empty line provided ; ; ; ; ; ; ; ; ; ; ; ;; PI:NAME:<NAME>END_PI excuses himself before leaving: ;; "Kate did not divide her program into sections properly!" ;; Whew... We're safe! For now. NIL |#
[ { "context": ";-*- Mode: Lisp -*-\n;;;; Author: Paul Dietz\n;;;; Created: Sat Nov 2 13:52:50 2002\n;;;; Cont", "end": 49, "score": 0.9998547434806824, "start": 39, "tag": "NAME", "value": "Paul Dietz" } ]
programs/ansi-test/iteration/loop5.lsp
TeamSPoon/wam_common_lisp_devel_workspace
8
;-*- Mode: Lisp -*- ;;;; Author: Paul Dietz ;;;; Created: Sat Nov 2 13:52:50 2002 ;;;; Contains: Tests of LOOP clause FOR-AS-ACROSS (deftest loop.5.1 (let ((x "abcd")) (loop for e across x collect e)) (#\a #\b #\c #\d)) (deftest loop.5.2 (let ((x "abcd")) (loop for e across (the string x) collect e)) (#\a #\b #\c #\d)) (deftest loop.5.3 (let ((x "abcd")) (loop for e across (the simple-string x) collect e)) (#\a #\b #\c #\d)) (deftest loop.5.4 (loop for e across "abcd" collect e) (#\a #\b #\c #\d)) (deftest loop.5.5 (loop for e across "abcd" for i from 1 to 3 collect e) (#\a #\b #\c)) (deftest loop.5.6 (loop for e of-type base-char across "abcd" for i from 1 to 3 collect e) (#\a #\b #\c)) (deftest loop.5.7 (let ((x (make-array '(4) :initial-contents "abcd" :element-type 'base-char))) (loop for e across (the base-string x) collect e)) (#\a #\b #\c #\d)) (deftest loop.5.8 (let ((x "abcd")) (loop for e of-type character across x collect e)) (#\a #\b #\c #\d)) (deftest loop.5.10 (let ((x #*00010110)) (loop for e across x collect e)) (0 0 0 1 0 1 1 0)) (deftest loop.5.11 (let ((x #*00010110)) (loop for e across (the bit-vector x) collect e)) (0 0 0 1 0 1 1 0)) (deftest loop.5.12 (let ((x #*00010110)) (loop for e across (the simple-bit-vector x) collect e)) (0 0 0 1 0 1 1 0)) (deftest loop.5.13 (let ((x #*00010110)) (loop for e of-type bit across (the simple-bit-vector x) collect e)) (0 0 0 1 0 1 1 0)) (deftest loop.5.14 (let ((x #*00010110)) (loop for e of-type bit across x for i from 1 to 4 collect e)) (0 0 0 1)) (deftest loop.5.20 (let ((x (vector 'a 'b 'c 'd))) (loop for e across x collect e)) (a b c d)) (deftest loop.5.21 (let ((x (vector 'a 'b 'c 'd))) (loop for e across (the vector x) collect e)) (a b c d)) (deftest loop.5.22 (let ((x (vector 'a 'b 'c 'd))) (loop for e across (the simple-vector x) collect e)) (a b c d)) (deftest loop.5.23 (let ((x (vector '(a) '(b) '(c) '(d)))) (loop for (e) across x collect e)) (a b c d)) (deftest loop.5.30 (let ((x (make-array '(5) :initial-contents '(a b c d e) :adjustable t))) (loop for e across x collect e)) (a b c d e)) (deftest loop.5.32 (let* ((x (make-array '(5) :initial-contents '(a b c d e))) (y (make-array '(3) :displaced-to x :displaced-index-offset 1))) (loop for e across y collect e)) (b c d)) ;;; tests of 'as' form (deftest loop.5.33 (loop as e across "abc" collect e) (#\a #\b #\c)) (deftest loop.5.34 (loop as e of-type character across "abc" collect e) (#\a #\b #\c)) (deftest loop.5.35 (loop as e of-type integer across (the simple-vector (coerce '(1 2 3) 'simple-vector)) sum e) 6) ;;; Loop across displaced vectors (deftest loop.5.36 (let* ((a (make-array '(10) :initial-contents '(a b c d e f g h i j))) (da (make-array '(5) :displaced-to a :displaced-index-offset 2))) (loop for e across da collect e)) (c d e f g)) (deftest loop.5.37 (let* ((a (make-array '(10) :element-type 'base-char :initial-contents "abcdefghij")) (da (make-array '(5) :element-type 'base-char :displaced-to a :displaced-index-offset 2))) (loop for e across da collect e)) (#\c #\d #\e #\f #\g)) (deftest loop.5.38 (let* ((a (make-array '(10) :element-type 'bit :initial-contents '(0 1 1 0 0 1 0 1 1 1))) (da (make-array '(5) :element-type 'bit :displaced-to a :displaced-index-offset 2))) (loop for e across da collect e)) (1 0 0 1 0)) (deftest loop.5.39 (let ((v (make-array '(10) :initial-contents '(1 2 3 4 5 6 7 8 9 10) :fill-pointer 6))) (loop for x across v collect x)) (1 2 3 4 5 6)) (deftest loop.5.40 (loop for i from 1 to 40 for type = `(unsigned-byte ,i) for v = (make-array '(10) :initial-contents '(0 0 1 1 0 1 1 1 0 0) :element-type type) for r = (loop for x across v collect x) unless (equal r '(0 0 1 1 0 1 1 1 0 0)) collect (list i r)) nil) (deftest loop.5.41 (loop for i from 1 to 40 for type = `(signed-byte ,i) for v = (make-array '(10) :initial-contents '(0 0 -1 -1 0 -1 -1 -1 0 0) :element-type type) for r = (loop for x across v collect x) unless (equal r '(0 0 -1 -1 0 -1 -1 -1 0 0)) collect (list i r)) nil) (deftest loop.5.42 (let ((vals '(0 0 1 1 0 1 1 1 0 0))) (loop for type in '(short-float single-float double-float long-float) for fvals = (loop for v in vals collect (coerce v type)) for v = (make-array '(10) :initial-contents fvals :element-type type) for r = (loop for x across v collect x) unless (equal r fvals) collect (list fvals r))) nil) (deftest loop.5.43 (let ((vals '(0 0 1 1 0 1 1 1 0 0))) (loop for etype in '(short-float single-float double-float long-float) for type = `(complex ,etype) for fvals = (loop for v in vals collect (coerce v type)) for v = (make-array '(10) :initial-contents fvals :element-type type) for r = (loop for x across v collect x) unless (equal r fvals) collect (list fvals r))) nil) ;;; Test that explicit calls to macroexpand in subforms ;;; are done in the correct environment (deftest loop.5.44 (macrolet ((%m (z) z)) (loop for x across (expand-in-current-env (%m "148X")) collect x)) (#\1 #\4 #\8 #\X)) (deftest loop.5.45 (macrolet ((%m (z) z)) (loop as x across (expand-in-current-env (%m #*00110110)) collect x)) (0 0 1 1 0 1 1 0)) ;;; FIXME ;;; Add tests for other specialized array types (integer types, floats, complex) ;;; Error cases (deftest loop.5.error.1 (signals-error (loop for (e . e) across (vector '(x . y) '(u . v)) collect e) program-error) t) (deftest loop.5.error.2 (signals-error (loop for e across (vector '(x . y) '(u . v)) for e from 1 to 5 collect e) program-error) t) (deftest loop.5.error.3 (signals-error (macroexpand '(loop for (e . e) across (vector '(x . y) '(u . v)) collect e)) program-error) t) (deftest loop.5.error.4 (signals-error (macroexpand '(loop for e across (vector '(x . y) '(u . v)) for e from 1 to 5 collect e)) program-error) t)
11148
;-*- Mode: Lisp -*- ;;;; Author: <NAME> ;;;; Created: Sat Nov 2 13:52:50 2002 ;;;; Contains: Tests of LOOP clause FOR-AS-ACROSS (deftest loop.5.1 (let ((x "abcd")) (loop for e across x collect e)) (#\a #\b #\c #\d)) (deftest loop.5.2 (let ((x "abcd")) (loop for e across (the string x) collect e)) (#\a #\b #\c #\d)) (deftest loop.5.3 (let ((x "abcd")) (loop for e across (the simple-string x) collect e)) (#\a #\b #\c #\d)) (deftest loop.5.4 (loop for e across "abcd" collect e) (#\a #\b #\c #\d)) (deftest loop.5.5 (loop for e across "abcd" for i from 1 to 3 collect e) (#\a #\b #\c)) (deftest loop.5.6 (loop for e of-type base-char across "abcd" for i from 1 to 3 collect e) (#\a #\b #\c)) (deftest loop.5.7 (let ((x (make-array '(4) :initial-contents "abcd" :element-type 'base-char))) (loop for e across (the base-string x) collect e)) (#\a #\b #\c #\d)) (deftest loop.5.8 (let ((x "abcd")) (loop for e of-type character across x collect e)) (#\a #\b #\c #\d)) (deftest loop.5.10 (let ((x #*00010110)) (loop for e across x collect e)) (0 0 0 1 0 1 1 0)) (deftest loop.5.11 (let ((x #*00010110)) (loop for e across (the bit-vector x) collect e)) (0 0 0 1 0 1 1 0)) (deftest loop.5.12 (let ((x #*00010110)) (loop for e across (the simple-bit-vector x) collect e)) (0 0 0 1 0 1 1 0)) (deftest loop.5.13 (let ((x #*00010110)) (loop for e of-type bit across (the simple-bit-vector x) collect e)) (0 0 0 1 0 1 1 0)) (deftest loop.5.14 (let ((x #*00010110)) (loop for e of-type bit across x for i from 1 to 4 collect e)) (0 0 0 1)) (deftest loop.5.20 (let ((x (vector 'a 'b 'c 'd))) (loop for e across x collect e)) (a b c d)) (deftest loop.5.21 (let ((x (vector 'a 'b 'c 'd))) (loop for e across (the vector x) collect e)) (a b c d)) (deftest loop.5.22 (let ((x (vector 'a 'b 'c 'd))) (loop for e across (the simple-vector x) collect e)) (a b c d)) (deftest loop.5.23 (let ((x (vector '(a) '(b) '(c) '(d)))) (loop for (e) across x collect e)) (a b c d)) (deftest loop.5.30 (let ((x (make-array '(5) :initial-contents '(a b c d e) :adjustable t))) (loop for e across x collect e)) (a b c d e)) (deftest loop.5.32 (let* ((x (make-array '(5) :initial-contents '(a b c d e))) (y (make-array '(3) :displaced-to x :displaced-index-offset 1))) (loop for e across y collect e)) (b c d)) ;;; tests of 'as' form (deftest loop.5.33 (loop as e across "abc" collect e) (#\a #\b #\c)) (deftest loop.5.34 (loop as e of-type character across "abc" collect e) (#\a #\b #\c)) (deftest loop.5.35 (loop as e of-type integer across (the simple-vector (coerce '(1 2 3) 'simple-vector)) sum e) 6) ;;; Loop across displaced vectors (deftest loop.5.36 (let* ((a (make-array '(10) :initial-contents '(a b c d e f g h i j))) (da (make-array '(5) :displaced-to a :displaced-index-offset 2))) (loop for e across da collect e)) (c d e f g)) (deftest loop.5.37 (let* ((a (make-array '(10) :element-type 'base-char :initial-contents "abcdefghij")) (da (make-array '(5) :element-type 'base-char :displaced-to a :displaced-index-offset 2))) (loop for e across da collect e)) (#\c #\d #\e #\f #\g)) (deftest loop.5.38 (let* ((a (make-array '(10) :element-type 'bit :initial-contents '(0 1 1 0 0 1 0 1 1 1))) (da (make-array '(5) :element-type 'bit :displaced-to a :displaced-index-offset 2))) (loop for e across da collect e)) (1 0 0 1 0)) (deftest loop.5.39 (let ((v (make-array '(10) :initial-contents '(1 2 3 4 5 6 7 8 9 10) :fill-pointer 6))) (loop for x across v collect x)) (1 2 3 4 5 6)) (deftest loop.5.40 (loop for i from 1 to 40 for type = `(unsigned-byte ,i) for v = (make-array '(10) :initial-contents '(0 0 1 1 0 1 1 1 0 0) :element-type type) for r = (loop for x across v collect x) unless (equal r '(0 0 1 1 0 1 1 1 0 0)) collect (list i r)) nil) (deftest loop.5.41 (loop for i from 1 to 40 for type = `(signed-byte ,i) for v = (make-array '(10) :initial-contents '(0 0 -1 -1 0 -1 -1 -1 0 0) :element-type type) for r = (loop for x across v collect x) unless (equal r '(0 0 -1 -1 0 -1 -1 -1 0 0)) collect (list i r)) nil) (deftest loop.5.42 (let ((vals '(0 0 1 1 0 1 1 1 0 0))) (loop for type in '(short-float single-float double-float long-float) for fvals = (loop for v in vals collect (coerce v type)) for v = (make-array '(10) :initial-contents fvals :element-type type) for r = (loop for x across v collect x) unless (equal r fvals) collect (list fvals r))) nil) (deftest loop.5.43 (let ((vals '(0 0 1 1 0 1 1 1 0 0))) (loop for etype in '(short-float single-float double-float long-float) for type = `(complex ,etype) for fvals = (loop for v in vals collect (coerce v type)) for v = (make-array '(10) :initial-contents fvals :element-type type) for r = (loop for x across v collect x) unless (equal r fvals) collect (list fvals r))) nil) ;;; Test that explicit calls to macroexpand in subforms ;;; are done in the correct environment (deftest loop.5.44 (macrolet ((%m (z) z)) (loop for x across (expand-in-current-env (%m "148X")) collect x)) (#\1 #\4 #\8 #\X)) (deftest loop.5.45 (macrolet ((%m (z) z)) (loop as x across (expand-in-current-env (%m #*00110110)) collect x)) (0 0 1 1 0 1 1 0)) ;;; FIXME ;;; Add tests for other specialized array types (integer types, floats, complex) ;;; Error cases (deftest loop.5.error.1 (signals-error (loop for (e . e) across (vector '(x . y) '(u . v)) collect e) program-error) t) (deftest loop.5.error.2 (signals-error (loop for e across (vector '(x . y) '(u . v)) for e from 1 to 5 collect e) program-error) t) (deftest loop.5.error.3 (signals-error (macroexpand '(loop for (e . e) across (vector '(x . y) '(u . v)) collect e)) program-error) t) (deftest loop.5.error.4 (signals-error (macroexpand '(loop for e across (vector '(x . y) '(u . v)) for e from 1 to 5 collect e)) program-error) t)
true
;-*- Mode: Lisp -*- ;;;; Author: PI:NAME:<NAME>END_PI ;;;; Created: Sat Nov 2 13:52:50 2002 ;;;; Contains: Tests of LOOP clause FOR-AS-ACROSS (deftest loop.5.1 (let ((x "abcd")) (loop for e across x collect e)) (#\a #\b #\c #\d)) (deftest loop.5.2 (let ((x "abcd")) (loop for e across (the string x) collect e)) (#\a #\b #\c #\d)) (deftest loop.5.3 (let ((x "abcd")) (loop for e across (the simple-string x) collect e)) (#\a #\b #\c #\d)) (deftest loop.5.4 (loop for e across "abcd" collect e) (#\a #\b #\c #\d)) (deftest loop.5.5 (loop for e across "abcd" for i from 1 to 3 collect e) (#\a #\b #\c)) (deftest loop.5.6 (loop for e of-type base-char across "abcd" for i from 1 to 3 collect e) (#\a #\b #\c)) (deftest loop.5.7 (let ((x (make-array '(4) :initial-contents "abcd" :element-type 'base-char))) (loop for e across (the base-string x) collect e)) (#\a #\b #\c #\d)) (deftest loop.5.8 (let ((x "abcd")) (loop for e of-type character across x collect e)) (#\a #\b #\c #\d)) (deftest loop.5.10 (let ((x #*00010110)) (loop for e across x collect e)) (0 0 0 1 0 1 1 0)) (deftest loop.5.11 (let ((x #*00010110)) (loop for e across (the bit-vector x) collect e)) (0 0 0 1 0 1 1 0)) (deftest loop.5.12 (let ((x #*00010110)) (loop for e across (the simple-bit-vector x) collect e)) (0 0 0 1 0 1 1 0)) (deftest loop.5.13 (let ((x #*00010110)) (loop for e of-type bit across (the simple-bit-vector x) collect e)) (0 0 0 1 0 1 1 0)) (deftest loop.5.14 (let ((x #*00010110)) (loop for e of-type bit across x for i from 1 to 4 collect e)) (0 0 0 1)) (deftest loop.5.20 (let ((x (vector 'a 'b 'c 'd))) (loop for e across x collect e)) (a b c d)) (deftest loop.5.21 (let ((x (vector 'a 'b 'c 'd))) (loop for e across (the vector x) collect e)) (a b c d)) (deftest loop.5.22 (let ((x (vector 'a 'b 'c 'd))) (loop for e across (the simple-vector x) collect e)) (a b c d)) (deftest loop.5.23 (let ((x (vector '(a) '(b) '(c) '(d)))) (loop for (e) across x collect e)) (a b c d)) (deftest loop.5.30 (let ((x (make-array '(5) :initial-contents '(a b c d e) :adjustable t))) (loop for e across x collect e)) (a b c d e)) (deftest loop.5.32 (let* ((x (make-array '(5) :initial-contents '(a b c d e))) (y (make-array '(3) :displaced-to x :displaced-index-offset 1))) (loop for e across y collect e)) (b c d)) ;;; tests of 'as' form (deftest loop.5.33 (loop as e across "abc" collect e) (#\a #\b #\c)) (deftest loop.5.34 (loop as e of-type character across "abc" collect e) (#\a #\b #\c)) (deftest loop.5.35 (loop as e of-type integer across (the simple-vector (coerce '(1 2 3) 'simple-vector)) sum e) 6) ;;; Loop across displaced vectors (deftest loop.5.36 (let* ((a (make-array '(10) :initial-contents '(a b c d e f g h i j))) (da (make-array '(5) :displaced-to a :displaced-index-offset 2))) (loop for e across da collect e)) (c d e f g)) (deftest loop.5.37 (let* ((a (make-array '(10) :element-type 'base-char :initial-contents "abcdefghij")) (da (make-array '(5) :element-type 'base-char :displaced-to a :displaced-index-offset 2))) (loop for e across da collect e)) (#\c #\d #\e #\f #\g)) (deftest loop.5.38 (let* ((a (make-array '(10) :element-type 'bit :initial-contents '(0 1 1 0 0 1 0 1 1 1))) (da (make-array '(5) :element-type 'bit :displaced-to a :displaced-index-offset 2))) (loop for e across da collect e)) (1 0 0 1 0)) (deftest loop.5.39 (let ((v (make-array '(10) :initial-contents '(1 2 3 4 5 6 7 8 9 10) :fill-pointer 6))) (loop for x across v collect x)) (1 2 3 4 5 6)) (deftest loop.5.40 (loop for i from 1 to 40 for type = `(unsigned-byte ,i) for v = (make-array '(10) :initial-contents '(0 0 1 1 0 1 1 1 0 0) :element-type type) for r = (loop for x across v collect x) unless (equal r '(0 0 1 1 0 1 1 1 0 0)) collect (list i r)) nil) (deftest loop.5.41 (loop for i from 1 to 40 for type = `(signed-byte ,i) for v = (make-array '(10) :initial-contents '(0 0 -1 -1 0 -1 -1 -1 0 0) :element-type type) for r = (loop for x across v collect x) unless (equal r '(0 0 -1 -1 0 -1 -1 -1 0 0)) collect (list i r)) nil) (deftest loop.5.42 (let ((vals '(0 0 1 1 0 1 1 1 0 0))) (loop for type in '(short-float single-float double-float long-float) for fvals = (loop for v in vals collect (coerce v type)) for v = (make-array '(10) :initial-contents fvals :element-type type) for r = (loop for x across v collect x) unless (equal r fvals) collect (list fvals r))) nil) (deftest loop.5.43 (let ((vals '(0 0 1 1 0 1 1 1 0 0))) (loop for etype in '(short-float single-float double-float long-float) for type = `(complex ,etype) for fvals = (loop for v in vals collect (coerce v type)) for v = (make-array '(10) :initial-contents fvals :element-type type) for r = (loop for x across v collect x) unless (equal r fvals) collect (list fvals r))) nil) ;;; Test that explicit calls to macroexpand in subforms ;;; are done in the correct environment (deftest loop.5.44 (macrolet ((%m (z) z)) (loop for x across (expand-in-current-env (%m "148X")) collect x)) (#\1 #\4 #\8 #\X)) (deftest loop.5.45 (macrolet ((%m (z) z)) (loop as x across (expand-in-current-env (%m #*00110110)) collect x)) (0 0 1 1 0 1 1 0)) ;;; FIXME ;;; Add tests for other specialized array types (integer types, floats, complex) ;;; Error cases (deftest loop.5.error.1 (signals-error (loop for (e . e) across (vector '(x . y) '(u . v)) collect e) program-error) t) (deftest loop.5.error.2 (signals-error (loop for e across (vector '(x . y) '(u . v)) for e from 1 to 5 collect e) program-error) t) (deftest loop.5.error.3 (signals-error (macroexpand '(loop for (e . e) across (vector '(x . y) '(u . v)) collect e)) program-error) t) (deftest loop.5.error.4 (signals-error (macroexpand '(loop for e across (vector '(x . y) '(u . v)) for e from 1 to 5 collect e)) program-error) t)
[ { "context": "track them down.\n\n;;; Copyright (c) 2002-2009, Dr. Edmund Weitz. All rights reserved.\n\n;;; Redistribution and use", "end": 517, "score": 0.9998334646224976, "start": 505, "tag": "NAME", "value": "Edmund Weitz" } ]
books/quicklisp/bundle/software/cl-ppcre-20190521-git/parser.lisp
mayankmanj/acl2
305
;;; -*- Mode: LISP; Syntax: COMMON-LISP; Package: CL-PPCRE; Base: 10 -*- ;;; $Header: /usr/local/cvsrep/cl-ppcre/parser.lisp,v 1.31 2009/09/17 19:17:31 edi Exp $ ;;; The parser will - with the help of the lexer - parse a regex ;;; string and convert it into a "parse tree" (see docs for details ;;; about the syntax of these trees). Note that the lexer might ;;; return illegal parse trees. It is assumed that the conversion ;;; process later on will track them down. ;;; Copyright (c) 2002-2009, 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-ppcre) (defun group (lexer) "Parses and consumes a <group>. The productions are: <group> -> \"\(\"<regex>\")\" \"\(?:\"<regex>\")\" \"\(?>\"<regex>\")\" \"\(?<flags>:\"<regex>\")\" \"\(?=\"<regex>\")\" \"\(?!\"<regex>\")\" \"\(?<=\"<regex>\")\" \"\(?<!\"<regex>\")\" \"\(?\(\"<num>\")\"<regex>\")\" \"\(?\(\"<regex>\")\"<regex>\")\" \"\(?<name>\"<regex>\")\" \(when *ALLOW-NAMED-REGISTERS* is T) <legal-token> where <flags> is parsed by the lexer function MAYBE-PARSE-FLAGS. Will return <parse-tree> or \(<grouping-type> <parse-tree>) where <grouping-type> is one of six keywords - see source for details." (declare #.*standard-optimize-settings*) (multiple-value-bind (open-token flags) (get-token lexer) (cond ((eq open-token :open-paren-paren) ;; special case for conditional regular expressions; note ;; that at this point we accept a couple of illegal ;; combinations which'll be sorted out later by the ;; converter (let* ((open-paren-pos (car (lexer-last-pos lexer))) ;; check if what follows "(?(" is a number (number (try-number lexer :no-whitespace-p t)) ;; make changes to extended-mode-p local (*extended-mode-p* *extended-mode-p*)) (declare (fixnum open-paren-pos)) (cond (number ;; condition is a number (i.e. refers to a ;; back-reference) (let* ((inner-close-token (get-token lexer)) (reg-expr (reg-expr lexer)) (close-token (get-token lexer))) (unless (eq inner-close-token :close-paren) (signal-syntax-error* (+ open-paren-pos 2) "Opening paren has no matching closing paren.")) (unless (eq close-token :close-paren) (signal-syntax-error* open-paren-pos "Opening paren has no matching closing paren.")) (list :branch number reg-expr))) (t ;; condition must be a full regex (actually a ;; look-behind or look-ahead); and here comes a ;; terrible kludge: instead of being cleanly ;; separated from the lexer, the parser pushes ;; back the lexer by one position, thereby ;; landing in the middle of the 'token' "(?(" - ;; yuck!! (decf (lexer-pos lexer)) (let* ((inner-reg-expr (group lexer)) (reg-expr (reg-expr lexer)) (close-token (get-token lexer))) (unless (eq close-token :close-paren) (signal-syntax-error* open-paren-pos "Opening paren has no matching closing paren.")) (list :branch inner-reg-expr reg-expr)))))) ((member open-token '(:open-paren :open-paren-colon :open-paren-greater :open-paren-equal :open-paren-exclamation :open-paren-less-equal :open-paren-less-exclamation :open-paren-less-letter) :test #'eq) ;; make changes to extended-mode-p local (let ((*extended-mode-p* *extended-mode-p*)) ;; we saw one of the six token representing opening ;; parentheses (let* ((open-paren-pos (car (lexer-last-pos lexer))) (register-name (when (eq open-token :open-paren-less-letter) (parse-register-name-aux lexer))) (reg-expr (reg-expr lexer)) (close-token (get-token lexer))) (when (or (eq open-token :open-paren) (eq open-token :open-paren-less-letter)) ;; if this is the "("<regex>")" or "(?"<name>""<regex>")" production we have to ;; increment the register counter of the lexer (incf (lexer-reg lexer))) (unless (eq close-token :close-paren) ;; the token following <regex> must be the closing ;; parenthesis or this is a syntax error (signal-syntax-error* open-paren-pos "Opening paren has no matching closing paren.")) (if flags ;; if the lexer has returned a list of flags this must ;; have been the "(?:"<regex>")" production (cons :group (nconc flags (list reg-expr))) (if (eq open-token :open-paren-less-letter) (list :named-register register-name reg-expr) (list (case open-token ((:open-paren) :register) ((:open-paren-colon) :group) ((:open-paren-greater) :standalone) ((:open-paren-equal) :positive-lookahead) ((:open-paren-exclamation) :negative-lookahead) ((:open-paren-less-equal) :positive-lookbehind) ((:open-paren-less-exclamation) :negative-lookbehind)) reg-expr)))))) (t ;; this is the <legal-token> production; <legal-token> is ;; any token which passes START-OF-SUBEXPR-P (otherwise ;; parsing had already stopped in the SEQ method) open-token)))) (defun greedy-quant (lexer) "Parses and consumes a <greedy-quant>. The productions are: <greedy-quant> -> <group> | <group><quantifier> where <quantifier> is parsed by the lexer function GET-QUANTIFIER. Will return <parse-tree> or (:GREEDY-REPETITION <min> <max> <parse-tree>)." (declare #.*standard-optimize-settings*) (let* ((group (group lexer)) (token (get-quantifier lexer))) (if token ;; if GET-QUANTIFIER returned a non-NIL value it's the ;; two-element list (<min> <max>) (list :greedy-repetition (first token) (second token) group) group))) (defun quant (lexer) "Parses and consumes a <quant>. The productions are: <quant> -> <greedy-quant> | <greedy-quant>\"?\". Will return the <parse-tree> returned by GREEDY-QUANT and optionally change :GREEDY-REPETITION to :NON-GREEDY-REPETITION." (declare #.*standard-optimize-settings*) (let* ((greedy-quant (greedy-quant lexer)) (pos (lexer-pos lexer)) (next-char (next-char lexer))) (when next-char (if (char= next-char #\?) (setf (car greedy-quant) :non-greedy-repetition) (setf (lexer-pos lexer) pos))) greedy-quant)) (defun seq (lexer) "Parses and consumes a <seq>. The productions are: <seq> -> <quant> | <quant><seq>. Will return <parse-tree> or (:SEQUENCE <parse-tree> <parse-tree>)." (declare #.*standard-optimize-settings*) (flet ((make-array-from-two-chars (char1 char2) (let ((string (make-array 2 :element-type 'character :fill-pointer t :adjustable t))) (setf (aref string 0) char1) (setf (aref string 1) char2) string))) ;; Note that we're calling START-OF-SUBEXPR-P before we actually try ;; to parse a <seq> or <quant> in order to catch empty regular ;; expressions (if (start-of-subexpr-p lexer) (loop with seq-is-sequence-p = nil with last-cdr for quant = (quant lexer) for quant-is-char-p = (characterp quant) for seq = quant then (cond ((and quant-is-char-p (characterp seq)) (make-array-from-two-chars seq quant)) ((and quant-is-char-p (stringp seq)) (vector-push-extend quant seq) seq) ((not seq-is-sequence-p) (setf last-cdr (list quant) seq-is-sequence-p t) (list* :sequence seq last-cdr)) ((and quant-is-char-p (characterp (car last-cdr))) (setf (car last-cdr) (make-array-from-two-chars (car last-cdr) quant)) seq) ((and quant-is-char-p (stringp (car last-cdr))) (vector-push-extend quant (car last-cdr)) seq) (t ;; if <seq> is also a :SEQUENCE parse tree we merge ;; both lists into one (let ((cons (list quant))) (psetf last-cdr cons (cdr last-cdr) cons)) seq)) while (start-of-subexpr-p lexer) finally (return seq)) :void))) (defun reg-expr (lexer) "Parses and consumes a <regex>, a complete regular expression. The productions are: <regex> -> <seq> | <seq>\"|\"<regex>. Will return <parse-tree> or (:ALTERNATION <parse-tree> <parse-tree>)." (declare #.*standard-optimize-settings*) (let ((pos (lexer-pos lexer))) (case (next-char lexer) ((nil) ;; if we didn't get any token we return :VOID which stands for ;; "empty regular expression" :void) ((#\|) ;; now check whether the expression started with a vertical ;; bar, i.e. <seq> - the left alternation - is empty (list :alternation :void (reg-expr lexer))) (otherwise ;; otherwise un-read the character we just saw and parse a ;; <seq> plus the character following it (setf (lexer-pos lexer) pos) (let* ((seq (seq lexer)) (pos (lexer-pos lexer))) (case (next-char lexer) ((nil) ;; no further character, just a <seq> seq) ((#\|) ;; if the character was a vertical bar, this is an ;; alternation and we have the second production (let ((reg-expr (reg-expr lexer))) (cond ((and (consp reg-expr) (eq (first reg-expr) :alternation)) ;; again we try to merge as above in SEQ (setf (cdr reg-expr) (cons seq (cdr reg-expr))) reg-expr) (t (list :alternation seq reg-expr))))) (otherwise ;; a character which is not a vertical bar - this is ;; either a syntax error or we're inside of a group and ;; the next character is a closing parenthesis; so we ;; just un-read the character and let another function ;; take care of it (setf (lexer-pos lexer) pos) seq))))))) (defun parse-string (string) "Translate the regex string STRING into a parse tree." (declare #.*standard-optimize-settings*) (let* ((lexer (make-lexer string)) (parse-tree (reg-expr lexer))) ;; check whether we've consumed the whole regex string (if (end-of-string-p lexer) parse-tree (signal-syntax-error* (lexer-pos lexer) "Expected end of string."))))
37998
;;; -*- Mode: LISP; Syntax: COMMON-LISP; Package: CL-PPCRE; Base: 10 -*- ;;; $Header: /usr/local/cvsrep/cl-ppcre/parser.lisp,v 1.31 2009/09/17 19:17:31 edi Exp $ ;;; The parser will - with the help of the lexer - parse a regex ;;; string and convert it into a "parse tree" (see docs for details ;;; about the syntax of these trees). Note that the lexer might ;;; return illegal parse trees. It is assumed that the conversion ;;; process later on will track them down. ;;; Copyright (c) 2002-2009, 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-ppcre) (defun group (lexer) "Parses and consumes a <group>. The productions are: <group> -> \"\(\"<regex>\")\" \"\(?:\"<regex>\")\" \"\(?>\"<regex>\")\" \"\(?<flags>:\"<regex>\")\" \"\(?=\"<regex>\")\" \"\(?!\"<regex>\")\" \"\(?<=\"<regex>\")\" \"\(?<!\"<regex>\")\" \"\(?\(\"<num>\")\"<regex>\")\" \"\(?\(\"<regex>\")\"<regex>\")\" \"\(?<name>\"<regex>\")\" \(when *ALLOW-NAMED-REGISTERS* is T) <legal-token> where <flags> is parsed by the lexer function MAYBE-PARSE-FLAGS. Will return <parse-tree> or \(<grouping-type> <parse-tree>) where <grouping-type> is one of six keywords - see source for details." (declare #.*standard-optimize-settings*) (multiple-value-bind (open-token flags) (get-token lexer) (cond ((eq open-token :open-paren-paren) ;; special case for conditional regular expressions; note ;; that at this point we accept a couple of illegal ;; combinations which'll be sorted out later by the ;; converter (let* ((open-paren-pos (car (lexer-last-pos lexer))) ;; check if what follows "(?(" is a number (number (try-number lexer :no-whitespace-p t)) ;; make changes to extended-mode-p local (*extended-mode-p* *extended-mode-p*)) (declare (fixnum open-paren-pos)) (cond (number ;; condition is a number (i.e. refers to a ;; back-reference) (let* ((inner-close-token (get-token lexer)) (reg-expr (reg-expr lexer)) (close-token (get-token lexer))) (unless (eq inner-close-token :close-paren) (signal-syntax-error* (+ open-paren-pos 2) "Opening paren has no matching closing paren.")) (unless (eq close-token :close-paren) (signal-syntax-error* open-paren-pos "Opening paren has no matching closing paren.")) (list :branch number reg-expr))) (t ;; condition must be a full regex (actually a ;; look-behind or look-ahead); and here comes a ;; terrible kludge: instead of being cleanly ;; separated from the lexer, the parser pushes ;; back the lexer by one position, thereby ;; landing in the middle of the 'token' "(?(" - ;; yuck!! (decf (lexer-pos lexer)) (let* ((inner-reg-expr (group lexer)) (reg-expr (reg-expr lexer)) (close-token (get-token lexer))) (unless (eq close-token :close-paren) (signal-syntax-error* open-paren-pos "Opening paren has no matching closing paren.")) (list :branch inner-reg-expr reg-expr)))))) ((member open-token '(:open-paren :open-paren-colon :open-paren-greater :open-paren-equal :open-paren-exclamation :open-paren-less-equal :open-paren-less-exclamation :open-paren-less-letter) :test #'eq) ;; make changes to extended-mode-p local (let ((*extended-mode-p* *extended-mode-p*)) ;; we saw one of the six token representing opening ;; parentheses (let* ((open-paren-pos (car (lexer-last-pos lexer))) (register-name (when (eq open-token :open-paren-less-letter) (parse-register-name-aux lexer))) (reg-expr (reg-expr lexer)) (close-token (get-token lexer))) (when (or (eq open-token :open-paren) (eq open-token :open-paren-less-letter)) ;; if this is the "("<regex>")" or "(?"<name>""<regex>")" production we have to ;; increment the register counter of the lexer (incf (lexer-reg lexer))) (unless (eq close-token :close-paren) ;; the token following <regex> must be the closing ;; parenthesis or this is a syntax error (signal-syntax-error* open-paren-pos "Opening paren has no matching closing paren.")) (if flags ;; if the lexer has returned a list of flags this must ;; have been the "(?:"<regex>")" production (cons :group (nconc flags (list reg-expr))) (if (eq open-token :open-paren-less-letter) (list :named-register register-name reg-expr) (list (case open-token ((:open-paren) :register) ((:open-paren-colon) :group) ((:open-paren-greater) :standalone) ((:open-paren-equal) :positive-lookahead) ((:open-paren-exclamation) :negative-lookahead) ((:open-paren-less-equal) :positive-lookbehind) ((:open-paren-less-exclamation) :negative-lookbehind)) reg-expr)))))) (t ;; this is the <legal-token> production; <legal-token> is ;; any token which passes START-OF-SUBEXPR-P (otherwise ;; parsing had already stopped in the SEQ method) open-token)))) (defun greedy-quant (lexer) "Parses and consumes a <greedy-quant>. The productions are: <greedy-quant> -> <group> | <group><quantifier> where <quantifier> is parsed by the lexer function GET-QUANTIFIER. Will return <parse-tree> or (:GREEDY-REPETITION <min> <max> <parse-tree>)." (declare #.*standard-optimize-settings*) (let* ((group (group lexer)) (token (get-quantifier lexer))) (if token ;; if GET-QUANTIFIER returned a non-NIL value it's the ;; two-element list (<min> <max>) (list :greedy-repetition (first token) (second token) group) group))) (defun quant (lexer) "Parses and consumes a <quant>. The productions are: <quant> -> <greedy-quant> | <greedy-quant>\"?\". Will return the <parse-tree> returned by GREEDY-QUANT and optionally change :GREEDY-REPETITION to :NON-GREEDY-REPETITION." (declare #.*standard-optimize-settings*) (let* ((greedy-quant (greedy-quant lexer)) (pos (lexer-pos lexer)) (next-char (next-char lexer))) (when next-char (if (char= next-char #\?) (setf (car greedy-quant) :non-greedy-repetition) (setf (lexer-pos lexer) pos))) greedy-quant)) (defun seq (lexer) "Parses and consumes a <seq>. The productions are: <seq> -> <quant> | <quant><seq>. Will return <parse-tree> or (:SEQUENCE <parse-tree> <parse-tree>)." (declare #.*standard-optimize-settings*) (flet ((make-array-from-two-chars (char1 char2) (let ((string (make-array 2 :element-type 'character :fill-pointer t :adjustable t))) (setf (aref string 0) char1) (setf (aref string 1) char2) string))) ;; Note that we're calling START-OF-SUBEXPR-P before we actually try ;; to parse a <seq> or <quant> in order to catch empty regular ;; expressions (if (start-of-subexpr-p lexer) (loop with seq-is-sequence-p = nil with last-cdr for quant = (quant lexer) for quant-is-char-p = (characterp quant) for seq = quant then (cond ((and quant-is-char-p (characterp seq)) (make-array-from-two-chars seq quant)) ((and quant-is-char-p (stringp seq)) (vector-push-extend quant seq) seq) ((not seq-is-sequence-p) (setf last-cdr (list quant) seq-is-sequence-p t) (list* :sequence seq last-cdr)) ((and quant-is-char-p (characterp (car last-cdr))) (setf (car last-cdr) (make-array-from-two-chars (car last-cdr) quant)) seq) ((and quant-is-char-p (stringp (car last-cdr))) (vector-push-extend quant (car last-cdr)) seq) (t ;; if <seq> is also a :SEQUENCE parse tree we merge ;; both lists into one (let ((cons (list quant))) (psetf last-cdr cons (cdr last-cdr) cons)) seq)) while (start-of-subexpr-p lexer) finally (return seq)) :void))) (defun reg-expr (lexer) "Parses and consumes a <regex>, a complete regular expression. The productions are: <regex> -> <seq> | <seq>\"|\"<regex>. Will return <parse-tree> or (:ALTERNATION <parse-tree> <parse-tree>)." (declare #.*standard-optimize-settings*) (let ((pos (lexer-pos lexer))) (case (next-char lexer) ((nil) ;; if we didn't get any token we return :VOID which stands for ;; "empty regular expression" :void) ((#\|) ;; now check whether the expression started with a vertical ;; bar, i.e. <seq> - the left alternation - is empty (list :alternation :void (reg-expr lexer))) (otherwise ;; otherwise un-read the character we just saw and parse a ;; <seq> plus the character following it (setf (lexer-pos lexer) pos) (let* ((seq (seq lexer)) (pos (lexer-pos lexer))) (case (next-char lexer) ((nil) ;; no further character, just a <seq> seq) ((#\|) ;; if the character was a vertical bar, this is an ;; alternation and we have the second production (let ((reg-expr (reg-expr lexer))) (cond ((and (consp reg-expr) (eq (first reg-expr) :alternation)) ;; again we try to merge as above in SEQ (setf (cdr reg-expr) (cons seq (cdr reg-expr))) reg-expr) (t (list :alternation seq reg-expr))))) (otherwise ;; a character which is not a vertical bar - this is ;; either a syntax error or we're inside of a group and ;; the next character is a closing parenthesis; so we ;; just un-read the character and let another function ;; take care of it (setf (lexer-pos lexer) pos) seq))))))) (defun parse-string (string) "Translate the regex string STRING into a parse tree." (declare #.*standard-optimize-settings*) (let* ((lexer (make-lexer string)) (parse-tree (reg-expr lexer))) ;; check whether we've consumed the whole regex string (if (end-of-string-p lexer) parse-tree (signal-syntax-error* (lexer-pos lexer) "Expected end of string."))))
true
;;; -*- Mode: LISP; Syntax: COMMON-LISP; Package: CL-PPCRE; Base: 10 -*- ;;; $Header: /usr/local/cvsrep/cl-ppcre/parser.lisp,v 1.31 2009/09/17 19:17:31 edi Exp $ ;;; The parser will - with the help of the lexer - parse a regex ;;; string and convert it into a "parse tree" (see docs for details ;;; about the syntax of these trees). Note that the lexer might ;;; return illegal parse trees. It is assumed that the conversion ;;; process later on will track them down. ;;; Copyright (c) 2002-2009, 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-ppcre) (defun group (lexer) "Parses and consumes a <group>. The productions are: <group> -> \"\(\"<regex>\")\" \"\(?:\"<regex>\")\" \"\(?>\"<regex>\")\" \"\(?<flags>:\"<regex>\")\" \"\(?=\"<regex>\")\" \"\(?!\"<regex>\")\" \"\(?<=\"<regex>\")\" \"\(?<!\"<regex>\")\" \"\(?\(\"<num>\")\"<regex>\")\" \"\(?\(\"<regex>\")\"<regex>\")\" \"\(?<name>\"<regex>\")\" \(when *ALLOW-NAMED-REGISTERS* is T) <legal-token> where <flags> is parsed by the lexer function MAYBE-PARSE-FLAGS. Will return <parse-tree> or \(<grouping-type> <parse-tree>) where <grouping-type> is one of six keywords - see source for details." (declare #.*standard-optimize-settings*) (multiple-value-bind (open-token flags) (get-token lexer) (cond ((eq open-token :open-paren-paren) ;; special case for conditional regular expressions; note ;; that at this point we accept a couple of illegal ;; combinations which'll be sorted out later by the ;; converter (let* ((open-paren-pos (car (lexer-last-pos lexer))) ;; check if what follows "(?(" is a number (number (try-number lexer :no-whitespace-p t)) ;; make changes to extended-mode-p local (*extended-mode-p* *extended-mode-p*)) (declare (fixnum open-paren-pos)) (cond (number ;; condition is a number (i.e. refers to a ;; back-reference) (let* ((inner-close-token (get-token lexer)) (reg-expr (reg-expr lexer)) (close-token (get-token lexer))) (unless (eq inner-close-token :close-paren) (signal-syntax-error* (+ open-paren-pos 2) "Opening paren has no matching closing paren.")) (unless (eq close-token :close-paren) (signal-syntax-error* open-paren-pos "Opening paren has no matching closing paren.")) (list :branch number reg-expr))) (t ;; condition must be a full regex (actually a ;; look-behind or look-ahead); and here comes a ;; terrible kludge: instead of being cleanly ;; separated from the lexer, the parser pushes ;; back the lexer by one position, thereby ;; landing in the middle of the 'token' "(?(" - ;; yuck!! (decf (lexer-pos lexer)) (let* ((inner-reg-expr (group lexer)) (reg-expr (reg-expr lexer)) (close-token (get-token lexer))) (unless (eq close-token :close-paren) (signal-syntax-error* open-paren-pos "Opening paren has no matching closing paren.")) (list :branch inner-reg-expr reg-expr)))))) ((member open-token '(:open-paren :open-paren-colon :open-paren-greater :open-paren-equal :open-paren-exclamation :open-paren-less-equal :open-paren-less-exclamation :open-paren-less-letter) :test #'eq) ;; make changes to extended-mode-p local (let ((*extended-mode-p* *extended-mode-p*)) ;; we saw one of the six token representing opening ;; parentheses (let* ((open-paren-pos (car (lexer-last-pos lexer))) (register-name (when (eq open-token :open-paren-less-letter) (parse-register-name-aux lexer))) (reg-expr (reg-expr lexer)) (close-token (get-token lexer))) (when (or (eq open-token :open-paren) (eq open-token :open-paren-less-letter)) ;; if this is the "("<regex>")" or "(?"<name>""<regex>")" production we have to ;; increment the register counter of the lexer (incf (lexer-reg lexer))) (unless (eq close-token :close-paren) ;; the token following <regex> must be the closing ;; parenthesis or this is a syntax error (signal-syntax-error* open-paren-pos "Opening paren has no matching closing paren.")) (if flags ;; if the lexer has returned a list of flags this must ;; have been the "(?:"<regex>")" production (cons :group (nconc flags (list reg-expr))) (if (eq open-token :open-paren-less-letter) (list :named-register register-name reg-expr) (list (case open-token ((:open-paren) :register) ((:open-paren-colon) :group) ((:open-paren-greater) :standalone) ((:open-paren-equal) :positive-lookahead) ((:open-paren-exclamation) :negative-lookahead) ((:open-paren-less-equal) :positive-lookbehind) ((:open-paren-less-exclamation) :negative-lookbehind)) reg-expr)))))) (t ;; this is the <legal-token> production; <legal-token> is ;; any token which passes START-OF-SUBEXPR-P (otherwise ;; parsing had already stopped in the SEQ method) open-token)))) (defun greedy-quant (lexer) "Parses and consumes a <greedy-quant>. The productions are: <greedy-quant> -> <group> | <group><quantifier> where <quantifier> is parsed by the lexer function GET-QUANTIFIER. Will return <parse-tree> or (:GREEDY-REPETITION <min> <max> <parse-tree>)." (declare #.*standard-optimize-settings*) (let* ((group (group lexer)) (token (get-quantifier lexer))) (if token ;; if GET-QUANTIFIER returned a non-NIL value it's the ;; two-element list (<min> <max>) (list :greedy-repetition (first token) (second token) group) group))) (defun quant (lexer) "Parses and consumes a <quant>. The productions are: <quant> -> <greedy-quant> | <greedy-quant>\"?\". Will return the <parse-tree> returned by GREEDY-QUANT and optionally change :GREEDY-REPETITION to :NON-GREEDY-REPETITION." (declare #.*standard-optimize-settings*) (let* ((greedy-quant (greedy-quant lexer)) (pos (lexer-pos lexer)) (next-char (next-char lexer))) (when next-char (if (char= next-char #\?) (setf (car greedy-quant) :non-greedy-repetition) (setf (lexer-pos lexer) pos))) greedy-quant)) (defun seq (lexer) "Parses and consumes a <seq>. The productions are: <seq> -> <quant> | <quant><seq>. Will return <parse-tree> or (:SEQUENCE <parse-tree> <parse-tree>)." (declare #.*standard-optimize-settings*) (flet ((make-array-from-two-chars (char1 char2) (let ((string (make-array 2 :element-type 'character :fill-pointer t :adjustable t))) (setf (aref string 0) char1) (setf (aref string 1) char2) string))) ;; Note that we're calling START-OF-SUBEXPR-P before we actually try ;; to parse a <seq> or <quant> in order to catch empty regular ;; expressions (if (start-of-subexpr-p lexer) (loop with seq-is-sequence-p = nil with last-cdr for quant = (quant lexer) for quant-is-char-p = (characterp quant) for seq = quant then (cond ((and quant-is-char-p (characterp seq)) (make-array-from-two-chars seq quant)) ((and quant-is-char-p (stringp seq)) (vector-push-extend quant seq) seq) ((not seq-is-sequence-p) (setf last-cdr (list quant) seq-is-sequence-p t) (list* :sequence seq last-cdr)) ((and quant-is-char-p (characterp (car last-cdr))) (setf (car last-cdr) (make-array-from-two-chars (car last-cdr) quant)) seq) ((and quant-is-char-p (stringp (car last-cdr))) (vector-push-extend quant (car last-cdr)) seq) (t ;; if <seq> is also a :SEQUENCE parse tree we merge ;; both lists into one (let ((cons (list quant))) (psetf last-cdr cons (cdr last-cdr) cons)) seq)) while (start-of-subexpr-p lexer) finally (return seq)) :void))) (defun reg-expr (lexer) "Parses and consumes a <regex>, a complete regular expression. The productions are: <regex> -> <seq> | <seq>\"|\"<regex>. Will return <parse-tree> or (:ALTERNATION <parse-tree> <parse-tree>)." (declare #.*standard-optimize-settings*) (let ((pos (lexer-pos lexer))) (case (next-char lexer) ((nil) ;; if we didn't get any token we return :VOID which stands for ;; "empty regular expression" :void) ((#\|) ;; now check whether the expression started with a vertical ;; bar, i.e. <seq> - the left alternation - is empty (list :alternation :void (reg-expr lexer))) (otherwise ;; otherwise un-read the character we just saw and parse a ;; <seq> plus the character following it (setf (lexer-pos lexer) pos) (let* ((seq (seq lexer)) (pos (lexer-pos lexer))) (case (next-char lexer) ((nil) ;; no further character, just a <seq> seq) ((#\|) ;; if the character was a vertical bar, this is an ;; alternation and we have the second production (let ((reg-expr (reg-expr lexer))) (cond ((and (consp reg-expr) (eq (first reg-expr) :alternation)) ;; again we try to merge as above in SEQ (setf (cdr reg-expr) (cons seq (cdr reg-expr))) reg-expr) (t (list :alternation seq reg-expr))))) (otherwise ;; a character which is not a vertical bar - this is ;; either a syntax error or we're inside of a group and ;; the next character is a closing parenthesis; so we ;; just un-read the character and let another function ;; take care of it (setf (lexer-pos lexer) pos) seq))))))) (defun parse-string (string) "Translate the regex string STRING into a parse tree." (declare #.*standard-optimize-settings*) (let* ((lexer (make-lexer string)) (parse-tree (reg-expr lexer))) ;; check whether we've consumed the whole regex string (if (end-of-string-p lexer) parse-tree (signal-syntax-error* (lexer-pos lexer) "Expected end of string."))))
[ { "context": "cl-project:make-project \"./\" :name \"pkg\" :author \"imcomputer\"\n :license \"...\" :depends-on '(...)' :email ", "end": 522, "score": 0.9993691444396973, "start": 512, "tag": "USERNAME", "value": "imcomputer" }, { "context": "ate user-p))\n \"User structure\"\n \n (name \"NoName\" :type string :read-only nil)\n (num 0 :type fi", "end": 3067, "score": 0.9090050458908081, "start": 3061, "tag": "USERNAME", "value": "NoName" }, { "context": "\t\t(person1 (make-instance 'person:<person> :name \"I. M. Computer\" \n :age 32))\n (num-vec ", "end": 3599, "score": 0.999862790107727, "start": 3585, "tag": "NAME", "value": "I. M. Computer" }, { "context": "mdopts using getopt\"\n (let ((verbose 0) (user \"World\") (num \"0\") (is-expt2 nil))\n (multiple-val", "end": 8890, "score": 0.809182345867157, "start": 8885, "tag": "USERNAME", "value": "World" } ]
app/src/main.lisp
thebridge0491/introlisp
0
":"; exec sbcl --script $0 $@ ":"; exit ;#!/usr/bin/env sbcl --script ; Common Lisp - comments style conventions ; title ;;;; Short title for block of code ; intro ;;; Description before block of code ; state ;; State of program or following code ; explanation ; Regarding line on which it appears ; single-line comment #| multi-line comment --- package manager - init/configure package --- (asdf:load-systems :cl-project) (cl-project:make-project "./" :name "pkg" :author "imcomputer" :license "..." :depends-on '(...)' :email "..." :description "...") --- generate docs --- (asdf:load-systems {:codex | :documentation-template} :pkg) ;(codex:document :pkg) (documentation-template:create-template :pkg :subtitle "Title" :target "docpath/dir/file.html") --- [native|byte]code - compile ; then run app --- ;[sbcl | clisp] [--load | -i] main.lisp [--eval | -x] '(pkg:save-image)' ;buildapp --load main.lisp --entry pkg:main --output main [sbcl | clisp] [--load | -i] main.lisp [--eval | -x] '(asdf:make :pkg/run-image)' ./main arg1 argN --- start REPL w/ loaded script ; then run app --- ; [sbcl | clisp] [--load | -i] main.lisp [--eval | -x] '(pkg:run-main)' -- arg1 argN ;[sbcl | clisp] [--load | -i] main.lisp ; --eval '(asdf:test-system :pkg/run)' -- arg1 argN [sbcl | clisp] [--load | -i] main.lisp [--eval | -x] '(main (list arg1 argN))' * > (main '("arg1" "argN")) --- help/info tools in REPL --- (apropos 'PATTERN [:PKG]) (describe 'SYMBOL) *features* (documentation 'NAME 'DOC-TYPE) ; --- DOC-TYPE(s): 'T|'TYPE|'FUNCTION|'VARIABLE|'STRUCTURE|'SETF |# ;(load "~/quicklisp/setup.lisp") ;(ql:register-local-projects) #| ;(require :asdf) (eval-when (:compile-toplevel :load-toplevel :execute) (require "asdf")) |# (asdf:load-systems :log4cl :unix-options :getopt :cli-parser :py-configparser :cl-ppcre :cl-json :cl-yaml :introlisp.util :introlisp.practice :introlisp.intro/src/lib :introlisp.intro/src/person) (defpackage :introlisp.intro/src/main (:documentation "Main app") (:use :cl :log4cl :unix-options :py-configparser :cl-ppcre :cl-json :cl-yaml) (:nicknames :introlisp.intro) (:export :main :run-main :save-image) ) (in-package :introlisp.intro/src/main) (rename-package :introlisp.util :introlisp.util '(:util)) (rename-package :introlisp.practice.classic :introlisp.practice.classic '(:classic)) (rename-package :introlisp.practice.sequenceops :introlisp.practice.sequenceops '(:sequenceops :seqops)) (rename-package :introlisp.intro/src/lib :introlisp.intro/src/lib '(:lib)) (rename-package :introlisp.intro/src/person :introlisp.intro/src/person '(:person)) (rename-package :introlisp.practice.classic.puzzles :introlisp.practice.classic.puzzles '(:puzzles)) (defstruct (user (:constructor make-user) (:constructor create-user (name num timein)) (:conc-name user-) (:predicate user-p)) "User structure" (name "NoName" :type string :read-only nil) (num 0 :type fixnum :read-only nil) (timein (encode-universal-time 0 0 0 1 1 1970) :type fixnum :read-only nil)) (defun run-intro (rsrc-dir name num is-expt2) "Run intro" (let* ((time-in (get-internal-real-time)) (pat "(?i:^quit$)") (ch #\Nul) (greet-path (merge-pathnames "greet.txt" rsrc-dir)) (delay-secs (ceiling (/ 25 10))) (user1 (make-user :name name :num num :timein (get-universal-time))) (person1 (make-instance 'person:<person> :name "I. M. Computer" :age 32)) (num-vec (vector #b1011 #o13 #xb 11)) ; (bin oct hex dec) (num-val 0) (time-dur 0.0) (lst '(2 1 0 4 3)) (rnd-state (make-random-state t)) (num-disks 4) (num-queens 8) (res-queens (puzzles:nqueens num-queens)) (queens-ndx (random (length res-queens) rnd-state)) (queens-answer (nth queens-ndx res-queens)) ) (setf num-val (reduce (lambda (a e) (+ a e)) num-vec :initial-value 0)) ;(if (not (= num-val ; (* (length num-vec) (aref num-vec 0)))) ; (error "Assert fails: len * 1st elem == num-val->~a" num-val)) (handler-case (assert (= num-val (* (length num-vec) (aref num-vec 0)))) (error (exc) (format t "~a~%" exc))) (setf ch (lib:delay-char (lambda () (sleep delay-secs)))) (if (= 0 (user-num user1)) (setf (user-num user1) (+ (random 18 rnd-state) 2))) (format t "~a match ~a to ~a~%" (if (cl-ppcre:scan pat name) "Good" "Does not") (user-name user1) pat) (format t "~a~%" (util:date-to-string (user-timein user1))) #| (catch 'prac (handler-bind ( (warning #'(lambda (exc) (format t "Warning Condition: ~a~%" exc) (throw 'prac t))) (file-error #'(lambda (exc) (format t "File Error Condition: ~a~%" exc) (throw 'prac t))) (error #'(lambda (exc) (format t "Error Condition: ~a~%" exc) (throw 'prac t)))) (format t "~a~%" (lib:greeting greet-path (user-name user1))))) |# (handler-case (format t "~a~%" (lib:greeting greet-path (user-name user1))) (warning (exc) (format t "Warning Condition: ~a~%" exc)) (file-error (exc) (format t "File Error Condition: ~a~%" exc)) (error (exc) (format t "Error Condition: ~a~%" exc))) (setf time-dur (/ (- (get-internal-real-time) time-in) internal-time-units-per-second)) (format t "(program ~a) Took ~,2f seconds.~%" (uiop:argv0) time-dur) (format t "~a~%" (make-string 40 :initial-element #\#)) (if is-expt2 (progn (format t "expt 2.0 ~,1f: ~,1f~%" (user-num user1) (classic:expt-i 2.0 (user-num user1))) (format t "reverse ~a: ~a~%" lst (seqops:reverse-i lst)) (format t "sort ~a #'<: ~a~%" (append '(9 9 9 9) lst) (sort (append '(9 9 9 9) lst) #'<)) ) (progn (format t "fact ~a: ~a~%" (user-num user1) (classic:fact-i (user-num user1))) (format t "index (= 3 e) ~a: ~a~%" lst (seqops:index-i (lambda (e) (equal e 3)) lst)) (format t "append ~a ~a: ~a~%" '(9 9 9 9) lst (append '(9 9 9 9) lst)) )) (format t "~a~%" (make-string 40 :initial-element #\#)) (format t "pascaltri ~a: ~a~%" 5 (classic:pascaltri-add 5)) (format t "~a~%" (util:mkstring-nested (string #\newline) " " "" (classic:pascaltri-add 5))) (format t "~a~%" (make-string 40 :initial-element #\#)) (multiple-value-bind (res stats moves) (puzzles:hanoi-moves 1 2 3 num-disks) (format t "hanoi-moves (result: ~a)~%(stats: ~a)" res stats)) (format t "~a~%" (util:mkstring-nested "" " " "" (multiple-value-bind (res stats moves) (puzzles:hanoi-moves 1 2 3 num-disks) (list moves)))) (format t "~a~%" (make-string 40 :initial-element #\#)) (format t "nqueens-grid ~a (idx: ~a): ~a" num-queens queens-ndx queens-answer) (format t "~a~%" (util:mkstring-nested (string #\newline) "-" "" (util:arr2d-to-nlsts (puzzles:nqueens-grid num-queens queens-answer)))) (format t "~a~%" (make-string 40 :initial-element #\#)) (format t "~a~%" #+ccl (ccl::class-slots (find-class 'person:<person>)) #+sbcl (sb-mop:class-slots (find-class 'person:<person>)) #+clisp (clos:class-slots (find-class 'person:<person>)) ) ;(format t "person-age person1: ~a~%" (slot-value person1 'person:age)) ;(setf (slot-value person1 'person:age) 33) (format t "person-age person1: ~a~%" (person:person-age person1)) (setf (person:person-age person1) 33) (format t "setf (person-age person1) 33:~%") (format t "~a~%" (person:peek-person person1)) (format t "type-of person1: ~a~%class-of person1: ~a~%" (type-of person1) (class-of person1)) (format t "~a~%" (make-string 40 :initial-element #\#)) )) (defun parse-cmdopts-unix-options (argv) "Parse cmdopts using unix-options" (unix-options:with-cli-options (argv t) ((2expt "Expt 2 n vice Fact n") (verbose (verbose "VERBOSITY" "Verbosity level")) (user (user "USER" "User name")) (num (num "NUM" "Number to factorialize"))) (values (or verbose 0) (or user "World") (or num "0") 2expt))) (defun show-help (progname) "Usage help" (format t "Usage: ~a [-h][-2][-v VERBOSITY][-u USER][-n NUM]~%" progname)) (defparameter *opts* '(("help" :none) ("verbose" :required) ("user" :required) ("num" :required) ("is-expt2" :none)) "Options for getopt") (defun parse-cmdopts-getopt (argv) "Parse cmdopts using getopt" (let ((verbose 0) (user "World") (num "0") (is-expt2 nil)) (multiple-value-bind (args opts) (getopt:getopt argv *opts*) ;(progn ; (mapcar (lambda (opt) ; (case (car opt) ; ("help" (show-help (uiop:argv0)) (uiop:quit)) ; (t ; {t|otherwise} ; (format t "??? No matching options.~%")))) (progn (mapcar (lambda (opt) (cond ((equal (car opt) "help") (show-help (uiop:argv0)) (uiop:quit)) ((equal (car opt) "is-expt2") (setf is-expt2 (cdr opt))) ((equal (car opt) "verbose") (setf verbose (cdr opt))) ((equal (car opt) "user") (setf user (cdr opt))) ((equal (car opt) "num") (setf num (cdr opt))) (t (format t "??? No matching options.~%")))) opts) nil) (values verbose user num is-expt2)))) (defparameter *option-conf* (list (make-instance 'cli-parser:cli-option :abbr "h" :full "help" :requires-arguments nil :description "Usage help" :example "--help") (make-instance 'cli-parser:cli-option :abbr "v" :full "verbose" :requires-arguments t :description "Verbosity level" :example "--verbose=3") (make-instance 'cli-parser:cli-option :abbr "u" :full "user" :requires-arguments t :description "User name" :example "--user=Name1") (make-instance 'cli-parser:cli-option :abbr "n" :full "num" :requires-arguments t :description "Number to factorialize" :example "--num=5") (make-instance 'cli-parser:cli-option :abbr "2" :full "is-expt2" :requires-arguments nil :description "Expt 2 n vice Fact n" :example "--is-expt2") ) "Options for cli-parser") (defun parse-cmdopts-cli-parser (argv) "Parse cmdopts using cli-parser" (let ((opt-hash (cli-parser:cli-parse argv *option-conf*))) (if (not (gethash "help" opt-hash t)) (progn (show-help (uiop:argv0)) (uiop:quit))) (values (car (gethash "verbose" opt-hash '(0))) (car (gethash "user" opt-hash '("World"))) (car (gethash "num" opt-hash '("0"))) (not (gethash "is-expt2" opt-hash t)) ))) (defun parse-cmdopts (argv) "Parse command-line options" (log:info '(root) "parse-cmdopts()") (cond (nil (parse-cmdopts-getopt argv)) (nil (parse-cmdopts-cli-parser argv)) (t (parse-cmdopts-unix-options argv)) )) (defun main (argv) "Entry point" (let* ((sys-dir (asdf:system-source-directory :introlisp.intro)) (rsrc-dir (pathname (or (uiop:getenv "RSRC_PATH") (merge-pathnames "resources/" sys-dir)))) (ini-cfg (py-configparser:make-config)) (alst-cfg (cl-json:decode-json-from-source (merge-pathnames "prac.json" rsrc-dir))) (cl-json:*json-symbols-package* nil) (obj-cfg (cl-json:with-decoder-simple-clos-semantics (cl-json:decode-json-from-source (merge-pathnames "prac_htbl.json" rsrc-dir)))) (htbl (make-hash-table :test 'equal)) (yaml-htbl (yaml:parse (merge-pathnames "prac.yaml" rsrc-dir))) ) (log:config :properties (merge-pathnames "log4cl.conf" rsrc-dir)) (py-configparser:read-files ini-cfg (list (merge-pathnames "prac.conf" rsrc-dir))) (maphash (lambda (k v) (setf (gethash (princ-to-string k) htbl) v)) obj-cfg) (maphash (lambda (k v) (setf (gethash (princ-to-string k) (gethash "USER-1" htbl)) v)) (gethash "USER-1" htbl)) (let* ((tup-vec (vector (cons (slot-value ini-cfg 'py-configparser:sections) (cons (py-configparser:get-option ini-cfg "default" "domain") (py-configparser:get-option ini-cfg "user1" "name"))) (cons alst-cfg (cons (cdr (assoc :domain alst-cfg)) (cdr (assoc :name (cdr (assoc :user-1 alst-cfg)))))) (cons (util:hashtbl->alist obj-cfg) (cons (gethash "DOMAIN" htbl) (gethash "NAME" (gethash "USER-1" htbl)))) (cons (util:hashtbl->alist yaml-htbl) (cons (gethash "domain" yaml-htbl) (gethash "name" (gethash "user1" yaml-htbl)))) ))) (map nil (lambda (tup3) (progn (format t "config: ~a~%" (car tup3)) (format t "domain: ~a~%" (cadr tup3)) (format t "user1Name: ~a~%" (cddr tup3)) )) tup-vec) ) (multiple-value-bind (verbose user num is-expt2) (parse-cmdopts argv) (handler-case (run-intro rsrc-dir user (or (parse-integer num :junk-allowed t) 5) is-expt2) (type-error (condition) (uiop:quit)))) )) ;(uiop:quit)) ;(if (member (pathname-name *load-truename*) (uiop:command-line-arguments) ; :test #'(lambda (x y) (search x y :test #'equalp))) ; (main (uiop:command-line-arguments))) ;(main (uiop:command-line-arguments)) (defun run-main () (main (uiop:command-line-arguments)) (uiop:quit) ) (defun save-image () #+sbcl (sb-ext:save-lisp-and-die "build/main" :executable t :toplevel 'introlisp.intro:run-main) #+clisp (ext:saveinitmem "build/main" :executable t :init-function 'introlisp.intro:run-main) #+ccl (ccl:save-application "build/main" :prepend-kernel t :toplevel-function 'introlisp.intro:run-main) )
30340
":"; exec sbcl --script $0 $@ ":"; exit ;#!/usr/bin/env sbcl --script ; Common Lisp - comments style conventions ; title ;;;; Short title for block of code ; intro ;;; Description before block of code ; state ;; State of program or following code ; explanation ; Regarding line on which it appears ; single-line comment #| multi-line comment --- package manager - init/configure package --- (asdf:load-systems :cl-project) (cl-project:make-project "./" :name "pkg" :author "imcomputer" :license "..." :depends-on '(...)' :email "..." :description "...") --- generate docs --- (asdf:load-systems {:codex | :documentation-template} :pkg) ;(codex:document :pkg) (documentation-template:create-template :pkg :subtitle "Title" :target "docpath/dir/file.html") --- [native|byte]code - compile ; then run app --- ;[sbcl | clisp] [--load | -i] main.lisp [--eval | -x] '(pkg:save-image)' ;buildapp --load main.lisp --entry pkg:main --output main [sbcl | clisp] [--load | -i] main.lisp [--eval | -x] '(asdf:make :pkg/run-image)' ./main arg1 argN --- start REPL w/ loaded script ; then run app --- ; [sbcl | clisp] [--load | -i] main.lisp [--eval | -x] '(pkg:run-main)' -- arg1 argN ;[sbcl | clisp] [--load | -i] main.lisp ; --eval '(asdf:test-system :pkg/run)' -- arg1 argN [sbcl | clisp] [--load | -i] main.lisp [--eval | -x] '(main (list arg1 argN))' * > (main '("arg1" "argN")) --- help/info tools in REPL --- (apropos 'PATTERN [:PKG]) (describe 'SYMBOL) *features* (documentation 'NAME 'DOC-TYPE) ; --- DOC-TYPE(s): 'T|'TYPE|'FUNCTION|'VARIABLE|'STRUCTURE|'SETF |# ;(load "~/quicklisp/setup.lisp") ;(ql:register-local-projects) #| ;(require :asdf) (eval-when (:compile-toplevel :load-toplevel :execute) (require "asdf")) |# (asdf:load-systems :log4cl :unix-options :getopt :cli-parser :py-configparser :cl-ppcre :cl-json :cl-yaml :introlisp.util :introlisp.practice :introlisp.intro/src/lib :introlisp.intro/src/person) (defpackage :introlisp.intro/src/main (:documentation "Main app") (:use :cl :log4cl :unix-options :py-configparser :cl-ppcre :cl-json :cl-yaml) (:nicknames :introlisp.intro) (:export :main :run-main :save-image) ) (in-package :introlisp.intro/src/main) (rename-package :introlisp.util :introlisp.util '(:util)) (rename-package :introlisp.practice.classic :introlisp.practice.classic '(:classic)) (rename-package :introlisp.practice.sequenceops :introlisp.practice.sequenceops '(:sequenceops :seqops)) (rename-package :introlisp.intro/src/lib :introlisp.intro/src/lib '(:lib)) (rename-package :introlisp.intro/src/person :introlisp.intro/src/person '(:person)) (rename-package :introlisp.practice.classic.puzzles :introlisp.practice.classic.puzzles '(:puzzles)) (defstruct (user (:constructor make-user) (:constructor create-user (name num timein)) (:conc-name user-) (:predicate user-p)) "User structure" (name "NoName" :type string :read-only nil) (num 0 :type fixnum :read-only nil) (timein (encode-universal-time 0 0 0 1 1 1970) :type fixnum :read-only nil)) (defun run-intro (rsrc-dir name num is-expt2) "Run intro" (let* ((time-in (get-internal-real-time)) (pat "(?i:^quit$)") (ch #\Nul) (greet-path (merge-pathnames "greet.txt" rsrc-dir)) (delay-secs (ceiling (/ 25 10))) (user1 (make-user :name name :num num :timein (get-universal-time))) (person1 (make-instance 'person:<person> :name "<NAME>" :age 32)) (num-vec (vector #b1011 #o13 #xb 11)) ; (bin oct hex dec) (num-val 0) (time-dur 0.0) (lst '(2 1 0 4 3)) (rnd-state (make-random-state t)) (num-disks 4) (num-queens 8) (res-queens (puzzles:nqueens num-queens)) (queens-ndx (random (length res-queens) rnd-state)) (queens-answer (nth queens-ndx res-queens)) ) (setf num-val (reduce (lambda (a e) (+ a e)) num-vec :initial-value 0)) ;(if (not (= num-val ; (* (length num-vec) (aref num-vec 0)))) ; (error "Assert fails: len * 1st elem == num-val->~a" num-val)) (handler-case (assert (= num-val (* (length num-vec) (aref num-vec 0)))) (error (exc) (format t "~a~%" exc))) (setf ch (lib:delay-char (lambda () (sleep delay-secs)))) (if (= 0 (user-num user1)) (setf (user-num user1) (+ (random 18 rnd-state) 2))) (format t "~a match ~a to ~a~%" (if (cl-ppcre:scan pat name) "Good" "Does not") (user-name user1) pat) (format t "~a~%" (util:date-to-string (user-timein user1))) #| (catch 'prac (handler-bind ( (warning #'(lambda (exc) (format t "Warning Condition: ~a~%" exc) (throw 'prac t))) (file-error #'(lambda (exc) (format t "File Error Condition: ~a~%" exc) (throw 'prac t))) (error #'(lambda (exc) (format t "Error Condition: ~a~%" exc) (throw 'prac t)))) (format t "~a~%" (lib:greeting greet-path (user-name user1))))) |# (handler-case (format t "~a~%" (lib:greeting greet-path (user-name user1))) (warning (exc) (format t "Warning Condition: ~a~%" exc)) (file-error (exc) (format t "File Error Condition: ~a~%" exc)) (error (exc) (format t "Error Condition: ~a~%" exc))) (setf time-dur (/ (- (get-internal-real-time) time-in) internal-time-units-per-second)) (format t "(program ~a) Took ~,2f seconds.~%" (uiop:argv0) time-dur) (format t "~a~%" (make-string 40 :initial-element #\#)) (if is-expt2 (progn (format t "expt 2.0 ~,1f: ~,1f~%" (user-num user1) (classic:expt-i 2.0 (user-num user1))) (format t "reverse ~a: ~a~%" lst (seqops:reverse-i lst)) (format t "sort ~a #'<: ~a~%" (append '(9 9 9 9) lst) (sort (append '(9 9 9 9) lst) #'<)) ) (progn (format t "fact ~a: ~a~%" (user-num user1) (classic:fact-i (user-num user1))) (format t "index (= 3 e) ~a: ~a~%" lst (seqops:index-i (lambda (e) (equal e 3)) lst)) (format t "append ~a ~a: ~a~%" '(9 9 9 9) lst (append '(9 9 9 9) lst)) )) (format t "~a~%" (make-string 40 :initial-element #\#)) (format t "pascaltri ~a: ~a~%" 5 (classic:pascaltri-add 5)) (format t "~a~%" (util:mkstring-nested (string #\newline) " " "" (classic:pascaltri-add 5))) (format t "~a~%" (make-string 40 :initial-element #\#)) (multiple-value-bind (res stats moves) (puzzles:hanoi-moves 1 2 3 num-disks) (format t "hanoi-moves (result: ~a)~%(stats: ~a)" res stats)) (format t "~a~%" (util:mkstring-nested "" " " "" (multiple-value-bind (res stats moves) (puzzles:hanoi-moves 1 2 3 num-disks) (list moves)))) (format t "~a~%" (make-string 40 :initial-element #\#)) (format t "nqueens-grid ~a (idx: ~a): ~a" num-queens queens-ndx queens-answer) (format t "~a~%" (util:mkstring-nested (string #\newline) "-" "" (util:arr2d-to-nlsts (puzzles:nqueens-grid num-queens queens-answer)))) (format t "~a~%" (make-string 40 :initial-element #\#)) (format t "~a~%" #+ccl (ccl::class-slots (find-class 'person:<person>)) #+sbcl (sb-mop:class-slots (find-class 'person:<person>)) #+clisp (clos:class-slots (find-class 'person:<person>)) ) ;(format t "person-age person1: ~a~%" (slot-value person1 'person:age)) ;(setf (slot-value person1 'person:age) 33) (format t "person-age person1: ~a~%" (person:person-age person1)) (setf (person:person-age person1) 33) (format t "setf (person-age person1) 33:~%") (format t "~a~%" (person:peek-person person1)) (format t "type-of person1: ~a~%class-of person1: ~a~%" (type-of person1) (class-of person1)) (format t "~a~%" (make-string 40 :initial-element #\#)) )) (defun parse-cmdopts-unix-options (argv) "Parse cmdopts using unix-options" (unix-options:with-cli-options (argv t) ((2expt "Expt 2 n vice Fact n") (verbose (verbose "VERBOSITY" "Verbosity level")) (user (user "USER" "User name")) (num (num "NUM" "Number to factorialize"))) (values (or verbose 0) (or user "World") (or num "0") 2expt))) (defun show-help (progname) "Usage help" (format t "Usage: ~a [-h][-2][-v VERBOSITY][-u USER][-n NUM]~%" progname)) (defparameter *opts* '(("help" :none) ("verbose" :required) ("user" :required) ("num" :required) ("is-expt2" :none)) "Options for getopt") (defun parse-cmdopts-getopt (argv) "Parse cmdopts using getopt" (let ((verbose 0) (user "World") (num "0") (is-expt2 nil)) (multiple-value-bind (args opts) (getopt:getopt argv *opts*) ;(progn ; (mapcar (lambda (opt) ; (case (car opt) ; ("help" (show-help (uiop:argv0)) (uiop:quit)) ; (t ; {t|otherwise} ; (format t "??? No matching options.~%")))) (progn (mapcar (lambda (opt) (cond ((equal (car opt) "help") (show-help (uiop:argv0)) (uiop:quit)) ((equal (car opt) "is-expt2") (setf is-expt2 (cdr opt))) ((equal (car opt) "verbose") (setf verbose (cdr opt))) ((equal (car opt) "user") (setf user (cdr opt))) ((equal (car opt) "num") (setf num (cdr opt))) (t (format t "??? No matching options.~%")))) opts) nil) (values verbose user num is-expt2)))) (defparameter *option-conf* (list (make-instance 'cli-parser:cli-option :abbr "h" :full "help" :requires-arguments nil :description "Usage help" :example "--help") (make-instance 'cli-parser:cli-option :abbr "v" :full "verbose" :requires-arguments t :description "Verbosity level" :example "--verbose=3") (make-instance 'cli-parser:cli-option :abbr "u" :full "user" :requires-arguments t :description "User name" :example "--user=Name1") (make-instance 'cli-parser:cli-option :abbr "n" :full "num" :requires-arguments t :description "Number to factorialize" :example "--num=5") (make-instance 'cli-parser:cli-option :abbr "2" :full "is-expt2" :requires-arguments nil :description "Expt 2 n vice Fact n" :example "--is-expt2") ) "Options for cli-parser") (defun parse-cmdopts-cli-parser (argv) "Parse cmdopts using cli-parser" (let ((opt-hash (cli-parser:cli-parse argv *option-conf*))) (if (not (gethash "help" opt-hash t)) (progn (show-help (uiop:argv0)) (uiop:quit))) (values (car (gethash "verbose" opt-hash '(0))) (car (gethash "user" opt-hash '("World"))) (car (gethash "num" opt-hash '("0"))) (not (gethash "is-expt2" opt-hash t)) ))) (defun parse-cmdopts (argv) "Parse command-line options" (log:info '(root) "parse-cmdopts()") (cond (nil (parse-cmdopts-getopt argv)) (nil (parse-cmdopts-cli-parser argv)) (t (parse-cmdopts-unix-options argv)) )) (defun main (argv) "Entry point" (let* ((sys-dir (asdf:system-source-directory :introlisp.intro)) (rsrc-dir (pathname (or (uiop:getenv "RSRC_PATH") (merge-pathnames "resources/" sys-dir)))) (ini-cfg (py-configparser:make-config)) (alst-cfg (cl-json:decode-json-from-source (merge-pathnames "prac.json" rsrc-dir))) (cl-json:*json-symbols-package* nil) (obj-cfg (cl-json:with-decoder-simple-clos-semantics (cl-json:decode-json-from-source (merge-pathnames "prac_htbl.json" rsrc-dir)))) (htbl (make-hash-table :test 'equal)) (yaml-htbl (yaml:parse (merge-pathnames "prac.yaml" rsrc-dir))) ) (log:config :properties (merge-pathnames "log4cl.conf" rsrc-dir)) (py-configparser:read-files ini-cfg (list (merge-pathnames "prac.conf" rsrc-dir))) (maphash (lambda (k v) (setf (gethash (princ-to-string k) htbl) v)) obj-cfg) (maphash (lambda (k v) (setf (gethash (princ-to-string k) (gethash "USER-1" htbl)) v)) (gethash "USER-1" htbl)) (let* ((tup-vec (vector (cons (slot-value ini-cfg 'py-configparser:sections) (cons (py-configparser:get-option ini-cfg "default" "domain") (py-configparser:get-option ini-cfg "user1" "name"))) (cons alst-cfg (cons (cdr (assoc :domain alst-cfg)) (cdr (assoc :name (cdr (assoc :user-1 alst-cfg)))))) (cons (util:hashtbl->alist obj-cfg) (cons (gethash "DOMAIN" htbl) (gethash "NAME" (gethash "USER-1" htbl)))) (cons (util:hashtbl->alist yaml-htbl) (cons (gethash "domain" yaml-htbl) (gethash "name" (gethash "user1" yaml-htbl)))) ))) (map nil (lambda (tup3) (progn (format t "config: ~a~%" (car tup3)) (format t "domain: ~a~%" (cadr tup3)) (format t "user1Name: ~a~%" (cddr tup3)) )) tup-vec) ) (multiple-value-bind (verbose user num is-expt2) (parse-cmdopts argv) (handler-case (run-intro rsrc-dir user (or (parse-integer num :junk-allowed t) 5) is-expt2) (type-error (condition) (uiop:quit)))) )) ;(uiop:quit)) ;(if (member (pathname-name *load-truename*) (uiop:command-line-arguments) ; :test #'(lambda (x y) (search x y :test #'equalp))) ; (main (uiop:command-line-arguments))) ;(main (uiop:command-line-arguments)) (defun run-main () (main (uiop:command-line-arguments)) (uiop:quit) ) (defun save-image () #+sbcl (sb-ext:save-lisp-and-die "build/main" :executable t :toplevel 'introlisp.intro:run-main) #+clisp (ext:saveinitmem "build/main" :executable t :init-function 'introlisp.intro:run-main) #+ccl (ccl:save-application "build/main" :prepend-kernel t :toplevel-function 'introlisp.intro:run-main) )
true
":"; exec sbcl --script $0 $@ ":"; exit ;#!/usr/bin/env sbcl --script ; Common Lisp - comments style conventions ; title ;;;; Short title for block of code ; intro ;;; Description before block of code ; state ;; State of program or following code ; explanation ; Regarding line on which it appears ; single-line comment #| multi-line comment --- package manager - init/configure package --- (asdf:load-systems :cl-project) (cl-project:make-project "./" :name "pkg" :author "imcomputer" :license "..." :depends-on '(...)' :email "..." :description "...") --- generate docs --- (asdf:load-systems {:codex | :documentation-template} :pkg) ;(codex:document :pkg) (documentation-template:create-template :pkg :subtitle "Title" :target "docpath/dir/file.html") --- [native|byte]code - compile ; then run app --- ;[sbcl | clisp] [--load | -i] main.lisp [--eval | -x] '(pkg:save-image)' ;buildapp --load main.lisp --entry pkg:main --output main [sbcl | clisp] [--load | -i] main.lisp [--eval | -x] '(asdf:make :pkg/run-image)' ./main arg1 argN --- start REPL w/ loaded script ; then run app --- ; [sbcl | clisp] [--load | -i] main.lisp [--eval | -x] '(pkg:run-main)' -- arg1 argN ;[sbcl | clisp] [--load | -i] main.lisp ; --eval '(asdf:test-system :pkg/run)' -- arg1 argN [sbcl | clisp] [--load | -i] main.lisp [--eval | -x] '(main (list arg1 argN))' * > (main '("arg1" "argN")) --- help/info tools in REPL --- (apropos 'PATTERN [:PKG]) (describe 'SYMBOL) *features* (documentation 'NAME 'DOC-TYPE) ; --- DOC-TYPE(s): 'T|'TYPE|'FUNCTION|'VARIABLE|'STRUCTURE|'SETF |# ;(load "~/quicklisp/setup.lisp") ;(ql:register-local-projects) #| ;(require :asdf) (eval-when (:compile-toplevel :load-toplevel :execute) (require "asdf")) |# (asdf:load-systems :log4cl :unix-options :getopt :cli-parser :py-configparser :cl-ppcre :cl-json :cl-yaml :introlisp.util :introlisp.practice :introlisp.intro/src/lib :introlisp.intro/src/person) (defpackage :introlisp.intro/src/main (:documentation "Main app") (:use :cl :log4cl :unix-options :py-configparser :cl-ppcre :cl-json :cl-yaml) (:nicknames :introlisp.intro) (:export :main :run-main :save-image) ) (in-package :introlisp.intro/src/main) (rename-package :introlisp.util :introlisp.util '(:util)) (rename-package :introlisp.practice.classic :introlisp.practice.classic '(:classic)) (rename-package :introlisp.practice.sequenceops :introlisp.practice.sequenceops '(:sequenceops :seqops)) (rename-package :introlisp.intro/src/lib :introlisp.intro/src/lib '(:lib)) (rename-package :introlisp.intro/src/person :introlisp.intro/src/person '(:person)) (rename-package :introlisp.practice.classic.puzzles :introlisp.practice.classic.puzzles '(:puzzles)) (defstruct (user (:constructor make-user) (:constructor create-user (name num timein)) (:conc-name user-) (:predicate user-p)) "User structure" (name "NoName" :type string :read-only nil) (num 0 :type fixnum :read-only nil) (timein (encode-universal-time 0 0 0 1 1 1970) :type fixnum :read-only nil)) (defun run-intro (rsrc-dir name num is-expt2) "Run intro" (let* ((time-in (get-internal-real-time)) (pat "(?i:^quit$)") (ch #\Nul) (greet-path (merge-pathnames "greet.txt" rsrc-dir)) (delay-secs (ceiling (/ 25 10))) (user1 (make-user :name name :num num :timein (get-universal-time))) (person1 (make-instance 'person:<person> :name "PI:NAME:<NAME>END_PI" :age 32)) (num-vec (vector #b1011 #o13 #xb 11)) ; (bin oct hex dec) (num-val 0) (time-dur 0.0) (lst '(2 1 0 4 3)) (rnd-state (make-random-state t)) (num-disks 4) (num-queens 8) (res-queens (puzzles:nqueens num-queens)) (queens-ndx (random (length res-queens) rnd-state)) (queens-answer (nth queens-ndx res-queens)) ) (setf num-val (reduce (lambda (a e) (+ a e)) num-vec :initial-value 0)) ;(if (not (= num-val ; (* (length num-vec) (aref num-vec 0)))) ; (error "Assert fails: len * 1st elem == num-val->~a" num-val)) (handler-case (assert (= num-val (* (length num-vec) (aref num-vec 0)))) (error (exc) (format t "~a~%" exc))) (setf ch (lib:delay-char (lambda () (sleep delay-secs)))) (if (= 0 (user-num user1)) (setf (user-num user1) (+ (random 18 rnd-state) 2))) (format t "~a match ~a to ~a~%" (if (cl-ppcre:scan pat name) "Good" "Does not") (user-name user1) pat) (format t "~a~%" (util:date-to-string (user-timein user1))) #| (catch 'prac (handler-bind ( (warning #'(lambda (exc) (format t "Warning Condition: ~a~%" exc) (throw 'prac t))) (file-error #'(lambda (exc) (format t "File Error Condition: ~a~%" exc) (throw 'prac t))) (error #'(lambda (exc) (format t "Error Condition: ~a~%" exc) (throw 'prac t)))) (format t "~a~%" (lib:greeting greet-path (user-name user1))))) |# (handler-case (format t "~a~%" (lib:greeting greet-path (user-name user1))) (warning (exc) (format t "Warning Condition: ~a~%" exc)) (file-error (exc) (format t "File Error Condition: ~a~%" exc)) (error (exc) (format t "Error Condition: ~a~%" exc))) (setf time-dur (/ (- (get-internal-real-time) time-in) internal-time-units-per-second)) (format t "(program ~a) Took ~,2f seconds.~%" (uiop:argv0) time-dur) (format t "~a~%" (make-string 40 :initial-element #\#)) (if is-expt2 (progn (format t "expt 2.0 ~,1f: ~,1f~%" (user-num user1) (classic:expt-i 2.0 (user-num user1))) (format t "reverse ~a: ~a~%" lst (seqops:reverse-i lst)) (format t "sort ~a #'<: ~a~%" (append '(9 9 9 9) lst) (sort (append '(9 9 9 9) lst) #'<)) ) (progn (format t "fact ~a: ~a~%" (user-num user1) (classic:fact-i (user-num user1))) (format t "index (= 3 e) ~a: ~a~%" lst (seqops:index-i (lambda (e) (equal e 3)) lst)) (format t "append ~a ~a: ~a~%" '(9 9 9 9) lst (append '(9 9 9 9) lst)) )) (format t "~a~%" (make-string 40 :initial-element #\#)) (format t "pascaltri ~a: ~a~%" 5 (classic:pascaltri-add 5)) (format t "~a~%" (util:mkstring-nested (string #\newline) " " "" (classic:pascaltri-add 5))) (format t "~a~%" (make-string 40 :initial-element #\#)) (multiple-value-bind (res stats moves) (puzzles:hanoi-moves 1 2 3 num-disks) (format t "hanoi-moves (result: ~a)~%(stats: ~a)" res stats)) (format t "~a~%" (util:mkstring-nested "" " " "" (multiple-value-bind (res stats moves) (puzzles:hanoi-moves 1 2 3 num-disks) (list moves)))) (format t "~a~%" (make-string 40 :initial-element #\#)) (format t "nqueens-grid ~a (idx: ~a): ~a" num-queens queens-ndx queens-answer) (format t "~a~%" (util:mkstring-nested (string #\newline) "-" "" (util:arr2d-to-nlsts (puzzles:nqueens-grid num-queens queens-answer)))) (format t "~a~%" (make-string 40 :initial-element #\#)) (format t "~a~%" #+ccl (ccl::class-slots (find-class 'person:<person>)) #+sbcl (sb-mop:class-slots (find-class 'person:<person>)) #+clisp (clos:class-slots (find-class 'person:<person>)) ) ;(format t "person-age person1: ~a~%" (slot-value person1 'person:age)) ;(setf (slot-value person1 'person:age) 33) (format t "person-age person1: ~a~%" (person:person-age person1)) (setf (person:person-age person1) 33) (format t "setf (person-age person1) 33:~%") (format t "~a~%" (person:peek-person person1)) (format t "type-of person1: ~a~%class-of person1: ~a~%" (type-of person1) (class-of person1)) (format t "~a~%" (make-string 40 :initial-element #\#)) )) (defun parse-cmdopts-unix-options (argv) "Parse cmdopts using unix-options" (unix-options:with-cli-options (argv t) ((2expt "Expt 2 n vice Fact n") (verbose (verbose "VERBOSITY" "Verbosity level")) (user (user "USER" "User name")) (num (num "NUM" "Number to factorialize"))) (values (or verbose 0) (or user "World") (or num "0") 2expt))) (defun show-help (progname) "Usage help" (format t "Usage: ~a [-h][-2][-v VERBOSITY][-u USER][-n NUM]~%" progname)) (defparameter *opts* '(("help" :none) ("verbose" :required) ("user" :required) ("num" :required) ("is-expt2" :none)) "Options for getopt") (defun parse-cmdopts-getopt (argv) "Parse cmdopts using getopt" (let ((verbose 0) (user "World") (num "0") (is-expt2 nil)) (multiple-value-bind (args opts) (getopt:getopt argv *opts*) ;(progn ; (mapcar (lambda (opt) ; (case (car opt) ; ("help" (show-help (uiop:argv0)) (uiop:quit)) ; (t ; {t|otherwise} ; (format t "??? No matching options.~%")))) (progn (mapcar (lambda (opt) (cond ((equal (car opt) "help") (show-help (uiop:argv0)) (uiop:quit)) ((equal (car opt) "is-expt2") (setf is-expt2 (cdr opt))) ((equal (car opt) "verbose") (setf verbose (cdr opt))) ((equal (car opt) "user") (setf user (cdr opt))) ((equal (car opt) "num") (setf num (cdr opt))) (t (format t "??? No matching options.~%")))) opts) nil) (values verbose user num is-expt2)))) (defparameter *option-conf* (list (make-instance 'cli-parser:cli-option :abbr "h" :full "help" :requires-arguments nil :description "Usage help" :example "--help") (make-instance 'cli-parser:cli-option :abbr "v" :full "verbose" :requires-arguments t :description "Verbosity level" :example "--verbose=3") (make-instance 'cli-parser:cli-option :abbr "u" :full "user" :requires-arguments t :description "User name" :example "--user=Name1") (make-instance 'cli-parser:cli-option :abbr "n" :full "num" :requires-arguments t :description "Number to factorialize" :example "--num=5") (make-instance 'cli-parser:cli-option :abbr "2" :full "is-expt2" :requires-arguments nil :description "Expt 2 n vice Fact n" :example "--is-expt2") ) "Options for cli-parser") (defun parse-cmdopts-cli-parser (argv) "Parse cmdopts using cli-parser" (let ((opt-hash (cli-parser:cli-parse argv *option-conf*))) (if (not (gethash "help" opt-hash t)) (progn (show-help (uiop:argv0)) (uiop:quit))) (values (car (gethash "verbose" opt-hash '(0))) (car (gethash "user" opt-hash '("World"))) (car (gethash "num" opt-hash '("0"))) (not (gethash "is-expt2" opt-hash t)) ))) (defun parse-cmdopts (argv) "Parse command-line options" (log:info '(root) "parse-cmdopts()") (cond (nil (parse-cmdopts-getopt argv)) (nil (parse-cmdopts-cli-parser argv)) (t (parse-cmdopts-unix-options argv)) )) (defun main (argv) "Entry point" (let* ((sys-dir (asdf:system-source-directory :introlisp.intro)) (rsrc-dir (pathname (or (uiop:getenv "RSRC_PATH") (merge-pathnames "resources/" sys-dir)))) (ini-cfg (py-configparser:make-config)) (alst-cfg (cl-json:decode-json-from-source (merge-pathnames "prac.json" rsrc-dir))) (cl-json:*json-symbols-package* nil) (obj-cfg (cl-json:with-decoder-simple-clos-semantics (cl-json:decode-json-from-source (merge-pathnames "prac_htbl.json" rsrc-dir)))) (htbl (make-hash-table :test 'equal)) (yaml-htbl (yaml:parse (merge-pathnames "prac.yaml" rsrc-dir))) ) (log:config :properties (merge-pathnames "log4cl.conf" rsrc-dir)) (py-configparser:read-files ini-cfg (list (merge-pathnames "prac.conf" rsrc-dir))) (maphash (lambda (k v) (setf (gethash (princ-to-string k) htbl) v)) obj-cfg) (maphash (lambda (k v) (setf (gethash (princ-to-string k) (gethash "USER-1" htbl)) v)) (gethash "USER-1" htbl)) (let* ((tup-vec (vector (cons (slot-value ini-cfg 'py-configparser:sections) (cons (py-configparser:get-option ini-cfg "default" "domain") (py-configparser:get-option ini-cfg "user1" "name"))) (cons alst-cfg (cons (cdr (assoc :domain alst-cfg)) (cdr (assoc :name (cdr (assoc :user-1 alst-cfg)))))) (cons (util:hashtbl->alist obj-cfg) (cons (gethash "DOMAIN" htbl) (gethash "NAME" (gethash "USER-1" htbl)))) (cons (util:hashtbl->alist yaml-htbl) (cons (gethash "domain" yaml-htbl) (gethash "name" (gethash "user1" yaml-htbl)))) ))) (map nil (lambda (tup3) (progn (format t "config: ~a~%" (car tup3)) (format t "domain: ~a~%" (cadr tup3)) (format t "user1Name: ~a~%" (cddr tup3)) )) tup-vec) ) (multiple-value-bind (verbose user num is-expt2) (parse-cmdopts argv) (handler-case (run-intro rsrc-dir user (or (parse-integer num :junk-allowed t) 5) is-expt2) (type-error (condition) (uiop:quit)))) )) ;(uiop:quit)) ;(if (member (pathname-name *load-truename*) (uiop:command-line-arguments) ; :test #'(lambda (x y) (search x y :test #'equalp))) ; (main (uiop:command-line-arguments))) ;(main (uiop:command-line-arguments)) (defun run-main () (main (uiop:command-line-arguments)) (uiop:quit) ) (defun save-image () #+sbcl (sb-ext:save-lisp-and-die "build/main" :executable t :toplevel 'introlisp.intro:run-main) #+clisp (ext:saveinitmem "build/main" :executable t :init-function 'introlisp.intro:run-main) #+ccl (ccl:save-application "build/main" :prepend-kernel t :toplevel-function 'introlisp.intro:run-main) )
[ { "context": "ory package for Maxima\n;;;\n;;; Copyright (C) 2008 Andrej Vodopivec <[email protected]>\n;;;\n;;; This progra", "end": 94, "score": 0.9998960494995117, "start": 78, "tag": "NAME", "value": "Andrej Vodopivec" }, { "context": "ima\n;;;\n;;; Copyright (C) 2008 Andrej Vodopivec <[email protected]>\n;;;\n;;; This program is free software; you can ", "end": 122, "score": 0.9999347925186157, "start": 96, "tag": "EMAIL", "value": "[email protected]" } ]
maxima/src/maxima/share/graphs/wiener_index.lisp
nilqed/spadlib
1
;;; ;;; GRAPHS - graph theory package for Maxima ;;; ;;; Copyright (C) 2008 Andrej Vodopivec <[email protected]> ;;; ;;; 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. ;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; ;;; This file contains programs for computing the ;;; Wiener index of a graph. It includes the algorithms for ;;; ordinary and weighted Wiener index computation. ;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; ;;; FLOYD-WARSHALL algorithm for all-pairs shortest paths ;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (in-package :maxima) (defun find-option (opt options &optional default) (dolist (o options) (cond ((eq o opt) (return-from find-option t)) ((and (listp o) (eq (cadr o) opt)) (return-from find-option (caddr o))))) default) (defmfun $floyd_warshall (g &rest options) (require-graph-or-digraph 1 'floyd_warshall g) (let* ((n (graph-order g)) (m (make-array (list n n))) (my-inf 1) (options (cons '((mlist simp)) options)) (weighted (find-option '$weighted options t)) (vertices (cdr (find-option '$vertices options))) (mat ($zeromatrix n n))) (unless vertices (setq vertices (vertices g))) (if weighted (dolist (e (cdr ($edges g))) (setq my-inf (m+ my-inf ($abs ($get_edge_weight e g 1))))) (setq my-inf (1+ (graph-order g)))) ;; setup the array (dotimes (i n) (dotimes (j n) (if (/= i j) (setf (aref m i j) (if weighted ($get_edge_weight `((mlist simp) ,(nth i vertices) ,(nth j vertices)) g 1 my-inf) (if (member (nth i vertices) (neighbors (nth j vertices) g)) 1 my-inf))) (setf (aref m i j) 0)))) ;; compute the distances (dotimes (k n) (dotimes (i n) (dotimes (j n) (when (eq (mlsp (m+ (aref m i k) (aref m k j)) (aref m i j)) t) (setf (aref m i j) (m+ (aref m i k) (aref m k j))))))) ;; check for negative cycles (dotimes (k n) (when (eq (mlsp (aref m k k) 0) t) ($error "Graph contains a negative cycle."))) ;; fill the matrix (dotimes (i n) (dotimes (j n) (setf (nth (1+ j) (nth (1+ i) mat)) (if (equal (aref m i j) my-inf) '$inf (aref m i j))))) mat)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; ;;; JOHNSON's algorithm for all pairs shortest path ;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun bellman-ford (s g) (let ((d (make-hash-table)) (edges (if (graph-p g) (append (edges g) (mapcar #'reverse (edges g))) (edges g))) (my-inf 1) (prev (make-hash-table))) (dolist (e (cdr ($edges g))) (setf my-inf (m+ my-inf ($abs ($get_edge_weight e g 1))))) ;; initialize distances (dolist (v (vertices g)) (if (= s v) (setf (gethash v d) 0) (setf (gethash v d) my-inf))) ;; relax edges (dotimes (i (1- (length (vertices g)))) (dolist (e edges) (let* ((u (first e)) (v (second e)) (nd (m+ (gethash u d) ($get_edge_weight `((mlist simp) ,@e) g)))) (when (and (not (equal (gethash u d) my-inf)) (eq (mgrp (gethash v d) nd) t)) (setf (gethash v d) nd) (setf (gethash v prev) u))))) ;; check for negative cycles (dolist (e edges) (let ((u (first e)) (v (second e))) (when (eq (mgrp (gethash v d) (m+ (gethash u d) ($get_edge_weight `((mlist simp) ,@e) g))) t) ($error "Graph contains a negative cycle.")))) (values d prev))) (defmfun $johnson (g &rest options) (let* ((h ($copy_graph g)) (n (graph-order g)) (options (cons '((mlist simp)) options)) (weighted (find-option '$weighted options t)) (vertices (cdr (find-option '$vertices options))) (m ($zeromatrix n n)) nv) (unless vertices (setq vertices (vertices g))) (setq nv (1+ (apply #'max vertices))) (when weighted (dolist (e (cdr ($edges g))) ($set_edge_weight e ($get_edge_weight e g) h))) ;; add a new vertex ($add_vertex nv h) (dolist (v vertices) ($add_edge `((mlist simp) ,nv ,v) h) ($set_edge_weight `((mlist simp) ,nv ,v) 0 h)) ;; run the bellman-ford algorithm (multiple-value-bind (d prev) (bellman-ford nv h) (declare (ignore prev)) ;; re-weight the edges (dolist (e (cdr ($edges g))) (let ((nw (m+ (if weighted ($get_edge_weight e g) 1) (gethash ($first e) d) (m- (gethash ($second e) d))))) ($set_edge_weight e nw h))) ($remove_vertex nv h) ;; run the dijkstra's algorithm for each vertex (dotimes (i n) (multiple-value-bind (dd pd) (dijkstra (nth i vertices) nv h) (declare (ignore pd)) (dotimes (j n) (when (/= i j) (setf (nth (1+ j) (nth (1+ i) m)) (if (eq '$inf (gethash (nth j vertices) dd)) '$inf (m+ (gethash (nth j vertices) dd) (m- (gethash (nth i vertices) d)) (gethash (nth j vertices) d)))))))) ;; return the matrix m m))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; ;;; JUVAN-MOHAR algorithm ;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun wiener-index (g) (let ((n (length (vertices g))) (q (make-hash-table)) (j 0) (k 1) (w 0) (visited (make-hash-table)) (d (make-hash-table :test #'equal)) (s (make-hash-table)) (c (make-hash-table :test #'equal)) (we (make-hash-table :test #'equal)) (wi 0)) ;; initialize array we (dolist (e (edges g)) (setf (gethash e we) 0)) ;; initialize arrays c and d (dolist (v (vertices g)) (dolist (u (vertices g)) (setf (gethash (list v u) c) 0) (setf (gethash (list v u) d) 0))) ;; For each vertex i (dolist (v (vertices g)) ;; initialize c (setf (gethash (list v v) c) 1) ;; we do a bfs search (dolist (i (vertices g)) (setf (gethash i visited) nil)) (setf (gethash 1 q) v (gethash v visited) t) (setq j 0 k 1) (loop while (< j k) do (incf j) (setq w (gethash j q)) (dolist (u (neighbors w g)) (unless (gethash u visited) (setf (gethash (list v u) d) (1+ (gethash (list v w) d))) (setf (gethash u visited) t) (incf k) (setf (gethash k q) u)) (when (> (gethash (list v u) d) (gethash (list v w) d)) (incf (gethash (list v u) c) (gethash (list v w) c))))) ;; and visit vertices in reverse order (loop for j from n downto 1 do (let ((w (gethash j q))) (setf (gethash w s) 0) (dolist (u (neighbors w g)) (when (< (gethash (list v w) d) (gethash (list v u) d)) (let ((x (* (/ (gethash (list v w) c) (gethash (list v u) c)) (1+ (gethash u s))))) (incf (gethash (list (min u w) (max u w)) we) (/ x 2)) (incf (gethash w s) x)))))) ) ;; Compute the Wiener index (dolist (e (edges g)) (incf wi (gethash e we))) wi)) (defmfun $wiener_index (g &rest options) (require-graph 1 'wiener_index g) (unless ($is_connected g) ($error "`wiener_index': input graph is not connected")) (let* ((weighted (find-option '$weighted options nil)) (algorithm (find-option '$algorithm options (if weighted '$floyd_warshall '$juvan_mohar)))) (case algorithm ($juvan_mohar (wiener-index g)) ($johnson (m// ($xreduce "+" ($flatten ($args ($johnson g `((mlist simp) $weighted ,weighted))))) 2)) ($floyd_warshall (m// ($xreduce "+" ($flatten ($args ($floyd_warshall g `((mlist simp) $weighted ,weighted))))) 2)) (t ($error "Unknown algorithm for WIENER_INDEX")))))
26923
;;; ;;; GRAPHS - graph theory package for Maxima ;;; ;;; Copyright (C) 2008 <NAME> <<EMAIL>> ;;; ;;; 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. ;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; ;;; This file contains programs for computing the ;;; Wiener index of a graph. It includes the algorithms for ;;; ordinary and weighted Wiener index computation. ;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; ;;; FLOYD-WARSHALL algorithm for all-pairs shortest paths ;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (in-package :maxima) (defun find-option (opt options &optional default) (dolist (o options) (cond ((eq o opt) (return-from find-option t)) ((and (listp o) (eq (cadr o) opt)) (return-from find-option (caddr o))))) default) (defmfun $floyd_warshall (g &rest options) (require-graph-or-digraph 1 'floyd_warshall g) (let* ((n (graph-order g)) (m (make-array (list n n))) (my-inf 1) (options (cons '((mlist simp)) options)) (weighted (find-option '$weighted options t)) (vertices (cdr (find-option '$vertices options))) (mat ($zeromatrix n n))) (unless vertices (setq vertices (vertices g))) (if weighted (dolist (e (cdr ($edges g))) (setq my-inf (m+ my-inf ($abs ($get_edge_weight e g 1))))) (setq my-inf (1+ (graph-order g)))) ;; setup the array (dotimes (i n) (dotimes (j n) (if (/= i j) (setf (aref m i j) (if weighted ($get_edge_weight `((mlist simp) ,(nth i vertices) ,(nth j vertices)) g 1 my-inf) (if (member (nth i vertices) (neighbors (nth j vertices) g)) 1 my-inf))) (setf (aref m i j) 0)))) ;; compute the distances (dotimes (k n) (dotimes (i n) (dotimes (j n) (when (eq (mlsp (m+ (aref m i k) (aref m k j)) (aref m i j)) t) (setf (aref m i j) (m+ (aref m i k) (aref m k j))))))) ;; check for negative cycles (dotimes (k n) (when (eq (mlsp (aref m k k) 0) t) ($error "Graph contains a negative cycle."))) ;; fill the matrix (dotimes (i n) (dotimes (j n) (setf (nth (1+ j) (nth (1+ i) mat)) (if (equal (aref m i j) my-inf) '$inf (aref m i j))))) mat)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; ;;; JOHNSON's algorithm for all pairs shortest path ;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun bellman-ford (s g) (let ((d (make-hash-table)) (edges (if (graph-p g) (append (edges g) (mapcar #'reverse (edges g))) (edges g))) (my-inf 1) (prev (make-hash-table))) (dolist (e (cdr ($edges g))) (setf my-inf (m+ my-inf ($abs ($get_edge_weight e g 1))))) ;; initialize distances (dolist (v (vertices g)) (if (= s v) (setf (gethash v d) 0) (setf (gethash v d) my-inf))) ;; relax edges (dotimes (i (1- (length (vertices g)))) (dolist (e edges) (let* ((u (first e)) (v (second e)) (nd (m+ (gethash u d) ($get_edge_weight `((mlist simp) ,@e) g)))) (when (and (not (equal (gethash u d) my-inf)) (eq (mgrp (gethash v d) nd) t)) (setf (gethash v d) nd) (setf (gethash v prev) u))))) ;; check for negative cycles (dolist (e edges) (let ((u (first e)) (v (second e))) (when (eq (mgrp (gethash v d) (m+ (gethash u d) ($get_edge_weight `((mlist simp) ,@e) g))) t) ($error "Graph contains a negative cycle.")))) (values d prev))) (defmfun $johnson (g &rest options) (let* ((h ($copy_graph g)) (n (graph-order g)) (options (cons '((mlist simp)) options)) (weighted (find-option '$weighted options t)) (vertices (cdr (find-option '$vertices options))) (m ($zeromatrix n n)) nv) (unless vertices (setq vertices (vertices g))) (setq nv (1+ (apply #'max vertices))) (when weighted (dolist (e (cdr ($edges g))) ($set_edge_weight e ($get_edge_weight e g) h))) ;; add a new vertex ($add_vertex nv h) (dolist (v vertices) ($add_edge `((mlist simp) ,nv ,v) h) ($set_edge_weight `((mlist simp) ,nv ,v) 0 h)) ;; run the bellman-ford algorithm (multiple-value-bind (d prev) (bellman-ford nv h) (declare (ignore prev)) ;; re-weight the edges (dolist (e (cdr ($edges g))) (let ((nw (m+ (if weighted ($get_edge_weight e g) 1) (gethash ($first e) d) (m- (gethash ($second e) d))))) ($set_edge_weight e nw h))) ($remove_vertex nv h) ;; run the dijkstra's algorithm for each vertex (dotimes (i n) (multiple-value-bind (dd pd) (dijkstra (nth i vertices) nv h) (declare (ignore pd)) (dotimes (j n) (when (/= i j) (setf (nth (1+ j) (nth (1+ i) m)) (if (eq '$inf (gethash (nth j vertices) dd)) '$inf (m+ (gethash (nth j vertices) dd) (m- (gethash (nth i vertices) d)) (gethash (nth j vertices) d)))))))) ;; return the matrix m m))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; ;;; JUVAN-MOHAR algorithm ;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun wiener-index (g) (let ((n (length (vertices g))) (q (make-hash-table)) (j 0) (k 1) (w 0) (visited (make-hash-table)) (d (make-hash-table :test #'equal)) (s (make-hash-table)) (c (make-hash-table :test #'equal)) (we (make-hash-table :test #'equal)) (wi 0)) ;; initialize array we (dolist (e (edges g)) (setf (gethash e we) 0)) ;; initialize arrays c and d (dolist (v (vertices g)) (dolist (u (vertices g)) (setf (gethash (list v u) c) 0) (setf (gethash (list v u) d) 0))) ;; For each vertex i (dolist (v (vertices g)) ;; initialize c (setf (gethash (list v v) c) 1) ;; we do a bfs search (dolist (i (vertices g)) (setf (gethash i visited) nil)) (setf (gethash 1 q) v (gethash v visited) t) (setq j 0 k 1) (loop while (< j k) do (incf j) (setq w (gethash j q)) (dolist (u (neighbors w g)) (unless (gethash u visited) (setf (gethash (list v u) d) (1+ (gethash (list v w) d))) (setf (gethash u visited) t) (incf k) (setf (gethash k q) u)) (when (> (gethash (list v u) d) (gethash (list v w) d)) (incf (gethash (list v u) c) (gethash (list v w) c))))) ;; and visit vertices in reverse order (loop for j from n downto 1 do (let ((w (gethash j q))) (setf (gethash w s) 0) (dolist (u (neighbors w g)) (when (< (gethash (list v w) d) (gethash (list v u) d)) (let ((x (* (/ (gethash (list v w) c) (gethash (list v u) c)) (1+ (gethash u s))))) (incf (gethash (list (min u w) (max u w)) we) (/ x 2)) (incf (gethash w s) x)))))) ) ;; Compute the Wiener index (dolist (e (edges g)) (incf wi (gethash e we))) wi)) (defmfun $wiener_index (g &rest options) (require-graph 1 'wiener_index g) (unless ($is_connected g) ($error "`wiener_index': input graph is not connected")) (let* ((weighted (find-option '$weighted options nil)) (algorithm (find-option '$algorithm options (if weighted '$floyd_warshall '$juvan_mohar)))) (case algorithm ($juvan_mohar (wiener-index g)) ($johnson (m// ($xreduce "+" ($flatten ($args ($johnson g `((mlist simp) $weighted ,weighted))))) 2)) ($floyd_warshall (m// ($xreduce "+" ($flatten ($args ($floyd_warshall g `((mlist simp) $weighted ,weighted))))) 2)) (t ($error "Unknown algorithm for WIENER_INDEX")))))
true
;;; ;;; GRAPHS - graph theory package for Maxima ;;; ;;; Copyright (C) 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 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. ;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; ;;; This file contains programs for computing the ;;; Wiener index of a graph. It includes the algorithms for ;;; ordinary and weighted Wiener index computation. ;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; ;;; FLOYD-WARSHALL algorithm for all-pairs shortest paths ;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (in-package :maxima) (defun find-option (opt options &optional default) (dolist (o options) (cond ((eq o opt) (return-from find-option t)) ((and (listp o) (eq (cadr o) opt)) (return-from find-option (caddr o))))) default) (defmfun $floyd_warshall (g &rest options) (require-graph-or-digraph 1 'floyd_warshall g) (let* ((n (graph-order g)) (m (make-array (list n n))) (my-inf 1) (options (cons '((mlist simp)) options)) (weighted (find-option '$weighted options t)) (vertices (cdr (find-option '$vertices options))) (mat ($zeromatrix n n))) (unless vertices (setq vertices (vertices g))) (if weighted (dolist (e (cdr ($edges g))) (setq my-inf (m+ my-inf ($abs ($get_edge_weight e g 1))))) (setq my-inf (1+ (graph-order g)))) ;; setup the array (dotimes (i n) (dotimes (j n) (if (/= i j) (setf (aref m i j) (if weighted ($get_edge_weight `((mlist simp) ,(nth i vertices) ,(nth j vertices)) g 1 my-inf) (if (member (nth i vertices) (neighbors (nth j vertices) g)) 1 my-inf))) (setf (aref m i j) 0)))) ;; compute the distances (dotimes (k n) (dotimes (i n) (dotimes (j n) (when (eq (mlsp (m+ (aref m i k) (aref m k j)) (aref m i j)) t) (setf (aref m i j) (m+ (aref m i k) (aref m k j))))))) ;; check for negative cycles (dotimes (k n) (when (eq (mlsp (aref m k k) 0) t) ($error "Graph contains a negative cycle."))) ;; fill the matrix (dotimes (i n) (dotimes (j n) (setf (nth (1+ j) (nth (1+ i) mat)) (if (equal (aref m i j) my-inf) '$inf (aref m i j))))) mat)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; ;;; JOHNSON's algorithm for all pairs shortest path ;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun bellman-ford (s g) (let ((d (make-hash-table)) (edges (if (graph-p g) (append (edges g) (mapcar #'reverse (edges g))) (edges g))) (my-inf 1) (prev (make-hash-table))) (dolist (e (cdr ($edges g))) (setf my-inf (m+ my-inf ($abs ($get_edge_weight e g 1))))) ;; initialize distances (dolist (v (vertices g)) (if (= s v) (setf (gethash v d) 0) (setf (gethash v d) my-inf))) ;; relax edges (dotimes (i (1- (length (vertices g)))) (dolist (e edges) (let* ((u (first e)) (v (second e)) (nd (m+ (gethash u d) ($get_edge_weight `((mlist simp) ,@e) g)))) (when (and (not (equal (gethash u d) my-inf)) (eq (mgrp (gethash v d) nd) t)) (setf (gethash v d) nd) (setf (gethash v prev) u))))) ;; check for negative cycles (dolist (e edges) (let ((u (first e)) (v (second e))) (when (eq (mgrp (gethash v d) (m+ (gethash u d) ($get_edge_weight `((mlist simp) ,@e) g))) t) ($error "Graph contains a negative cycle.")))) (values d prev))) (defmfun $johnson (g &rest options) (let* ((h ($copy_graph g)) (n (graph-order g)) (options (cons '((mlist simp)) options)) (weighted (find-option '$weighted options t)) (vertices (cdr (find-option '$vertices options))) (m ($zeromatrix n n)) nv) (unless vertices (setq vertices (vertices g))) (setq nv (1+ (apply #'max vertices))) (when weighted (dolist (e (cdr ($edges g))) ($set_edge_weight e ($get_edge_weight e g) h))) ;; add a new vertex ($add_vertex nv h) (dolist (v vertices) ($add_edge `((mlist simp) ,nv ,v) h) ($set_edge_weight `((mlist simp) ,nv ,v) 0 h)) ;; run the bellman-ford algorithm (multiple-value-bind (d prev) (bellman-ford nv h) (declare (ignore prev)) ;; re-weight the edges (dolist (e (cdr ($edges g))) (let ((nw (m+ (if weighted ($get_edge_weight e g) 1) (gethash ($first e) d) (m- (gethash ($second e) d))))) ($set_edge_weight e nw h))) ($remove_vertex nv h) ;; run the dijkstra's algorithm for each vertex (dotimes (i n) (multiple-value-bind (dd pd) (dijkstra (nth i vertices) nv h) (declare (ignore pd)) (dotimes (j n) (when (/= i j) (setf (nth (1+ j) (nth (1+ i) m)) (if (eq '$inf (gethash (nth j vertices) dd)) '$inf (m+ (gethash (nth j vertices) dd) (m- (gethash (nth i vertices) d)) (gethash (nth j vertices) d)))))))) ;; return the matrix m m))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; ;;; JUVAN-MOHAR algorithm ;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun wiener-index (g) (let ((n (length (vertices g))) (q (make-hash-table)) (j 0) (k 1) (w 0) (visited (make-hash-table)) (d (make-hash-table :test #'equal)) (s (make-hash-table)) (c (make-hash-table :test #'equal)) (we (make-hash-table :test #'equal)) (wi 0)) ;; initialize array we (dolist (e (edges g)) (setf (gethash e we) 0)) ;; initialize arrays c and d (dolist (v (vertices g)) (dolist (u (vertices g)) (setf (gethash (list v u) c) 0) (setf (gethash (list v u) d) 0))) ;; For each vertex i (dolist (v (vertices g)) ;; initialize c (setf (gethash (list v v) c) 1) ;; we do a bfs search (dolist (i (vertices g)) (setf (gethash i visited) nil)) (setf (gethash 1 q) v (gethash v visited) t) (setq j 0 k 1) (loop while (< j k) do (incf j) (setq w (gethash j q)) (dolist (u (neighbors w g)) (unless (gethash u visited) (setf (gethash (list v u) d) (1+ (gethash (list v w) d))) (setf (gethash u visited) t) (incf k) (setf (gethash k q) u)) (when (> (gethash (list v u) d) (gethash (list v w) d)) (incf (gethash (list v u) c) (gethash (list v w) c))))) ;; and visit vertices in reverse order (loop for j from n downto 1 do (let ((w (gethash j q))) (setf (gethash w s) 0) (dolist (u (neighbors w g)) (when (< (gethash (list v w) d) (gethash (list v u) d)) (let ((x (* (/ (gethash (list v w) c) (gethash (list v u) c)) (1+ (gethash u s))))) (incf (gethash (list (min u w) (max u w)) we) (/ x 2)) (incf (gethash w s) x)))))) ) ;; Compute the Wiener index (dolist (e (edges g)) (incf wi (gethash e we))) wi)) (defmfun $wiener_index (g &rest options) (require-graph 1 'wiener_index g) (unless ($is_connected g) ($error "`wiener_index': input graph is not connected")) (let* ((weighted (find-option '$weighted options nil)) (algorithm (find-option '$algorithm options (if weighted '$floyd_warshall '$juvan_mohar)))) (case algorithm ($juvan_mohar (wiener-index g)) ($johnson (m// ($xreduce "+" ($flatten ($args ($johnson g `((mlist simp) $weighted ,weighted))))) 2)) ($floyd_warshall (m// ($xreduce "+" ($flatten ($args ($floyd_warshall g `((mlist simp) $weighted ,weighted))))) 2)) (t ($error "Unknown algorithm for WIENER_INDEX")))))
[ { "context": "---------------\n;; Deal with floats....\n;;\n;; From Peter Siebel\n;;\n\n(defun scale-integer (value bits)\n (if (zero", "end": 94, "score": 0.9997909665107727, "start": 82, "tag": "NAME", "value": "Peter Siebel" } ]
src/encode-float.lisp
npsimons/cl-mongo
72
(in-package :cl-mongo) ;;-------------------- ;; Deal with floats.... ;; ;; From Peter Siebel ;; (defun scale-integer (value bits) (if (zerop value) (values 0 0) (let ((scale (- bits (integer-length value)))) (values (round (* value (expt 2 scale))) scale)))) (defun scale (mantissa exponent mantissa-bits) (multiple-value-bind (mantissa scale) (scale-integer mantissa mantissa-bits) (values mantissa (- exponent scale)))) (defun denormalize (mantissa exponent bias mantissa-byte) (multiple-value-bind (mantissa exponent) (scale mantissa exponent (byte-size mantissa-byte)) (incf exponent (byte-size mantissa-byte)) (values (ash mantissa (- exponent (1+ (- bias)))) (- bias)))) (defun encode-float-bits (float sign-byte exponent-byte mantissa-byte bias) (multiple-value-bind (original-mantissa original-exponent sign) (integer-decode-float (float float 0d0)) (multiple-value-bind (mantissa exponent) (scale original-mantissa original-exponent (1+ (byte-size mantissa-byte))) (incf exponent (byte-size mantissa-byte)) (when (zerop mantissa) (setf exponent (- bias))) (when (<= exponent (- bias)) (setf (values mantissa exponent) (denormalize original-mantissa original-exponent bias mantissa-byte))) (incf exponent bias) (when (> (integer-length exponent) (byte-size exponent-byte)) (setf mantissa 0 exponent (ldb (byte (byte-size exponent-byte) 0) (lognot 0)))) (let ((result 0)) (setf (ldb sign-byte result) (if (plusp sign) 0 1)) (setf (ldb exponent-byte result) exponent) (setf (ldb mantissa-byte result) mantissa) result)))) (defun encode-double-float-bits (float) (encode-float-bits float (byte 1 63) (byte 11 52) (byte 52 0) 1023)) (defun decode-float-bits (bits sign-byte exponent-byte mantissa-byte bias) (let ((sign (if (zerop (ldb sign-byte bits)) 1 -1)) (exponent (ldb exponent-byte bits)) (mantissa (ldb mantissa-byte bits))) (if (= (logcount (ldb exponent-byte bits)) (byte-size exponent-byte)) (if (zerop mantissa) (if (plusp sign) 'positive-infinity 'negative-infinity) 'not-a-number) (progn (when (plusp exponent) (incf mantissa (expt 2 (byte-size mantissa-byte)))) (if (zerop exponent) (setf exponent (- 1 bias (byte-size mantissa-byte))) (setf exponent (- (- exponent (byte-size mantissa-byte)) bias))) (float (* sign (* mantissa (expt 2 exponent))) 0d0))))) (defun decode-double-float-bits (bits) (decode-float-bits bits (byte 1 63) (byte 11 52) (byte 52 0) 1023))
70248
(in-package :cl-mongo) ;;-------------------- ;; Deal with floats.... ;; ;; From <NAME> ;; (defun scale-integer (value bits) (if (zerop value) (values 0 0) (let ((scale (- bits (integer-length value)))) (values (round (* value (expt 2 scale))) scale)))) (defun scale (mantissa exponent mantissa-bits) (multiple-value-bind (mantissa scale) (scale-integer mantissa mantissa-bits) (values mantissa (- exponent scale)))) (defun denormalize (mantissa exponent bias mantissa-byte) (multiple-value-bind (mantissa exponent) (scale mantissa exponent (byte-size mantissa-byte)) (incf exponent (byte-size mantissa-byte)) (values (ash mantissa (- exponent (1+ (- bias)))) (- bias)))) (defun encode-float-bits (float sign-byte exponent-byte mantissa-byte bias) (multiple-value-bind (original-mantissa original-exponent sign) (integer-decode-float (float float 0d0)) (multiple-value-bind (mantissa exponent) (scale original-mantissa original-exponent (1+ (byte-size mantissa-byte))) (incf exponent (byte-size mantissa-byte)) (when (zerop mantissa) (setf exponent (- bias))) (when (<= exponent (- bias)) (setf (values mantissa exponent) (denormalize original-mantissa original-exponent bias mantissa-byte))) (incf exponent bias) (when (> (integer-length exponent) (byte-size exponent-byte)) (setf mantissa 0 exponent (ldb (byte (byte-size exponent-byte) 0) (lognot 0)))) (let ((result 0)) (setf (ldb sign-byte result) (if (plusp sign) 0 1)) (setf (ldb exponent-byte result) exponent) (setf (ldb mantissa-byte result) mantissa) result)))) (defun encode-double-float-bits (float) (encode-float-bits float (byte 1 63) (byte 11 52) (byte 52 0) 1023)) (defun decode-float-bits (bits sign-byte exponent-byte mantissa-byte bias) (let ((sign (if (zerop (ldb sign-byte bits)) 1 -1)) (exponent (ldb exponent-byte bits)) (mantissa (ldb mantissa-byte bits))) (if (= (logcount (ldb exponent-byte bits)) (byte-size exponent-byte)) (if (zerop mantissa) (if (plusp sign) 'positive-infinity 'negative-infinity) 'not-a-number) (progn (when (plusp exponent) (incf mantissa (expt 2 (byte-size mantissa-byte)))) (if (zerop exponent) (setf exponent (- 1 bias (byte-size mantissa-byte))) (setf exponent (- (- exponent (byte-size mantissa-byte)) bias))) (float (* sign (* mantissa (expt 2 exponent))) 0d0))))) (defun decode-double-float-bits (bits) (decode-float-bits bits (byte 1 63) (byte 11 52) (byte 52 0) 1023))
true
(in-package :cl-mongo) ;;-------------------- ;; Deal with floats.... ;; ;; From PI:NAME:<NAME>END_PI ;; (defun scale-integer (value bits) (if (zerop value) (values 0 0) (let ((scale (- bits (integer-length value)))) (values (round (* value (expt 2 scale))) scale)))) (defun scale (mantissa exponent mantissa-bits) (multiple-value-bind (mantissa scale) (scale-integer mantissa mantissa-bits) (values mantissa (- exponent scale)))) (defun denormalize (mantissa exponent bias mantissa-byte) (multiple-value-bind (mantissa exponent) (scale mantissa exponent (byte-size mantissa-byte)) (incf exponent (byte-size mantissa-byte)) (values (ash mantissa (- exponent (1+ (- bias)))) (- bias)))) (defun encode-float-bits (float sign-byte exponent-byte mantissa-byte bias) (multiple-value-bind (original-mantissa original-exponent sign) (integer-decode-float (float float 0d0)) (multiple-value-bind (mantissa exponent) (scale original-mantissa original-exponent (1+ (byte-size mantissa-byte))) (incf exponent (byte-size mantissa-byte)) (when (zerop mantissa) (setf exponent (- bias))) (when (<= exponent (- bias)) (setf (values mantissa exponent) (denormalize original-mantissa original-exponent bias mantissa-byte))) (incf exponent bias) (when (> (integer-length exponent) (byte-size exponent-byte)) (setf mantissa 0 exponent (ldb (byte (byte-size exponent-byte) 0) (lognot 0)))) (let ((result 0)) (setf (ldb sign-byte result) (if (plusp sign) 0 1)) (setf (ldb exponent-byte result) exponent) (setf (ldb mantissa-byte result) mantissa) result)))) (defun encode-double-float-bits (float) (encode-float-bits float (byte 1 63) (byte 11 52) (byte 52 0) 1023)) (defun decode-float-bits (bits sign-byte exponent-byte mantissa-byte bias) (let ((sign (if (zerop (ldb sign-byte bits)) 1 -1)) (exponent (ldb exponent-byte bits)) (mantissa (ldb mantissa-byte bits))) (if (= (logcount (ldb exponent-byte bits)) (byte-size exponent-byte)) (if (zerop mantissa) (if (plusp sign) 'positive-infinity 'negative-infinity) 'not-a-number) (progn (when (plusp exponent) (incf mantissa (expt 2 (byte-size mantissa-byte)))) (if (zerop exponent) (setf exponent (- 1 bias (byte-size mantissa-byte))) (setf exponent (- (- exponent (byte-size mantissa-byte)) bias))) (float (* sign (* mantissa (expt 2 exponent))) 0d0))))) (defun decode-double-float-bits (bits) (decode-float-bits bits (byte 1 63) (byte 11 52) (byte 52 0) 1023))
[ { "context": "e for Project Euler Problem 57.\n;;\n;; Code author: Russell A. Edson\n;; Date last modified: 31/08/2021\n\n;; Here we are", "end": 73, "score": 0.9997819066047668, "start": 57, "tag": "NAME", "value": "Russell A. Edson" } ]
problem_057.lisp
RussellAndrewEdson/project_euler_solutions
0
;; Code for Project Euler Problem 57. ;; ;; Code author: Russell A. Edson ;; Date last modified: 31/08/2021 ;; Here we are interested in continued fractions and convergents. ;; (Peeking ahead, we see some later problems that probably also ;; benefit from hitting them with computed convergents, e.g. ;; Problem 65 and Problem 66, so it's worth taking some effort to ;; get the scaffolding planned out now.) ;; A continued fraction has the form ;; a0 + 1/(a1 + 1/(a2 + 1/(a3 + ...))) ;; and we'll generally represent them in the standard form ;; [a0, a1, a2, a3, ...] ;; as an infinitely long list, say. Lazy lists are a very nice ;; computational representation of such infinitely-long lists, ;; which we can implement with generator functions and closures. (defvar sqrt2-continued-fraction (let* ((a (list 1)) (next-digit (lambda () 2)) (expand-list-to-an ;; Expand the list up to a_n (indexed from n = 0) (lambda (n) (loop while (>= n (length a)) do (setf a (append a (list (funcall next-digit)))))))) (list ;; Return the nth digit in the fraction (indexed from 0) (lambda (n) (if (>= n (length a)) (funcall expand-list-to-an n) (nth n a))) ;; Return all of the digits up to and including n (indexed from 0) (lambda (n) (if (>= n (length a)) (funcall expand-list-to-an n)) (subseq a 0 (1+ n)))))) (defun sqrt2-continued-fraction (n) "Return [a0, a1, a2, ..., a(N)] for the sqrt(2) continued fraction." (funcall (cadr sqrt2-continued-fraction) n)) (sqrt2-continued-fraction 0) ;;=> (1) (sqrt2-continued-fraction 1) ;;=> (1 2) (sqrt2-continued-fraction 10) ;;=> (1 2 2 2 2 2 2 2 2 2 2) ;; We can evaluate a continued fraction (convergent) most easily ;; by starting at the end and working our way back up iteratively. (defun eval-convergent (continued-fraction) "Evaluate the given CONTINUED-FRACTION and return its rational form." (let* ((denominators (reverse continued-fraction)) (convergent (car denominators))) (loop for number in (cdr denominators) do (setf convergent (+ (/ 1 convergent) number))) convergent)) (eval-convergent (sqrt2-continued-fraction 0)) ;;=> 1 (eval-convergent (sqrt2-continued-fraction 1)) ;;=> 3/2 (mapcar (lambda (n) (eval-convergent (sqrt2-continued-fraction n))) (loop for n from 0 to 10 collecting n)) ;;=> (1 3/2 7/5 17/12 41/29 99/70 239/169 577/408 1393/985 ;;=> 3363/2378 8119/5741) ;; For this problem we want to know when the numerator has more digits ;; than the denominator in the first 1000 expansions (i.e. convergents), ;; so we can first generate a list of those convergents: (time (defvar sqrt2-convergents (mapcar (lambda (n) (eval-convergent (sqrt2-continued-fraction n))) (loop for n from 1 to 1000 collecting n)))) ;;=> Evaluation took: ;;=> 0.124 seconds of real time ;;=> 0.109375 seconds of total run time (0.109375 user, 0.000000 system) ;;=> [ Run times consist of 0.031 seconds GC time, and 0.079 seconds non-GC time. ] ;;=> 87.90% CPU ;;=> 321,677,922 processor cycles ;;=> 216,191,568 bytes consed ;;=> ;;=> SQRT2-CONVERGENTS ;; And then we simply loop over these, counting the number of digits ;; in the numerator and denominators and keeping track of those with ;; more digits in the numerator, as desired. (defun digits (number) "Return the set of digits in the given NUMBER." (mapcar #'digit-char-p (coerce (write-to-string number) 'list))) (loop for convergent in sqrt2-convergents when (> (length (digits (numerator convergent))) (length (digits (denominator convergent)))) count convergent) ;;=> 153
34858
;; Code for Project Euler Problem 57. ;; ;; Code author: <NAME> ;; Date last modified: 31/08/2021 ;; Here we are interested in continued fractions and convergents. ;; (Peeking ahead, we see some later problems that probably also ;; benefit from hitting them with computed convergents, e.g. ;; Problem 65 and Problem 66, so it's worth taking some effort to ;; get the scaffolding planned out now.) ;; A continued fraction has the form ;; a0 + 1/(a1 + 1/(a2 + 1/(a3 + ...))) ;; and we'll generally represent them in the standard form ;; [a0, a1, a2, a3, ...] ;; as an infinitely long list, say. Lazy lists are a very nice ;; computational representation of such infinitely-long lists, ;; which we can implement with generator functions and closures. (defvar sqrt2-continued-fraction (let* ((a (list 1)) (next-digit (lambda () 2)) (expand-list-to-an ;; Expand the list up to a_n (indexed from n = 0) (lambda (n) (loop while (>= n (length a)) do (setf a (append a (list (funcall next-digit)))))))) (list ;; Return the nth digit in the fraction (indexed from 0) (lambda (n) (if (>= n (length a)) (funcall expand-list-to-an n) (nth n a))) ;; Return all of the digits up to and including n (indexed from 0) (lambda (n) (if (>= n (length a)) (funcall expand-list-to-an n)) (subseq a 0 (1+ n)))))) (defun sqrt2-continued-fraction (n) "Return [a0, a1, a2, ..., a(N)] for the sqrt(2) continued fraction." (funcall (cadr sqrt2-continued-fraction) n)) (sqrt2-continued-fraction 0) ;;=> (1) (sqrt2-continued-fraction 1) ;;=> (1 2) (sqrt2-continued-fraction 10) ;;=> (1 2 2 2 2 2 2 2 2 2 2) ;; We can evaluate a continued fraction (convergent) most easily ;; by starting at the end and working our way back up iteratively. (defun eval-convergent (continued-fraction) "Evaluate the given CONTINUED-FRACTION and return its rational form." (let* ((denominators (reverse continued-fraction)) (convergent (car denominators))) (loop for number in (cdr denominators) do (setf convergent (+ (/ 1 convergent) number))) convergent)) (eval-convergent (sqrt2-continued-fraction 0)) ;;=> 1 (eval-convergent (sqrt2-continued-fraction 1)) ;;=> 3/2 (mapcar (lambda (n) (eval-convergent (sqrt2-continued-fraction n))) (loop for n from 0 to 10 collecting n)) ;;=> (1 3/2 7/5 17/12 41/29 99/70 239/169 577/408 1393/985 ;;=> 3363/2378 8119/5741) ;; For this problem we want to know when the numerator has more digits ;; than the denominator in the first 1000 expansions (i.e. convergents), ;; so we can first generate a list of those convergents: (time (defvar sqrt2-convergents (mapcar (lambda (n) (eval-convergent (sqrt2-continued-fraction n))) (loop for n from 1 to 1000 collecting n)))) ;;=> Evaluation took: ;;=> 0.124 seconds of real time ;;=> 0.109375 seconds of total run time (0.109375 user, 0.000000 system) ;;=> [ Run times consist of 0.031 seconds GC time, and 0.079 seconds non-GC time. ] ;;=> 87.90% CPU ;;=> 321,677,922 processor cycles ;;=> 216,191,568 bytes consed ;;=> ;;=> SQRT2-CONVERGENTS ;; And then we simply loop over these, counting the number of digits ;; in the numerator and denominators and keeping track of those with ;; more digits in the numerator, as desired. (defun digits (number) "Return the set of digits in the given NUMBER." (mapcar #'digit-char-p (coerce (write-to-string number) 'list))) (loop for convergent in sqrt2-convergents when (> (length (digits (numerator convergent))) (length (digits (denominator convergent)))) count convergent) ;;=> 153
true
;; Code for Project Euler Problem 57. ;; ;; Code author: PI:NAME:<NAME>END_PI ;; Date last modified: 31/08/2021 ;; Here we are interested in continued fractions and convergents. ;; (Peeking ahead, we see some later problems that probably also ;; benefit from hitting them with computed convergents, e.g. ;; Problem 65 and Problem 66, so it's worth taking some effort to ;; get the scaffolding planned out now.) ;; A continued fraction has the form ;; a0 + 1/(a1 + 1/(a2 + 1/(a3 + ...))) ;; and we'll generally represent them in the standard form ;; [a0, a1, a2, a3, ...] ;; as an infinitely long list, say. Lazy lists are a very nice ;; computational representation of such infinitely-long lists, ;; which we can implement with generator functions and closures. (defvar sqrt2-continued-fraction (let* ((a (list 1)) (next-digit (lambda () 2)) (expand-list-to-an ;; Expand the list up to a_n (indexed from n = 0) (lambda (n) (loop while (>= n (length a)) do (setf a (append a (list (funcall next-digit)))))))) (list ;; Return the nth digit in the fraction (indexed from 0) (lambda (n) (if (>= n (length a)) (funcall expand-list-to-an n) (nth n a))) ;; Return all of the digits up to and including n (indexed from 0) (lambda (n) (if (>= n (length a)) (funcall expand-list-to-an n)) (subseq a 0 (1+ n)))))) (defun sqrt2-continued-fraction (n) "Return [a0, a1, a2, ..., a(N)] for the sqrt(2) continued fraction." (funcall (cadr sqrt2-continued-fraction) n)) (sqrt2-continued-fraction 0) ;;=> (1) (sqrt2-continued-fraction 1) ;;=> (1 2) (sqrt2-continued-fraction 10) ;;=> (1 2 2 2 2 2 2 2 2 2 2) ;; We can evaluate a continued fraction (convergent) most easily ;; by starting at the end and working our way back up iteratively. (defun eval-convergent (continued-fraction) "Evaluate the given CONTINUED-FRACTION and return its rational form." (let* ((denominators (reverse continued-fraction)) (convergent (car denominators))) (loop for number in (cdr denominators) do (setf convergent (+ (/ 1 convergent) number))) convergent)) (eval-convergent (sqrt2-continued-fraction 0)) ;;=> 1 (eval-convergent (sqrt2-continued-fraction 1)) ;;=> 3/2 (mapcar (lambda (n) (eval-convergent (sqrt2-continued-fraction n))) (loop for n from 0 to 10 collecting n)) ;;=> (1 3/2 7/5 17/12 41/29 99/70 239/169 577/408 1393/985 ;;=> 3363/2378 8119/5741) ;; For this problem we want to know when the numerator has more digits ;; than the denominator in the first 1000 expansions (i.e. convergents), ;; so we can first generate a list of those convergents: (time (defvar sqrt2-convergents (mapcar (lambda (n) (eval-convergent (sqrt2-continued-fraction n))) (loop for n from 1 to 1000 collecting n)))) ;;=> Evaluation took: ;;=> 0.124 seconds of real time ;;=> 0.109375 seconds of total run time (0.109375 user, 0.000000 system) ;;=> [ Run times consist of 0.031 seconds GC time, and 0.079 seconds non-GC time. ] ;;=> 87.90% CPU ;;=> 321,677,922 processor cycles ;;=> 216,191,568 bytes consed ;;=> ;;=> SQRT2-CONVERGENTS ;; And then we simply loop over these, counting the number of digits ;; in the numerator and denominators and keeping track of those with ;; more digits in the numerator, as desired. (defun digits (number) "Return the set of digits in the given NUMBER." (mapcar #'digit-char-p (coerce (write-to-string number) 'list))) (loop for convergent in sqrt2-convergents when (> (length (digits (numerator convergent))) (length (digits (denominator convergent)))) count convergent) ;;=> 153
[ { "context": ";;;; Copyright (c) Frank James 2015 <[email protected]>\n;;;; This code is ", "end": 30, "score": 0.9998303651809692, "start": 19, "tag": "NAME", "value": "Frank James" }, { "context": ";;;; Copyright (c) Frank James 2015 <[email protected]>\n;;;; This code is licensed under the MIT license", "end": 60, "score": 0.9999265074729919, "start": 37, "tag": "EMAIL", "value": "[email protected]" } ]
bind.lisp
fjames86/frpc
8
;;;; Copyright (c) Frank James 2015 <[email protected]> ;;;; This code is licensed under the MIT license. ;;; This file implements portmap (version 2) and rpcbind (versions 3 and 4) (defpackage #:frpc.bind (:use #:cl #:frpc) (:export #:mapping #:make-mapping #:mapping-program #:mapping-version #:mapping-protocol #:mapping-port #:binding #:binding-program #:binding-version #:binding-netid #:binding-addr #:binding-owner ;; the rpc functions #:call-null #:call-set #:call-unset #:call-get-port #:call-dump #:call-callit #:call-null3 #:call-set3 #:call-unset3 #:call-get-addr3 #:call-dump3 #:call-broadcast3 #:call-get-time3 #:call-uaddr2taddr3 #:call-taddr2uaddr3 #:call-null4 #:call-set4 #:call-unset4 #:call-get-addr4 #:call-dump4 #:call-broadcast4 #:call-get-time4 #:call-uaddr2taddr4 #:call-taddr2uaddr4 #:call-get-version-addr #:call-indirect #:call-get-addr-list #:call-stat-by-version ;; underlying API #:add-mapping #:rem-mapping #:add-all-mappings #:remove-all-mappings #:find-mapping)) (in-package #:frpc.bind) (defconstant +pmapper-program+ 100000) (defprogram port-mapper 100000) (use-rpc-host '*rpc-host* 111) ;; ------- port mapper structs ---------- (defxenum mapping-protocol (:tcp 6) (:udp 17)) (defxstruct mapping () (program :uint32) (version :uint32) (protocol mapping-protocol :tcp) (port :uint32)) (defun mapping-eql (m1 m2) (and (= (mapping-program m1) (mapping-program m2)) (= (mapping-version m1) (mapping-version m2)) (eq (mapping-protocol m1) (mapping-protocol m2)) (if (and (mapping-port m1) (mapping-port m2) (not (zerop (mapping-port m1))) (not (zerop (mapping-port m2)))) (= (mapping-port m1) (mapping-port m2)) t))) ;; ---------------------------------- ;; Port mapper: ;; needs to keep a mapping of ports to mapping structs ;; (defvar *mappings* nil) (defun add-mapping (mapping) "Add a port mapping." ;; only add the mapping if it's not already mapped (pushnew mapping *mappings* :test #'mapping-eql)) (defun rem-mapping (mapping) "Remove a port mapping." (setf *mappings* (remove-if (lambda (m) (mapping-eql m mapping)) *mappings*))) (defun find-mapping (mapping &optional map-port) "Lookup a port mapping matching the program, version and protocol specified in the mapping structure. if MAP-PORT is provided, will also match this port." (let ((port (mapping-port mapping))) (find-if (lambda (m) (and (mapping-eql m mapping) (if map-port (= map-port port) t))) *mappings*))) (defun generate-mapping-list (tcp-ports udp-ports &key programs) "Generate a list of all mappings for the programs hosted by this Lisp image." (let (mappings-to-add) (dolist (ppair frpc::*handlers*) (destructuring-bind (program . versions) ppair (when (or (= program 100000) (if programs (member program programs) t)) (dolist (vpair versions) (let ((version (car vpair))) (dolist (uport udp-ports) ;; only advertise the portmap program on port 111. ;; Yes, it can be contacted on ANY port our rpc server is running, but we keep that a secret. (when (or (and (= program +pmapper-program+) (= uport 111)) (and (not (= program +pmapper-program+)) (not (= uport 111)))) (push (make-mapping :program program :version version :protocol :udp :port uport) mappings-to-add))) (dolist (tport tcp-ports) (when (or (and (= program +pmapper-program+) (= tport 111)) (and (not (= program +pmapper-program+)) (not (= tport 111)))) (push (make-mapping :program program :version version :protocol :tcp :port tport) mappings-to-add)))))))) mappings-to-add)) (defun add-all-mappings (tcp-ports udp-ports &key rpc programs) (let ((mappings-to-add (generate-mapping-list tcp-ports udp-ports :programs programs))) (dolist (m mappings-to-add) ;; add the mapping to our local repository (add-mapping m) ;; add to the remote portmap program (when rpc (handler-case (call-set m :host "localhost" :client (make-instance 'unix-client)) (error (e) (frpc-log :info "Failed to map ~A" e)))))) nil) (defun remove-all-mappings (tcp-ports udp-ports &key rpc programs) (let ((mappings-to-add (generate-mapping-list tcp-ports udp-ports :programs programs))) (dolist (m mappings-to-add) ;; add the mapping to our local repository (rem-mapping m) ;; call the remote portmap program (when rpc (handler-case (call-unset m :host "localhost" :client (make-instance 'unix-client)) (error (e) (frpc-log :info "Failed to unmap ~A" e)))))) nil) ;; ---------------------- ;; NULL -- test communication to the port mapper (defun %handle-null (void) (declare (ignore void)) nil) (defrpc call-null 0 :void :void (:program port-mapper 2) (:handler #'%handle-null)) ;; --------------- ;; only allow it to be called if the host is localhost and the user has been authenticated to some level (defun auth-or-fail () (when (or (not (equalp *rpc-remote-host* #(127 0 0 1))) (eq (opaque-auth-flavour *rpc-remote-auth*) :auth-null)) (frpc-log :info "Rejected ~S ~S" *rpc-remote-host* (opaque-auth-flavour *rpc-remote-auth*)) (error 'rpc-auth-error :stat :auth-tooweak))) ;; SET -- set a port mapping (defun %handle-set (mapping) (auth-or-fail) (add-mapping mapping) t) (defrpc call-set 1 mapping :boolean (:program port-mapper 2) (:arg-transformer (mapping) mapping) (:documentation "Set a port mapping.") (:handler #'%handle-set)) ;; ------------------- ;; UNSET -- remove a port mapping (defun %handle-unset (mapping) (auth-or-fail) (when (find-mapping mapping) (rem-mapping mapping) t)) (defrpc call-unset 2 mapping :boolean (:program port-mapper 2) (:arg-transformer (mapping) mapping) (:documentation "Remove a port mapping.") (:handler #'%handle-unset)) ;; ---------------------- ;; GET-PORT -- lookup a port mapping for a given program/version (defun %handle-get-port (mapping) (let ((m (find-if (lambda (m) (and (= (mapping-program mapping) (mapping-program m)) (eq (mapping-protocol mapping) (mapping-protocol m)))) *mappings*))) (if m (mapping-port m) 0))) (defrpc call-get-port 3 mapping :uint32 (:program port-mapper 2) (:arg-transformer (program &key (query-protocol :udp)) (make-mapping :program program :protocol (or query-protocol :udp))) (:documentation "Query the port for the specified program.") (:handler #'%handle-get-port)) ;; ------------------------ ;; DUMP -- list all mappings ;; define our own type for a list of mappings ;; should be something like ;; (defxstruct mapping-list () ;; (map mapping) ;; (next (:optional mapping-list))) ;; but this doesn't scale well if the list is long ;; so we use a hand-written iterative function instead (defxtype mapping-list () ((stream) (do ((maps nil) (done nil)) (done maps) (let ((map (read-xtype 'mapping stream))) (push map maps) (let ((next (read-xtype :boolean stream))) (unless next (setf done t)))))) ((stream mlist) (do ((mlist mlist (cdr mlist))) ((null mlist)) (write-xtype 'mapping stream (car mlist)) (if (cdr mlist) (write-xtype :boolean stream t) (write-xtype :boolean stream nil))))) (defun %handle-dump (void) (declare (ignore void)) *mappings*) (defrpc call-dump 4 :void (:optional mapping-list) (:program port-mapper 2) (:documentation "List all available port mappings.") (:handler #'%handle-dump)) ;; ---------------------------------------- ;; In the spec it says we should be able to call any (mapped) rpc on the local machine communicating ;; only via UDP. We run all RPC programs from within the same Lisp image so we can directly ;; execute the handler without having to do any real proxy RPCs. (defun %handle-callit (args) (destructuring-bind (program version proc arg-buffer) args ;; find the handler and port mapping (frpc-log :trace "CALLIT ~A:~A:~A" program version proc) (let ((mapping (find-mapping (make-mapping :program program :version version :protocol :udp))) (h (find-handler program version proc))) (cond ((and (null mapping) (null h)) ;; error: no mapping or no handler. signalling an error here ;; causes the server to be silent (not reply) (error "proc not found")) (h ;; found the handler, run it (destructuring-bind (reader writer handler) h (if handler (let ((res (funcall handler (unpack reader arg-buffer)))) (list (mapping-port mapping) (pack writer res))) (error "no handler")))) (mapping ;; we have a mapping, but no handler defined. this means ;; the rpc server lives out-of-process i.e. in another Lisp image ;; we must therefore contact it via UDP and await a response. ;; NOTE: if the handler really is living in our image then ;; this will lock for 1 second because we have sent a ;; message to ourselves. (let ((port (mapping-port mapping))) (let ((res (call-rpc #'frpc::write-octet-array arg-buffer #'frpc::read-octet-array :host "localhost" :port port :program program :version version :proc proc))) (list port res)))))))) (defrpc call-callit 5 (:list :uint32 :uint32 :uint32 (:varray* :octet)) ;; prog version proc args (:list :uint32 (:varray* :octet)) ;; port result (:program port-mapper 2) (:arg-transformer (program version proc packed-args) (list program version proc packed-args)) (:documentation "Execute an RPC via the remote port mapper proxy. Returns (list PORT RES) where RES is an opaque array of the packed result. The result needs to be extracted using FRPC:UNPACK. The result type is recommended to be a well-defined type, i.e. represented by a symbol, so that it has an easy reader function available.") (:handler #'%handle-callit)) ;; ------------------------------------------------------------ (defxstruct binding () (program :uint32) (version :uint32) (netid :string) (addr :string) (owner :string)) (defxtype binding-list () ((stream) (read-xtype-list stream 'binding)) ((stream mappings) (write-xtype-list stream 'binding mappings))) (defxstruct rpcb-remote-call-arg () (program :uint32) (version :uint32) (proc :uint32) (args (:varray* :octet))) (defxtype* rpb-remote-call-res () (:list :string ;; addr (:varray* :octet))) ;; results (defxstruct rpcb-entry () (maddr :string) (netid :string) (semantics :uint32) (protof :string) ;; protocol family (proto :string)) ;; protocol (defxtype rpcb-entry-list () ((stream) (read-xtype-list stream 'rpcb-entry)) ((stream list) (write-xtype-list stream 'rpcb-entry list))) (defconstant +rpcbs-highproc+ 13) (defconstant +rpcb-vers-stat+ 3) (defxstruct rpcbs-addr () (program :uint32) (version :uint32) (success :int32) (failure :int32) (netid :string)) (defxtype rpcbs-addr-list () ((stream) (read-xtype-list stream 'rpcbs-addr)) ((stream list) (write-xtype-list stream 'rpbs-addr list))) (defxstruct rpcbs-rmtcall () (program :uint32) (version :uint32) (proc :uint32) (success :int32) (failure :int32) (indirect :int32) (netid :string)) (defxtype rpcbs-rmtcall-list () ((stream) (read-xtype-list stream 'rpcbs-rmtcall)) ((stream list) (write-xtype-list stream 'rpcbs-rmtcall list))) (defxtype* rpcbs-proc () (:array :int32 +rpcbs-highproc+)) (defxstruct rpcb-stat () (info rpcbs-proc) (setinfo :int32) (unsetinfo :int32) (addrinfo (:optional rpcbs-addr-list)) (rmtinfo (:optional rpcbs-rmtcall-list))) (defxtype* rpcb-stat-byvers () (:array rpcb-stat +rpcb-vers-stat+)) (defxtype* netbuf () (:list :uint32 (:varray* :octet))) ;; -------------- version 3 ----------- (defrpc call-null3 0 :void :void (:program port-mapper 3)) (defrpc call-set3 1 binding :boolean (:program port-mapper 3)) (defrpc call-unset3 2 binding :boolean (:program port-mapper 3)) (defrpc call-get-addr3 3 binding :string (:program port-mapper 3)) (defrpc call-dump3 4 :void (:optional binding-list) (:program port-mapper 3)) (defrpc call-broadcast3 5 rpcb-rmtcall-args rpcb-rmtcall-res (:program port-mapper 3)) (defrpc call-get-time3 6 :void :uint32 (:program port-mapper 3)) (defrpc call-uaddr2taddr3 7 :string netbuf (:program port-mapper 3)) (defrpc call-taddr2uaddr3 8 netbuf :string (:program port-mapper 3)) ;; ------------- version 4 ------------- (defrpc call-null4 0 :void :void (:program port-mapper 4)) (defrpc call-set4 1 binding :boolean (:program port-mapper 4)) (defrpc call-unset4 2 binding :boolean (:program port-mapper 4)) (defrpc call-get-addr4 3 binding :string (:program port-mapper 4)) (defrpc call-dump4 4 :void (:optional binding-list) (:program port-mapper 4)) (defrpc call-broadcast4 5 rpcb-rmtcall-args rpcb-rmtcall-res (:program port-mapper 4)) (defrpc call-get-time4 6 :void :uint32 (:program port-mapper 4)) (defrpc call-uaddr2taddr4 7 :string netbuf (:program port-mapper 4)) (defrpc call-taddr2uaddr4 8 netbuf :string (:program port-mapper 4)) (defrpc call-get-version-addr 9 binding :string (:program port-mapper 4)) (defrpc call-indirect 10 rpcb-rmtcall-args rpcb-rmtcall-res (:program port-mapper 4)) (defrpc call-get-addr-list 11 binding (:optional rpcb-entry-list) (:program port-mapper 4)) (defrpc call-stat-by-version 12 :void rpcb-stat-by-vers (:program port-mapper 4))
16806
;;;; Copyright (c) <NAME> 2015 <<EMAIL>> ;;;; This code is licensed under the MIT license. ;;; This file implements portmap (version 2) and rpcbind (versions 3 and 4) (defpackage #:frpc.bind (:use #:cl #:frpc) (:export #:mapping #:make-mapping #:mapping-program #:mapping-version #:mapping-protocol #:mapping-port #:binding #:binding-program #:binding-version #:binding-netid #:binding-addr #:binding-owner ;; the rpc functions #:call-null #:call-set #:call-unset #:call-get-port #:call-dump #:call-callit #:call-null3 #:call-set3 #:call-unset3 #:call-get-addr3 #:call-dump3 #:call-broadcast3 #:call-get-time3 #:call-uaddr2taddr3 #:call-taddr2uaddr3 #:call-null4 #:call-set4 #:call-unset4 #:call-get-addr4 #:call-dump4 #:call-broadcast4 #:call-get-time4 #:call-uaddr2taddr4 #:call-taddr2uaddr4 #:call-get-version-addr #:call-indirect #:call-get-addr-list #:call-stat-by-version ;; underlying API #:add-mapping #:rem-mapping #:add-all-mappings #:remove-all-mappings #:find-mapping)) (in-package #:frpc.bind) (defconstant +pmapper-program+ 100000) (defprogram port-mapper 100000) (use-rpc-host '*rpc-host* 111) ;; ------- port mapper structs ---------- (defxenum mapping-protocol (:tcp 6) (:udp 17)) (defxstruct mapping () (program :uint32) (version :uint32) (protocol mapping-protocol :tcp) (port :uint32)) (defun mapping-eql (m1 m2) (and (= (mapping-program m1) (mapping-program m2)) (= (mapping-version m1) (mapping-version m2)) (eq (mapping-protocol m1) (mapping-protocol m2)) (if (and (mapping-port m1) (mapping-port m2) (not (zerop (mapping-port m1))) (not (zerop (mapping-port m2)))) (= (mapping-port m1) (mapping-port m2)) t))) ;; ---------------------------------- ;; Port mapper: ;; needs to keep a mapping of ports to mapping structs ;; (defvar *mappings* nil) (defun add-mapping (mapping) "Add a port mapping." ;; only add the mapping if it's not already mapped (pushnew mapping *mappings* :test #'mapping-eql)) (defun rem-mapping (mapping) "Remove a port mapping." (setf *mappings* (remove-if (lambda (m) (mapping-eql m mapping)) *mappings*))) (defun find-mapping (mapping &optional map-port) "Lookup a port mapping matching the program, version and protocol specified in the mapping structure. if MAP-PORT is provided, will also match this port." (let ((port (mapping-port mapping))) (find-if (lambda (m) (and (mapping-eql m mapping) (if map-port (= map-port port) t))) *mappings*))) (defun generate-mapping-list (tcp-ports udp-ports &key programs) "Generate a list of all mappings for the programs hosted by this Lisp image." (let (mappings-to-add) (dolist (ppair frpc::*handlers*) (destructuring-bind (program . versions) ppair (when (or (= program 100000) (if programs (member program programs) t)) (dolist (vpair versions) (let ((version (car vpair))) (dolist (uport udp-ports) ;; only advertise the portmap program on port 111. ;; Yes, it can be contacted on ANY port our rpc server is running, but we keep that a secret. (when (or (and (= program +pmapper-program+) (= uport 111)) (and (not (= program +pmapper-program+)) (not (= uport 111)))) (push (make-mapping :program program :version version :protocol :udp :port uport) mappings-to-add))) (dolist (tport tcp-ports) (when (or (and (= program +pmapper-program+) (= tport 111)) (and (not (= program +pmapper-program+)) (not (= tport 111)))) (push (make-mapping :program program :version version :protocol :tcp :port tport) mappings-to-add)))))))) mappings-to-add)) (defun add-all-mappings (tcp-ports udp-ports &key rpc programs) (let ((mappings-to-add (generate-mapping-list tcp-ports udp-ports :programs programs))) (dolist (m mappings-to-add) ;; add the mapping to our local repository (add-mapping m) ;; add to the remote portmap program (when rpc (handler-case (call-set m :host "localhost" :client (make-instance 'unix-client)) (error (e) (frpc-log :info "Failed to map ~A" e)))))) nil) (defun remove-all-mappings (tcp-ports udp-ports &key rpc programs) (let ((mappings-to-add (generate-mapping-list tcp-ports udp-ports :programs programs))) (dolist (m mappings-to-add) ;; add the mapping to our local repository (rem-mapping m) ;; call the remote portmap program (when rpc (handler-case (call-unset m :host "localhost" :client (make-instance 'unix-client)) (error (e) (frpc-log :info "Failed to unmap ~A" e)))))) nil) ;; ---------------------- ;; NULL -- test communication to the port mapper (defun %handle-null (void) (declare (ignore void)) nil) (defrpc call-null 0 :void :void (:program port-mapper 2) (:handler #'%handle-null)) ;; --------------- ;; only allow it to be called if the host is localhost and the user has been authenticated to some level (defun auth-or-fail () (when (or (not (equalp *rpc-remote-host* #(127 0 0 1))) (eq (opaque-auth-flavour *rpc-remote-auth*) :auth-null)) (frpc-log :info "Rejected ~S ~S" *rpc-remote-host* (opaque-auth-flavour *rpc-remote-auth*)) (error 'rpc-auth-error :stat :auth-tooweak))) ;; SET -- set a port mapping (defun %handle-set (mapping) (auth-or-fail) (add-mapping mapping) t) (defrpc call-set 1 mapping :boolean (:program port-mapper 2) (:arg-transformer (mapping) mapping) (:documentation "Set a port mapping.") (:handler #'%handle-set)) ;; ------------------- ;; UNSET -- remove a port mapping (defun %handle-unset (mapping) (auth-or-fail) (when (find-mapping mapping) (rem-mapping mapping) t)) (defrpc call-unset 2 mapping :boolean (:program port-mapper 2) (:arg-transformer (mapping) mapping) (:documentation "Remove a port mapping.") (:handler #'%handle-unset)) ;; ---------------------- ;; GET-PORT -- lookup a port mapping for a given program/version (defun %handle-get-port (mapping) (let ((m (find-if (lambda (m) (and (= (mapping-program mapping) (mapping-program m)) (eq (mapping-protocol mapping) (mapping-protocol m)))) *mappings*))) (if m (mapping-port m) 0))) (defrpc call-get-port 3 mapping :uint32 (:program port-mapper 2) (:arg-transformer (program &key (query-protocol :udp)) (make-mapping :program program :protocol (or query-protocol :udp))) (:documentation "Query the port for the specified program.") (:handler #'%handle-get-port)) ;; ------------------------ ;; DUMP -- list all mappings ;; define our own type for a list of mappings ;; should be something like ;; (defxstruct mapping-list () ;; (map mapping) ;; (next (:optional mapping-list))) ;; but this doesn't scale well if the list is long ;; so we use a hand-written iterative function instead (defxtype mapping-list () ((stream) (do ((maps nil) (done nil)) (done maps) (let ((map (read-xtype 'mapping stream))) (push map maps) (let ((next (read-xtype :boolean stream))) (unless next (setf done t)))))) ((stream mlist) (do ((mlist mlist (cdr mlist))) ((null mlist)) (write-xtype 'mapping stream (car mlist)) (if (cdr mlist) (write-xtype :boolean stream t) (write-xtype :boolean stream nil))))) (defun %handle-dump (void) (declare (ignore void)) *mappings*) (defrpc call-dump 4 :void (:optional mapping-list) (:program port-mapper 2) (:documentation "List all available port mappings.") (:handler #'%handle-dump)) ;; ---------------------------------------- ;; In the spec it says we should be able to call any (mapped) rpc on the local machine communicating ;; only via UDP. We run all RPC programs from within the same Lisp image so we can directly ;; execute the handler without having to do any real proxy RPCs. (defun %handle-callit (args) (destructuring-bind (program version proc arg-buffer) args ;; find the handler and port mapping (frpc-log :trace "CALLIT ~A:~A:~A" program version proc) (let ((mapping (find-mapping (make-mapping :program program :version version :protocol :udp))) (h (find-handler program version proc))) (cond ((and (null mapping) (null h)) ;; error: no mapping or no handler. signalling an error here ;; causes the server to be silent (not reply) (error "proc not found")) (h ;; found the handler, run it (destructuring-bind (reader writer handler) h (if handler (let ((res (funcall handler (unpack reader arg-buffer)))) (list (mapping-port mapping) (pack writer res))) (error "no handler")))) (mapping ;; we have a mapping, but no handler defined. this means ;; the rpc server lives out-of-process i.e. in another Lisp image ;; we must therefore contact it via UDP and await a response. ;; NOTE: if the handler really is living in our image then ;; this will lock for 1 second because we have sent a ;; message to ourselves. (let ((port (mapping-port mapping))) (let ((res (call-rpc #'frpc::write-octet-array arg-buffer #'frpc::read-octet-array :host "localhost" :port port :program program :version version :proc proc))) (list port res)))))))) (defrpc call-callit 5 (:list :uint32 :uint32 :uint32 (:varray* :octet)) ;; prog version proc args (:list :uint32 (:varray* :octet)) ;; port result (:program port-mapper 2) (:arg-transformer (program version proc packed-args) (list program version proc packed-args)) (:documentation "Execute an RPC via the remote port mapper proxy. Returns (list PORT RES) where RES is an opaque array of the packed result. The result needs to be extracted using FRPC:UNPACK. The result type is recommended to be a well-defined type, i.e. represented by a symbol, so that it has an easy reader function available.") (:handler #'%handle-callit)) ;; ------------------------------------------------------------ (defxstruct binding () (program :uint32) (version :uint32) (netid :string) (addr :string) (owner :string)) (defxtype binding-list () ((stream) (read-xtype-list stream 'binding)) ((stream mappings) (write-xtype-list stream 'binding mappings))) (defxstruct rpcb-remote-call-arg () (program :uint32) (version :uint32) (proc :uint32) (args (:varray* :octet))) (defxtype* rpb-remote-call-res () (:list :string ;; addr (:varray* :octet))) ;; results (defxstruct rpcb-entry () (maddr :string) (netid :string) (semantics :uint32) (protof :string) ;; protocol family (proto :string)) ;; protocol (defxtype rpcb-entry-list () ((stream) (read-xtype-list stream 'rpcb-entry)) ((stream list) (write-xtype-list stream 'rpcb-entry list))) (defconstant +rpcbs-highproc+ 13) (defconstant +rpcb-vers-stat+ 3) (defxstruct rpcbs-addr () (program :uint32) (version :uint32) (success :int32) (failure :int32) (netid :string)) (defxtype rpcbs-addr-list () ((stream) (read-xtype-list stream 'rpcbs-addr)) ((stream list) (write-xtype-list stream 'rpbs-addr list))) (defxstruct rpcbs-rmtcall () (program :uint32) (version :uint32) (proc :uint32) (success :int32) (failure :int32) (indirect :int32) (netid :string)) (defxtype rpcbs-rmtcall-list () ((stream) (read-xtype-list stream 'rpcbs-rmtcall)) ((stream list) (write-xtype-list stream 'rpcbs-rmtcall list))) (defxtype* rpcbs-proc () (:array :int32 +rpcbs-highproc+)) (defxstruct rpcb-stat () (info rpcbs-proc) (setinfo :int32) (unsetinfo :int32) (addrinfo (:optional rpcbs-addr-list)) (rmtinfo (:optional rpcbs-rmtcall-list))) (defxtype* rpcb-stat-byvers () (:array rpcb-stat +rpcb-vers-stat+)) (defxtype* netbuf () (:list :uint32 (:varray* :octet))) ;; -------------- version 3 ----------- (defrpc call-null3 0 :void :void (:program port-mapper 3)) (defrpc call-set3 1 binding :boolean (:program port-mapper 3)) (defrpc call-unset3 2 binding :boolean (:program port-mapper 3)) (defrpc call-get-addr3 3 binding :string (:program port-mapper 3)) (defrpc call-dump3 4 :void (:optional binding-list) (:program port-mapper 3)) (defrpc call-broadcast3 5 rpcb-rmtcall-args rpcb-rmtcall-res (:program port-mapper 3)) (defrpc call-get-time3 6 :void :uint32 (:program port-mapper 3)) (defrpc call-uaddr2taddr3 7 :string netbuf (:program port-mapper 3)) (defrpc call-taddr2uaddr3 8 netbuf :string (:program port-mapper 3)) ;; ------------- version 4 ------------- (defrpc call-null4 0 :void :void (:program port-mapper 4)) (defrpc call-set4 1 binding :boolean (:program port-mapper 4)) (defrpc call-unset4 2 binding :boolean (:program port-mapper 4)) (defrpc call-get-addr4 3 binding :string (:program port-mapper 4)) (defrpc call-dump4 4 :void (:optional binding-list) (:program port-mapper 4)) (defrpc call-broadcast4 5 rpcb-rmtcall-args rpcb-rmtcall-res (:program port-mapper 4)) (defrpc call-get-time4 6 :void :uint32 (:program port-mapper 4)) (defrpc call-uaddr2taddr4 7 :string netbuf (:program port-mapper 4)) (defrpc call-taddr2uaddr4 8 netbuf :string (:program port-mapper 4)) (defrpc call-get-version-addr 9 binding :string (:program port-mapper 4)) (defrpc call-indirect 10 rpcb-rmtcall-args rpcb-rmtcall-res (:program port-mapper 4)) (defrpc call-get-addr-list 11 binding (:optional rpcb-entry-list) (:program port-mapper 4)) (defrpc call-stat-by-version 12 :void rpcb-stat-by-vers (:program port-mapper 4))
true
;;;; Copyright (c) PI:NAME:<NAME>END_PI 2015 <PI:EMAIL:<EMAIL>END_PI> ;;;; This code is licensed under the MIT license. ;;; This file implements portmap (version 2) and rpcbind (versions 3 and 4) (defpackage #:frpc.bind (:use #:cl #:frpc) (:export #:mapping #:make-mapping #:mapping-program #:mapping-version #:mapping-protocol #:mapping-port #:binding #:binding-program #:binding-version #:binding-netid #:binding-addr #:binding-owner ;; the rpc functions #:call-null #:call-set #:call-unset #:call-get-port #:call-dump #:call-callit #:call-null3 #:call-set3 #:call-unset3 #:call-get-addr3 #:call-dump3 #:call-broadcast3 #:call-get-time3 #:call-uaddr2taddr3 #:call-taddr2uaddr3 #:call-null4 #:call-set4 #:call-unset4 #:call-get-addr4 #:call-dump4 #:call-broadcast4 #:call-get-time4 #:call-uaddr2taddr4 #:call-taddr2uaddr4 #:call-get-version-addr #:call-indirect #:call-get-addr-list #:call-stat-by-version ;; underlying API #:add-mapping #:rem-mapping #:add-all-mappings #:remove-all-mappings #:find-mapping)) (in-package #:frpc.bind) (defconstant +pmapper-program+ 100000) (defprogram port-mapper 100000) (use-rpc-host '*rpc-host* 111) ;; ------- port mapper structs ---------- (defxenum mapping-protocol (:tcp 6) (:udp 17)) (defxstruct mapping () (program :uint32) (version :uint32) (protocol mapping-protocol :tcp) (port :uint32)) (defun mapping-eql (m1 m2) (and (= (mapping-program m1) (mapping-program m2)) (= (mapping-version m1) (mapping-version m2)) (eq (mapping-protocol m1) (mapping-protocol m2)) (if (and (mapping-port m1) (mapping-port m2) (not (zerop (mapping-port m1))) (not (zerop (mapping-port m2)))) (= (mapping-port m1) (mapping-port m2)) t))) ;; ---------------------------------- ;; Port mapper: ;; needs to keep a mapping of ports to mapping structs ;; (defvar *mappings* nil) (defun add-mapping (mapping) "Add a port mapping." ;; only add the mapping if it's not already mapped (pushnew mapping *mappings* :test #'mapping-eql)) (defun rem-mapping (mapping) "Remove a port mapping." (setf *mappings* (remove-if (lambda (m) (mapping-eql m mapping)) *mappings*))) (defun find-mapping (mapping &optional map-port) "Lookup a port mapping matching the program, version and protocol specified in the mapping structure. if MAP-PORT is provided, will also match this port." (let ((port (mapping-port mapping))) (find-if (lambda (m) (and (mapping-eql m mapping) (if map-port (= map-port port) t))) *mappings*))) (defun generate-mapping-list (tcp-ports udp-ports &key programs) "Generate a list of all mappings for the programs hosted by this Lisp image." (let (mappings-to-add) (dolist (ppair frpc::*handlers*) (destructuring-bind (program . versions) ppair (when (or (= program 100000) (if programs (member program programs) t)) (dolist (vpair versions) (let ((version (car vpair))) (dolist (uport udp-ports) ;; only advertise the portmap program on port 111. ;; Yes, it can be contacted on ANY port our rpc server is running, but we keep that a secret. (when (or (and (= program +pmapper-program+) (= uport 111)) (and (not (= program +pmapper-program+)) (not (= uport 111)))) (push (make-mapping :program program :version version :protocol :udp :port uport) mappings-to-add))) (dolist (tport tcp-ports) (when (or (and (= program +pmapper-program+) (= tport 111)) (and (not (= program +pmapper-program+)) (not (= tport 111)))) (push (make-mapping :program program :version version :protocol :tcp :port tport) mappings-to-add)))))))) mappings-to-add)) (defun add-all-mappings (tcp-ports udp-ports &key rpc programs) (let ((mappings-to-add (generate-mapping-list tcp-ports udp-ports :programs programs))) (dolist (m mappings-to-add) ;; add the mapping to our local repository (add-mapping m) ;; add to the remote portmap program (when rpc (handler-case (call-set m :host "localhost" :client (make-instance 'unix-client)) (error (e) (frpc-log :info "Failed to map ~A" e)))))) nil) (defun remove-all-mappings (tcp-ports udp-ports &key rpc programs) (let ((mappings-to-add (generate-mapping-list tcp-ports udp-ports :programs programs))) (dolist (m mappings-to-add) ;; add the mapping to our local repository (rem-mapping m) ;; call the remote portmap program (when rpc (handler-case (call-unset m :host "localhost" :client (make-instance 'unix-client)) (error (e) (frpc-log :info "Failed to unmap ~A" e)))))) nil) ;; ---------------------- ;; NULL -- test communication to the port mapper (defun %handle-null (void) (declare (ignore void)) nil) (defrpc call-null 0 :void :void (:program port-mapper 2) (:handler #'%handle-null)) ;; --------------- ;; only allow it to be called if the host is localhost and the user has been authenticated to some level (defun auth-or-fail () (when (or (not (equalp *rpc-remote-host* #(127 0 0 1))) (eq (opaque-auth-flavour *rpc-remote-auth*) :auth-null)) (frpc-log :info "Rejected ~S ~S" *rpc-remote-host* (opaque-auth-flavour *rpc-remote-auth*)) (error 'rpc-auth-error :stat :auth-tooweak))) ;; SET -- set a port mapping (defun %handle-set (mapping) (auth-or-fail) (add-mapping mapping) t) (defrpc call-set 1 mapping :boolean (:program port-mapper 2) (:arg-transformer (mapping) mapping) (:documentation "Set a port mapping.") (:handler #'%handle-set)) ;; ------------------- ;; UNSET -- remove a port mapping (defun %handle-unset (mapping) (auth-or-fail) (when (find-mapping mapping) (rem-mapping mapping) t)) (defrpc call-unset 2 mapping :boolean (:program port-mapper 2) (:arg-transformer (mapping) mapping) (:documentation "Remove a port mapping.") (:handler #'%handle-unset)) ;; ---------------------- ;; GET-PORT -- lookup a port mapping for a given program/version (defun %handle-get-port (mapping) (let ((m (find-if (lambda (m) (and (= (mapping-program mapping) (mapping-program m)) (eq (mapping-protocol mapping) (mapping-protocol m)))) *mappings*))) (if m (mapping-port m) 0))) (defrpc call-get-port 3 mapping :uint32 (:program port-mapper 2) (:arg-transformer (program &key (query-protocol :udp)) (make-mapping :program program :protocol (or query-protocol :udp))) (:documentation "Query the port for the specified program.") (:handler #'%handle-get-port)) ;; ------------------------ ;; DUMP -- list all mappings ;; define our own type for a list of mappings ;; should be something like ;; (defxstruct mapping-list () ;; (map mapping) ;; (next (:optional mapping-list))) ;; but this doesn't scale well if the list is long ;; so we use a hand-written iterative function instead (defxtype mapping-list () ((stream) (do ((maps nil) (done nil)) (done maps) (let ((map (read-xtype 'mapping stream))) (push map maps) (let ((next (read-xtype :boolean stream))) (unless next (setf done t)))))) ((stream mlist) (do ((mlist mlist (cdr mlist))) ((null mlist)) (write-xtype 'mapping stream (car mlist)) (if (cdr mlist) (write-xtype :boolean stream t) (write-xtype :boolean stream nil))))) (defun %handle-dump (void) (declare (ignore void)) *mappings*) (defrpc call-dump 4 :void (:optional mapping-list) (:program port-mapper 2) (:documentation "List all available port mappings.") (:handler #'%handle-dump)) ;; ---------------------------------------- ;; In the spec it says we should be able to call any (mapped) rpc on the local machine communicating ;; only via UDP. We run all RPC programs from within the same Lisp image so we can directly ;; execute the handler without having to do any real proxy RPCs. (defun %handle-callit (args) (destructuring-bind (program version proc arg-buffer) args ;; find the handler and port mapping (frpc-log :trace "CALLIT ~A:~A:~A" program version proc) (let ((mapping (find-mapping (make-mapping :program program :version version :protocol :udp))) (h (find-handler program version proc))) (cond ((and (null mapping) (null h)) ;; error: no mapping or no handler. signalling an error here ;; causes the server to be silent (not reply) (error "proc not found")) (h ;; found the handler, run it (destructuring-bind (reader writer handler) h (if handler (let ((res (funcall handler (unpack reader arg-buffer)))) (list (mapping-port mapping) (pack writer res))) (error "no handler")))) (mapping ;; we have a mapping, but no handler defined. this means ;; the rpc server lives out-of-process i.e. in another Lisp image ;; we must therefore contact it via UDP and await a response. ;; NOTE: if the handler really is living in our image then ;; this will lock for 1 second because we have sent a ;; message to ourselves. (let ((port (mapping-port mapping))) (let ((res (call-rpc #'frpc::write-octet-array arg-buffer #'frpc::read-octet-array :host "localhost" :port port :program program :version version :proc proc))) (list port res)))))))) (defrpc call-callit 5 (:list :uint32 :uint32 :uint32 (:varray* :octet)) ;; prog version proc args (:list :uint32 (:varray* :octet)) ;; port result (:program port-mapper 2) (:arg-transformer (program version proc packed-args) (list program version proc packed-args)) (:documentation "Execute an RPC via the remote port mapper proxy. Returns (list PORT RES) where RES is an opaque array of the packed result. The result needs to be extracted using FRPC:UNPACK. The result type is recommended to be a well-defined type, i.e. represented by a symbol, so that it has an easy reader function available.") (:handler #'%handle-callit)) ;; ------------------------------------------------------------ (defxstruct binding () (program :uint32) (version :uint32) (netid :string) (addr :string) (owner :string)) (defxtype binding-list () ((stream) (read-xtype-list stream 'binding)) ((stream mappings) (write-xtype-list stream 'binding mappings))) (defxstruct rpcb-remote-call-arg () (program :uint32) (version :uint32) (proc :uint32) (args (:varray* :octet))) (defxtype* rpb-remote-call-res () (:list :string ;; addr (:varray* :octet))) ;; results (defxstruct rpcb-entry () (maddr :string) (netid :string) (semantics :uint32) (protof :string) ;; protocol family (proto :string)) ;; protocol (defxtype rpcb-entry-list () ((stream) (read-xtype-list stream 'rpcb-entry)) ((stream list) (write-xtype-list stream 'rpcb-entry list))) (defconstant +rpcbs-highproc+ 13) (defconstant +rpcb-vers-stat+ 3) (defxstruct rpcbs-addr () (program :uint32) (version :uint32) (success :int32) (failure :int32) (netid :string)) (defxtype rpcbs-addr-list () ((stream) (read-xtype-list stream 'rpcbs-addr)) ((stream list) (write-xtype-list stream 'rpbs-addr list))) (defxstruct rpcbs-rmtcall () (program :uint32) (version :uint32) (proc :uint32) (success :int32) (failure :int32) (indirect :int32) (netid :string)) (defxtype rpcbs-rmtcall-list () ((stream) (read-xtype-list stream 'rpcbs-rmtcall)) ((stream list) (write-xtype-list stream 'rpcbs-rmtcall list))) (defxtype* rpcbs-proc () (:array :int32 +rpcbs-highproc+)) (defxstruct rpcb-stat () (info rpcbs-proc) (setinfo :int32) (unsetinfo :int32) (addrinfo (:optional rpcbs-addr-list)) (rmtinfo (:optional rpcbs-rmtcall-list))) (defxtype* rpcb-stat-byvers () (:array rpcb-stat +rpcb-vers-stat+)) (defxtype* netbuf () (:list :uint32 (:varray* :octet))) ;; -------------- version 3 ----------- (defrpc call-null3 0 :void :void (:program port-mapper 3)) (defrpc call-set3 1 binding :boolean (:program port-mapper 3)) (defrpc call-unset3 2 binding :boolean (:program port-mapper 3)) (defrpc call-get-addr3 3 binding :string (:program port-mapper 3)) (defrpc call-dump3 4 :void (:optional binding-list) (:program port-mapper 3)) (defrpc call-broadcast3 5 rpcb-rmtcall-args rpcb-rmtcall-res (:program port-mapper 3)) (defrpc call-get-time3 6 :void :uint32 (:program port-mapper 3)) (defrpc call-uaddr2taddr3 7 :string netbuf (:program port-mapper 3)) (defrpc call-taddr2uaddr3 8 netbuf :string (:program port-mapper 3)) ;; ------------- version 4 ------------- (defrpc call-null4 0 :void :void (:program port-mapper 4)) (defrpc call-set4 1 binding :boolean (:program port-mapper 4)) (defrpc call-unset4 2 binding :boolean (:program port-mapper 4)) (defrpc call-get-addr4 3 binding :string (:program port-mapper 4)) (defrpc call-dump4 4 :void (:optional binding-list) (:program port-mapper 4)) (defrpc call-broadcast4 5 rpcb-rmtcall-args rpcb-rmtcall-res (:program port-mapper 4)) (defrpc call-get-time4 6 :void :uint32 (:program port-mapper 4)) (defrpc call-uaddr2taddr4 7 :string netbuf (:program port-mapper 4)) (defrpc call-taddr2uaddr4 8 netbuf :string (:program port-mapper 4)) (defrpc call-get-version-addr 9 binding :string (:program port-mapper 4)) (defrpc call-indirect 10 rpcb-rmtcall-args rpcb-rmtcall-res (:program port-mapper 4)) (defrpc call-get-addr-list 11 binding (:optional rpcb-entry-list) (:program port-mapper 4)) (defrpc call-stat-by-version 12 :void rpcb-stat-by-vers (:program port-mapper 4))
[ { "context": ";;;; truth-table.lisp\n;;;;\n;;;; Author: Charles Zhang\n\n(in-package #:cl-quil)\n\n;;;; This file contains ", "end": 53, "score": 0.9998497366905212, "start": 40, "tag": "NAME", "value": "Charles Zhang" } ]
src/compilers/truth-table.lisp
franzinc/quilc
1
;;;; truth-table.lisp ;;;; ;;;; Author: Charles Zhang (in-package #:cl-quil) ;;;; This file contains the data structure representation for ;;;; manipulating boolean functions. (defun missing-arg () (error "Required argument missing.")) ;;; This representation is not particularly optimized for efficiency. (defstruct (truth-table (:constructor make-truth-table (n-vars &key initial-contents &aux (bits (make-array (ash 1 n-vars) :element-type 'bit :initial-contents initial-contents))))) "This structure represents a boolean function {0...2^n-1} -> {0, 1} using a bit vector." ;; Is this slot actually necessary? (n-vars (missing-arg) :type fixnum) (bits (missing-arg) :type simple-bit-vector)) (defun truth-table-has-var (truth-table var) "Check if truth table depends on VAR." (declare (type truth-table truth-table)) (let ((bits (truth-table-bits truth-table))) (dotimes (i (length bits) nil) (when (/= (aref bits i) (aref bits (logxor i (ash 1 var)))) (return t))))) (defun truth-table-swap! (truth-table var1 var2) (declare (type truth-table truth-table)) (unless (= var1 var2) (let ((bits (truth-table-bits truth-table))) (dotimes (i (length bits) nil) (when (and (logbitp var1 i) (not (logbitp var2 i))) (rotatef (aref bits i) (aref bits (logxor i (+ (ash 1 var1) (ash 1 var2))))))))) truth-table) (defun truth-table-minimize-base! (truth-table) "Return the minimal functional support indices of TRUTH-TABLE and reorder the truth table such that the support are indexed by 0...k where k is the amount of support." (declare (type truth-table truth-table)) (let ((supports '()) (k 0)) (dotimes (i (truth-table-n-vars truth-table)) (when (truth-table-has-var truth-table i) (when (< k i) (truth-table-swap! truth-table k i)) (push i supports) (incf k))) (setf (truth-table-n-vars truth-table) k) (setf (truth-table-bits truth-table) (adjust-array (truth-table-bits truth-table) (ash 1 k))) (values truth-table supports))) (defun truth-table-zero-p (truth-table) "Check if the truth table represents the constant 0 function." (declare (type truth-table truth-table)) (not (find 1 (truth-table-bits truth-table)))) (defun truth-table-one-p (truth-table) "Check if the truth table represents the constant 1 function." (declare (type truth-table truth-table)) (not (find 0 (truth-table-bits truth-table)))) (defun truth-table-cofactor0 (truth-table index) "Find the 0-cofactor of TRUTH-TABLE with respect to INDEX." (declare (type truth-table truth-table)) (make-truth-table (truth-table-n-vars truth-table) :initial-contents (let ((bits (truth-table-bits truth-table))) (loop :for k :from 0 :below (length bits) :collect (aref bits (logandc2 k (ash 1 index))))))) (defun truth-table-cofactor1 (truth-table index) "Find the 1-cofactor of the TRUTH-TABLE with respect to INDEX." (declare (type truth-table truth-table)) (make-truth-table (truth-table-n-vars truth-table) :initial-contents (let ((bits (truth-table-bits truth-table))) (loop :for k :from 0 :below (length bits) :collect (aref bits (logior k (ash 1 index))))))) (defun truth-table-xor (truth-table1 truth-table2) (declare (type truth-table truth-table1 truth-table2)) (let ((n-vars (truth-table-n-vars truth-table1))) (assert (= n-vars (truth-table-n-vars truth-table2))) (make-truth-table n-vars :initial-contents (bit-xor (truth-table-bits truth-table1) (truth-table-bits truth-table2))))) (defun make-cube () "Create a cube, representing the product of boolean variables. 0 means not present, +/-1 represent polarity or sign of the boolean variable in the cube." (make-array 0)) (defun cube-add-literal (cube index polarity) (declare (type (member -1 1) polarity)) (let* ((new-length (max (length cube) (1+ index))) (new-cube (make-array new-length :initial-element 0))) (loop :for i :from 0 :for trit :across cube :do (setf (aref new-cube i) trit)) (setf (aref new-cube index) polarity) new-cube)) ;;; This algorithm applies recursively the positive Davio ;;; decomposition which eventually leads into the PPRM representation ;;; of a function. An ESOP (Exclusive Sum Of Products) is represented ;;; by a list of cubes. (defun truth-table-esop-from-pprm (truth-table) "Given a truth table, return a list of cubes which when disjoined represent the PPRM representation of the boolean function encoded by TRUTH-TABLE." (let ((cubes (make-hash-table :test #'equalp))) (labels ((decompose (table index cube) ;; terminal cases (cond ((truth-table-zero-p table)) ((truth-table-one-p table) (setf (gethash cube cubes) t)) (t (let ((cofactor0 (truth-table-cofactor0 table index)) (cofactor1 (truth-table-cofactor1 table index))) (decompose cofactor0 (1+ index) cube) (decompose (truth-table-xor cofactor0 cofactor1) (1+ index) (cube-add-literal cube index 1))))))) (decompose truth-table 0 (make-cube)) (a:hash-table-keys cubes))))
6583
;;;; truth-table.lisp ;;;; ;;;; Author: <NAME> (in-package #:cl-quil) ;;;; This file contains the data structure representation for ;;;; manipulating boolean functions. (defun missing-arg () (error "Required argument missing.")) ;;; This representation is not particularly optimized for efficiency. (defstruct (truth-table (:constructor make-truth-table (n-vars &key initial-contents &aux (bits (make-array (ash 1 n-vars) :element-type 'bit :initial-contents initial-contents))))) "This structure represents a boolean function {0...2^n-1} -> {0, 1} using a bit vector." ;; Is this slot actually necessary? (n-vars (missing-arg) :type fixnum) (bits (missing-arg) :type simple-bit-vector)) (defun truth-table-has-var (truth-table var) "Check if truth table depends on VAR." (declare (type truth-table truth-table)) (let ((bits (truth-table-bits truth-table))) (dotimes (i (length bits) nil) (when (/= (aref bits i) (aref bits (logxor i (ash 1 var)))) (return t))))) (defun truth-table-swap! (truth-table var1 var2) (declare (type truth-table truth-table)) (unless (= var1 var2) (let ((bits (truth-table-bits truth-table))) (dotimes (i (length bits) nil) (when (and (logbitp var1 i) (not (logbitp var2 i))) (rotatef (aref bits i) (aref bits (logxor i (+ (ash 1 var1) (ash 1 var2))))))))) truth-table) (defun truth-table-minimize-base! (truth-table) "Return the minimal functional support indices of TRUTH-TABLE and reorder the truth table such that the support are indexed by 0...k where k is the amount of support." (declare (type truth-table truth-table)) (let ((supports '()) (k 0)) (dotimes (i (truth-table-n-vars truth-table)) (when (truth-table-has-var truth-table i) (when (< k i) (truth-table-swap! truth-table k i)) (push i supports) (incf k))) (setf (truth-table-n-vars truth-table) k) (setf (truth-table-bits truth-table) (adjust-array (truth-table-bits truth-table) (ash 1 k))) (values truth-table supports))) (defun truth-table-zero-p (truth-table) "Check if the truth table represents the constant 0 function." (declare (type truth-table truth-table)) (not (find 1 (truth-table-bits truth-table)))) (defun truth-table-one-p (truth-table) "Check if the truth table represents the constant 1 function." (declare (type truth-table truth-table)) (not (find 0 (truth-table-bits truth-table)))) (defun truth-table-cofactor0 (truth-table index) "Find the 0-cofactor of TRUTH-TABLE with respect to INDEX." (declare (type truth-table truth-table)) (make-truth-table (truth-table-n-vars truth-table) :initial-contents (let ((bits (truth-table-bits truth-table))) (loop :for k :from 0 :below (length bits) :collect (aref bits (logandc2 k (ash 1 index))))))) (defun truth-table-cofactor1 (truth-table index) "Find the 1-cofactor of the TRUTH-TABLE with respect to INDEX." (declare (type truth-table truth-table)) (make-truth-table (truth-table-n-vars truth-table) :initial-contents (let ((bits (truth-table-bits truth-table))) (loop :for k :from 0 :below (length bits) :collect (aref bits (logior k (ash 1 index))))))) (defun truth-table-xor (truth-table1 truth-table2) (declare (type truth-table truth-table1 truth-table2)) (let ((n-vars (truth-table-n-vars truth-table1))) (assert (= n-vars (truth-table-n-vars truth-table2))) (make-truth-table n-vars :initial-contents (bit-xor (truth-table-bits truth-table1) (truth-table-bits truth-table2))))) (defun make-cube () "Create a cube, representing the product of boolean variables. 0 means not present, +/-1 represent polarity or sign of the boolean variable in the cube." (make-array 0)) (defun cube-add-literal (cube index polarity) (declare (type (member -1 1) polarity)) (let* ((new-length (max (length cube) (1+ index))) (new-cube (make-array new-length :initial-element 0))) (loop :for i :from 0 :for trit :across cube :do (setf (aref new-cube i) trit)) (setf (aref new-cube index) polarity) new-cube)) ;;; This algorithm applies recursively the positive Davio ;;; decomposition which eventually leads into the PPRM representation ;;; of a function. An ESOP (Exclusive Sum Of Products) is represented ;;; by a list of cubes. (defun truth-table-esop-from-pprm (truth-table) "Given a truth table, return a list of cubes which when disjoined represent the PPRM representation of the boolean function encoded by TRUTH-TABLE." (let ((cubes (make-hash-table :test #'equalp))) (labels ((decompose (table index cube) ;; terminal cases (cond ((truth-table-zero-p table)) ((truth-table-one-p table) (setf (gethash cube cubes) t)) (t (let ((cofactor0 (truth-table-cofactor0 table index)) (cofactor1 (truth-table-cofactor1 table index))) (decompose cofactor0 (1+ index) cube) (decompose (truth-table-xor cofactor0 cofactor1) (1+ index) (cube-add-literal cube index 1))))))) (decompose truth-table 0 (make-cube)) (a:hash-table-keys cubes))))
true
;;;; truth-table.lisp ;;;; ;;;; Author: PI:NAME:<NAME>END_PI (in-package #:cl-quil) ;;;; This file contains the data structure representation for ;;;; manipulating boolean functions. (defun missing-arg () (error "Required argument missing.")) ;;; This representation is not particularly optimized for efficiency. (defstruct (truth-table (:constructor make-truth-table (n-vars &key initial-contents &aux (bits (make-array (ash 1 n-vars) :element-type 'bit :initial-contents initial-contents))))) "This structure represents a boolean function {0...2^n-1} -> {0, 1} using a bit vector." ;; Is this slot actually necessary? (n-vars (missing-arg) :type fixnum) (bits (missing-arg) :type simple-bit-vector)) (defun truth-table-has-var (truth-table var) "Check if truth table depends on VAR." (declare (type truth-table truth-table)) (let ((bits (truth-table-bits truth-table))) (dotimes (i (length bits) nil) (when (/= (aref bits i) (aref bits (logxor i (ash 1 var)))) (return t))))) (defun truth-table-swap! (truth-table var1 var2) (declare (type truth-table truth-table)) (unless (= var1 var2) (let ((bits (truth-table-bits truth-table))) (dotimes (i (length bits) nil) (when (and (logbitp var1 i) (not (logbitp var2 i))) (rotatef (aref bits i) (aref bits (logxor i (+ (ash 1 var1) (ash 1 var2))))))))) truth-table) (defun truth-table-minimize-base! (truth-table) "Return the minimal functional support indices of TRUTH-TABLE and reorder the truth table such that the support are indexed by 0...k where k is the amount of support." (declare (type truth-table truth-table)) (let ((supports '()) (k 0)) (dotimes (i (truth-table-n-vars truth-table)) (when (truth-table-has-var truth-table i) (when (< k i) (truth-table-swap! truth-table k i)) (push i supports) (incf k))) (setf (truth-table-n-vars truth-table) k) (setf (truth-table-bits truth-table) (adjust-array (truth-table-bits truth-table) (ash 1 k))) (values truth-table supports))) (defun truth-table-zero-p (truth-table) "Check if the truth table represents the constant 0 function." (declare (type truth-table truth-table)) (not (find 1 (truth-table-bits truth-table)))) (defun truth-table-one-p (truth-table) "Check if the truth table represents the constant 1 function." (declare (type truth-table truth-table)) (not (find 0 (truth-table-bits truth-table)))) (defun truth-table-cofactor0 (truth-table index) "Find the 0-cofactor of TRUTH-TABLE with respect to INDEX." (declare (type truth-table truth-table)) (make-truth-table (truth-table-n-vars truth-table) :initial-contents (let ((bits (truth-table-bits truth-table))) (loop :for k :from 0 :below (length bits) :collect (aref bits (logandc2 k (ash 1 index))))))) (defun truth-table-cofactor1 (truth-table index) "Find the 1-cofactor of the TRUTH-TABLE with respect to INDEX." (declare (type truth-table truth-table)) (make-truth-table (truth-table-n-vars truth-table) :initial-contents (let ((bits (truth-table-bits truth-table))) (loop :for k :from 0 :below (length bits) :collect (aref bits (logior k (ash 1 index))))))) (defun truth-table-xor (truth-table1 truth-table2) (declare (type truth-table truth-table1 truth-table2)) (let ((n-vars (truth-table-n-vars truth-table1))) (assert (= n-vars (truth-table-n-vars truth-table2))) (make-truth-table n-vars :initial-contents (bit-xor (truth-table-bits truth-table1) (truth-table-bits truth-table2))))) (defun make-cube () "Create a cube, representing the product of boolean variables. 0 means not present, +/-1 represent polarity or sign of the boolean variable in the cube." (make-array 0)) (defun cube-add-literal (cube index polarity) (declare (type (member -1 1) polarity)) (let* ((new-length (max (length cube) (1+ index))) (new-cube (make-array new-length :initial-element 0))) (loop :for i :from 0 :for trit :across cube :do (setf (aref new-cube i) trit)) (setf (aref new-cube index) polarity) new-cube)) ;;; This algorithm applies recursively the positive Davio ;;; decomposition which eventually leads into the PPRM representation ;;; of a function. An ESOP (Exclusive Sum Of Products) is represented ;;; by a list of cubes. (defun truth-table-esop-from-pprm (truth-table) "Given a truth table, return a list of cubes which when disjoined represent the PPRM representation of the boolean function encoded by TRUTH-TABLE." (let ((cubes (make-hash-table :test #'equalp))) (labels ((decompose (table index cube) ;; terminal cases (cond ((truth-table-zero-p table)) ((truth-table-one-p table) (setf (gethash cube cubes) t)) (t (let ((cofactor0 (truth-table-cofactor0 table index)) (cofactor1 (truth-table-cofactor1 table index))) (decompose cofactor0 (1+ index) cube) (decompose (truth-table-xor cofactor0 cofactor1) (1+ index) (cube-add-literal cube index 1))))))) (decompose truth-table 0 (make-cube)) (a:hash-table-keys cubes))))
[ { "context": "me*))))\n(defsystem :owl2\n :name \"OWL\"\n :author \"Alan Ruttenberg\"\n :license \"BSD\"\n :components\n ((:module \"basi", "end": 345, "score": 0.9998834729194641, "start": 330, "tag": "NAME", "value": "Alan Ruttenberg" } ]
owl2/owl2.asd
alanruttenberg/lsw2
22
;;;; -*- Mode: LISP -*- ;;;; (in-package :asdf) (setf (logical-pathname-translations "owl2") `(("**;*.*" ,(make-pathname :directory (append (pathname-directory *load-pathname*) '(:wild-inferiors)) :name :wild :type :wild :defaults *load-pathname*)))) (defsystem :owl2 :name "OWL" :author "Alan Ruttenberg" :license "BSD" :components ((:module "basics" :pathname "" :components ((:file "package") (:file "owlapi") (:file "debug")) :serial t) (:module matcher :pathname "" :components ((:file "auxfns") (:file "patmatch"))) (:module translate :pathname "" :serial t :components ((:file "parse-mapping-spec") (:file "generate-mapping") (:file "the-mapping") (:file "swrl-rdf-mapping") (:file "manchester-class-expression") (:file "to-owl-syntax") (:file "sparql") (:file "sparql-owlbgp") (:file "sparql-twerpish") (:file "graph") (:file "axioms") (:file "weaken") ; (:file "materialize-restrictions-for-triplestore") (:file "explanation") (:file "local") (:file "module") (:file "inferred-axioms") (:file "create-external-derived") (:file "terminal-alternate-symbols") (:file "jena") (:file "label-source") (:file "owl-to-lisp-syntax"); (:file "clean-subclass-tree") (:file "violations") (:file "to-owlapi-class-expression") (:file "text-classtree") (:file "dl-query") (:file "hermit-debug") (:file "domain-and-range") (:file "short-form-providers") (:file "diff") (:file "release") ; (:file "html-description") (:file "describe") (:file "logger-control") (:file "owl-to-fol") ) :depends-on (matcher basics) )) :depends-on (util xmls owl2libs-mvn2 logic)) (defun cl-user::test-lsw2-owlapi () (let ((*load-verbose* nil)) (uiop/utility:with-muffled-conditions ((list 'style-warning 'asdf::bad-system-name)) (require :testing))) (let ((cl-user::*read-time-uri* t)) (funcall (intern "RUN" 'prove) #P"owl2:test-lsw2-owl2.lisp"))) ;;;; eof
64109
;;;; -*- Mode: LISP -*- ;;;; (in-package :asdf) (setf (logical-pathname-translations "owl2") `(("**;*.*" ,(make-pathname :directory (append (pathname-directory *load-pathname*) '(:wild-inferiors)) :name :wild :type :wild :defaults *load-pathname*)))) (defsystem :owl2 :name "OWL" :author "<NAME>" :license "BSD" :components ((:module "basics" :pathname "" :components ((:file "package") (:file "owlapi") (:file "debug")) :serial t) (:module matcher :pathname "" :components ((:file "auxfns") (:file "patmatch"))) (:module translate :pathname "" :serial t :components ((:file "parse-mapping-spec") (:file "generate-mapping") (:file "the-mapping") (:file "swrl-rdf-mapping") (:file "manchester-class-expression") (:file "to-owl-syntax") (:file "sparql") (:file "sparql-owlbgp") (:file "sparql-twerpish") (:file "graph") (:file "axioms") (:file "weaken") ; (:file "materialize-restrictions-for-triplestore") (:file "explanation") (:file "local") (:file "module") (:file "inferred-axioms") (:file "create-external-derived") (:file "terminal-alternate-symbols") (:file "jena") (:file "label-source") (:file "owl-to-lisp-syntax"); (:file "clean-subclass-tree") (:file "violations") (:file "to-owlapi-class-expression") (:file "text-classtree") (:file "dl-query") (:file "hermit-debug") (:file "domain-and-range") (:file "short-form-providers") (:file "diff") (:file "release") ; (:file "html-description") (:file "describe") (:file "logger-control") (:file "owl-to-fol") ) :depends-on (matcher basics) )) :depends-on (util xmls owl2libs-mvn2 logic)) (defun cl-user::test-lsw2-owlapi () (let ((*load-verbose* nil)) (uiop/utility:with-muffled-conditions ((list 'style-warning 'asdf::bad-system-name)) (require :testing))) (let ((cl-user::*read-time-uri* t)) (funcall (intern "RUN" 'prove) #P"owl2:test-lsw2-owl2.lisp"))) ;;;; eof
true
;;;; -*- Mode: LISP -*- ;;;; (in-package :asdf) (setf (logical-pathname-translations "owl2") `(("**;*.*" ,(make-pathname :directory (append (pathname-directory *load-pathname*) '(:wild-inferiors)) :name :wild :type :wild :defaults *load-pathname*)))) (defsystem :owl2 :name "OWL" :author "PI:NAME:<NAME>END_PI" :license "BSD" :components ((:module "basics" :pathname "" :components ((:file "package") (:file "owlapi") (:file "debug")) :serial t) (:module matcher :pathname "" :components ((:file "auxfns") (:file "patmatch"))) (:module translate :pathname "" :serial t :components ((:file "parse-mapping-spec") (:file "generate-mapping") (:file "the-mapping") (:file "swrl-rdf-mapping") (:file "manchester-class-expression") (:file "to-owl-syntax") (:file "sparql") (:file "sparql-owlbgp") (:file "sparql-twerpish") (:file "graph") (:file "axioms") (:file "weaken") ; (:file "materialize-restrictions-for-triplestore") (:file "explanation") (:file "local") (:file "module") (:file "inferred-axioms") (:file "create-external-derived") (:file "terminal-alternate-symbols") (:file "jena") (:file "label-source") (:file "owl-to-lisp-syntax"); (:file "clean-subclass-tree") (:file "violations") (:file "to-owlapi-class-expression") (:file "text-classtree") (:file "dl-query") (:file "hermit-debug") (:file "domain-and-range") (:file "short-form-providers") (:file "diff") (:file "release") ; (:file "html-description") (:file "describe") (:file "logger-control") (:file "owl-to-fol") ) :depends-on (matcher basics) )) :depends-on (util xmls owl2libs-mvn2 logic)) (defun cl-user::test-lsw2-owlapi () (let ((*load-verbose* nil)) (uiop/utility:with-muffled-conditions ((list 'style-warning 'asdf::bad-system-name)) (require :testing))) (let ((cl-user::*read-time-uri* t)) (funcall (intern "RUN" 'prove) #P"owl2:test-lsw2-owl2.lisp"))) ;;;; eof
[ { "context": "-----------\n#|\nThe MIT License\n\nCopyright (c) 2018 Emotiq AG\n\nPermission is hereby granted, free of charge, to", "end": 227, "score": 0.924776017665863, "start": 218, "tag": "NAME", "value": "Emotiq AG" }, { "context": "k\n\n(defvar *local-nodes* '((\"Malachite.local\" . \"10.0.1.6\")\n (\"Dachshund.local\" . \"", "end": 1464, "score": 0.9996811151504517, "start": 1456, "tag": "IP_ADDRESS", "value": "10.0.1.6" }, { "context": "\")\n (\"Dachshund.local\" . \"10.0.1.3\")\n (\"Rambo\" . \"", "end": 1522, "score": 0.999687135219574, "start": 1514, "tag": "IP_ADDRESS", "value": "10.0.1.3" }, { "context": "\")\n (\"Rambo\" . \"10.0.1.13\")\n (\"ChromeKote.local\" . ", "end": 1581, "score": 0.9996562600135803, "start": 1572, "tag": "IP_ADDRESS", "value": "10.0.1.13" }, { "context": ")\n (\"ChromeKote.local\" . \"10.0.1.36\")))\n\n(defun get-local-ipv4 (node-name)\n (cdr (as", "end": 1641, "score": 0.999648928642273, "start": 1632, "tag": "IP_ADDRESS", "value": "10.0.1.36" }, { "context": "9064889348739))\n\nCOSI-SIMGEN 23 > (send (gethash \"10.0.1.6\" *ip-node-tbl*) :public-key (make-node-ref *my-no", "end": 26648, "score": 0.9992935657501221, "start": 26640, "tag": "IP_ADDRESS", "value": "10.0.1.6" }, { "context": "make-node-ref *my-node*))\n\nConnecting to #$(NODE \"10.0.1.6\" 65000)\n(FORWARDING \"10.0.1.6\" (QUOTE ((:PUBLIC-K", "end": 26736, "score": 0.9992868900299072, "start": 26728, "tag": "IP_ADDRESS", "value": "10.0.1.6" }, { "context": "necting to #$(NODE \"10.0.1.6\" 65000)\n(FORWARDING \"10.0.1.6\" (QUOTE ((:PUBLIC-KEY #<NODE-REF 40200014C3>) 601", "end": 26766, "score": 0.9993082880973816, "start": 26758, "tag": "IP_ADDRESS", "value": "10.0.1.6" }, { "context": "8558528841292842)))\n==> output window\n(:PKEY+ZKP (85567609167286331213658310505812381800188423169595965874", "end": 27045, "score": 0.7732579112052917, "start": 27039, "tag": "KEY", "value": "855676" }, { "context": "841292842)))\n==> output window\n(:PKEY+ZKP (855676091672863312136583105058123818001884231695959658747310415728", "end": 27055, "score": 0.7260234951972961, "start": 27046, "tag": "KEY", "value": "916728633" }, { "context": "=> output window\n(:PKEY+ZKP (855676091672863312136583105058123818001884231695959658747310415728976873", "end": 27061, "score": 0.6117695569992065, "start": 27060, "tag": "KEY", "value": "5" }, { "context": " output window\n(:PKEY+ZKP (855676091672863312136583105058123818001884231695959658747310415728976873583", "end": 27064, "score": 0.6588996648788452, "start": 27062, "tag": "KEY", "value": "31" }, { "context": "tput window\n(:PKEY+ZKP (855676091672863312136583105058123818001884231695959658747310415728976873583 1", "end": 27066, "score": 0.5896544456481934, "start": 27065, "tag": "KEY", "value": "5" }, { "context": "indow\n(:PKEY+ZKP (855676091672863312136583105058123818001884231695959658747310415728976873583 1989410", "end": 27072, "score": 0.6822463274002075, "start": 27071, "tag": "KEY", "value": "3" }, { "context": "list *leader-node*))\n\n(setf *real-nodes* (remove \"10.0.1.13\" *real-nodes*\n :test 's", "end": 53390, "score": 0.9996174573898315, "start": 53381, "tag": "IP_ADDRESS", "value": "10.0.1.13" }, { "context": "--------------------------\n\n(defvar *dachshund* \"10.0.1.3\")\n(defvar *malachite* \"10.0.1.6\")\n(defvar *rambo", "end": 54814, "score": 0.9996331930160522, "start": 54806, "tag": "IP_ADDRESS", "value": "10.0.1.3" }, { "context": "ar *dachshund* \"10.0.1.3\")\n(defvar *malachite* \"10.0.1.6\")\n(defvar *rambo* \"10.0.1.13\")\n\n(defmethod d", "end": 54847, "score": 0.9996340870857239, "start": 54839, "tag": "IP_ADDRESS", "value": "10.0.1.6" }, { "context": "ar *malachite* \"10.0.1.6\")\n(defvar *rambo* \"10.0.1.13\")\n\n(defmethod damage ((ip string) t/f)\n (damage ", "end": 54881, "score": 0.9996516108512878, "start": 54872, "tag": "IP_ADDRESS", "value": "10.0.1.13" } ]
src/Cosi-Schnorr/random-partition.lisp
easye/emotiq
109
;; random-partition.lisp -- Generate simulation trees of network nodes for Cosi ;; ;; DM/Emotiq 02/18 ;; ------------------------------------------------------------------------- #| The MIT License Copyright (c) 2018 Emotiq AG Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. |# (in-package :cosi-simgen) (declaim (optimize (debug 3))) ;; -------------------------------------------------------------------- ;; Physical network (defvar *local-nodes* '(("Malachite.local" . "10.0.1.6") ("Dachshund.local" . "10.0.1.3") ("Rambo" . "10.0.1.13") ("ChromeKote.local" . "10.0.1.36"))) (defun get-local-ipv4 (node-name) (cdr (assoc node-name *local-nodes* :test 'string-equal))) (defun get-my-ipv4 () (get-local-ipv4 (machine-instance))) (defvar *real-nodes* (mapcar 'cdr *local-nodes*)) (defvar *leader-node* (get-local-ipv4 "Dachshund.local")) ;;(defvar *leader-node* (get-local-ipv4 "ChromeKote.local")) (defvar *top-node* nil) ;; current leader node (defvar *my-node* nil) ;; which node my machine is on ;; default-timeout-period needs to be made smarter, based on node height in tree (defparameter *default-timeout-period* ;; good for 1600 nodes on single machine #+:LISPWORKS 10 #+:ALLEGRO 70 #+:CLOZURE 70) ;; ---------------------------------------------------------------------- ;; Network Tree Nodes (defvar *bins-per-node* 9) ;; prolly needs to be >3 for BFT (defun make-subs () (make-array *bins-per-node* :initial-element nil)) (defclass node () ((ip :accessor node-ip ;; IPv4 string for this node :initarg :ip) (uuid :accessor node-uuid ;; UUID for this node :initarg :uuid) (pkeyzkp :accessor node-pkeyzkp ;; public key + ZKP :initarg :pkeyzkp) (skey :accessor node-skey ;; private key :initarg :skey) (pkey :accessor node-pkey ;; cached ECC point for public key :initarg :pkey) (realnode :accessor node-realnode ;; t/f - t when this is a real IPv4 node, nil for fake :initform nil) (parent :accessor node-parent ;; points to node of group parent :initarg :parent :initform nil) (subs :accessor node-subs ;; list of group members beyond self :initarg :subs :initform (make-subs)) (bit :accessor node-bit ;; bit position in bitmap :initform 0) ;; ------------------------------------- (real-ip :accessor node-real-ip ;; real node for this node :initarg :real-ip) (ok :accessor node-ok ;; t if we participated in round 1 :initform nil) (v :accessor node-v ;; first round random seed :initform nil) (seq :accessor node-seq ;; first round ID :initform nil) (byz :accessor node-byz ;; Byzantine misbehav type :initform nil) (parts :accessor node-parts ;; group participants in first round commitment :initform nil) (bad :accessor node-bad ;; if true then node was corrupted :initform nil) (load :accessor node-load ;; cpu loading of group for this node :initform 1) (self :accessor node-self ;; ptr to Actor handler :initarg :self) )) (defmethod node-bitmap ((node node)) (ash 1 (node-bit node))) (defmethod iteri-subs ((node node) fn) (loop for sub across (node-subs node) for ix from 0 when sub do (funcall fn ix sub))) (defmethod iter-subs ((node node) fn) (iteri-subs node (lambda (ix sub) (declare (ignore ix)) (funcall fn sub)))) (defmethod set-node-load (node) (setf (node-load node) (1+ (loop for sub across (node-subs node) when sub sum (node-load sub))))) ;; -------------------------------------------------------------------- ;; For now, 4 different ways to specify a node: ;; 1. node structure pointer ;; 2. IPv4 address (in dotted string notation) ;; 3. UUID (needs uuid-to-integer for keying *uuid-node* table) ;; 4. PKEY (compressed public key ECC point) ;; XREF from IPv4 address to Tree Node (defvar *ip-node-tbl* (make-hash-table :test 'equal)) ;; IPv4 string as key (defvar *uuid-node-tbl* (make-hash-table)) ;; UUID integer as key (defvar *pkey-node-tbl* (make-hash-table)) ;; compressed ECC pt integer as key (defvar *pkey-skey-tbl* (make-hash-table)) ;; commpressed ECC pt integer as key ;; ------------------------------------------------------------------- (defvar *comm-ip* nil) (defun make-node (ipstr uuid pkeyzkp parent) (let* ((cmpr-pkey (third pkeyzkp)) (node (make-instance 'node :ip ipstr :uuid uuid :skey (gethash cmpr-pkey *pkey-skey-tbl*) :pkey (edec:ed-decompress-pt cmpr-pkey) :pkeyzkp pkeyzkp :parent parent :real-ip *comm-ip* ))) (setf (node-self node) (make-node-dispatcher node) (gethash ipstr *ip-node-tbl*) node (gethash (node-uuid node) *uuid-node-tbl*) node (gethash cmpr-pkey *pkey-node-tbl*) node))) (defun need-to-specify (&rest args) (declare (ignore args)) (error "Need to specify...")) #+:ALLEGRO (defun allegro-dotted-to-integer (string) (multiple-value-bind (start end starts ends) (#~m/^([0-9]+).([0-9]+).([0-9]+).([0-9]+)$/ string) (declare (ignore start end)) (reduce (lambda (ans pair) (destructuring-bind (start . end) pair (logior (ash ans 8) (parse-integer string :start start :end end)))) (nreverse (pairlis (coerce starts 'list) (coerce ends 'list))) :initial-value 0))) #+:ALLEGRO (defun allegro-integer-to-dotted (val) (let ((parts (um:nlet-tail iter ((n 4) (pos 0) (ans nil)) (if (zerop n) ans (iter (1- n) (+ pos 8) (cons (ldb (byte 8 pos) val) ans))) ))) (format nil "~{~d~^.~}" parts))) (defun dotted-string-to-integer (string) #+:LISPWORKS (comm:string-ip-address string) #+:OPENMCL (ccl::dotted-to-ipaddr string) #+:ALLEGRO (allegro-dotted-to-integer string)) (defun integer-to-dotted-string (val) #+:LISPWORKS (comm:ip-address-string val) #+:OPENMCL (CCL::ipaddr-to-dotted val) #+:ALLEGRO (allegro-integer-to-dotted val)) (defun gen-uuid-int () (uuid:uuid-to-integer (uuid:make-v1-uuid))) (defun gen-node-id (ip) (if (consp ip) (values-list ip) (multiple-value-bind (skey pkey) (edec:ed-random-pair) (let ((zkp (compute-pkey-zkp skey pkey))) (setf (gethash (third zkp) *pkey-skey-tbl*) skey) (values ip (gen-uuid-int) zkp) )))) ;; ------------------------------------------------------------- (defvar *node-bit-tbl* #()) (defun assign-bits () ;; assign bit positions to each node (let ((collected (um:accum acc (maphash (lambda (k node) (declare (ignore k)) (acc node)) *ip-node-tbl*)))) (setf collected (sort collected '< :key 'node-uuid)) (loop for node in collected for ix from 0 do (setf (node-bit node) ix)) (setf *node-bit-tbl* (coerce collected 'vector)) )) ;; ------------------------------------------------------------------- ;; Node construction (defun partition (node ip-list &key (key 'identity)) (let* ((bins (make-subs)) (nbins (length bins)) (vnode (dotted-string-to-integer (node-ip node)))) (mapc (lambda (ip-arg) (let* ((vip (dotted-string-to-integer (funcall key ip-arg))) (ix (mod (logxor vnode vip) nbins))) (push ip-arg (aref bins ix)))) ip-list) (setf (node-subs node) bins))) (defun inner-make-node-tree (ip ip-list &optional parent) (multiple-value-bind (ipstr uuid pkeyzkp) (gen-node-id ip) (let ((node (make-node ipstr uuid pkeyzkp parent))) (when ip-list (let ((bins (partition node ip-list :key (lambda (ip-arg) (if (consp ip-arg) (car ip-arg) ip-arg))))) (iteri-subs node (lambda (ix subs) (setf (aref bins ix) (inner-make-node-tree (car subs) (cdr subs) node)))) (set-node-load node))) node))) (defun make-node-tree (ip vlist) ;; main entry point - captures IPv4 of arg ip for use as real-ip in ;; succeeding nodes (multiple-value-bind (ipstr uuid pkeyzp) (gen-node-id ip) (let ((*comm-ip* ipstr)) (inner-make-node-tree (list ipstr uuid pkeyzp) vlist)))) ;; -------------------------------------------------------------------- ;; for visual debugging... #+:LISPWORKS (progn (defmethod children (x layout) nil) (defmethod children ((node node) layout) (remove nil (coerce (node-subs node) 'list))) (defun split-to-octets (val) (um:nlet-tail iter ((n 4) (val val) (lst nil)) (if (zerop n) lst (iter (1- n) (ash val -8) (cons (ldb (byte 8 0) val) lst))) )) (defclass red-text (capi:item-pinboard-object) ()) (defclass black-text (capi:item-pinboard-object) ()) (defmethod capi:draw-pinboard-object :around (pinboard (self red-text) &key &allow-other-keys) (gp:with-graphics-state (pinboard :foreground :red) (call-next-method))) (defmethod make-node-pane (graphics-port (node node)) (declare (ignore graphics-port)) (let ((txt (node-ip node))) (make-instance (if (node-realnode node) 'red-text 'black-text) :text txt))) (defmethod view-tree ((tree node) &key (layout :left-right)) (capi:contain (make-instance 'capi:graph-pane :layout-function layout :roots (list tree) :node-pane-function 'make-node-pane :children-function (lambda (node) (children node layout)) )))) ;; -------------------------------------------------------------------- ;; Initial Tree Generation and Persistence (defvar *default-data-file* "cosi-nodes.txt") (defvar *default-key-file* "cosi-keying.txt") (defun generate-ip () ;; generate a unique random IPv4 address (let ((ip (integer-to-dotted-string (random #.(expt 2 32))))) (if (gethash ip *ip-node-tbl*) (generate-ip) ;; should be unlikely, would be 50% at around 2^16 nodes (setf (gethash ip *ip-node-tbl*) ip)))) (defmethod pair-ip-uuid ((node node)) (list (node-ip node) (node-uuid node) (node-pkeyzkp node))) (defmethod pair-ip-uuid ((ip string)) (pair-ip-uuid (gethash ip *ip-node-tbl*))) (defun gen-main-tree (leader real-nodes grps) (let* ((trees (mapcar 'make-node-tree real-nodes grps)) (main-tree (find leader trees :test 'string= :key 'node-ip))) ;; mark the real nodes as special (mapc (lambda (tree) (setf (node-realnode tree) t)) trees) ;; attach the non-leader real nodes to the leader node (let ((all-but (remove main-tree trees))) (setf (node-subs main-tree) (concatenate 'vector (node-subs main-tree) (apply 'vector all-but))) (dolist (tree all-but) (setf (node-parent tree) main-tree))) main-tree)) ;; -------------------------------------------------------------- ;; Generate Tree / Keying and save to startup init files (defun generate-tree (&key fname (nel 1000)) (let* ((leader *leader-node*) (real-nodes (remove-duplicates *real-nodes* :test 'string=))) ;; ensure leader is in the real-nodes collection (assert (member leader real-nodes :test 'string=)) ;; pre-populate hash table with real-nodes (clrhash *ip-node-tbl*) (clrhash *uuid-node-tbl*) (clrhash *pkey-node-tbl*) (clrhash *pkey-skey-tbl*) (dolist (ip real-nodes) (setf (gethash ip *ip-node-tbl*) ip)) ;; build the trees (let* ((nreal (length real-nodes)) (nel/grp (ceiling nel nreal)) (grps (loop repeat nreal collect (loop repeat nel/grp collect (generate-ip)))) (main-tree (gen-main-tree leader real-nodes grps))) ;; save nodes as a text file for later (with-open-file (f (merge-pathnames #+:LISPWORKS (sys:get-folder-path :documents) #+(OR :ALLEGRO :OPENMCL) "~/Documents/" (or fname *default-data-file*)) :direction :output :if-does-not-exist :create :if-exists :rename) (with-standard-io-syntax (let ((*print-readably* t) ;; to get readable UUID's (*print-right-margin* 128)) (pprint `(:leader ,leader :real-nodes ,(mapcar 'pair-ip-uuid real-nodes) :groups ,(mapcar (lambda (grp) (mapcar 'pair-ip-uuid grp)) grps)) f)))) ;; write the pkey/skey associations (with-open-file (f (merge-pathnames #+:LISPWORKS (sys:get-folder-path :documents) #+(OR :ALLEGRO :OPENMCL) "~/Documents/" *default-key-file*) :direction :output :if-does-not-exist :create :if-exists :rename) (let ((keys nil)) (maphash (lambda (k v) (push (cons k v) keys)) *pkey-skey-tbl*) (with-standard-io-syntax (pprint keys f)))) (assign-bits) #+:LISPWORKS (view-tree main-tree) (setf *my-node* main-tree *top-node* main-tree) ))) ;; --------------------------------------------------------------- ;; Tree reconstruction from startup init files (defun read-data-file (path) (with-open-file (f path :direction :input) (read f))) (defun reconstruct-tree (&key fname) ;; read the keying file (let* ((key-path (merge-pathnames #+:LISPWORKS (sys:get-folder-path :documents) #+(OR :ALLEGRO :OPENMCL) "~/Documents/" *default-key-file*)) (keys (read-data-file key-path)) (data-path (merge-pathnames #+:LISPWORKS (sys:get-folder-path :documents) #+(OR :ALLEGRO :OPENMCL) "~/Documents/" (or fname *default-data-file*))) (data (read-data-file data-path)) (leader (getf data :leader)) (real-nodes (getf data :real-nodes)) (grps (getf data :groups))) ;; sanity checking (assert (member leader real-nodes :test 'string= :key 'car)) (labels ((no-dups (lst) (dolist (ip lst) (destructuring-bind (ipstr uuid zkp) ip (assert (null (gethash ipstr *ip-node-tbl*))) (assert (null (gethash uuid *uuid-node-tbl*))) (destructuring-bind (r c pcmpr) zkp (declare (ignore r c)) (assert (null (gethash pcmpr *pkey-node-tbl*))) (check-pkey zkp) (setf (gethash ipstr *ip-node-tbl*) ip (gethash uuid *uuid-node-tbl*) ip (gethash pcmpr *pkey-node-tbl*) ip) ))))) (clrhash *ip-node-tbl*) (clrhash *uuid-node-tbl*) (clrhash *pkey-node-tbl*) (no-dups real-nodes) (mapc #'no-dups grps)) ;; reconstruct keying info (clrhash *pkey-skey-tbl*) (mapc (lambda (pair) (destructuring-bind (k . v) pair ;; k is integer, compressed pkey ECC pt ;; v is skey integer ;; decompression checks for valid ECC pt (assert (ed-pt= (ed-nth-pt v) (ed-decompress-pt k))) (setf (gethash k *pkey-skey-tbl*) v))) keys) ;; reconstruct the trees (let ((main-tree (gen-main-tree leader real-nodes grps))) (assign-bits) #+:LISPWORKS (view-tree main-tree) (setf *top-node* main-tree *my-node* (gethash (get-my-ipv4) *ip-node-tbl*))))) ;; --------------------------------------------------------------- ;; New leader node election... tree rearrangement (defun notify-real-descendents (node &rest msg) (labels ((recurse (sub-node) (if (node-realnode sub-node) (apply 'send sub-node msg) (iter-subs sub-node #'recurse)))) (iter-subs node #'recurse))) (defun all-nodes-except (node) (delete node (um:accum acc (maphash (um:compose #'acc 'um:snd) *ip-node-tbl*)))) (defun node-model-rebuild-tree (parent node nlist) (let ((bins (partition node nlist :key 'node-ip))) (iteri-subs node (lambda (ix subs) (setf (aref bins ix) (node-model-rebuild-tree node (car subs) (cdr subs))))) (setf (node-parent node) parent) (set-node-load node) node)) (defun node-elect-new-leader (new-leader-ip) (let ((new-top-node (gethash new-leader-ip *ip-node-tbl*))) ;; Maybe... ready for prime time? (cond ((null new-top-node) (error "Not a valid leader node: ~A" new-leader-ip)) ((eq new-top-node *top-node*) ;; nothing to do here... ) (t (setf *top-node* new-top-node) (node-model-rebuild-tree nil new-top-node (all-nodes-except new-top-node)) ;; ;; The following broadcast will cause us to get another ;; notification, but by then the *top-node* will already ;; have been set to new-leader-ip, and so no endless loop ;; will occur. ;; (notify-real-descendents new-top-node :election new-leader-ip)) ))) ;; --------------------------------------------------------- ;; Node insertion/change (defun bin-for-ip (node ip) (let ((vnode (dotted-string-to-integer (node-ip node))) (vip (dotted-string-to-integer ip))) (mod (logxor vnode vip) (length (node-subs node))))) (defun increase-loading (parent-node) (when parent-node (incf (node-load parent-node)) (increase-loading (node-parent parent-node)))) (defun node-model-insert-node (node new-node-info) ;; info is (ipv4 UUID pkeyzkp) (destructuring-bind (ipstr uuid pkeyzkp) new-node-info (let* ((ix (bin-for-ip node ipstr)) (bins (node-subs node)) (sub-node (aref bins ix))) (if sub-node ;; continue in parallel with our copy of tree (node-model-insert-node sub-node new-node-info) ;; else (let ((new-node (make-node ipstr uuid pkeyzkp node))) (setf (node-real-ip new-node) ipstr (node-realnode new-node) t (node-skey new-node) nil (aref bins ix) new-node) (incf (node-load node)) (increase-loading (node-parent node))) )))) (defun node-insert-node (node new-node-info) (destructuring-bind (ipstr uuid pkeyzkp) new-node-info (let ((new-node (gethash ipstr *ip-node-tbl*))) (if new-node ;; already present in tree? ;; maybe caller just wants to change UUID or keying ;; won't be able to sign unless it know skey (multiple-value-bind (pkey ok) (check-pkey pkeyzkp) (when ok (setf (node-uuid new-node) uuid (node-pkeyzkp new-node) pkeyzkp (node-pkey new-node) pkey ;; cache the decompressed key (node-realnode new-node) t (node-real-ip new-node) ipstr))) ;; else - not already present (node-model-insert-node *top-node* new-node-info)))) (notify-real-descendents node :insert-node new-node-info)) ;; --------------------------------------------------------- (defun node-model-remove-node (gone-node) (remhash (node-ip gone-node) *ip-node-tbl*) (remhash (node-uuid gone-node) *uuid-node-tbl*) (let ((pcmpr (third (node-pkeyzkp gone-node)))) (remhash pcmpr *pkey-node-tbl*) (remhash pcmpr *pkey-skey-tbl*))) (defun node-remove-node (node gone-node-ipv4) (let ((gone-node (gethash gone-node-ipv4 *ip-node-tbl*))) (when gone-node (node-model-remove-node gone-node) ;; must rebuild tree to absorb node's subnodes (node-model-rebuild-tree nil *top-node* (all-nodes-except *top-node*)) (when (eq node *top-node*) (notify-real-descendents node :remove-node gone-node-ipv4))))) ;; ----------------------------------------------------------------- (defun NYI (&rest args) (error "Not yet implemented: ~A" args)) ;; ------------------------------------------------------- (defun make-node-dispatcher (node) ;; use indirection to node-dispatcher for while we are debugging and ;; extending the dispatcher. Saves reconstructing the tree every ;; time the dispatching chanages. (ac:make-actor ;; one of these closures is stored in the SELF slot of every node (lambda (&rest msg) (apply 'node-dispatcher node msg)))) (defun crash-recovery () (maphash (lambda (k node) (declare (ignore k)) (setf (node-self node) (make-node-dispatcher node))) *ip-node-tbl*)) (defun node-dispatcher (node &rest msg) (um:dcase msg ;; ---------------------------- ;; user accessible entry points - directed to leader node (:cosi (reply-to msg) (node-compute-cosi node reply-to msg)) (:validate (reply-to msg sig) (reply reply-to :validation (node-validate-cosi node msg sig))) (:public-key (reply-to) (reply reply-to :pkey+zkp (node-pkeyzkp node))) (:add/change-node (new-node-info) (node-insert-node node new-node-info)) (:remove-node (node-ip) (node-remove-node node node-ip)) (:election (new-leader-ip) (node-elect-new-leader new-leader-ip)) ;; ------------------------------- ;; internal comms between Cosi nodes (:commitment (reply-to msg seq) (node-cosi-commitment node reply-to msg seq)) (:signing (reply-to c c1 seq) (node-cosi-signing node reply-to c c1 seq)) ;; ----------------------------------- ;; for sim and debug (:answer (&rest msg) ;; for round-trip testing (ac:pr msg)) (:reset () (node-reset-nodes node)) (t (&rest msg) (error "Unknown message: ~A~%Node: ~A" msg (node-ip node))) )) ;; ------------------------------------------------------------------ ;; GET-PUBLIC-KEY - This is here primarily for testing the network. ;; Not really an RPC call, and results will show in the output ;; browser, not returned to caller. ;; ;; RPC violates the basic premise of the point-and-shoot design. ;; Responders are free to ignore, be deaf, or send us garbage at any ;; time. ;; ;; The design of the system is aimed at coexistence in a Byzantine network. ;; (defun get-public-key (uuid) (let ((node (gethash uuid *uuid-node-tbl*))) (when node (spawn (lambda () (let ((ret (make-return-addr (node-real-ip *my-node*)))) (send node :public-key ret) (recv (msg (unregister-return-addr ret) (pr msg)) ))) )))) #| (send *top-node* :public-key (make-node-ref *my-node*)) ==> see results in output window (:PKEY+ZKP (849707610687761353988031598913888011454228809522136330182685594047565816483 77424688591828692687552806917061506619936267795838123291694715575735109065947 2463653704506470449709613051914446331689964762794940591210756129064889348739)) COSI-SIMGEN 23 > (send (gethash "10.0.1.6" *ip-node-tbl*) :public-key (make-node-ref *my-node*)) Connecting to #$(NODE "10.0.1.6" 65000) (FORWARDING "10.0.1.6" (QUOTE ((:PUBLIC-KEY #<NODE-REF 40200014C3>) 601290835549702797100992963662352678603116278028765925372703953633797770499 56627041402452754830116071111198944351637771601751353481660603190062587211624 23801716726735741425848558528841292842))) ==> output window (:PKEY+ZKP (855676091672863312136583105058123818001884231695959658747310415728976873583 19894104797779289660345137228823739121774277312822467740314566093297448396984 2080524722754689845098528285145820902670538507089109456806581872878115260191)) |# ;; ---------------------------- (defvar *cosi-port* 65001) (defclass return-addr () ((ip :accessor return-addr-ip ;; the real IPv4 for returns :initarg :ip) (port :accessor return-addr-port ;; the real IPv4 port for returns :initarg :port) (aid :accessor return-addr-aid ;; actor id for returns :initarg :aid))) (defvar *aid-tbl* ;; assoc between Actors and AID's #+:LISPWORKS (make-hash-table :weak-kind :value) #+:ALLEGRO (make-hash-table :values :weak) #+:CLOZURE (make-hash-table :weak :value) ) (defmethod unregister-return-addr ((ret return-addr)) (remhash (return-addr-aid ret) *aid-tbl*) (become 'do-nothing)) (defmethod make-return-addr ((ipv4 string) &optional (port *cosi-port*)) ;; can only be called from within an Actor body (let ((aid (gen-uuid-int)) (self (current-actor))) (unless self (error "MAKE-RETURN-ADDR can only be performed by an Actor")) (setf (gethash aid *aid-tbl*) self) (make-instance 'return-addr :ip ipv4 :port port :aid aid))) ;; ----------------------------------------------------------- (defmethod send ((node node) &rest msg) (unless (node-byz node) (socket-send (node-ip node) (node-real-ip node) *cosi-port* msg))) (defmethod send ((ref return-addr) &rest msg) (socket-send ref (return-addr-ip ref) (return-addr-port ref) msg)) (defmethod send ((node null) &rest msg) (ac:pr :sent-to-null msg) msg) (defmethod send (dest &rest msg) (apply 'ac:send dest msg)) ;; ----------------- (defun reply (reply-to &rest msg) (apply 'send reply-to :answer msg)) ;; ----------------------------------------------------- ;; THE SOCKET INTERFACE... ;; ----------------------------------------------------- (defvar *max-buffer-length* 65500) (defun cosi-service-handler (buf) (multiple-value-bind (ans err) (ignore-errors (loenc:decode buf)) (unless err (multiple-value-bind (packet t/f) (verify-hmac ans) (when t/f (destructuring-bind (dest msg-verb &rest msg-args) packet (cond ((eql :SHUTDOWN-SERVER msg-verb) :SHUTDOWN-SERVER) (t (let ((true-dest (dest-ip dest))) ;; for debug... ------------------- (when (eq true-dest (node-self *my-node*)) (pr (format nil "forwarding-to-me: ~A" (cons msg-verb msg-args)))) ;; ------------------ (apply 'send true-dest msg-verb msg-args) t)) ))) )))) (defun shutdown-server (&optional (port *cosi-port*)) (when *my-node* (let ((me (node-ip *my-node*))) (socket-send me me port '(:SHUTDOWN-SERVER))))) (defun socket-send (ip real-ip real-port msg) (let* ((quad (make-hmac (list* ip msg) (node-skey *my-node*) (node-uuid *my-node*))) (packet (loenc:encode quad)) (nb (length packet))) (internal-send-socket real-ip real-port packet nb))) ;; ------------------------------------------------------------------ (defmethod dest-ip ((ip string)) (let ((node (gethash ip *ip-node-tbl*))) (when node (node-self node)))) (defmethod dest-ip ((ret return-addr)) (gethash (return-addr-aid ret) *aid-tbl*)) ;; ------------------------------------------------------------------ ;; deprecated... #+:xLISPWORKS (progn ;; TCP/IP stream over Butterfly (defun socket-send (ip real-ip msg) ;; replace this with USOCKETS protocol (let* ((quad (make-hmac msg (node-skey *my-node*) (node-uuid *my-node*))) (agent-ip (format nil "eval@~A" real-ip))) ;; (format t "~%SOCKET-SEND: ~A ~A ~A" ip real-ip msg) #+:LISPWORKS (bfly:! agent-ip `(forwarding ,ip ',quad)))) (defun forwarding (dest quad) ;; (format t "~%FORWARDING: ~A ~A" dest quad) (multiple-value-bind (msg t/f) (verify-hmac quad) ;; might want to log incomings that fail the HMAC ;; just dropping on floor here... (when t/f (let ((true-dest (dest-ip dest))) (when true-dest (when (equal true-dest (node-self *my-node*)) (ac:pr (format nil "forwarding-to-me: ~A" msg))) (apply 'send true-dest msg)))) ))) ;; ------------------------------------------------------------------ #-:LISPWORKS (progn ;; USOCKET interface for ACL (defun #1=serve-cosi-port (socket) (let ((maxbuf (make-array *max-buffer-length* :element-type '(unsigned-byte 8)))) ;; (pr :server-starting-up) (unwind-protect (loop (multiple-value-bind (buf buf-len rem-ip rem-port) (usocket:socket-receive socket maxbuf (length maxbuf)) (declare (ignore rem-ip rem-port)) ;; (pr :sock-read buf-len rem-ip rem-port (loenc:decode buf)) (when (eql :SHUTDOWN-SERVER (cosi-service-handler buf)) (return-from #1#)))) ;; unwinding (usocket:socket-close socket) ;; (pr :server-stopped) ))) (defun start-ephemeral-server (&optional (port 0)) (let* ((my-ip (node-real-ip *my-node*)) (socket (usocket:socket-connect nil nil :protocol :datagram :local-host my-ip :local-port port ))) (mpcompat:process-run-function "UDP Cosi Server" nil 'serve-cosi-port socket) (usocket:get-local-port socket))) (defun start-server () (start-ephemeral-server *cosi-port*)) (defun internal-send-socket (ip port packet nb) (let ((socket (usocket:socket-connect ip port :protocol :datagram))) ;(pr :sock-send (length packet) real-ip packet) (unless (eql nb (usocket:socket-send socket packet nb)) (pr :socket-send-error ip packet)) (usocket:socket-close socket) ))) ;; ------------------------------------------------------------------ #+:LISPWORKS (progn ;; LW UDP Async interface (defvar *udp-wait-collection* nil) (defun ensure-udp-wait-state-collection () (or *udp-wait-collection* (let ((new (comm:create-and-run-wait-state-collection "UDP Cosi Service"))) (if (sys:compare-and-swap *udp-wait-collection* nil new) new (progn ; Another process just set it. (comm:wait-state-collection-stop-loop new) *udp-wait-collection*))))) ;; ------------------------- ;; Server side (defun #1=udp-cosi-server-process-request (async-io-state string bytes-num ip-address port-num) (declare (ignore bytes-num ip-address port-num)) (let ((status (comm:async-io-state-read-status async-io-state))) (when status ;; something went wrong (pr (format nil "UDP example server: got error ~s, restarting" status)) (comm:close-async-io-state async-io-state) (start-server) (return-from #1#)) (if (eql :SHUTDOWN-SERVER (cosi-service-handler string)) (comm:close-async-io-state async-io-state) (udp-cosi-server-receive-next async-io-state)))) (defun udp-cosi-server-receive-next (async-io-state ) (comm:async-io-state-receive-message async-io-state (make-array *max-buffer-length* :element-type '(unsigned-byte 8)) 'udp-cosi-server-process-request :needs-address t)) (defun start-ephemeral-server (&optional (port 0)) (let ((async-io-state (comm:create-async-io-state-and-udp-socket (ensure-udp-wait-state-collection) :name "UDP Cosi server socket" :local-port port))) (udp-cosi-server-receive-next async-io-state) (multiple-value-bind (ip-addr ip-port) (comm:async-io-state-address async-io-state) (declare (ignore ip-addr)) ip-port))) (defun start-server () (start-ephemeral-server *cosi-port*)) ;; ----------------- ;; Client side (defun internal-udp-cosi-client-send-request (callback ip-address ip-port packet) (let* ((collection (ensure-udp-wait-state-collection)) (async-io-state (comm:create-async-io-state-and-udp-socket collection))) (comm:async-io-state-send-message-to-address async-io-state ip-address ip-port packet callback) async-io-state)) (defun internal-send-socket (ip port packet nb) (declare (ignore nb)) (internal-udp-cosi-client-send-request 'comm:close-async-io-state ip port packet) )) #| (defun ptst () ;; test requesting a public key (spawn (lambda () (let* ((port (start-ephemeral-server)) (ret (make-return-addr (node-real-ip *my-node*) port))) (labels ((exit () (become 'do-nothing) (unregister-return-addr ret) (shutdown-server port))) (pr :my-port port) #+:LISPWORKS (inspect ret) (send *my-node* :public-key ret) (recv (msg (pr :I-got... msg) (exit)) :TIMEOUT 2 :ON-TIMEOUT (progn (pr :I-timed-out...) (exit)) )))) )) (defun stst (msg) ;; test getting a signature & verifying it (spawn (lambda () (let* ((port (start-ephemeral-server)) (ret (make-return-addr (node-real-ip *my-node*) port))) (labels ((exit () (become 'do-nothing) (unregister-return-addr ret) (shutdown-server port))) (pr :my-port port) #+:LISPWORKS (inspect ret) (send *top-node* :cosi ret msg) (recv ((list :answer (and packet (list :signature xmsg sig))) (pr :I-got... packet) (pr (format nil "Witnesses: ~A" (logcount (um:last1 sig)))) (send *my-node* :validate ret msg sig) (recv (ansv (pr :Validation ansv) (exit)) :TIMEOUT 1 :ON-TIMEOUT (pr :timed-out-on-signature-verification) (exit))) (xmsg (pr :what!? xmsg) (exit)) :TIMEOUT 15 :ON-TIMEOUT (progn (pr :I-timed-out...) (exit)) )))) )) |# ;; -------------------------------------------------------------- (defun make-hmac (msg skey uuid) ;; Every packet sent to another node is accompanied by an HMAC that ;; is unforgeable. If a MITM attack occurs, the receiving node will ;; fail HMAC verification and just drop the incoming packet on the ;; floor. So MITM modifications become tantamount to a DOS attack. (multiple-value-bind (v vpt) (ed-random-pair) (let* ((c (hash-pt-msg vpt msg)) (r (with-mod *ed-r* (m- v (m* c skey))))) (list msg r c uuid)))) (defun verify-hmac (quad) ;; Every incoming packet is scrutinized for a valid HMAC. If it ;; checks out then the packet is dispatched to an operation. ;; Otherwise it is just dropped on the floor. (when (and (consp quad) (= 4 (length quad))) (destructuring-bind (msg r c uuid) quad (let* ((node (gethash uuid *uuid-node-tbl*)) (pkey (node-pkey node)) (vpt (ed-add (ed-nth-pt r) (ed-mul pkey c))) (cc (hash-pt-msg vpt msg))) (values msg (= cc c)) )))) ;; -------------------------------------------------------------------- ;; Message handlers for verifier nodes (defun node-validate-cosi (node msg sig) ;; toplevel entry for Cosi signature validation checking (declare (ignore node)) ;; not needed here... (destructuring-bind (c r ids) sig (let* ((tkey (reduce (lambda (ans node) (if (and node (logbitp (node-bit node) ids)) (ed-add ans (node-pkey node)) ans)) *node-bit-tbl* :initial-value (ed-neutral-point))) (vpt (ed-add (ed-nth-pt r) (ed-mul tkey c))) (h (hash-pt-msg vpt msg))) (= h c)) )) ;; ----------------------------------------------------------------------- #-:LISPWORKS (defparameter *dly-instr* (ac:make-actor (lambda (&rest args) (declare (ignore args)) t))) #+:LISPWORKS (defparameter *dly-instr* (ac:make-actor (let ((data nil) (pltsym :plt)) (um:dlambda (:incr (dly) #+:LISPWORKS (push dly data)) (:clr () (setf data nil)) (:pltwin (sym) (setf pltsym sym)) (:plt () #+:LISPWORKS (plt:histogram pltsym data :clear t :ylog t :xrange '(0 1.2) :thick 2 ;; :cum t :norm nil :title "Measured Delay Ratios" :xtitle "Delay-Ratio" :ytitle "Counts") (plt:plot pltsym '(1 1) '(0.1 1e6) :color :red)) )))) ;; ----------------------------------------------------------------------- (defun msg-ok (msg node) (declare (ignore msg)) (not (node-byz node))) ;; for now... should look at node-byz to see how to mess it up (defun mark-node-no-response (node sub) (declare (ignore node sub)) ;; for now... nil) (defun mark-node-corrupted (node sub) (declare (ignore node)) ;; for now... (setf (node-bad sub) t) nil) ;; ----------------------- (defun clear-bad () (send-real-nodes :reset)) (defun node-reset-nodes (node) (declare (ignore node)) (loop for node across *node-bit-tbl* do (setf (node-bad node) nil))) ;; --------------- (defun send-subs (node &rest msg) (iter-subs node (lambda (sub) (apply 'send sub msg)))) (defun group-subs (node) (um:accum acc (iter-subs node #'acc))) (defun send-real-nodes (&rest msg) (loop for ip in *real-nodes* do (apply 'send (gethash ip *ip-node-tbl*) msg))) ;; ----------------------------------------------------------------------- (defun sub-commitment (my-ip msg seq-id) (=lambda (node) (let ((start (get-universal-time)) (timeout 10 ;; (* (node-load node) *default-timeout-period*) ) (ret-addr (make-return-addr my-ip))) (send node :commitment ret-addr msg seq-id) (labels ((!dly () #+:LISPWORKS (send *dly-instr* :incr (/ (- (get-universal-time) start) timeout))) (=return (val) (!dly) (unregister-return-addr ret-addr) (=values val)) (wait () (recv ((list* :commit sub-seq ans) (if (eql sub-seq seq-id) (=return ans) (wait))) (_ (wait)) :TIMEOUT timeout :ON-TIMEOUT (progn (pr (format nil "SubCommitment timeout waiting for ~A" (node-ip node))) (=return nil)) ))) (wait)) ))) (defun node-cosi-commitment (node reply-to msg seq-id) ;; ;; First phase of Cosi: ;; Generate a fresh random ECC pair: (v, v*G) ;; ;; Decide if msg warrants a commitment. If so add our contribution ;; to the random challenge, hold on to the secret seed, v. Collect ;; contributions from group members and add to the random ;; challenge ECC pt. ;; ;; Compute local validity challenges for all the group members. ;; ;; Return both the accumulated random point and our particular ;; point for use in the local validity challenge. ;; (multiple-value-bind (v vpt) (ed-random-pair) (let* ((subs (remove-if 'node-bad (group-subs node))) (ok (msg-ok msg node)) (bits (if ok (node-bitmap node) 0)) (vsum (if ok vpt (ed-neutral-point)))) (setf (node-seq node) seq-id (node-parts node) nil (node-v node) v (node-ok node) ok) ;; indicate our participation in phase 1 (=bind (lst) (pmapcar (sub-commitment (node-real-ip node) msg seq-id) subs) (labels ((fold-answer (ans sub) (cond ((null ans) (pr (format nil "No commitmemt: ~A" (node-ip sub))) (mark-node-no-response node sub)) (t (destructuring-bind (sub-ptsum sub-pt sub-bits) ans ;; fold in the subtree answer (setf bits (logior bits sub-bits) vsum (ed-add vsum (ed-decompress-pt sub-ptsum))) ;; compute a random challenge for node validity checking (let ((chk (hash-pt-msg (ed-decompress-pt sub-pt) msg))) ;; accumulate participants for phase 2 (push (list sub msg chk) (node-parts node)) ))) ))) (mapc #'fold-answer lst subs) (send reply-to :commit seq-id (ed-compress-pt vsum) (ed-compress-pt vpt) bits) ))))) ;; ------------------------------ (defun sub-signing (my-ip c seq-id) (=lambda (node chk) (let ((start (get-universal-time)) (timeout 10 ;; (* (node-load node) *default-timeout-period*) ) (ret-addr (make-return-addr my-ip))) (send node :signing ret-addr c chk seq-id) (labels ((!dly () #+:LISPWORKS (send *dly-instr* :incr (/ (- (get-universal-time) start) timeout))) (=return (val) (!dly) (unregister-return-addr ret-addr) (=values val)) (wait () (recv ((list* :signed sub-seq ans) (if (eql sub-seq seq-id) (=return ans) ;; else (wait))) ((list (or :missing-node :invalid-commitment) sub-seq) (if (eql sub-seq seq-id) (=return nil) ;; else (wait))) (_ (wait)) :TIMEOUT timeout :ON-TIMEOUT (progn (pr (format nil "SubSigning timeout waiting for ~A" (node-ip node))) (=return nil)) ))) (wait)) ))) (defun node-cosi-signing (node reply-to c c1 seq-id) ;; ;; Second phase of Cosi: ;; Given challenge value c, compute the signature value ;; r = v - c * skey. ;; If we decided against signing in the first phase, ;; then we shouldn't even be called ;; (cond ((and (integerp c) ;; valid setup for phase 2? (integerp c1) (eql seq-id (node-seq node))) (labels ((compute-signage (challenge) (with-mod *ed-r* (m- (node-v node) (m* challenge (node-skey node)))))) (let* ((ok (node-ok node)) ;; did we participate in phase 1? (subs (mapcar 'first (node-parts node))) (chks (mapcar 'third (node-parts node))) (rsum (if ok (compute-signage c) 0)) (r1 (compute-signage c1)) (missing nil)) (setf (node-v node) nil ;; done with these (node-seq node) nil) (=bind (r-lst) (pmapcar (sub-signing (node-real-ip node) c seq-id) subs chks) (labels ((fold-answer (sub-rs sub-chk) (destructuring-bind (sub msg chk) sub-chk (cond ((null sub-rs) ;; no response from node, or bad subtree (pr (format nil "No signing: ~A" sub)) (mark-node-no-response node sub) (setf missing t)) (t (destructuring-bind (sub-r sub-r1) sub-rs ;; first validate the sub (if (node-validate-cosi node msg (list chk sub-r1 (node-bitmap sub))) (unless missing ;; sub was ok, but if we had some missing ;; subs, don't waste time computing ;; anything (with-mod *ed-r* (setf rsum (m+ rsum sub-r)))) (progn ;; sub gave a corrupt answer on the local challenge (pr (format nil "Corrupt node: ~A" (node-ip sub))) (mark-node-corrupted node sub) (setf missing t)) ))) )))) (mapc #'fold-answer r-lst (node-parts node)) (if missing (send reply-to :missing-node seq-id) (send reply-to :signed seq-id rsum r1)) ))))) (t ;; else -- bad args (send reply-to :invalid-commitment seq-id)) ;; request restart )) ;; ----------------------------------------------------------- (defun node-compute-cosi (node reply-to msg) ;; top-level entry for Cosi signature creation ;; assume for now that leader cannot be corrupted... (let ((sess (gen-uuid-int)) (self (current-actor))) (ac:self-call :commitment self msg sess) (labels ((unknown-message (msg) (error "Unknown message: ~A" msg)) (wait-commitment () (recv ((list :commit seq vpt vsubpt bits) (cond ((eql seq sess) ;; compute global challenge (let ((c (hash-pt-msg (ed-decompress-pt vpt) msg)) (c1 (hash-pt-msg (ed-decompress-pt vsubpt) msg))) (ac:self-call :signing self c c1 sess) (labels ((wait-signing () (recv ((list :signed seq r r1) (declare (ignore r1)) (cond ((eql seq sess) (let ((sig (list c r bits))) (if (node-validate-cosi node msg sig) ;; we completed successfully (reply reply-to (list :signature msg sig)) ;; bad signature, try again (reply reply-to :corrupt-cosi-network) ))) (t ;; seq mismatch ;; must have been a late arrival (wait-signing)) )) ((list :missing-node seq) (cond ((eql seq sess) ;; retry from start (pr "Witness dropout, signing restart") (node-compute-cosi node reply-to msg)) (t ;; seq mismatch ;; must have been a late arrival (wait-signing)) )) ((list :invalid-commitment seq) (cond ((eql seq sess) (pr "Invalid commitment, signing restart") (node-compute-cosi node reply-to msg)) (t ;; seq mismatch ;; must have been a late arrival (wait-signing)) )) (msg ;; other messages during signing phase (unknown-message msg)) ))) (wait-signing)) )) ;; end of big COND clause ;; ------------------------------------ (t ;; seq mismatch ;; must have been a late arrival (wait-commitment)) )) ;; end of message pattern ;; --------------------------------- (msg ;; other messages during commitment phase (unknown-message msg)) ))) (wait-commitment)))) #| ;; FOR TESTING!!! (setup-server) (set-executive-pool 1) (setf *real-nodes* (list *leader-node*)) (setf *real-nodes* (remove "10.0.1.13" *real-nodes* :test 'string-equal)) (generate-tree :nel 100) (reconstruct-tree) |# (defun tst () (spawn (lambda () (send *dly-instr* :clr) (send *dly-instr* :pltwin :histo-4) (let ((ret (make-return-addr (node-real-ip *my-node*))) (start (get-universal-time))) (labels ((exit () (unregister-return-addr ret))) (send *top-node* :cosi ret "This is a test message!") (recv ((list :answer (and msg (list :signature txt (and sig (list _ _ bits))))) (send *dly-instr* :plt) (ac:pr (format nil "Total Witnesses: ~D" (logcount bits)) msg (format nil "Duration = ~A" (- (get-universal-time) start))) (send *my-node* :validate ret txt sig) (recv ((list :answer :validation t/f) (if t/f (ac:pr :valid-signature) (ac:pr :invalid-signature)) (exit)) (msg (error "ValHuh?: ~A" msg) (exit)) )) (msg (error "Huh? ~A" msg) (exit)) )))))) ;; ------------------------------------------------------------- (defvar *dachshund* "10.0.1.3") (defvar *malachite* "10.0.1.6") (defvar *rambo* "10.0.1.13") (defmethod damage ((ip string) t/f) (damage (gethash ip *ip-node-tbl*) t/f)) (defmethod damage ((node node) t/f) (setf (node-byz node) t/f)) (defun init-sim () (shutdown-server) (reconstruct-tree) (start-server))
75744
;; random-partition.lisp -- Generate simulation trees of network nodes for Cosi ;; ;; DM/Emotiq 02/18 ;; ------------------------------------------------------------------------- #| The MIT License Copyright (c) 2018 <NAME> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. |# (in-package :cosi-simgen) (declaim (optimize (debug 3))) ;; -------------------------------------------------------------------- ;; Physical network (defvar *local-nodes* '(("Malachite.local" . "10.0.1.6") ("Dachshund.local" . "10.0.1.3") ("Rambo" . "10.0.1.13") ("ChromeKote.local" . "10.0.1.36"))) (defun get-local-ipv4 (node-name) (cdr (assoc node-name *local-nodes* :test 'string-equal))) (defun get-my-ipv4 () (get-local-ipv4 (machine-instance))) (defvar *real-nodes* (mapcar 'cdr *local-nodes*)) (defvar *leader-node* (get-local-ipv4 "Dachshund.local")) ;;(defvar *leader-node* (get-local-ipv4 "ChromeKote.local")) (defvar *top-node* nil) ;; current leader node (defvar *my-node* nil) ;; which node my machine is on ;; default-timeout-period needs to be made smarter, based on node height in tree (defparameter *default-timeout-period* ;; good for 1600 nodes on single machine #+:LISPWORKS 10 #+:ALLEGRO 70 #+:CLOZURE 70) ;; ---------------------------------------------------------------------- ;; Network Tree Nodes (defvar *bins-per-node* 9) ;; prolly needs to be >3 for BFT (defun make-subs () (make-array *bins-per-node* :initial-element nil)) (defclass node () ((ip :accessor node-ip ;; IPv4 string for this node :initarg :ip) (uuid :accessor node-uuid ;; UUID for this node :initarg :uuid) (pkeyzkp :accessor node-pkeyzkp ;; public key + ZKP :initarg :pkeyzkp) (skey :accessor node-skey ;; private key :initarg :skey) (pkey :accessor node-pkey ;; cached ECC point for public key :initarg :pkey) (realnode :accessor node-realnode ;; t/f - t when this is a real IPv4 node, nil for fake :initform nil) (parent :accessor node-parent ;; points to node of group parent :initarg :parent :initform nil) (subs :accessor node-subs ;; list of group members beyond self :initarg :subs :initform (make-subs)) (bit :accessor node-bit ;; bit position in bitmap :initform 0) ;; ------------------------------------- (real-ip :accessor node-real-ip ;; real node for this node :initarg :real-ip) (ok :accessor node-ok ;; t if we participated in round 1 :initform nil) (v :accessor node-v ;; first round random seed :initform nil) (seq :accessor node-seq ;; first round ID :initform nil) (byz :accessor node-byz ;; Byzantine misbehav type :initform nil) (parts :accessor node-parts ;; group participants in first round commitment :initform nil) (bad :accessor node-bad ;; if true then node was corrupted :initform nil) (load :accessor node-load ;; cpu loading of group for this node :initform 1) (self :accessor node-self ;; ptr to Actor handler :initarg :self) )) (defmethod node-bitmap ((node node)) (ash 1 (node-bit node))) (defmethod iteri-subs ((node node) fn) (loop for sub across (node-subs node) for ix from 0 when sub do (funcall fn ix sub))) (defmethod iter-subs ((node node) fn) (iteri-subs node (lambda (ix sub) (declare (ignore ix)) (funcall fn sub)))) (defmethod set-node-load (node) (setf (node-load node) (1+ (loop for sub across (node-subs node) when sub sum (node-load sub))))) ;; -------------------------------------------------------------------- ;; For now, 4 different ways to specify a node: ;; 1. node structure pointer ;; 2. IPv4 address (in dotted string notation) ;; 3. UUID (needs uuid-to-integer for keying *uuid-node* table) ;; 4. PKEY (compressed public key ECC point) ;; XREF from IPv4 address to Tree Node (defvar *ip-node-tbl* (make-hash-table :test 'equal)) ;; IPv4 string as key (defvar *uuid-node-tbl* (make-hash-table)) ;; UUID integer as key (defvar *pkey-node-tbl* (make-hash-table)) ;; compressed ECC pt integer as key (defvar *pkey-skey-tbl* (make-hash-table)) ;; commpressed ECC pt integer as key ;; ------------------------------------------------------------------- (defvar *comm-ip* nil) (defun make-node (ipstr uuid pkeyzkp parent) (let* ((cmpr-pkey (third pkeyzkp)) (node (make-instance 'node :ip ipstr :uuid uuid :skey (gethash cmpr-pkey *pkey-skey-tbl*) :pkey (edec:ed-decompress-pt cmpr-pkey) :pkeyzkp pkeyzkp :parent parent :real-ip *comm-ip* ))) (setf (node-self node) (make-node-dispatcher node) (gethash ipstr *ip-node-tbl*) node (gethash (node-uuid node) *uuid-node-tbl*) node (gethash cmpr-pkey *pkey-node-tbl*) node))) (defun need-to-specify (&rest args) (declare (ignore args)) (error "Need to specify...")) #+:ALLEGRO (defun allegro-dotted-to-integer (string) (multiple-value-bind (start end starts ends) (#~m/^([0-9]+).([0-9]+).([0-9]+).([0-9]+)$/ string) (declare (ignore start end)) (reduce (lambda (ans pair) (destructuring-bind (start . end) pair (logior (ash ans 8) (parse-integer string :start start :end end)))) (nreverse (pairlis (coerce starts 'list) (coerce ends 'list))) :initial-value 0))) #+:ALLEGRO (defun allegro-integer-to-dotted (val) (let ((parts (um:nlet-tail iter ((n 4) (pos 0) (ans nil)) (if (zerop n) ans (iter (1- n) (+ pos 8) (cons (ldb (byte 8 pos) val) ans))) ))) (format nil "~{~d~^.~}" parts))) (defun dotted-string-to-integer (string) #+:LISPWORKS (comm:string-ip-address string) #+:OPENMCL (ccl::dotted-to-ipaddr string) #+:ALLEGRO (allegro-dotted-to-integer string)) (defun integer-to-dotted-string (val) #+:LISPWORKS (comm:ip-address-string val) #+:OPENMCL (CCL::ipaddr-to-dotted val) #+:ALLEGRO (allegro-integer-to-dotted val)) (defun gen-uuid-int () (uuid:uuid-to-integer (uuid:make-v1-uuid))) (defun gen-node-id (ip) (if (consp ip) (values-list ip) (multiple-value-bind (skey pkey) (edec:ed-random-pair) (let ((zkp (compute-pkey-zkp skey pkey))) (setf (gethash (third zkp) *pkey-skey-tbl*) skey) (values ip (gen-uuid-int) zkp) )))) ;; ------------------------------------------------------------- (defvar *node-bit-tbl* #()) (defun assign-bits () ;; assign bit positions to each node (let ((collected (um:accum acc (maphash (lambda (k node) (declare (ignore k)) (acc node)) *ip-node-tbl*)))) (setf collected (sort collected '< :key 'node-uuid)) (loop for node in collected for ix from 0 do (setf (node-bit node) ix)) (setf *node-bit-tbl* (coerce collected 'vector)) )) ;; ------------------------------------------------------------------- ;; Node construction (defun partition (node ip-list &key (key 'identity)) (let* ((bins (make-subs)) (nbins (length bins)) (vnode (dotted-string-to-integer (node-ip node)))) (mapc (lambda (ip-arg) (let* ((vip (dotted-string-to-integer (funcall key ip-arg))) (ix (mod (logxor vnode vip) nbins))) (push ip-arg (aref bins ix)))) ip-list) (setf (node-subs node) bins))) (defun inner-make-node-tree (ip ip-list &optional parent) (multiple-value-bind (ipstr uuid pkeyzkp) (gen-node-id ip) (let ((node (make-node ipstr uuid pkeyzkp parent))) (when ip-list (let ((bins (partition node ip-list :key (lambda (ip-arg) (if (consp ip-arg) (car ip-arg) ip-arg))))) (iteri-subs node (lambda (ix subs) (setf (aref bins ix) (inner-make-node-tree (car subs) (cdr subs) node)))) (set-node-load node))) node))) (defun make-node-tree (ip vlist) ;; main entry point - captures IPv4 of arg ip for use as real-ip in ;; succeeding nodes (multiple-value-bind (ipstr uuid pkeyzp) (gen-node-id ip) (let ((*comm-ip* ipstr)) (inner-make-node-tree (list ipstr uuid pkeyzp) vlist)))) ;; -------------------------------------------------------------------- ;; for visual debugging... #+:LISPWORKS (progn (defmethod children (x layout) nil) (defmethod children ((node node) layout) (remove nil (coerce (node-subs node) 'list))) (defun split-to-octets (val) (um:nlet-tail iter ((n 4) (val val) (lst nil)) (if (zerop n) lst (iter (1- n) (ash val -8) (cons (ldb (byte 8 0) val) lst))) )) (defclass red-text (capi:item-pinboard-object) ()) (defclass black-text (capi:item-pinboard-object) ()) (defmethod capi:draw-pinboard-object :around (pinboard (self red-text) &key &allow-other-keys) (gp:with-graphics-state (pinboard :foreground :red) (call-next-method))) (defmethod make-node-pane (graphics-port (node node)) (declare (ignore graphics-port)) (let ((txt (node-ip node))) (make-instance (if (node-realnode node) 'red-text 'black-text) :text txt))) (defmethod view-tree ((tree node) &key (layout :left-right)) (capi:contain (make-instance 'capi:graph-pane :layout-function layout :roots (list tree) :node-pane-function 'make-node-pane :children-function (lambda (node) (children node layout)) )))) ;; -------------------------------------------------------------------- ;; Initial Tree Generation and Persistence (defvar *default-data-file* "cosi-nodes.txt") (defvar *default-key-file* "cosi-keying.txt") (defun generate-ip () ;; generate a unique random IPv4 address (let ((ip (integer-to-dotted-string (random #.(expt 2 32))))) (if (gethash ip *ip-node-tbl*) (generate-ip) ;; should be unlikely, would be 50% at around 2^16 nodes (setf (gethash ip *ip-node-tbl*) ip)))) (defmethod pair-ip-uuid ((node node)) (list (node-ip node) (node-uuid node) (node-pkeyzkp node))) (defmethod pair-ip-uuid ((ip string)) (pair-ip-uuid (gethash ip *ip-node-tbl*))) (defun gen-main-tree (leader real-nodes grps) (let* ((trees (mapcar 'make-node-tree real-nodes grps)) (main-tree (find leader trees :test 'string= :key 'node-ip))) ;; mark the real nodes as special (mapc (lambda (tree) (setf (node-realnode tree) t)) trees) ;; attach the non-leader real nodes to the leader node (let ((all-but (remove main-tree trees))) (setf (node-subs main-tree) (concatenate 'vector (node-subs main-tree) (apply 'vector all-but))) (dolist (tree all-but) (setf (node-parent tree) main-tree))) main-tree)) ;; -------------------------------------------------------------- ;; Generate Tree / Keying and save to startup init files (defun generate-tree (&key fname (nel 1000)) (let* ((leader *leader-node*) (real-nodes (remove-duplicates *real-nodes* :test 'string=))) ;; ensure leader is in the real-nodes collection (assert (member leader real-nodes :test 'string=)) ;; pre-populate hash table with real-nodes (clrhash *ip-node-tbl*) (clrhash *uuid-node-tbl*) (clrhash *pkey-node-tbl*) (clrhash *pkey-skey-tbl*) (dolist (ip real-nodes) (setf (gethash ip *ip-node-tbl*) ip)) ;; build the trees (let* ((nreal (length real-nodes)) (nel/grp (ceiling nel nreal)) (grps (loop repeat nreal collect (loop repeat nel/grp collect (generate-ip)))) (main-tree (gen-main-tree leader real-nodes grps))) ;; save nodes as a text file for later (with-open-file (f (merge-pathnames #+:LISPWORKS (sys:get-folder-path :documents) #+(OR :ALLEGRO :OPENMCL) "~/Documents/" (or fname *default-data-file*)) :direction :output :if-does-not-exist :create :if-exists :rename) (with-standard-io-syntax (let ((*print-readably* t) ;; to get readable UUID's (*print-right-margin* 128)) (pprint `(:leader ,leader :real-nodes ,(mapcar 'pair-ip-uuid real-nodes) :groups ,(mapcar (lambda (grp) (mapcar 'pair-ip-uuid grp)) grps)) f)))) ;; write the pkey/skey associations (with-open-file (f (merge-pathnames #+:LISPWORKS (sys:get-folder-path :documents) #+(OR :ALLEGRO :OPENMCL) "~/Documents/" *default-key-file*) :direction :output :if-does-not-exist :create :if-exists :rename) (let ((keys nil)) (maphash (lambda (k v) (push (cons k v) keys)) *pkey-skey-tbl*) (with-standard-io-syntax (pprint keys f)))) (assign-bits) #+:LISPWORKS (view-tree main-tree) (setf *my-node* main-tree *top-node* main-tree) ))) ;; --------------------------------------------------------------- ;; Tree reconstruction from startup init files (defun read-data-file (path) (with-open-file (f path :direction :input) (read f))) (defun reconstruct-tree (&key fname) ;; read the keying file (let* ((key-path (merge-pathnames #+:LISPWORKS (sys:get-folder-path :documents) #+(OR :ALLEGRO :OPENMCL) "~/Documents/" *default-key-file*)) (keys (read-data-file key-path)) (data-path (merge-pathnames #+:LISPWORKS (sys:get-folder-path :documents) #+(OR :ALLEGRO :OPENMCL) "~/Documents/" (or fname *default-data-file*))) (data (read-data-file data-path)) (leader (getf data :leader)) (real-nodes (getf data :real-nodes)) (grps (getf data :groups))) ;; sanity checking (assert (member leader real-nodes :test 'string= :key 'car)) (labels ((no-dups (lst) (dolist (ip lst) (destructuring-bind (ipstr uuid zkp) ip (assert (null (gethash ipstr *ip-node-tbl*))) (assert (null (gethash uuid *uuid-node-tbl*))) (destructuring-bind (r c pcmpr) zkp (declare (ignore r c)) (assert (null (gethash pcmpr *pkey-node-tbl*))) (check-pkey zkp) (setf (gethash ipstr *ip-node-tbl*) ip (gethash uuid *uuid-node-tbl*) ip (gethash pcmpr *pkey-node-tbl*) ip) ))))) (clrhash *ip-node-tbl*) (clrhash *uuid-node-tbl*) (clrhash *pkey-node-tbl*) (no-dups real-nodes) (mapc #'no-dups grps)) ;; reconstruct keying info (clrhash *pkey-skey-tbl*) (mapc (lambda (pair) (destructuring-bind (k . v) pair ;; k is integer, compressed pkey ECC pt ;; v is skey integer ;; decompression checks for valid ECC pt (assert (ed-pt= (ed-nth-pt v) (ed-decompress-pt k))) (setf (gethash k *pkey-skey-tbl*) v))) keys) ;; reconstruct the trees (let ((main-tree (gen-main-tree leader real-nodes grps))) (assign-bits) #+:LISPWORKS (view-tree main-tree) (setf *top-node* main-tree *my-node* (gethash (get-my-ipv4) *ip-node-tbl*))))) ;; --------------------------------------------------------------- ;; New leader node election... tree rearrangement (defun notify-real-descendents (node &rest msg) (labels ((recurse (sub-node) (if (node-realnode sub-node) (apply 'send sub-node msg) (iter-subs sub-node #'recurse)))) (iter-subs node #'recurse))) (defun all-nodes-except (node) (delete node (um:accum acc (maphash (um:compose #'acc 'um:snd) *ip-node-tbl*)))) (defun node-model-rebuild-tree (parent node nlist) (let ((bins (partition node nlist :key 'node-ip))) (iteri-subs node (lambda (ix subs) (setf (aref bins ix) (node-model-rebuild-tree node (car subs) (cdr subs))))) (setf (node-parent node) parent) (set-node-load node) node)) (defun node-elect-new-leader (new-leader-ip) (let ((new-top-node (gethash new-leader-ip *ip-node-tbl*))) ;; Maybe... ready for prime time? (cond ((null new-top-node) (error "Not a valid leader node: ~A" new-leader-ip)) ((eq new-top-node *top-node*) ;; nothing to do here... ) (t (setf *top-node* new-top-node) (node-model-rebuild-tree nil new-top-node (all-nodes-except new-top-node)) ;; ;; The following broadcast will cause us to get another ;; notification, but by then the *top-node* will already ;; have been set to new-leader-ip, and so no endless loop ;; will occur. ;; (notify-real-descendents new-top-node :election new-leader-ip)) ))) ;; --------------------------------------------------------- ;; Node insertion/change (defun bin-for-ip (node ip) (let ((vnode (dotted-string-to-integer (node-ip node))) (vip (dotted-string-to-integer ip))) (mod (logxor vnode vip) (length (node-subs node))))) (defun increase-loading (parent-node) (when parent-node (incf (node-load parent-node)) (increase-loading (node-parent parent-node)))) (defun node-model-insert-node (node new-node-info) ;; info is (ipv4 UUID pkeyzkp) (destructuring-bind (ipstr uuid pkeyzkp) new-node-info (let* ((ix (bin-for-ip node ipstr)) (bins (node-subs node)) (sub-node (aref bins ix))) (if sub-node ;; continue in parallel with our copy of tree (node-model-insert-node sub-node new-node-info) ;; else (let ((new-node (make-node ipstr uuid pkeyzkp node))) (setf (node-real-ip new-node) ipstr (node-realnode new-node) t (node-skey new-node) nil (aref bins ix) new-node) (incf (node-load node)) (increase-loading (node-parent node))) )))) (defun node-insert-node (node new-node-info) (destructuring-bind (ipstr uuid pkeyzkp) new-node-info (let ((new-node (gethash ipstr *ip-node-tbl*))) (if new-node ;; already present in tree? ;; maybe caller just wants to change UUID or keying ;; won't be able to sign unless it know skey (multiple-value-bind (pkey ok) (check-pkey pkeyzkp) (when ok (setf (node-uuid new-node) uuid (node-pkeyzkp new-node) pkeyzkp (node-pkey new-node) pkey ;; cache the decompressed key (node-realnode new-node) t (node-real-ip new-node) ipstr))) ;; else - not already present (node-model-insert-node *top-node* new-node-info)))) (notify-real-descendents node :insert-node new-node-info)) ;; --------------------------------------------------------- (defun node-model-remove-node (gone-node) (remhash (node-ip gone-node) *ip-node-tbl*) (remhash (node-uuid gone-node) *uuid-node-tbl*) (let ((pcmpr (third (node-pkeyzkp gone-node)))) (remhash pcmpr *pkey-node-tbl*) (remhash pcmpr *pkey-skey-tbl*))) (defun node-remove-node (node gone-node-ipv4) (let ((gone-node (gethash gone-node-ipv4 *ip-node-tbl*))) (when gone-node (node-model-remove-node gone-node) ;; must rebuild tree to absorb node's subnodes (node-model-rebuild-tree nil *top-node* (all-nodes-except *top-node*)) (when (eq node *top-node*) (notify-real-descendents node :remove-node gone-node-ipv4))))) ;; ----------------------------------------------------------------- (defun NYI (&rest args) (error "Not yet implemented: ~A" args)) ;; ------------------------------------------------------- (defun make-node-dispatcher (node) ;; use indirection to node-dispatcher for while we are debugging and ;; extending the dispatcher. Saves reconstructing the tree every ;; time the dispatching chanages. (ac:make-actor ;; one of these closures is stored in the SELF slot of every node (lambda (&rest msg) (apply 'node-dispatcher node msg)))) (defun crash-recovery () (maphash (lambda (k node) (declare (ignore k)) (setf (node-self node) (make-node-dispatcher node))) *ip-node-tbl*)) (defun node-dispatcher (node &rest msg) (um:dcase msg ;; ---------------------------- ;; user accessible entry points - directed to leader node (:cosi (reply-to msg) (node-compute-cosi node reply-to msg)) (:validate (reply-to msg sig) (reply reply-to :validation (node-validate-cosi node msg sig))) (:public-key (reply-to) (reply reply-to :pkey+zkp (node-pkeyzkp node))) (:add/change-node (new-node-info) (node-insert-node node new-node-info)) (:remove-node (node-ip) (node-remove-node node node-ip)) (:election (new-leader-ip) (node-elect-new-leader new-leader-ip)) ;; ------------------------------- ;; internal comms between Cosi nodes (:commitment (reply-to msg seq) (node-cosi-commitment node reply-to msg seq)) (:signing (reply-to c c1 seq) (node-cosi-signing node reply-to c c1 seq)) ;; ----------------------------------- ;; for sim and debug (:answer (&rest msg) ;; for round-trip testing (ac:pr msg)) (:reset () (node-reset-nodes node)) (t (&rest msg) (error "Unknown message: ~A~%Node: ~A" msg (node-ip node))) )) ;; ------------------------------------------------------------------ ;; GET-PUBLIC-KEY - This is here primarily for testing the network. ;; Not really an RPC call, and results will show in the output ;; browser, not returned to caller. ;; ;; RPC violates the basic premise of the point-and-shoot design. ;; Responders are free to ignore, be deaf, or send us garbage at any ;; time. ;; ;; The design of the system is aimed at coexistence in a Byzantine network. ;; (defun get-public-key (uuid) (let ((node (gethash uuid *uuid-node-tbl*))) (when node (spawn (lambda () (let ((ret (make-return-addr (node-real-ip *my-node*)))) (send node :public-key ret) (recv (msg (unregister-return-addr ret) (pr msg)) ))) )))) #| (send *top-node* :public-key (make-node-ref *my-node*)) ==> see results in output window (:PKEY+ZKP (849707610687761353988031598913888011454228809522136330182685594047565816483 77424688591828692687552806917061506619936267795838123291694715575735109065947 2463653704506470449709613051914446331689964762794940591210756129064889348739)) COSI-SIMGEN 23 > (send (gethash "10.0.1.6" *ip-node-tbl*) :public-key (make-node-ref *my-node*)) Connecting to #$(NODE "10.0.1.6" 65000) (FORWARDING "10.0.1.6" (QUOTE ((:PUBLIC-KEY #<NODE-REF 40200014C3>) 601290835549702797100992963662352678603116278028765925372703953633797770499 56627041402452754830116071111198944351637771601751353481660603190062587211624 23801716726735741425848558528841292842))) ==> output window (:PKEY+ZKP (<KEY>0<KEY>12136<KEY>8<KEY>0<KEY>05812<KEY>818001884231695959658747310415728976873583 19894104797779289660345137228823739121774277312822467740314566093297448396984 2080524722754689845098528285145820902670538507089109456806581872878115260191)) |# ;; ---------------------------- (defvar *cosi-port* 65001) (defclass return-addr () ((ip :accessor return-addr-ip ;; the real IPv4 for returns :initarg :ip) (port :accessor return-addr-port ;; the real IPv4 port for returns :initarg :port) (aid :accessor return-addr-aid ;; actor id for returns :initarg :aid))) (defvar *aid-tbl* ;; assoc between Actors and AID's #+:LISPWORKS (make-hash-table :weak-kind :value) #+:ALLEGRO (make-hash-table :values :weak) #+:CLOZURE (make-hash-table :weak :value) ) (defmethod unregister-return-addr ((ret return-addr)) (remhash (return-addr-aid ret) *aid-tbl*) (become 'do-nothing)) (defmethod make-return-addr ((ipv4 string) &optional (port *cosi-port*)) ;; can only be called from within an Actor body (let ((aid (gen-uuid-int)) (self (current-actor))) (unless self (error "MAKE-RETURN-ADDR can only be performed by an Actor")) (setf (gethash aid *aid-tbl*) self) (make-instance 'return-addr :ip ipv4 :port port :aid aid))) ;; ----------------------------------------------------------- (defmethod send ((node node) &rest msg) (unless (node-byz node) (socket-send (node-ip node) (node-real-ip node) *cosi-port* msg))) (defmethod send ((ref return-addr) &rest msg) (socket-send ref (return-addr-ip ref) (return-addr-port ref) msg)) (defmethod send ((node null) &rest msg) (ac:pr :sent-to-null msg) msg) (defmethod send (dest &rest msg) (apply 'ac:send dest msg)) ;; ----------------- (defun reply (reply-to &rest msg) (apply 'send reply-to :answer msg)) ;; ----------------------------------------------------- ;; THE SOCKET INTERFACE... ;; ----------------------------------------------------- (defvar *max-buffer-length* 65500) (defun cosi-service-handler (buf) (multiple-value-bind (ans err) (ignore-errors (loenc:decode buf)) (unless err (multiple-value-bind (packet t/f) (verify-hmac ans) (when t/f (destructuring-bind (dest msg-verb &rest msg-args) packet (cond ((eql :SHUTDOWN-SERVER msg-verb) :SHUTDOWN-SERVER) (t (let ((true-dest (dest-ip dest))) ;; for debug... ------------------- (when (eq true-dest (node-self *my-node*)) (pr (format nil "forwarding-to-me: ~A" (cons msg-verb msg-args)))) ;; ------------------ (apply 'send true-dest msg-verb msg-args) t)) ))) )))) (defun shutdown-server (&optional (port *cosi-port*)) (when *my-node* (let ((me (node-ip *my-node*))) (socket-send me me port '(:SHUTDOWN-SERVER))))) (defun socket-send (ip real-ip real-port msg) (let* ((quad (make-hmac (list* ip msg) (node-skey *my-node*) (node-uuid *my-node*))) (packet (loenc:encode quad)) (nb (length packet))) (internal-send-socket real-ip real-port packet nb))) ;; ------------------------------------------------------------------ (defmethod dest-ip ((ip string)) (let ((node (gethash ip *ip-node-tbl*))) (when node (node-self node)))) (defmethod dest-ip ((ret return-addr)) (gethash (return-addr-aid ret) *aid-tbl*)) ;; ------------------------------------------------------------------ ;; deprecated... #+:xLISPWORKS (progn ;; TCP/IP stream over Butterfly (defun socket-send (ip real-ip msg) ;; replace this with USOCKETS protocol (let* ((quad (make-hmac msg (node-skey *my-node*) (node-uuid *my-node*))) (agent-ip (format nil "eval@~A" real-ip))) ;; (format t "~%SOCKET-SEND: ~A ~A ~A" ip real-ip msg) #+:LISPWORKS (bfly:! agent-ip `(forwarding ,ip ',quad)))) (defun forwarding (dest quad) ;; (format t "~%FORWARDING: ~A ~A" dest quad) (multiple-value-bind (msg t/f) (verify-hmac quad) ;; might want to log incomings that fail the HMAC ;; just dropping on floor here... (when t/f (let ((true-dest (dest-ip dest))) (when true-dest (when (equal true-dest (node-self *my-node*)) (ac:pr (format nil "forwarding-to-me: ~A" msg))) (apply 'send true-dest msg)))) ))) ;; ------------------------------------------------------------------ #-:LISPWORKS (progn ;; USOCKET interface for ACL (defun #1=serve-cosi-port (socket) (let ((maxbuf (make-array *max-buffer-length* :element-type '(unsigned-byte 8)))) ;; (pr :server-starting-up) (unwind-protect (loop (multiple-value-bind (buf buf-len rem-ip rem-port) (usocket:socket-receive socket maxbuf (length maxbuf)) (declare (ignore rem-ip rem-port)) ;; (pr :sock-read buf-len rem-ip rem-port (loenc:decode buf)) (when (eql :SHUTDOWN-SERVER (cosi-service-handler buf)) (return-from #1#)))) ;; unwinding (usocket:socket-close socket) ;; (pr :server-stopped) ))) (defun start-ephemeral-server (&optional (port 0)) (let* ((my-ip (node-real-ip *my-node*)) (socket (usocket:socket-connect nil nil :protocol :datagram :local-host my-ip :local-port port ))) (mpcompat:process-run-function "UDP Cosi Server" nil 'serve-cosi-port socket) (usocket:get-local-port socket))) (defun start-server () (start-ephemeral-server *cosi-port*)) (defun internal-send-socket (ip port packet nb) (let ((socket (usocket:socket-connect ip port :protocol :datagram))) ;(pr :sock-send (length packet) real-ip packet) (unless (eql nb (usocket:socket-send socket packet nb)) (pr :socket-send-error ip packet)) (usocket:socket-close socket) ))) ;; ------------------------------------------------------------------ #+:LISPWORKS (progn ;; LW UDP Async interface (defvar *udp-wait-collection* nil) (defun ensure-udp-wait-state-collection () (or *udp-wait-collection* (let ((new (comm:create-and-run-wait-state-collection "UDP Cosi Service"))) (if (sys:compare-and-swap *udp-wait-collection* nil new) new (progn ; Another process just set it. (comm:wait-state-collection-stop-loop new) *udp-wait-collection*))))) ;; ------------------------- ;; Server side (defun #1=udp-cosi-server-process-request (async-io-state string bytes-num ip-address port-num) (declare (ignore bytes-num ip-address port-num)) (let ((status (comm:async-io-state-read-status async-io-state))) (when status ;; something went wrong (pr (format nil "UDP example server: got error ~s, restarting" status)) (comm:close-async-io-state async-io-state) (start-server) (return-from #1#)) (if (eql :SHUTDOWN-SERVER (cosi-service-handler string)) (comm:close-async-io-state async-io-state) (udp-cosi-server-receive-next async-io-state)))) (defun udp-cosi-server-receive-next (async-io-state ) (comm:async-io-state-receive-message async-io-state (make-array *max-buffer-length* :element-type '(unsigned-byte 8)) 'udp-cosi-server-process-request :needs-address t)) (defun start-ephemeral-server (&optional (port 0)) (let ((async-io-state (comm:create-async-io-state-and-udp-socket (ensure-udp-wait-state-collection) :name "UDP Cosi server socket" :local-port port))) (udp-cosi-server-receive-next async-io-state) (multiple-value-bind (ip-addr ip-port) (comm:async-io-state-address async-io-state) (declare (ignore ip-addr)) ip-port))) (defun start-server () (start-ephemeral-server *cosi-port*)) ;; ----------------- ;; Client side (defun internal-udp-cosi-client-send-request (callback ip-address ip-port packet) (let* ((collection (ensure-udp-wait-state-collection)) (async-io-state (comm:create-async-io-state-and-udp-socket collection))) (comm:async-io-state-send-message-to-address async-io-state ip-address ip-port packet callback) async-io-state)) (defun internal-send-socket (ip port packet nb) (declare (ignore nb)) (internal-udp-cosi-client-send-request 'comm:close-async-io-state ip port packet) )) #| (defun ptst () ;; test requesting a public key (spawn (lambda () (let* ((port (start-ephemeral-server)) (ret (make-return-addr (node-real-ip *my-node*) port))) (labels ((exit () (become 'do-nothing) (unregister-return-addr ret) (shutdown-server port))) (pr :my-port port) #+:LISPWORKS (inspect ret) (send *my-node* :public-key ret) (recv (msg (pr :I-got... msg) (exit)) :TIMEOUT 2 :ON-TIMEOUT (progn (pr :I-timed-out...) (exit)) )))) )) (defun stst (msg) ;; test getting a signature & verifying it (spawn (lambda () (let* ((port (start-ephemeral-server)) (ret (make-return-addr (node-real-ip *my-node*) port))) (labels ((exit () (become 'do-nothing) (unregister-return-addr ret) (shutdown-server port))) (pr :my-port port) #+:LISPWORKS (inspect ret) (send *top-node* :cosi ret msg) (recv ((list :answer (and packet (list :signature xmsg sig))) (pr :I-got... packet) (pr (format nil "Witnesses: ~A" (logcount (um:last1 sig)))) (send *my-node* :validate ret msg sig) (recv (ansv (pr :Validation ansv) (exit)) :TIMEOUT 1 :ON-TIMEOUT (pr :timed-out-on-signature-verification) (exit))) (xmsg (pr :what!? xmsg) (exit)) :TIMEOUT 15 :ON-TIMEOUT (progn (pr :I-timed-out...) (exit)) )))) )) |# ;; -------------------------------------------------------------- (defun make-hmac (msg skey uuid) ;; Every packet sent to another node is accompanied by an HMAC that ;; is unforgeable. If a MITM attack occurs, the receiving node will ;; fail HMAC verification and just drop the incoming packet on the ;; floor. So MITM modifications become tantamount to a DOS attack. (multiple-value-bind (v vpt) (ed-random-pair) (let* ((c (hash-pt-msg vpt msg)) (r (with-mod *ed-r* (m- v (m* c skey))))) (list msg r c uuid)))) (defun verify-hmac (quad) ;; Every incoming packet is scrutinized for a valid HMAC. If it ;; checks out then the packet is dispatched to an operation. ;; Otherwise it is just dropped on the floor. (when (and (consp quad) (= 4 (length quad))) (destructuring-bind (msg r c uuid) quad (let* ((node (gethash uuid *uuid-node-tbl*)) (pkey (node-pkey node)) (vpt (ed-add (ed-nth-pt r) (ed-mul pkey c))) (cc (hash-pt-msg vpt msg))) (values msg (= cc c)) )))) ;; -------------------------------------------------------------------- ;; Message handlers for verifier nodes (defun node-validate-cosi (node msg sig) ;; toplevel entry for Cosi signature validation checking (declare (ignore node)) ;; not needed here... (destructuring-bind (c r ids) sig (let* ((tkey (reduce (lambda (ans node) (if (and node (logbitp (node-bit node) ids)) (ed-add ans (node-pkey node)) ans)) *node-bit-tbl* :initial-value (ed-neutral-point))) (vpt (ed-add (ed-nth-pt r) (ed-mul tkey c))) (h (hash-pt-msg vpt msg))) (= h c)) )) ;; ----------------------------------------------------------------------- #-:LISPWORKS (defparameter *dly-instr* (ac:make-actor (lambda (&rest args) (declare (ignore args)) t))) #+:LISPWORKS (defparameter *dly-instr* (ac:make-actor (let ((data nil) (pltsym :plt)) (um:dlambda (:incr (dly) #+:LISPWORKS (push dly data)) (:clr () (setf data nil)) (:pltwin (sym) (setf pltsym sym)) (:plt () #+:LISPWORKS (plt:histogram pltsym data :clear t :ylog t :xrange '(0 1.2) :thick 2 ;; :cum t :norm nil :title "Measured Delay Ratios" :xtitle "Delay-Ratio" :ytitle "Counts") (plt:plot pltsym '(1 1) '(0.1 1e6) :color :red)) )))) ;; ----------------------------------------------------------------------- (defun msg-ok (msg node) (declare (ignore msg)) (not (node-byz node))) ;; for now... should look at node-byz to see how to mess it up (defun mark-node-no-response (node sub) (declare (ignore node sub)) ;; for now... nil) (defun mark-node-corrupted (node sub) (declare (ignore node)) ;; for now... (setf (node-bad sub) t) nil) ;; ----------------------- (defun clear-bad () (send-real-nodes :reset)) (defun node-reset-nodes (node) (declare (ignore node)) (loop for node across *node-bit-tbl* do (setf (node-bad node) nil))) ;; --------------- (defun send-subs (node &rest msg) (iter-subs node (lambda (sub) (apply 'send sub msg)))) (defun group-subs (node) (um:accum acc (iter-subs node #'acc))) (defun send-real-nodes (&rest msg) (loop for ip in *real-nodes* do (apply 'send (gethash ip *ip-node-tbl*) msg))) ;; ----------------------------------------------------------------------- (defun sub-commitment (my-ip msg seq-id) (=lambda (node) (let ((start (get-universal-time)) (timeout 10 ;; (* (node-load node) *default-timeout-period*) ) (ret-addr (make-return-addr my-ip))) (send node :commitment ret-addr msg seq-id) (labels ((!dly () #+:LISPWORKS (send *dly-instr* :incr (/ (- (get-universal-time) start) timeout))) (=return (val) (!dly) (unregister-return-addr ret-addr) (=values val)) (wait () (recv ((list* :commit sub-seq ans) (if (eql sub-seq seq-id) (=return ans) (wait))) (_ (wait)) :TIMEOUT timeout :ON-TIMEOUT (progn (pr (format nil "SubCommitment timeout waiting for ~A" (node-ip node))) (=return nil)) ))) (wait)) ))) (defun node-cosi-commitment (node reply-to msg seq-id) ;; ;; First phase of Cosi: ;; Generate a fresh random ECC pair: (v, v*G) ;; ;; Decide if msg warrants a commitment. If so add our contribution ;; to the random challenge, hold on to the secret seed, v. Collect ;; contributions from group members and add to the random ;; challenge ECC pt. ;; ;; Compute local validity challenges for all the group members. ;; ;; Return both the accumulated random point and our particular ;; point for use in the local validity challenge. ;; (multiple-value-bind (v vpt) (ed-random-pair) (let* ((subs (remove-if 'node-bad (group-subs node))) (ok (msg-ok msg node)) (bits (if ok (node-bitmap node) 0)) (vsum (if ok vpt (ed-neutral-point)))) (setf (node-seq node) seq-id (node-parts node) nil (node-v node) v (node-ok node) ok) ;; indicate our participation in phase 1 (=bind (lst) (pmapcar (sub-commitment (node-real-ip node) msg seq-id) subs) (labels ((fold-answer (ans sub) (cond ((null ans) (pr (format nil "No commitmemt: ~A" (node-ip sub))) (mark-node-no-response node sub)) (t (destructuring-bind (sub-ptsum sub-pt sub-bits) ans ;; fold in the subtree answer (setf bits (logior bits sub-bits) vsum (ed-add vsum (ed-decompress-pt sub-ptsum))) ;; compute a random challenge for node validity checking (let ((chk (hash-pt-msg (ed-decompress-pt sub-pt) msg))) ;; accumulate participants for phase 2 (push (list sub msg chk) (node-parts node)) ))) ))) (mapc #'fold-answer lst subs) (send reply-to :commit seq-id (ed-compress-pt vsum) (ed-compress-pt vpt) bits) ))))) ;; ------------------------------ (defun sub-signing (my-ip c seq-id) (=lambda (node chk) (let ((start (get-universal-time)) (timeout 10 ;; (* (node-load node) *default-timeout-period*) ) (ret-addr (make-return-addr my-ip))) (send node :signing ret-addr c chk seq-id) (labels ((!dly () #+:LISPWORKS (send *dly-instr* :incr (/ (- (get-universal-time) start) timeout))) (=return (val) (!dly) (unregister-return-addr ret-addr) (=values val)) (wait () (recv ((list* :signed sub-seq ans) (if (eql sub-seq seq-id) (=return ans) ;; else (wait))) ((list (or :missing-node :invalid-commitment) sub-seq) (if (eql sub-seq seq-id) (=return nil) ;; else (wait))) (_ (wait)) :TIMEOUT timeout :ON-TIMEOUT (progn (pr (format nil "SubSigning timeout waiting for ~A" (node-ip node))) (=return nil)) ))) (wait)) ))) (defun node-cosi-signing (node reply-to c c1 seq-id) ;; ;; Second phase of Cosi: ;; Given challenge value c, compute the signature value ;; r = v - c * skey. ;; If we decided against signing in the first phase, ;; then we shouldn't even be called ;; (cond ((and (integerp c) ;; valid setup for phase 2? (integerp c1) (eql seq-id (node-seq node))) (labels ((compute-signage (challenge) (with-mod *ed-r* (m- (node-v node) (m* challenge (node-skey node)))))) (let* ((ok (node-ok node)) ;; did we participate in phase 1? (subs (mapcar 'first (node-parts node))) (chks (mapcar 'third (node-parts node))) (rsum (if ok (compute-signage c) 0)) (r1 (compute-signage c1)) (missing nil)) (setf (node-v node) nil ;; done with these (node-seq node) nil) (=bind (r-lst) (pmapcar (sub-signing (node-real-ip node) c seq-id) subs chks) (labels ((fold-answer (sub-rs sub-chk) (destructuring-bind (sub msg chk) sub-chk (cond ((null sub-rs) ;; no response from node, or bad subtree (pr (format nil "No signing: ~A" sub)) (mark-node-no-response node sub) (setf missing t)) (t (destructuring-bind (sub-r sub-r1) sub-rs ;; first validate the sub (if (node-validate-cosi node msg (list chk sub-r1 (node-bitmap sub))) (unless missing ;; sub was ok, but if we had some missing ;; subs, don't waste time computing ;; anything (with-mod *ed-r* (setf rsum (m+ rsum sub-r)))) (progn ;; sub gave a corrupt answer on the local challenge (pr (format nil "Corrupt node: ~A" (node-ip sub))) (mark-node-corrupted node sub) (setf missing t)) ))) )))) (mapc #'fold-answer r-lst (node-parts node)) (if missing (send reply-to :missing-node seq-id) (send reply-to :signed seq-id rsum r1)) ))))) (t ;; else -- bad args (send reply-to :invalid-commitment seq-id)) ;; request restart )) ;; ----------------------------------------------------------- (defun node-compute-cosi (node reply-to msg) ;; top-level entry for Cosi signature creation ;; assume for now that leader cannot be corrupted... (let ((sess (gen-uuid-int)) (self (current-actor))) (ac:self-call :commitment self msg sess) (labels ((unknown-message (msg) (error "Unknown message: ~A" msg)) (wait-commitment () (recv ((list :commit seq vpt vsubpt bits) (cond ((eql seq sess) ;; compute global challenge (let ((c (hash-pt-msg (ed-decompress-pt vpt) msg)) (c1 (hash-pt-msg (ed-decompress-pt vsubpt) msg))) (ac:self-call :signing self c c1 sess) (labels ((wait-signing () (recv ((list :signed seq r r1) (declare (ignore r1)) (cond ((eql seq sess) (let ((sig (list c r bits))) (if (node-validate-cosi node msg sig) ;; we completed successfully (reply reply-to (list :signature msg sig)) ;; bad signature, try again (reply reply-to :corrupt-cosi-network) ))) (t ;; seq mismatch ;; must have been a late arrival (wait-signing)) )) ((list :missing-node seq) (cond ((eql seq sess) ;; retry from start (pr "Witness dropout, signing restart") (node-compute-cosi node reply-to msg)) (t ;; seq mismatch ;; must have been a late arrival (wait-signing)) )) ((list :invalid-commitment seq) (cond ((eql seq sess) (pr "Invalid commitment, signing restart") (node-compute-cosi node reply-to msg)) (t ;; seq mismatch ;; must have been a late arrival (wait-signing)) )) (msg ;; other messages during signing phase (unknown-message msg)) ))) (wait-signing)) )) ;; end of big COND clause ;; ------------------------------------ (t ;; seq mismatch ;; must have been a late arrival (wait-commitment)) )) ;; end of message pattern ;; --------------------------------- (msg ;; other messages during commitment phase (unknown-message msg)) ))) (wait-commitment)))) #| ;; FOR TESTING!!! (setup-server) (set-executive-pool 1) (setf *real-nodes* (list *leader-node*)) (setf *real-nodes* (remove "10.0.1.13" *real-nodes* :test 'string-equal)) (generate-tree :nel 100) (reconstruct-tree) |# (defun tst () (spawn (lambda () (send *dly-instr* :clr) (send *dly-instr* :pltwin :histo-4) (let ((ret (make-return-addr (node-real-ip *my-node*))) (start (get-universal-time))) (labels ((exit () (unregister-return-addr ret))) (send *top-node* :cosi ret "This is a test message!") (recv ((list :answer (and msg (list :signature txt (and sig (list _ _ bits))))) (send *dly-instr* :plt) (ac:pr (format nil "Total Witnesses: ~D" (logcount bits)) msg (format nil "Duration = ~A" (- (get-universal-time) start))) (send *my-node* :validate ret txt sig) (recv ((list :answer :validation t/f) (if t/f (ac:pr :valid-signature) (ac:pr :invalid-signature)) (exit)) (msg (error "ValHuh?: ~A" msg) (exit)) )) (msg (error "Huh? ~A" msg) (exit)) )))))) ;; ------------------------------------------------------------- (defvar *dachshund* "10.0.1.3") (defvar *malachite* "10.0.1.6") (defvar *rambo* "10.0.1.13") (defmethod damage ((ip string) t/f) (damage (gethash ip *ip-node-tbl*) t/f)) (defmethod damage ((node node) t/f) (setf (node-byz node) t/f)) (defun init-sim () (shutdown-server) (reconstruct-tree) (start-server))
true
;; random-partition.lisp -- Generate simulation trees of network nodes for Cosi ;; ;; DM/Emotiq 02/18 ;; ------------------------------------------------------------------------- #| The MIT License Copyright (c) 2018 PI:NAME:<NAME>END_PI Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. |# (in-package :cosi-simgen) (declaim (optimize (debug 3))) ;; -------------------------------------------------------------------- ;; Physical network (defvar *local-nodes* '(("Malachite.local" . "10.0.1.6") ("Dachshund.local" . "10.0.1.3") ("Rambo" . "10.0.1.13") ("ChromeKote.local" . "10.0.1.36"))) (defun get-local-ipv4 (node-name) (cdr (assoc node-name *local-nodes* :test 'string-equal))) (defun get-my-ipv4 () (get-local-ipv4 (machine-instance))) (defvar *real-nodes* (mapcar 'cdr *local-nodes*)) (defvar *leader-node* (get-local-ipv4 "Dachshund.local")) ;;(defvar *leader-node* (get-local-ipv4 "ChromeKote.local")) (defvar *top-node* nil) ;; current leader node (defvar *my-node* nil) ;; which node my machine is on ;; default-timeout-period needs to be made smarter, based on node height in tree (defparameter *default-timeout-period* ;; good for 1600 nodes on single machine #+:LISPWORKS 10 #+:ALLEGRO 70 #+:CLOZURE 70) ;; ---------------------------------------------------------------------- ;; Network Tree Nodes (defvar *bins-per-node* 9) ;; prolly needs to be >3 for BFT (defun make-subs () (make-array *bins-per-node* :initial-element nil)) (defclass node () ((ip :accessor node-ip ;; IPv4 string for this node :initarg :ip) (uuid :accessor node-uuid ;; UUID for this node :initarg :uuid) (pkeyzkp :accessor node-pkeyzkp ;; public key + ZKP :initarg :pkeyzkp) (skey :accessor node-skey ;; private key :initarg :skey) (pkey :accessor node-pkey ;; cached ECC point for public key :initarg :pkey) (realnode :accessor node-realnode ;; t/f - t when this is a real IPv4 node, nil for fake :initform nil) (parent :accessor node-parent ;; points to node of group parent :initarg :parent :initform nil) (subs :accessor node-subs ;; list of group members beyond self :initarg :subs :initform (make-subs)) (bit :accessor node-bit ;; bit position in bitmap :initform 0) ;; ------------------------------------- (real-ip :accessor node-real-ip ;; real node for this node :initarg :real-ip) (ok :accessor node-ok ;; t if we participated in round 1 :initform nil) (v :accessor node-v ;; first round random seed :initform nil) (seq :accessor node-seq ;; first round ID :initform nil) (byz :accessor node-byz ;; Byzantine misbehav type :initform nil) (parts :accessor node-parts ;; group participants in first round commitment :initform nil) (bad :accessor node-bad ;; if true then node was corrupted :initform nil) (load :accessor node-load ;; cpu loading of group for this node :initform 1) (self :accessor node-self ;; ptr to Actor handler :initarg :self) )) (defmethod node-bitmap ((node node)) (ash 1 (node-bit node))) (defmethod iteri-subs ((node node) fn) (loop for sub across (node-subs node) for ix from 0 when sub do (funcall fn ix sub))) (defmethod iter-subs ((node node) fn) (iteri-subs node (lambda (ix sub) (declare (ignore ix)) (funcall fn sub)))) (defmethod set-node-load (node) (setf (node-load node) (1+ (loop for sub across (node-subs node) when sub sum (node-load sub))))) ;; -------------------------------------------------------------------- ;; For now, 4 different ways to specify a node: ;; 1. node structure pointer ;; 2. IPv4 address (in dotted string notation) ;; 3. UUID (needs uuid-to-integer for keying *uuid-node* table) ;; 4. PKEY (compressed public key ECC point) ;; XREF from IPv4 address to Tree Node (defvar *ip-node-tbl* (make-hash-table :test 'equal)) ;; IPv4 string as key (defvar *uuid-node-tbl* (make-hash-table)) ;; UUID integer as key (defvar *pkey-node-tbl* (make-hash-table)) ;; compressed ECC pt integer as key (defvar *pkey-skey-tbl* (make-hash-table)) ;; commpressed ECC pt integer as key ;; ------------------------------------------------------------------- (defvar *comm-ip* nil) (defun make-node (ipstr uuid pkeyzkp parent) (let* ((cmpr-pkey (third pkeyzkp)) (node (make-instance 'node :ip ipstr :uuid uuid :skey (gethash cmpr-pkey *pkey-skey-tbl*) :pkey (edec:ed-decompress-pt cmpr-pkey) :pkeyzkp pkeyzkp :parent parent :real-ip *comm-ip* ))) (setf (node-self node) (make-node-dispatcher node) (gethash ipstr *ip-node-tbl*) node (gethash (node-uuid node) *uuid-node-tbl*) node (gethash cmpr-pkey *pkey-node-tbl*) node))) (defun need-to-specify (&rest args) (declare (ignore args)) (error "Need to specify...")) #+:ALLEGRO (defun allegro-dotted-to-integer (string) (multiple-value-bind (start end starts ends) (#~m/^([0-9]+).([0-9]+).([0-9]+).([0-9]+)$/ string) (declare (ignore start end)) (reduce (lambda (ans pair) (destructuring-bind (start . end) pair (logior (ash ans 8) (parse-integer string :start start :end end)))) (nreverse (pairlis (coerce starts 'list) (coerce ends 'list))) :initial-value 0))) #+:ALLEGRO (defun allegro-integer-to-dotted (val) (let ((parts (um:nlet-tail iter ((n 4) (pos 0) (ans nil)) (if (zerop n) ans (iter (1- n) (+ pos 8) (cons (ldb (byte 8 pos) val) ans))) ))) (format nil "~{~d~^.~}" parts))) (defun dotted-string-to-integer (string) #+:LISPWORKS (comm:string-ip-address string) #+:OPENMCL (ccl::dotted-to-ipaddr string) #+:ALLEGRO (allegro-dotted-to-integer string)) (defun integer-to-dotted-string (val) #+:LISPWORKS (comm:ip-address-string val) #+:OPENMCL (CCL::ipaddr-to-dotted val) #+:ALLEGRO (allegro-integer-to-dotted val)) (defun gen-uuid-int () (uuid:uuid-to-integer (uuid:make-v1-uuid))) (defun gen-node-id (ip) (if (consp ip) (values-list ip) (multiple-value-bind (skey pkey) (edec:ed-random-pair) (let ((zkp (compute-pkey-zkp skey pkey))) (setf (gethash (third zkp) *pkey-skey-tbl*) skey) (values ip (gen-uuid-int) zkp) )))) ;; ------------------------------------------------------------- (defvar *node-bit-tbl* #()) (defun assign-bits () ;; assign bit positions to each node (let ((collected (um:accum acc (maphash (lambda (k node) (declare (ignore k)) (acc node)) *ip-node-tbl*)))) (setf collected (sort collected '< :key 'node-uuid)) (loop for node in collected for ix from 0 do (setf (node-bit node) ix)) (setf *node-bit-tbl* (coerce collected 'vector)) )) ;; ------------------------------------------------------------------- ;; Node construction (defun partition (node ip-list &key (key 'identity)) (let* ((bins (make-subs)) (nbins (length bins)) (vnode (dotted-string-to-integer (node-ip node)))) (mapc (lambda (ip-arg) (let* ((vip (dotted-string-to-integer (funcall key ip-arg))) (ix (mod (logxor vnode vip) nbins))) (push ip-arg (aref bins ix)))) ip-list) (setf (node-subs node) bins))) (defun inner-make-node-tree (ip ip-list &optional parent) (multiple-value-bind (ipstr uuid pkeyzkp) (gen-node-id ip) (let ((node (make-node ipstr uuid pkeyzkp parent))) (when ip-list (let ((bins (partition node ip-list :key (lambda (ip-arg) (if (consp ip-arg) (car ip-arg) ip-arg))))) (iteri-subs node (lambda (ix subs) (setf (aref bins ix) (inner-make-node-tree (car subs) (cdr subs) node)))) (set-node-load node))) node))) (defun make-node-tree (ip vlist) ;; main entry point - captures IPv4 of arg ip for use as real-ip in ;; succeeding nodes (multiple-value-bind (ipstr uuid pkeyzp) (gen-node-id ip) (let ((*comm-ip* ipstr)) (inner-make-node-tree (list ipstr uuid pkeyzp) vlist)))) ;; -------------------------------------------------------------------- ;; for visual debugging... #+:LISPWORKS (progn (defmethod children (x layout) nil) (defmethod children ((node node) layout) (remove nil (coerce (node-subs node) 'list))) (defun split-to-octets (val) (um:nlet-tail iter ((n 4) (val val) (lst nil)) (if (zerop n) lst (iter (1- n) (ash val -8) (cons (ldb (byte 8 0) val) lst))) )) (defclass red-text (capi:item-pinboard-object) ()) (defclass black-text (capi:item-pinboard-object) ()) (defmethod capi:draw-pinboard-object :around (pinboard (self red-text) &key &allow-other-keys) (gp:with-graphics-state (pinboard :foreground :red) (call-next-method))) (defmethod make-node-pane (graphics-port (node node)) (declare (ignore graphics-port)) (let ((txt (node-ip node))) (make-instance (if (node-realnode node) 'red-text 'black-text) :text txt))) (defmethod view-tree ((tree node) &key (layout :left-right)) (capi:contain (make-instance 'capi:graph-pane :layout-function layout :roots (list tree) :node-pane-function 'make-node-pane :children-function (lambda (node) (children node layout)) )))) ;; -------------------------------------------------------------------- ;; Initial Tree Generation and Persistence (defvar *default-data-file* "cosi-nodes.txt") (defvar *default-key-file* "cosi-keying.txt") (defun generate-ip () ;; generate a unique random IPv4 address (let ((ip (integer-to-dotted-string (random #.(expt 2 32))))) (if (gethash ip *ip-node-tbl*) (generate-ip) ;; should be unlikely, would be 50% at around 2^16 nodes (setf (gethash ip *ip-node-tbl*) ip)))) (defmethod pair-ip-uuid ((node node)) (list (node-ip node) (node-uuid node) (node-pkeyzkp node))) (defmethod pair-ip-uuid ((ip string)) (pair-ip-uuid (gethash ip *ip-node-tbl*))) (defun gen-main-tree (leader real-nodes grps) (let* ((trees (mapcar 'make-node-tree real-nodes grps)) (main-tree (find leader trees :test 'string= :key 'node-ip))) ;; mark the real nodes as special (mapc (lambda (tree) (setf (node-realnode tree) t)) trees) ;; attach the non-leader real nodes to the leader node (let ((all-but (remove main-tree trees))) (setf (node-subs main-tree) (concatenate 'vector (node-subs main-tree) (apply 'vector all-but))) (dolist (tree all-but) (setf (node-parent tree) main-tree))) main-tree)) ;; -------------------------------------------------------------- ;; Generate Tree / Keying and save to startup init files (defun generate-tree (&key fname (nel 1000)) (let* ((leader *leader-node*) (real-nodes (remove-duplicates *real-nodes* :test 'string=))) ;; ensure leader is in the real-nodes collection (assert (member leader real-nodes :test 'string=)) ;; pre-populate hash table with real-nodes (clrhash *ip-node-tbl*) (clrhash *uuid-node-tbl*) (clrhash *pkey-node-tbl*) (clrhash *pkey-skey-tbl*) (dolist (ip real-nodes) (setf (gethash ip *ip-node-tbl*) ip)) ;; build the trees (let* ((nreal (length real-nodes)) (nel/grp (ceiling nel nreal)) (grps (loop repeat nreal collect (loop repeat nel/grp collect (generate-ip)))) (main-tree (gen-main-tree leader real-nodes grps))) ;; save nodes as a text file for later (with-open-file (f (merge-pathnames #+:LISPWORKS (sys:get-folder-path :documents) #+(OR :ALLEGRO :OPENMCL) "~/Documents/" (or fname *default-data-file*)) :direction :output :if-does-not-exist :create :if-exists :rename) (with-standard-io-syntax (let ((*print-readably* t) ;; to get readable UUID's (*print-right-margin* 128)) (pprint `(:leader ,leader :real-nodes ,(mapcar 'pair-ip-uuid real-nodes) :groups ,(mapcar (lambda (grp) (mapcar 'pair-ip-uuid grp)) grps)) f)))) ;; write the pkey/skey associations (with-open-file (f (merge-pathnames #+:LISPWORKS (sys:get-folder-path :documents) #+(OR :ALLEGRO :OPENMCL) "~/Documents/" *default-key-file*) :direction :output :if-does-not-exist :create :if-exists :rename) (let ((keys nil)) (maphash (lambda (k v) (push (cons k v) keys)) *pkey-skey-tbl*) (with-standard-io-syntax (pprint keys f)))) (assign-bits) #+:LISPWORKS (view-tree main-tree) (setf *my-node* main-tree *top-node* main-tree) ))) ;; --------------------------------------------------------------- ;; Tree reconstruction from startup init files (defun read-data-file (path) (with-open-file (f path :direction :input) (read f))) (defun reconstruct-tree (&key fname) ;; read the keying file (let* ((key-path (merge-pathnames #+:LISPWORKS (sys:get-folder-path :documents) #+(OR :ALLEGRO :OPENMCL) "~/Documents/" *default-key-file*)) (keys (read-data-file key-path)) (data-path (merge-pathnames #+:LISPWORKS (sys:get-folder-path :documents) #+(OR :ALLEGRO :OPENMCL) "~/Documents/" (or fname *default-data-file*))) (data (read-data-file data-path)) (leader (getf data :leader)) (real-nodes (getf data :real-nodes)) (grps (getf data :groups))) ;; sanity checking (assert (member leader real-nodes :test 'string= :key 'car)) (labels ((no-dups (lst) (dolist (ip lst) (destructuring-bind (ipstr uuid zkp) ip (assert (null (gethash ipstr *ip-node-tbl*))) (assert (null (gethash uuid *uuid-node-tbl*))) (destructuring-bind (r c pcmpr) zkp (declare (ignore r c)) (assert (null (gethash pcmpr *pkey-node-tbl*))) (check-pkey zkp) (setf (gethash ipstr *ip-node-tbl*) ip (gethash uuid *uuid-node-tbl*) ip (gethash pcmpr *pkey-node-tbl*) ip) ))))) (clrhash *ip-node-tbl*) (clrhash *uuid-node-tbl*) (clrhash *pkey-node-tbl*) (no-dups real-nodes) (mapc #'no-dups grps)) ;; reconstruct keying info (clrhash *pkey-skey-tbl*) (mapc (lambda (pair) (destructuring-bind (k . v) pair ;; k is integer, compressed pkey ECC pt ;; v is skey integer ;; decompression checks for valid ECC pt (assert (ed-pt= (ed-nth-pt v) (ed-decompress-pt k))) (setf (gethash k *pkey-skey-tbl*) v))) keys) ;; reconstruct the trees (let ((main-tree (gen-main-tree leader real-nodes grps))) (assign-bits) #+:LISPWORKS (view-tree main-tree) (setf *top-node* main-tree *my-node* (gethash (get-my-ipv4) *ip-node-tbl*))))) ;; --------------------------------------------------------------- ;; New leader node election... tree rearrangement (defun notify-real-descendents (node &rest msg) (labels ((recurse (sub-node) (if (node-realnode sub-node) (apply 'send sub-node msg) (iter-subs sub-node #'recurse)))) (iter-subs node #'recurse))) (defun all-nodes-except (node) (delete node (um:accum acc (maphash (um:compose #'acc 'um:snd) *ip-node-tbl*)))) (defun node-model-rebuild-tree (parent node nlist) (let ((bins (partition node nlist :key 'node-ip))) (iteri-subs node (lambda (ix subs) (setf (aref bins ix) (node-model-rebuild-tree node (car subs) (cdr subs))))) (setf (node-parent node) parent) (set-node-load node) node)) (defun node-elect-new-leader (new-leader-ip) (let ((new-top-node (gethash new-leader-ip *ip-node-tbl*))) ;; Maybe... ready for prime time? (cond ((null new-top-node) (error "Not a valid leader node: ~A" new-leader-ip)) ((eq new-top-node *top-node*) ;; nothing to do here... ) (t (setf *top-node* new-top-node) (node-model-rebuild-tree nil new-top-node (all-nodes-except new-top-node)) ;; ;; The following broadcast will cause us to get another ;; notification, but by then the *top-node* will already ;; have been set to new-leader-ip, and so no endless loop ;; will occur. ;; (notify-real-descendents new-top-node :election new-leader-ip)) ))) ;; --------------------------------------------------------- ;; Node insertion/change (defun bin-for-ip (node ip) (let ((vnode (dotted-string-to-integer (node-ip node))) (vip (dotted-string-to-integer ip))) (mod (logxor vnode vip) (length (node-subs node))))) (defun increase-loading (parent-node) (when parent-node (incf (node-load parent-node)) (increase-loading (node-parent parent-node)))) (defun node-model-insert-node (node new-node-info) ;; info is (ipv4 UUID pkeyzkp) (destructuring-bind (ipstr uuid pkeyzkp) new-node-info (let* ((ix (bin-for-ip node ipstr)) (bins (node-subs node)) (sub-node (aref bins ix))) (if sub-node ;; continue in parallel with our copy of tree (node-model-insert-node sub-node new-node-info) ;; else (let ((new-node (make-node ipstr uuid pkeyzkp node))) (setf (node-real-ip new-node) ipstr (node-realnode new-node) t (node-skey new-node) nil (aref bins ix) new-node) (incf (node-load node)) (increase-loading (node-parent node))) )))) (defun node-insert-node (node new-node-info) (destructuring-bind (ipstr uuid pkeyzkp) new-node-info (let ((new-node (gethash ipstr *ip-node-tbl*))) (if new-node ;; already present in tree? ;; maybe caller just wants to change UUID or keying ;; won't be able to sign unless it know skey (multiple-value-bind (pkey ok) (check-pkey pkeyzkp) (when ok (setf (node-uuid new-node) uuid (node-pkeyzkp new-node) pkeyzkp (node-pkey new-node) pkey ;; cache the decompressed key (node-realnode new-node) t (node-real-ip new-node) ipstr))) ;; else - not already present (node-model-insert-node *top-node* new-node-info)))) (notify-real-descendents node :insert-node new-node-info)) ;; --------------------------------------------------------- (defun node-model-remove-node (gone-node) (remhash (node-ip gone-node) *ip-node-tbl*) (remhash (node-uuid gone-node) *uuid-node-tbl*) (let ((pcmpr (third (node-pkeyzkp gone-node)))) (remhash pcmpr *pkey-node-tbl*) (remhash pcmpr *pkey-skey-tbl*))) (defun node-remove-node (node gone-node-ipv4) (let ((gone-node (gethash gone-node-ipv4 *ip-node-tbl*))) (when gone-node (node-model-remove-node gone-node) ;; must rebuild tree to absorb node's subnodes (node-model-rebuild-tree nil *top-node* (all-nodes-except *top-node*)) (when (eq node *top-node*) (notify-real-descendents node :remove-node gone-node-ipv4))))) ;; ----------------------------------------------------------------- (defun NYI (&rest args) (error "Not yet implemented: ~A" args)) ;; ------------------------------------------------------- (defun make-node-dispatcher (node) ;; use indirection to node-dispatcher for while we are debugging and ;; extending the dispatcher. Saves reconstructing the tree every ;; time the dispatching chanages. (ac:make-actor ;; one of these closures is stored in the SELF slot of every node (lambda (&rest msg) (apply 'node-dispatcher node msg)))) (defun crash-recovery () (maphash (lambda (k node) (declare (ignore k)) (setf (node-self node) (make-node-dispatcher node))) *ip-node-tbl*)) (defun node-dispatcher (node &rest msg) (um:dcase msg ;; ---------------------------- ;; user accessible entry points - directed to leader node (:cosi (reply-to msg) (node-compute-cosi node reply-to msg)) (:validate (reply-to msg sig) (reply reply-to :validation (node-validate-cosi node msg sig))) (:public-key (reply-to) (reply reply-to :pkey+zkp (node-pkeyzkp node))) (:add/change-node (new-node-info) (node-insert-node node new-node-info)) (:remove-node (node-ip) (node-remove-node node node-ip)) (:election (new-leader-ip) (node-elect-new-leader new-leader-ip)) ;; ------------------------------- ;; internal comms between Cosi nodes (:commitment (reply-to msg seq) (node-cosi-commitment node reply-to msg seq)) (:signing (reply-to c c1 seq) (node-cosi-signing node reply-to c c1 seq)) ;; ----------------------------------- ;; for sim and debug (:answer (&rest msg) ;; for round-trip testing (ac:pr msg)) (:reset () (node-reset-nodes node)) (t (&rest msg) (error "Unknown message: ~A~%Node: ~A" msg (node-ip node))) )) ;; ------------------------------------------------------------------ ;; GET-PUBLIC-KEY - This is here primarily for testing the network. ;; Not really an RPC call, and results will show in the output ;; browser, not returned to caller. ;; ;; RPC violates the basic premise of the point-and-shoot design. ;; Responders are free to ignore, be deaf, or send us garbage at any ;; time. ;; ;; The design of the system is aimed at coexistence in a Byzantine network. ;; (defun get-public-key (uuid) (let ((node (gethash uuid *uuid-node-tbl*))) (when node (spawn (lambda () (let ((ret (make-return-addr (node-real-ip *my-node*)))) (send node :public-key ret) (recv (msg (unregister-return-addr ret) (pr msg)) ))) )))) #| (send *top-node* :public-key (make-node-ref *my-node*)) ==> see results in output window (:PKEY+ZKP (849707610687761353988031598913888011454228809522136330182685594047565816483 77424688591828692687552806917061506619936267795838123291694715575735109065947 2463653704506470449709613051914446331689964762794940591210756129064889348739)) COSI-SIMGEN 23 > (send (gethash "10.0.1.6" *ip-node-tbl*) :public-key (make-node-ref *my-node*)) Connecting to #$(NODE "10.0.1.6" 65000) (FORWARDING "10.0.1.6" (QUOTE ((:PUBLIC-KEY #<NODE-REF 40200014C3>) 601290835549702797100992963662352678603116278028765925372703953633797770499 56627041402452754830116071111198944351637771601751353481660603190062587211624 23801716726735741425848558528841292842))) ==> output window (:PKEY+ZKP (PI:KEY:<KEY>END_PI0PI:KEY:<KEY>END_PI12136PI:KEY:<KEY>END_PI8PI:KEY:<KEY>END_PI0PI:KEY:<KEY>END_PI05812PI:KEY:<KEY>END_PI818001884231695959658747310415728976873583 19894104797779289660345137228823739121774277312822467740314566093297448396984 2080524722754689845098528285145820902670538507089109456806581872878115260191)) |# ;; ---------------------------- (defvar *cosi-port* 65001) (defclass return-addr () ((ip :accessor return-addr-ip ;; the real IPv4 for returns :initarg :ip) (port :accessor return-addr-port ;; the real IPv4 port for returns :initarg :port) (aid :accessor return-addr-aid ;; actor id for returns :initarg :aid))) (defvar *aid-tbl* ;; assoc between Actors and AID's #+:LISPWORKS (make-hash-table :weak-kind :value) #+:ALLEGRO (make-hash-table :values :weak) #+:CLOZURE (make-hash-table :weak :value) ) (defmethod unregister-return-addr ((ret return-addr)) (remhash (return-addr-aid ret) *aid-tbl*) (become 'do-nothing)) (defmethod make-return-addr ((ipv4 string) &optional (port *cosi-port*)) ;; can only be called from within an Actor body (let ((aid (gen-uuid-int)) (self (current-actor))) (unless self (error "MAKE-RETURN-ADDR can only be performed by an Actor")) (setf (gethash aid *aid-tbl*) self) (make-instance 'return-addr :ip ipv4 :port port :aid aid))) ;; ----------------------------------------------------------- (defmethod send ((node node) &rest msg) (unless (node-byz node) (socket-send (node-ip node) (node-real-ip node) *cosi-port* msg))) (defmethod send ((ref return-addr) &rest msg) (socket-send ref (return-addr-ip ref) (return-addr-port ref) msg)) (defmethod send ((node null) &rest msg) (ac:pr :sent-to-null msg) msg) (defmethod send (dest &rest msg) (apply 'ac:send dest msg)) ;; ----------------- (defun reply (reply-to &rest msg) (apply 'send reply-to :answer msg)) ;; ----------------------------------------------------- ;; THE SOCKET INTERFACE... ;; ----------------------------------------------------- (defvar *max-buffer-length* 65500) (defun cosi-service-handler (buf) (multiple-value-bind (ans err) (ignore-errors (loenc:decode buf)) (unless err (multiple-value-bind (packet t/f) (verify-hmac ans) (when t/f (destructuring-bind (dest msg-verb &rest msg-args) packet (cond ((eql :SHUTDOWN-SERVER msg-verb) :SHUTDOWN-SERVER) (t (let ((true-dest (dest-ip dest))) ;; for debug... ------------------- (when (eq true-dest (node-self *my-node*)) (pr (format nil "forwarding-to-me: ~A" (cons msg-verb msg-args)))) ;; ------------------ (apply 'send true-dest msg-verb msg-args) t)) ))) )))) (defun shutdown-server (&optional (port *cosi-port*)) (when *my-node* (let ((me (node-ip *my-node*))) (socket-send me me port '(:SHUTDOWN-SERVER))))) (defun socket-send (ip real-ip real-port msg) (let* ((quad (make-hmac (list* ip msg) (node-skey *my-node*) (node-uuid *my-node*))) (packet (loenc:encode quad)) (nb (length packet))) (internal-send-socket real-ip real-port packet nb))) ;; ------------------------------------------------------------------ (defmethod dest-ip ((ip string)) (let ((node (gethash ip *ip-node-tbl*))) (when node (node-self node)))) (defmethod dest-ip ((ret return-addr)) (gethash (return-addr-aid ret) *aid-tbl*)) ;; ------------------------------------------------------------------ ;; deprecated... #+:xLISPWORKS (progn ;; TCP/IP stream over Butterfly (defun socket-send (ip real-ip msg) ;; replace this with USOCKETS protocol (let* ((quad (make-hmac msg (node-skey *my-node*) (node-uuid *my-node*))) (agent-ip (format nil "eval@~A" real-ip))) ;; (format t "~%SOCKET-SEND: ~A ~A ~A" ip real-ip msg) #+:LISPWORKS (bfly:! agent-ip `(forwarding ,ip ',quad)))) (defun forwarding (dest quad) ;; (format t "~%FORWARDING: ~A ~A" dest quad) (multiple-value-bind (msg t/f) (verify-hmac quad) ;; might want to log incomings that fail the HMAC ;; just dropping on floor here... (when t/f (let ((true-dest (dest-ip dest))) (when true-dest (when (equal true-dest (node-self *my-node*)) (ac:pr (format nil "forwarding-to-me: ~A" msg))) (apply 'send true-dest msg)))) ))) ;; ------------------------------------------------------------------ #-:LISPWORKS (progn ;; USOCKET interface for ACL (defun #1=serve-cosi-port (socket) (let ((maxbuf (make-array *max-buffer-length* :element-type '(unsigned-byte 8)))) ;; (pr :server-starting-up) (unwind-protect (loop (multiple-value-bind (buf buf-len rem-ip rem-port) (usocket:socket-receive socket maxbuf (length maxbuf)) (declare (ignore rem-ip rem-port)) ;; (pr :sock-read buf-len rem-ip rem-port (loenc:decode buf)) (when (eql :SHUTDOWN-SERVER (cosi-service-handler buf)) (return-from #1#)))) ;; unwinding (usocket:socket-close socket) ;; (pr :server-stopped) ))) (defun start-ephemeral-server (&optional (port 0)) (let* ((my-ip (node-real-ip *my-node*)) (socket (usocket:socket-connect nil nil :protocol :datagram :local-host my-ip :local-port port ))) (mpcompat:process-run-function "UDP Cosi Server" nil 'serve-cosi-port socket) (usocket:get-local-port socket))) (defun start-server () (start-ephemeral-server *cosi-port*)) (defun internal-send-socket (ip port packet nb) (let ((socket (usocket:socket-connect ip port :protocol :datagram))) ;(pr :sock-send (length packet) real-ip packet) (unless (eql nb (usocket:socket-send socket packet nb)) (pr :socket-send-error ip packet)) (usocket:socket-close socket) ))) ;; ------------------------------------------------------------------ #+:LISPWORKS (progn ;; LW UDP Async interface (defvar *udp-wait-collection* nil) (defun ensure-udp-wait-state-collection () (or *udp-wait-collection* (let ((new (comm:create-and-run-wait-state-collection "UDP Cosi Service"))) (if (sys:compare-and-swap *udp-wait-collection* nil new) new (progn ; Another process just set it. (comm:wait-state-collection-stop-loop new) *udp-wait-collection*))))) ;; ------------------------- ;; Server side (defun #1=udp-cosi-server-process-request (async-io-state string bytes-num ip-address port-num) (declare (ignore bytes-num ip-address port-num)) (let ((status (comm:async-io-state-read-status async-io-state))) (when status ;; something went wrong (pr (format nil "UDP example server: got error ~s, restarting" status)) (comm:close-async-io-state async-io-state) (start-server) (return-from #1#)) (if (eql :SHUTDOWN-SERVER (cosi-service-handler string)) (comm:close-async-io-state async-io-state) (udp-cosi-server-receive-next async-io-state)))) (defun udp-cosi-server-receive-next (async-io-state ) (comm:async-io-state-receive-message async-io-state (make-array *max-buffer-length* :element-type '(unsigned-byte 8)) 'udp-cosi-server-process-request :needs-address t)) (defun start-ephemeral-server (&optional (port 0)) (let ((async-io-state (comm:create-async-io-state-and-udp-socket (ensure-udp-wait-state-collection) :name "UDP Cosi server socket" :local-port port))) (udp-cosi-server-receive-next async-io-state) (multiple-value-bind (ip-addr ip-port) (comm:async-io-state-address async-io-state) (declare (ignore ip-addr)) ip-port))) (defun start-server () (start-ephemeral-server *cosi-port*)) ;; ----------------- ;; Client side (defun internal-udp-cosi-client-send-request (callback ip-address ip-port packet) (let* ((collection (ensure-udp-wait-state-collection)) (async-io-state (comm:create-async-io-state-and-udp-socket collection))) (comm:async-io-state-send-message-to-address async-io-state ip-address ip-port packet callback) async-io-state)) (defun internal-send-socket (ip port packet nb) (declare (ignore nb)) (internal-udp-cosi-client-send-request 'comm:close-async-io-state ip port packet) )) #| (defun ptst () ;; test requesting a public key (spawn (lambda () (let* ((port (start-ephemeral-server)) (ret (make-return-addr (node-real-ip *my-node*) port))) (labels ((exit () (become 'do-nothing) (unregister-return-addr ret) (shutdown-server port))) (pr :my-port port) #+:LISPWORKS (inspect ret) (send *my-node* :public-key ret) (recv (msg (pr :I-got... msg) (exit)) :TIMEOUT 2 :ON-TIMEOUT (progn (pr :I-timed-out...) (exit)) )))) )) (defun stst (msg) ;; test getting a signature & verifying it (spawn (lambda () (let* ((port (start-ephemeral-server)) (ret (make-return-addr (node-real-ip *my-node*) port))) (labels ((exit () (become 'do-nothing) (unregister-return-addr ret) (shutdown-server port))) (pr :my-port port) #+:LISPWORKS (inspect ret) (send *top-node* :cosi ret msg) (recv ((list :answer (and packet (list :signature xmsg sig))) (pr :I-got... packet) (pr (format nil "Witnesses: ~A" (logcount (um:last1 sig)))) (send *my-node* :validate ret msg sig) (recv (ansv (pr :Validation ansv) (exit)) :TIMEOUT 1 :ON-TIMEOUT (pr :timed-out-on-signature-verification) (exit))) (xmsg (pr :what!? xmsg) (exit)) :TIMEOUT 15 :ON-TIMEOUT (progn (pr :I-timed-out...) (exit)) )))) )) |# ;; -------------------------------------------------------------- (defun make-hmac (msg skey uuid) ;; Every packet sent to another node is accompanied by an HMAC that ;; is unforgeable. If a MITM attack occurs, the receiving node will ;; fail HMAC verification and just drop the incoming packet on the ;; floor. So MITM modifications become tantamount to a DOS attack. (multiple-value-bind (v vpt) (ed-random-pair) (let* ((c (hash-pt-msg vpt msg)) (r (with-mod *ed-r* (m- v (m* c skey))))) (list msg r c uuid)))) (defun verify-hmac (quad) ;; Every incoming packet is scrutinized for a valid HMAC. If it ;; checks out then the packet is dispatched to an operation. ;; Otherwise it is just dropped on the floor. (when (and (consp quad) (= 4 (length quad))) (destructuring-bind (msg r c uuid) quad (let* ((node (gethash uuid *uuid-node-tbl*)) (pkey (node-pkey node)) (vpt (ed-add (ed-nth-pt r) (ed-mul pkey c))) (cc (hash-pt-msg vpt msg))) (values msg (= cc c)) )))) ;; -------------------------------------------------------------------- ;; Message handlers for verifier nodes (defun node-validate-cosi (node msg sig) ;; toplevel entry for Cosi signature validation checking (declare (ignore node)) ;; not needed here... (destructuring-bind (c r ids) sig (let* ((tkey (reduce (lambda (ans node) (if (and node (logbitp (node-bit node) ids)) (ed-add ans (node-pkey node)) ans)) *node-bit-tbl* :initial-value (ed-neutral-point))) (vpt (ed-add (ed-nth-pt r) (ed-mul tkey c))) (h (hash-pt-msg vpt msg))) (= h c)) )) ;; ----------------------------------------------------------------------- #-:LISPWORKS (defparameter *dly-instr* (ac:make-actor (lambda (&rest args) (declare (ignore args)) t))) #+:LISPWORKS (defparameter *dly-instr* (ac:make-actor (let ((data nil) (pltsym :plt)) (um:dlambda (:incr (dly) #+:LISPWORKS (push dly data)) (:clr () (setf data nil)) (:pltwin (sym) (setf pltsym sym)) (:plt () #+:LISPWORKS (plt:histogram pltsym data :clear t :ylog t :xrange '(0 1.2) :thick 2 ;; :cum t :norm nil :title "Measured Delay Ratios" :xtitle "Delay-Ratio" :ytitle "Counts") (plt:plot pltsym '(1 1) '(0.1 1e6) :color :red)) )))) ;; ----------------------------------------------------------------------- (defun msg-ok (msg node) (declare (ignore msg)) (not (node-byz node))) ;; for now... should look at node-byz to see how to mess it up (defun mark-node-no-response (node sub) (declare (ignore node sub)) ;; for now... nil) (defun mark-node-corrupted (node sub) (declare (ignore node)) ;; for now... (setf (node-bad sub) t) nil) ;; ----------------------- (defun clear-bad () (send-real-nodes :reset)) (defun node-reset-nodes (node) (declare (ignore node)) (loop for node across *node-bit-tbl* do (setf (node-bad node) nil))) ;; --------------- (defun send-subs (node &rest msg) (iter-subs node (lambda (sub) (apply 'send sub msg)))) (defun group-subs (node) (um:accum acc (iter-subs node #'acc))) (defun send-real-nodes (&rest msg) (loop for ip in *real-nodes* do (apply 'send (gethash ip *ip-node-tbl*) msg))) ;; ----------------------------------------------------------------------- (defun sub-commitment (my-ip msg seq-id) (=lambda (node) (let ((start (get-universal-time)) (timeout 10 ;; (* (node-load node) *default-timeout-period*) ) (ret-addr (make-return-addr my-ip))) (send node :commitment ret-addr msg seq-id) (labels ((!dly () #+:LISPWORKS (send *dly-instr* :incr (/ (- (get-universal-time) start) timeout))) (=return (val) (!dly) (unregister-return-addr ret-addr) (=values val)) (wait () (recv ((list* :commit sub-seq ans) (if (eql sub-seq seq-id) (=return ans) (wait))) (_ (wait)) :TIMEOUT timeout :ON-TIMEOUT (progn (pr (format nil "SubCommitment timeout waiting for ~A" (node-ip node))) (=return nil)) ))) (wait)) ))) (defun node-cosi-commitment (node reply-to msg seq-id) ;; ;; First phase of Cosi: ;; Generate a fresh random ECC pair: (v, v*G) ;; ;; Decide if msg warrants a commitment. If so add our contribution ;; to the random challenge, hold on to the secret seed, v. Collect ;; contributions from group members and add to the random ;; challenge ECC pt. ;; ;; Compute local validity challenges for all the group members. ;; ;; Return both the accumulated random point and our particular ;; point for use in the local validity challenge. ;; (multiple-value-bind (v vpt) (ed-random-pair) (let* ((subs (remove-if 'node-bad (group-subs node))) (ok (msg-ok msg node)) (bits (if ok (node-bitmap node) 0)) (vsum (if ok vpt (ed-neutral-point)))) (setf (node-seq node) seq-id (node-parts node) nil (node-v node) v (node-ok node) ok) ;; indicate our participation in phase 1 (=bind (lst) (pmapcar (sub-commitment (node-real-ip node) msg seq-id) subs) (labels ((fold-answer (ans sub) (cond ((null ans) (pr (format nil "No commitmemt: ~A" (node-ip sub))) (mark-node-no-response node sub)) (t (destructuring-bind (sub-ptsum sub-pt sub-bits) ans ;; fold in the subtree answer (setf bits (logior bits sub-bits) vsum (ed-add vsum (ed-decompress-pt sub-ptsum))) ;; compute a random challenge for node validity checking (let ((chk (hash-pt-msg (ed-decompress-pt sub-pt) msg))) ;; accumulate participants for phase 2 (push (list sub msg chk) (node-parts node)) ))) ))) (mapc #'fold-answer lst subs) (send reply-to :commit seq-id (ed-compress-pt vsum) (ed-compress-pt vpt) bits) ))))) ;; ------------------------------ (defun sub-signing (my-ip c seq-id) (=lambda (node chk) (let ((start (get-universal-time)) (timeout 10 ;; (* (node-load node) *default-timeout-period*) ) (ret-addr (make-return-addr my-ip))) (send node :signing ret-addr c chk seq-id) (labels ((!dly () #+:LISPWORKS (send *dly-instr* :incr (/ (- (get-universal-time) start) timeout))) (=return (val) (!dly) (unregister-return-addr ret-addr) (=values val)) (wait () (recv ((list* :signed sub-seq ans) (if (eql sub-seq seq-id) (=return ans) ;; else (wait))) ((list (or :missing-node :invalid-commitment) sub-seq) (if (eql sub-seq seq-id) (=return nil) ;; else (wait))) (_ (wait)) :TIMEOUT timeout :ON-TIMEOUT (progn (pr (format nil "SubSigning timeout waiting for ~A" (node-ip node))) (=return nil)) ))) (wait)) ))) (defun node-cosi-signing (node reply-to c c1 seq-id) ;; ;; Second phase of Cosi: ;; Given challenge value c, compute the signature value ;; r = v - c * skey. ;; If we decided against signing in the first phase, ;; then we shouldn't even be called ;; (cond ((and (integerp c) ;; valid setup for phase 2? (integerp c1) (eql seq-id (node-seq node))) (labels ((compute-signage (challenge) (with-mod *ed-r* (m- (node-v node) (m* challenge (node-skey node)))))) (let* ((ok (node-ok node)) ;; did we participate in phase 1? (subs (mapcar 'first (node-parts node))) (chks (mapcar 'third (node-parts node))) (rsum (if ok (compute-signage c) 0)) (r1 (compute-signage c1)) (missing nil)) (setf (node-v node) nil ;; done with these (node-seq node) nil) (=bind (r-lst) (pmapcar (sub-signing (node-real-ip node) c seq-id) subs chks) (labels ((fold-answer (sub-rs sub-chk) (destructuring-bind (sub msg chk) sub-chk (cond ((null sub-rs) ;; no response from node, or bad subtree (pr (format nil "No signing: ~A" sub)) (mark-node-no-response node sub) (setf missing t)) (t (destructuring-bind (sub-r sub-r1) sub-rs ;; first validate the sub (if (node-validate-cosi node msg (list chk sub-r1 (node-bitmap sub))) (unless missing ;; sub was ok, but if we had some missing ;; subs, don't waste time computing ;; anything (with-mod *ed-r* (setf rsum (m+ rsum sub-r)))) (progn ;; sub gave a corrupt answer on the local challenge (pr (format nil "Corrupt node: ~A" (node-ip sub))) (mark-node-corrupted node sub) (setf missing t)) ))) )))) (mapc #'fold-answer r-lst (node-parts node)) (if missing (send reply-to :missing-node seq-id) (send reply-to :signed seq-id rsum r1)) ))))) (t ;; else -- bad args (send reply-to :invalid-commitment seq-id)) ;; request restart )) ;; ----------------------------------------------------------- (defun node-compute-cosi (node reply-to msg) ;; top-level entry for Cosi signature creation ;; assume for now that leader cannot be corrupted... (let ((sess (gen-uuid-int)) (self (current-actor))) (ac:self-call :commitment self msg sess) (labels ((unknown-message (msg) (error "Unknown message: ~A" msg)) (wait-commitment () (recv ((list :commit seq vpt vsubpt bits) (cond ((eql seq sess) ;; compute global challenge (let ((c (hash-pt-msg (ed-decompress-pt vpt) msg)) (c1 (hash-pt-msg (ed-decompress-pt vsubpt) msg))) (ac:self-call :signing self c c1 sess) (labels ((wait-signing () (recv ((list :signed seq r r1) (declare (ignore r1)) (cond ((eql seq sess) (let ((sig (list c r bits))) (if (node-validate-cosi node msg sig) ;; we completed successfully (reply reply-to (list :signature msg sig)) ;; bad signature, try again (reply reply-to :corrupt-cosi-network) ))) (t ;; seq mismatch ;; must have been a late arrival (wait-signing)) )) ((list :missing-node seq) (cond ((eql seq sess) ;; retry from start (pr "Witness dropout, signing restart") (node-compute-cosi node reply-to msg)) (t ;; seq mismatch ;; must have been a late arrival (wait-signing)) )) ((list :invalid-commitment seq) (cond ((eql seq sess) (pr "Invalid commitment, signing restart") (node-compute-cosi node reply-to msg)) (t ;; seq mismatch ;; must have been a late arrival (wait-signing)) )) (msg ;; other messages during signing phase (unknown-message msg)) ))) (wait-signing)) )) ;; end of big COND clause ;; ------------------------------------ (t ;; seq mismatch ;; must have been a late arrival (wait-commitment)) )) ;; end of message pattern ;; --------------------------------- (msg ;; other messages during commitment phase (unknown-message msg)) ))) (wait-commitment)))) #| ;; FOR TESTING!!! (setup-server) (set-executive-pool 1) (setf *real-nodes* (list *leader-node*)) (setf *real-nodes* (remove "10.0.1.13" *real-nodes* :test 'string-equal)) (generate-tree :nel 100) (reconstruct-tree) |# (defun tst () (spawn (lambda () (send *dly-instr* :clr) (send *dly-instr* :pltwin :histo-4) (let ((ret (make-return-addr (node-real-ip *my-node*))) (start (get-universal-time))) (labels ((exit () (unregister-return-addr ret))) (send *top-node* :cosi ret "This is a test message!") (recv ((list :answer (and msg (list :signature txt (and sig (list _ _ bits))))) (send *dly-instr* :plt) (ac:pr (format nil "Total Witnesses: ~D" (logcount bits)) msg (format nil "Duration = ~A" (- (get-universal-time) start))) (send *my-node* :validate ret txt sig) (recv ((list :answer :validation t/f) (if t/f (ac:pr :valid-signature) (ac:pr :invalid-signature)) (exit)) (msg (error "ValHuh?: ~A" msg) (exit)) )) (msg (error "Huh? ~A" msg) (exit)) )))))) ;; ------------------------------------------------------------- (defvar *dachshund* "10.0.1.3") (defvar *malachite* "10.0.1.6") (defvar *rambo* "10.0.1.13") (defmethod damage ((ip string) t/f) (damage (gethash ip *ip-node-tbl*) t/f)) (defmethod damage ((node node) t/f) (setf (node-byz node) t/f)) (defun init-sim () (shutdown-server) (reconstruct-tree) (start-server))
[ { "context": " :description \"Describe pidling here\"\n :author \"Your Name <[email protected]>\"\n :license \"Specify lice", "end": 103, "score": 0.9884132146835327, "start": 94, "tag": "NAME", "value": "Your Name" }, { "context": "ion \"Describe pidling here\"\n :author \"Your Name <[email protected]>\"\n :license \"Specify license here\"\n :depends-on", "end": 126, "score": 0.9999123811721802, "start": 105, "tag": "EMAIL", "value": "[email protected]" } ]
pidling.asd
ibawt/pidling
1
;;;; pidling.asd (asdf:defsystem #:pidling :description "Describe pidling here" :author "Your Name <[email protected]>" :license "Specify license here" :depends-on (#:sdl2 #:sdl2-image #:cl-opengl #:trivial-main-thread) :serial t :components ((:file "package") (:file "pidling") (:file "app")))
37611
;;;; pidling.asd (asdf:defsystem #:pidling :description "Describe pidling here" :author "<NAME> <<EMAIL>>" :license "Specify license here" :depends-on (#:sdl2 #:sdl2-image #:cl-opengl #:trivial-main-thread) :serial t :components ((:file "package") (:file "pidling") (:file "app")))
true
;;;; pidling.asd (asdf:defsystem #:pidling :description "Describe pidling here" :author "PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>" :license "Specify license here" :depends-on (#:sdl2 #:sdl2-image #:cl-opengl #:trivial-main-thread) :serial t :components ((:file "package") (:file "pidling") (:file "app")))
[ { "context": "s for Snark\"\n :version \"20120808r022\"\n :author \"Mark E. Stickel, SRI International\"\n :author \"Matthias Hölzl, LM", "end": 165, "score": 0.9998764991760254, "start": 150, "tag": "NAME", "value": "Mark E. Stickel" }, { "context": "r \"Mark E. Stickel, SRI International\"\n :author \"Matthias Hölzl, LMU\"\n :license \"MPL 1.1, see file LICENSE\"\n :d", "end": 211, "score": 0.9998795390129089, "start": 197, "tag": "NAME", "value": "Matthias Hölzl" } ]
programs/snark/snark-examples.asd
TeamSPoon/wam_common_lisp_devel_workspace
1
(in-package :common-lisp-user) (asdf:defsystem #:snark-examples :serial t :description "Examples for Snark" :version "20120808r022" :author "Mark E. Stickel, SRI International" :author "Matthias Hölzl, LMU" :license "MPL 1.1, see file LICENSE" :depends-on (#:snark) :pathname "examples/" :components ((:file "overbeek-test") (:file "front-last-example") (:file "steamroller-example") (:file "reverse-example") (:file "hot-drink-example") (:file "coder-examples") (:file "latin-squares")))
75508
(in-package :common-lisp-user) (asdf:defsystem #:snark-examples :serial t :description "Examples for Snark" :version "20120808r022" :author "<NAME>, SRI International" :author "<NAME>, LMU" :license "MPL 1.1, see file LICENSE" :depends-on (#:snark) :pathname "examples/" :components ((:file "overbeek-test") (:file "front-last-example") (:file "steamroller-example") (:file "reverse-example") (:file "hot-drink-example") (:file "coder-examples") (:file "latin-squares")))
true
(in-package :common-lisp-user) (asdf:defsystem #:snark-examples :serial t :description "Examples for Snark" :version "20120808r022" :author "PI:NAME:<NAME>END_PI, SRI International" :author "PI:NAME:<NAME>END_PI, LMU" :license "MPL 1.1, see file LICENSE" :depends-on (#:snark) :pathname "examples/" :components ((:file "overbeek-test") (:file "front-last-example") (:file "steamroller-example") (:file "reverse-example") (:file "hot-drink-example") (:file "coder-examples") (:file "latin-squares")))
[ { "context": ";-*- Mode: Lisp -*-\n;;;; Author: Paul Dietz\n;;;; Created: Thu Apr 9 19:32:56 1998\n;;;; Cont", "end": 49, "score": 0.9998432993888855, "start": 39, "tag": "NAME", "value": "Paul Dietz" } ]
programs/ansi-test/universe.lsp
TeamSPoon/wam_common_lisp_devel_workspace
1
;-*- Mode: Lisp -*- ;;;; Author: Paul Dietz ;;;; Created: Thu Apr 9 19:32:56 1998 ;;;; Contains: A global variable containing a list of ;;;; as many kinds of CL objects as we can think of ;;;; This list is used to test many other CL functions (in-package :cl-test) (defparameter *condition-types* '(arithmetic-error cell-error condition control-error division-by-zero end-of-file error file-error floating-point-inexact floating-point-invalid-operation floating-point-underflow floating-point-overflow package-error parse-error print-not-readable program-error reader-error serious-condition simple-condition simple-error simple-type-error simple-warning storage-condition stream-error style-warning type-error unbound-slot unbound-variable undefined-function warning)) (defparameter *condition-objects* (locally (declare (optimize safety)) (loop for tp in *condition-types* append (handler-case (list (make-condition tp)) (error () nil))))) (defparameter *standard-package-names* '("COMMON-LISP" "COMMON-LISP-USER" "KEYWORD")) (defparameter *package-objects* (locally (declare (optimize safety)) (loop for pname in *standard-package-names* append (handler-case (let ((pkg (find-package pname))) (and pkg (list pkg))) (error () nil))))) (defparameter *integers* (remove-duplicates `( 0 ;; Integers near the fixnum/bignum boundaries ,@(loop for i from -5 to 5 collect (+ i most-positive-fixnum)) ,@(loop for i from -5 to 5 collect (+ i most-negative-fixnum)) ;; Powers of two, negatives, and off by one. ,@(loop for i from 1 to 64 collect (ash 1 i)) ,@(loop for i from 1 to 64 collect (1- (ash 1 i))) ,@(loop for i from 1 to 64 collect (ash -1 i)) ,@(loop for i from 1 to 64 collect (1+ (ash -1 i))) ;; A big integer ,(expt 17 50) ;; Some arbitrarily chosen integers 12387131 1272314 231 -131 -561823 23713 -1234611312123 444121 991))) (defparameter *floats* (append (loop for sym in '(pi most-positive-short-float least-positive-short-float least-positive-normalized-short-float most-positive-double-float least-positive-double-float least-positive-normalized-double-float most-positive-long-float least-positive-long-float least-positive-normalized-long-float most-positive-single-float least-positive-single-float least-positive-normalized-single-float most-negative-short-float least-negative-short-float least-negative-normalized-short-float most-negative-single-float least-negative-single-float least-negative-normalized-single-float most-negative-double-float least-negative-double-float least-negative-normalized-double-float most-negative-long-float least-negative-long-float least-negative-normalized-long-float short-float-epsilon short-float-negative-epsilon single-float-epsilon single-float-negative-epsilon double-float-epsilon double-float-negative-epsilon long-float-epsilon long-float-negative-epsilon) when (boundp sym) collect (symbol-value sym)) (list 0.0 1.0 -1.0 313123.13 283143.231 -314781.9 1.31283d2 834.13812D-45 8131238.1E14 -4618926.231e-2 -37818.131F3 81.318231f-19 1.31273s3 12361.12S-7 6124.124l0 13123.1L-23))) (defparameter *ratios* '(1/3 1/1000 1/1000000000000000 -10/3 -1000/7 -987129387912381/13612986912361 189729874978126783786123/1234678123487612347896123467851234671234)) (defparameter *complexes* '(#C(0.0 0.0) #C(1.0 0.0) #C(0.0 1.0) #C(1.0 1.0) #C(-1.0 -1.0) #C(1289713.12312 -9.12681271) #C(1.0D100 1.0D100) #C(-1.0D-100 -1.0D-100) #C(10.0s0 20.0s0) #C(100.0l0 200.0l0) #C(1.0s0 2.0f0) #C(1.0s0 3.0d0) #C(1.0s0 4.0l0) #C(1.0f0 5.0d0) #C(1.0f0 6.0l0) #C(1.0d0 7.0l0) #C(1.0f0 2.0s0) #C(1.0d0 3.0s0) #C(1.0l0 4.0s0) #C(1.0d0 5.0f0) #C(1.0l0 6.0f0) #C(1.0l0 7.0d0) #C(1/2 1/3) )) (defparameter *numbers* (append *integers* *floats* *ratios* *complexes*)) (defparameter *reals* (append *integers* *floats* *ratios*)) (defparameter *rationals* (append *integers* *ratios*)) (defun try-to-read-chars (&rest namelist) (declare (optimize safety)) (loop for name in namelist append (handler-case (list (read-from-string (concatenate 'string "\#\\" name))) (error () nil)))) (defparameter *characters* (remove-duplicates `(#\Newline #\Space ,@(try-to-read-chars "Rubout" "Page" "Tab" "Backspace" "Return" "Linefeed" "Null") #\a #\A #\0 #\9 #\. #\( #\) #\[ #\] ))) (defparameter *strings* (append (and (code-char 0) (list (make-string 1 :initial-element (code-char 0)) (make-string 10 :initial-element (code-char 0)))) (list "" "A" "a" "0" "abcdef" "~!@#$%^&*()_+`1234567890-=<,>.?/:;\"'{[}]|\\ abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWYXZ" (make-string 100000 :initial-element #\g) (let ((s (make-string 256))) (loop for i from 0 to 255 do (let ((c (code-char i))) (when c (setf (elt s i) c)))) s) ;; Specialized strings (make-array 3 :element-type 'character :displaced-to (make-array 5 :element-type 'character :initial-contents "abcde") :displaced-index-offset 1) (make-array 10 :initial-element #\x :fill-pointer 5 :element-type 'character) (make-array 10 :initial-element #\x :element-type 'base-char) (make-array 3 :initial-element #\y :adjustable t :element-type 'base-char) ))) (defparameter *conses* (list (list 'a 'b) (list nil) (list 1 2 3 4 5 6))) (defparameter *circular-conses* (list (let ((s (copy-list '(a b c d)))) (nconc s s) s) (let ((s (list nil))) (setf (car s) s) s) (let ((s (list nil))) (setf (car s) s) (setf (cdr s) s)))) (defparameter *booleans* '(nil t)) (defparameter *keywords* '(:a :b :|| :|a| :|1234|)) (defparameter *uninterned-symbols* (list '#:nil '#:t '#:foo '#:||)) (defparameter *cl-test-symbols* `(,(intern "a" :cl-test) ,(intern "" :cl-test) ,@(and (code-char 0) (list (intern (make-string 1 :initial-element (code-char 0)) :cl-test))) ,@(and (code-char 0) (let* ((s (make-string 10 :initial-element (code-char 0))) (s2 (copy-seq s)) (s3 (copy-seq s))) (setf (subseq s 3 4) "a") (setf (subseq s2 4 5) "a") (setf (subseq s3 4 5) "a") (setf (subseq s3 7 8) "b") (list (intern s :cl-test) (intern s2 :cl-test) (intern s3 :cl-test)))) )) (defparameter *cl-user-symbols* '(cl-user::foo cl-user::x cl-user::cons cl-user::lambda cl-user::*print-readably* cl-user::push)) (defparameter *symbols* (append *booleans* *keywords* *uninterned-symbols* *cl-test-symbols* *cl-user-symbols*)) (defparameter *array-dimensions* (loop for i from 0 to 8 collect (loop for j from 1 to i collect 2))) (defparameter *default-array-target* (make-array '(300))) (defparameter *arrays* (append (list (make-array '10)) (mapcar #'make-array *array-dimensions*) ;; typed arrays (loop for tp in '(fixnum float bit character base-char (signed-byte 8) (unsigned-byte 8)) for element in '(18 16.0f0 0 #\x #\y 127 200) append (loop for d in *array-dimensions* collect (make-array d :element-type tp :initial-element element))) ;; More typed arrays (loop for i from 1 to 64 append (list (make-array 10 :element-type `(unsigned-byte ,i) :initial-element 1) (make-array 10 :element-type `(signed-byte ,i) :initial-element 0))) ;; adjustable arrays (loop for d in *array-dimensions* collect (make-array d :adjustable t)) ;; Displaced arrays (loop for d in *array-dimensions* for i from 1 collect (make-array d :displaced-to *default-array-target* :displaced-index-offset i)) (list #() #* #*00000 #*1010101010101101 (make-array 10 :element-type 'bit :initial-contents '(0 1 1 0 1 1 1 1 0 1) :fill-pointer 8) (make-array 5 :element-type 'bit :displaced-to #*0111000110 :displaced-index-offset 3) (make-array 10 :element-type 'bit :initial-contents '(1 1 0 0 1 1 1 0 1 1) :adjustable t) ) ;; Integer arrays (list (make-array '(10) :element-type '(integer 0 (256)) :initial-contents '(8 9 10 11 12 1 2 3 4 5)) (make-array '(10) :element-type '(integer -128 (128)) :initial-contents '(8 9 -10 11 -12 1 -2 -3 4 5)) (make-array '(6) :element-type '(integer 0 (#.(ash 1 16))) :initial-contents '(5 9 100 1312 23432 87)) (make-array '(4) :element-type '(integer 0 (#.(ash 1 28))) :initial-contents '(100000 231213 8123712 19)) (make-array '(4) :element-type '(integer 0 (#.(ash 1 32))) :initial-contents '(#.(1- (ash 1 32)) 0 872312 10000000)) (make-array nil :element-type '(integer 0 (256)) :initial-element 14) (make-array '(2 2) :element-type '(integer 0 (256)) :initial-contents '((34 98)(14 119))) ) ;; Float arrays (list (make-array '(5) :element-type 'short-float :initial-contents '(1.0s0 2.0s0 3.0s0 4.0s0 5.0s0)) (make-array '(5) :element-type 'single-float :initial-contents '(1.0f0 2.0f0 3.0f0 4.0f0 5.0f0)) (make-array '(5) :element-type 'double-float :initial-contents '(1.0d0 2.0d0 3.0d0 4.0d0 5.0d0)) (make-array '(5) :element-type 'long-float :initial-contents '(1.0l0 2.0l0 3.0l0 4.0l0 5.0l0)) ) ;; The ever-popular NIL array (locally (declare (optimize safety)) (handler-case (list (make-array '(0) :element-type nil)) (error () nil))) ;; more kinds of arrays here later? )) (defparameter *hash-tables* (list (make-hash-table) (make-hash-table :test #'eq) (make-hash-table :test #'eql) (make-hash-table :test #'equal) #-(or CMU ECL) (make-hash-table :test #'equalp) )) (defparameter *pathnames* (locally (declare (optimize safety)) (loop for form in '((make-pathname :name "foo") (make-pathname :name "FOO" :case :common) (make-pathname :name "bar") (make-pathname :name "foo" :type "txt") (make-pathname :name "bar" :type "txt") (make-pathname :name "XYZ" :type "TXT" :case :common) (make-pathname :name nil) (make-pathname :name :wild) (make-pathname :name nil :type "txt") (make-pathname :name :wild :type "txt") (make-pathname :name :wild :type "TXT" :case :common) (make-pathname :name :wild :type "abc" :case :common) (make-pathname :directory :wild) (make-pathname :type :wild) (make-pathname :version :wild) (make-pathname :version :newest)) append (ignore-errors (eval `(list ,form)))))) (eval-when (:compile-toplevel :load-toplevel :execute) (locally (declare (optimize safety)) (ignore-errors (setf (logical-pathname-translations "CLTESTROOT") `(("**;*.*.*" ,(merge-pathnames "sandbox/" (make-pathname :directory '(:absolute :wild-inferiors) :name :wild :type :wild)))))) (ignore-errors (setf (logical-pathname-translations "CLTEST") `(("**;*.*.*" ,(merge-pathnames "sandbox/" (make-pathname :directory (append (pathname-directory (truename (make-pathname))) '(:wild-inferiors)) :name :wild :type :wild)))))) )) (defparameter *logical-pathnames* (locally (declare (optimize safety)) (append (ignore-errors (list (logical-pathname "CLTESTROOT:"))) ))) (defparameter *streams* (remove-duplicates (remove-if #'null (list *debug-io* *error-output* *query-io* *standard-input* *standard-output* *terminal-io* *trace-output*)))) (defparameter *readtables* (list *readtable* (copy-readtable))) (defstruct foo-structure x y z) (defstruct bar-structure x y z) (defparameter *structures* (list (make-foo-structure :x 1 :y 'a :z nil) (make-foo-structure :x 1 :y 'a :z nil) (make-bar-structure :x 1 :y 'a :z nil) )) (defun meaningless-user-function-for-universe (x y z) (list (+ x 1) (+ y 2) (+ z 3))) (defgeneric meaningless-user-generic-function-for-universe (x y z) #+(or (not :gcl) :ansi-cl) (:method ((x integer) (y integer) (z integer)) (+ x y z))) (eval-when (:load-toplevel :execute) (compile 'meaningless-user-function-for-universe) ;; Conditionalize to avoid a cmucl bug #-(or cmu gcl ecl) (compile 'meaningless-user-generic-function-for-universe) ) (defparameter *functions* (list #'cons #'car #'append #'values (macro-function 'cond) #'meaningless-user-function-for-universe #'meaningless-user-generic-function-for-universe #'(lambda (x) x) (compile nil '(lambda (x) x)))) (defparameter *methods* (list #+(or (not :gcl) :ansi-cl ) (find-method #'meaningless-user-generic-function-for-universe nil (mapcar #'find-class '(integer integer integer))) ;; Add more methods here )) (defparameter *random-states* (list (make-random-state))) (defparameter *universe* (remove-duplicates (append *symbols* *numbers* *characters* (mapcar #'copy-seq *strings*) *conses* *condition-objects* *package-objects* *arrays* *hash-tables* *pathnames* *logical-pathnames* *streams* *readtables* *structures* *functions* *random-states* *methods* nil))) (defparameter *mini-universe* (remove-duplicates (append (mapcar #'first (list *symbols* *numbers* *characters* (list (copy-seq (first *strings*))) *conses* *condition-objects* *package-objects* *arrays* *hash-tables* *pathnames* *logical-pathnames* *streams* *readtables* *structures* *functions* *random-states* *methods*)) '(;;; Others to fill in gaps 1.2s0 1.3f0 1.5d0 1.8l0 3/5 10000000000000000000000)))) (defparameter *classes* (remove-duplicates (mapcar #'class-of *universe*))) (defparameter *built-in-classes* (remove-if-not #'(lambda (x) (typep x 'built-in-class)) *classes*))
1507
;-*- Mode: Lisp -*- ;;;; Author: <NAME> ;;;; Created: Thu Apr 9 19:32:56 1998 ;;;; Contains: A global variable containing a list of ;;;; as many kinds of CL objects as we can think of ;;;; This list is used to test many other CL functions (in-package :cl-test) (defparameter *condition-types* '(arithmetic-error cell-error condition control-error division-by-zero end-of-file error file-error floating-point-inexact floating-point-invalid-operation floating-point-underflow floating-point-overflow package-error parse-error print-not-readable program-error reader-error serious-condition simple-condition simple-error simple-type-error simple-warning storage-condition stream-error style-warning type-error unbound-slot unbound-variable undefined-function warning)) (defparameter *condition-objects* (locally (declare (optimize safety)) (loop for tp in *condition-types* append (handler-case (list (make-condition tp)) (error () nil))))) (defparameter *standard-package-names* '("COMMON-LISP" "COMMON-LISP-USER" "KEYWORD")) (defparameter *package-objects* (locally (declare (optimize safety)) (loop for pname in *standard-package-names* append (handler-case (let ((pkg (find-package pname))) (and pkg (list pkg))) (error () nil))))) (defparameter *integers* (remove-duplicates `( 0 ;; Integers near the fixnum/bignum boundaries ,@(loop for i from -5 to 5 collect (+ i most-positive-fixnum)) ,@(loop for i from -5 to 5 collect (+ i most-negative-fixnum)) ;; Powers of two, negatives, and off by one. ,@(loop for i from 1 to 64 collect (ash 1 i)) ,@(loop for i from 1 to 64 collect (1- (ash 1 i))) ,@(loop for i from 1 to 64 collect (ash -1 i)) ,@(loop for i from 1 to 64 collect (1+ (ash -1 i))) ;; A big integer ,(expt 17 50) ;; Some arbitrarily chosen integers 12387131 1272314 231 -131 -561823 23713 -1234611312123 444121 991))) (defparameter *floats* (append (loop for sym in '(pi most-positive-short-float least-positive-short-float least-positive-normalized-short-float most-positive-double-float least-positive-double-float least-positive-normalized-double-float most-positive-long-float least-positive-long-float least-positive-normalized-long-float most-positive-single-float least-positive-single-float least-positive-normalized-single-float most-negative-short-float least-negative-short-float least-negative-normalized-short-float most-negative-single-float least-negative-single-float least-negative-normalized-single-float most-negative-double-float least-negative-double-float least-negative-normalized-double-float most-negative-long-float least-negative-long-float least-negative-normalized-long-float short-float-epsilon short-float-negative-epsilon single-float-epsilon single-float-negative-epsilon double-float-epsilon double-float-negative-epsilon long-float-epsilon long-float-negative-epsilon) when (boundp sym) collect (symbol-value sym)) (list 0.0 1.0 -1.0 313123.13 283143.231 -314781.9 1.31283d2 834.13812D-45 8131238.1E14 -4618926.231e-2 -37818.131F3 81.318231f-19 1.31273s3 12361.12S-7 6124.124l0 13123.1L-23))) (defparameter *ratios* '(1/3 1/1000 1/1000000000000000 -10/3 -1000/7 -987129387912381/13612986912361 189729874978126783786123/1234678123487612347896123467851234671234)) (defparameter *complexes* '(#C(0.0 0.0) #C(1.0 0.0) #C(0.0 1.0) #C(1.0 1.0) #C(-1.0 -1.0) #C(1289713.12312 -9.12681271) #C(1.0D100 1.0D100) #C(-1.0D-100 -1.0D-100) #C(10.0s0 20.0s0) #C(100.0l0 200.0l0) #C(1.0s0 2.0f0) #C(1.0s0 3.0d0) #C(1.0s0 4.0l0) #C(1.0f0 5.0d0) #C(1.0f0 6.0l0) #C(1.0d0 7.0l0) #C(1.0f0 2.0s0) #C(1.0d0 3.0s0) #C(1.0l0 4.0s0) #C(1.0d0 5.0f0) #C(1.0l0 6.0f0) #C(1.0l0 7.0d0) #C(1/2 1/3) )) (defparameter *numbers* (append *integers* *floats* *ratios* *complexes*)) (defparameter *reals* (append *integers* *floats* *ratios*)) (defparameter *rationals* (append *integers* *ratios*)) (defun try-to-read-chars (&rest namelist) (declare (optimize safety)) (loop for name in namelist append (handler-case (list (read-from-string (concatenate 'string "\#\\" name))) (error () nil)))) (defparameter *characters* (remove-duplicates `(#\Newline #\Space ,@(try-to-read-chars "Rubout" "Page" "Tab" "Backspace" "Return" "Linefeed" "Null") #\a #\A #\0 #\9 #\. #\( #\) #\[ #\] ))) (defparameter *strings* (append (and (code-char 0) (list (make-string 1 :initial-element (code-char 0)) (make-string 10 :initial-element (code-char 0)))) (list "" "A" "a" "0" "abcdef" "~!@#$%^&*()_+`1234567890-=<,>.?/:;\"'{[}]|\\ abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWYXZ" (make-string 100000 :initial-element #\g) (let ((s (make-string 256))) (loop for i from 0 to 255 do (let ((c (code-char i))) (when c (setf (elt s i) c)))) s) ;; Specialized strings (make-array 3 :element-type 'character :displaced-to (make-array 5 :element-type 'character :initial-contents "abcde") :displaced-index-offset 1) (make-array 10 :initial-element #\x :fill-pointer 5 :element-type 'character) (make-array 10 :initial-element #\x :element-type 'base-char) (make-array 3 :initial-element #\y :adjustable t :element-type 'base-char) ))) (defparameter *conses* (list (list 'a 'b) (list nil) (list 1 2 3 4 5 6))) (defparameter *circular-conses* (list (let ((s (copy-list '(a b c d)))) (nconc s s) s) (let ((s (list nil))) (setf (car s) s) s) (let ((s (list nil))) (setf (car s) s) (setf (cdr s) s)))) (defparameter *booleans* '(nil t)) (defparameter *keywords* '(:a :b :|| :|a| :|1234|)) (defparameter *uninterned-symbols* (list '#:nil '#:t '#:foo '#:||)) (defparameter *cl-test-symbols* `(,(intern "a" :cl-test) ,(intern "" :cl-test) ,@(and (code-char 0) (list (intern (make-string 1 :initial-element (code-char 0)) :cl-test))) ,@(and (code-char 0) (let* ((s (make-string 10 :initial-element (code-char 0))) (s2 (copy-seq s)) (s3 (copy-seq s))) (setf (subseq s 3 4) "a") (setf (subseq s2 4 5) "a") (setf (subseq s3 4 5) "a") (setf (subseq s3 7 8) "b") (list (intern s :cl-test) (intern s2 :cl-test) (intern s3 :cl-test)))) )) (defparameter *cl-user-symbols* '(cl-user::foo cl-user::x cl-user::cons cl-user::lambda cl-user::*print-readably* cl-user::push)) (defparameter *symbols* (append *booleans* *keywords* *uninterned-symbols* *cl-test-symbols* *cl-user-symbols*)) (defparameter *array-dimensions* (loop for i from 0 to 8 collect (loop for j from 1 to i collect 2))) (defparameter *default-array-target* (make-array '(300))) (defparameter *arrays* (append (list (make-array '10)) (mapcar #'make-array *array-dimensions*) ;; typed arrays (loop for tp in '(fixnum float bit character base-char (signed-byte 8) (unsigned-byte 8)) for element in '(18 16.0f0 0 #\x #\y 127 200) append (loop for d in *array-dimensions* collect (make-array d :element-type tp :initial-element element))) ;; More typed arrays (loop for i from 1 to 64 append (list (make-array 10 :element-type `(unsigned-byte ,i) :initial-element 1) (make-array 10 :element-type `(signed-byte ,i) :initial-element 0))) ;; adjustable arrays (loop for d in *array-dimensions* collect (make-array d :adjustable t)) ;; Displaced arrays (loop for d in *array-dimensions* for i from 1 collect (make-array d :displaced-to *default-array-target* :displaced-index-offset i)) (list #() #* #*00000 #*1010101010101101 (make-array 10 :element-type 'bit :initial-contents '(0 1 1 0 1 1 1 1 0 1) :fill-pointer 8) (make-array 5 :element-type 'bit :displaced-to #*0111000110 :displaced-index-offset 3) (make-array 10 :element-type 'bit :initial-contents '(1 1 0 0 1 1 1 0 1 1) :adjustable t) ) ;; Integer arrays (list (make-array '(10) :element-type '(integer 0 (256)) :initial-contents '(8 9 10 11 12 1 2 3 4 5)) (make-array '(10) :element-type '(integer -128 (128)) :initial-contents '(8 9 -10 11 -12 1 -2 -3 4 5)) (make-array '(6) :element-type '(integer 0 (#.(ash 1 16))) :initial-contents '(5 9 100 1312 23432 87)) (make-array '(4) :element-type '(integer 0 (#.(ash 1 28))) :initial-contents '(100000 231213 8123712 19)) (make-array '(4) :element-type '(integer 0 (#.(ash 1 32))) :initial-contents '(#.(1- (ash 1 32)) 0 872312 10000000)) (make-array nil :element-type '(integer 0 (256)) :initial-element 14) (make-array '(2 2) :element-type '(integer 0 (256)) :initial-contents '((34 98)(14 119))) ) ;; Float arrays (list (make-array '(5) :element-type 'short-float :initial-contents '(1.0s0 2.0s0 3.0s0 4.0s0 5.0s0)) (make-array '(5) :element-type 'single-float :initial-contents '(1.0f0 2.0f0 3.0f0 4.0f0 5.0f0)) (make-array '(5) :element-type 'double-float :initial-contents '(1.0d0 2.0d0 3.0d0 4.0d0 5.0d0)) (make-array '(5) :element-type 'long-float :initial-contents '(1.0l0 2.0l0 3.0l0 4.0l0 5.0l0)) ) ;; The ever-popular NIL array (locally (declare (optimize safety)) (handler-case (list (make-array '(0) :element-type nil)) (error () nil))) ;; more kinds of arrays here later? )) (defparameter *hash-tables* (list (make-hash-table) (make-hash-table :test #'eq) (make-hash-table :test #'eql) (make-hash-table :test #'equal) #-(or CMU ECL) (make-hash-table :test #'equalp) )) (defparameter *pathnames* (locally (declare (optimize safety)) (loop for form in '((make-pathname :name "foo") (make-pathname :name "FOO" :case :common) (make-pathname :name "bar") (make-pathname :name "foo" :type "txt") (make-pathname :name "bar" :type "txt") (make-pathname :name "XYZ" :type "TXT" :case :common) (make-pathname :name nil) (make-pathname :name :wild) (make-pathname :name nil :type "txt") (make-pathname :name :wild :type "txt") (make-pathname :name :wild :type "TXT" :case :common) (make-pathname :name :wild :type "abc" :case :common) (make-pathname :directory :wild) (make-pathname :type :wild) (make-pathname :version :wild) (make-pathname :version :newest)) append (ignore-errors (eval `(list ,form)))))) (eval-when (:compile-toplevel :load-toplevel :execute) (locally (declare (optimize safety)) (ignore-errors (setf (logical-pathname-translations "CLTESTROOT") `(("**;*.*.*" ,(merge-pathnames "sandbox/" (make-pathname :directory '(:absolute :wild-inferiors) :name :wild :type :wild)))))) (ignore-errors (setf (logical-pathname-translations "CLTEST") `(("**;*.*.*" ,(merge-pathnames "sandbox/" (make-pathname :directory (append (pathname-directory (truename (make-pathname))) '(:wild-inferiors)) :name :wild :type :wild)))))) )) (defparameter *logical-pathnames* (locally (declare (optimize safety)) (append (ignore-errors (list (logical-pathname "CLTESTROOT:"))) ))) (defparameter *streams* (remove-duplicates (remove-if #'null (list *debug-io* *error-output* *query-io* *standard-input* *standard-output* *terminal-io* *trace-output*)))) (defparameter *readtables* (list *readtable* (copy-readtable))) (defstruct foo-structure x y z) (defstruct bar-structure x y z) (defparameter *structures* (list (make-foo-structure :x 1 :y 'a :z nil) (make-foo-structure :x 1 :y 'a :z nil) (make-bar-structure :x 1 :y 'a :z nil) )) (defun meaningless-user-function-for-universe (x y z) (list (+ x 1) (+ y 2) (+ z 3))) (defgeneric meaningless-user-generic-function-for-universe (x y z) #+(or (not :gcl) :ansi-cl) (:method ((x integer) (y integer) (z integer)) (+ x y z))) (eval-when (:load-toplevel :execute) (compile 'meaningless-user-function-for-universe) ;; Conditionalize to avoid a cmucl bug #-(or cmu gcl ecl) (compile 'meaningless-user-generic-function-for-universe) ) (defparameter *functions* (list #'cons #'car #'append #'values (macro-function 'cond) #'meaningless-user-function-for-universe #'meaningless-user-generic-function-for-universe #'(lambda (x) x) (compile nil '(lambda (x) x)))) (defparameter *methods* (list #+(or (not :gcl) :ansi-cl ) (find-method #'meaningless-user-generic-function-for-universe nil (mapcar #'find-class '(integer integer integer))) ;; Add more methods here )) (defparameter *random-states* (list (make-random-state))) (defparameter *universe* (remove-duplicates (append *symbols* *numbers* *characters* (mapcar #'copy-seq *strings*) *conses* *condition-objects* *package-objects* *arrays* *hash-tables* *pathnames* *logical-pathnames* *streams* *readtables* *structures* *functions* *random-states* *methods* nil))) (defparameter *mini-universe* (remove-duplicates (append (mapcar #'first (list *symbols* *numbers* *characters* (list (copy-seq (first *strings*))) *conses* *condition-objects* *package-objects* *arrays* *hash-tables* *pathnames* *logical-pathnames* *streams* *readtables* *structures* *functions* *random-states* *methods*)) '(;;; Others to fill in gaps 1.2s0 1.3f0 1.5d0 1.8l0 3/5 10000000000000000000000)))) (defparameter *classes* (remove-duplicates (mapcar #'class-of *universe*))) (defparameter *built-in-classes* (remove-if-not #'(lambda (x) (typep x 'built-in-class)) *classes*))
true
;-*- Mode: Lisp -*- ;;;; Author: PI:NAME:<NAME>END_PI ;;;; Created: Thu Apr 9 19:32:56 1998 ;;;; Contains: A global variable containing a list of ;;;; as many kinds of CL objects as we can think of ;;;; This list is used to test many other CL functions (in-package :cl-test) (defparameter *condition-types* '(arithmetic-error cell-error condition control-error division-by-zero end-of-file error file-error floating-point-inexact floating-point-invalid-operation floating-point-underflow floating-point-overflow package-error parse-error print-not-readable program-error reader-error serious-condition simple-condition simple-error simple-type-error simple-warning storage-condition stream-error style-warning type-error unbound-slot unbound-variable undefined-function warning)) (defparameter *condition-objects* (locally (declare (optimize safety)) (loop for tp in *condition-types* append (handler-case (list (make-condition tp)) (error () nil))))) (defparameter *standard-package-names* '("COMMON-LISP" "COMMON-LISP-USER" "KEYWORD")) (defparameter *package-objects* (locally (declare (optimize safety)) (loop for pname in *standard-package-names* append (handler-case (let ((pkg (find-package pname))) (and pkg (list pkg))) (error () nil))))) (defparameter *integers* (remove-duplicates `( 0 ;; Integers near the fixnum/bignum boundaries ,@(loop for i from -5 to 5 collect (+ i most-positive-fixnum)) ,@(loop for i from -5 to 5 collect (+ i most-negative-fixnum)) ;; Powers of two, negatives, and off by one. ,@(loop for i from 1 to 64 collect (ash 1 i)) ,@(loop for i from 1 to 64 collect (1- (ash 1 i))) ,@(loop for i from 1 to 64 collect (ash -1 i)) ,@(loop for i from 1 to 64 collect (1+ (ash -1 i))) ;; A big integer ,(expt 17 50) ;; Some arbitrarily chosen integers 12387131 1272314 231 -131 -561823 23713 -1234611312123 444121 991))) (defparameter *floats* (append (loop for sym in '(pi most-positive-short-float least-positive-short-float least-positive-normalized-short-float most-positive-double-float least-positive-double-float least-positive-normalized-double-float most-positive-long-float least-positive-long-float least-positive-normalized-long-float most-positive-single-float least-positive-single-float least-positive-normalized-single-float most-negative-short-float least-negative-short-float least-negative-normalized-short-float most-negative-single-float least-negative-single-float least-negative-normalized-single-float most-negative-double-float least-negative-double-float least-negative-normalized-double-float most-negative-long-float least-negative-long-float least-negative-normalized-long-float short-float-epsilon short-float-negative-epsilon single-float-epsilon single-float-negative-epsilon double-float-epsilon double-float-negative-epsilon long-float-epsilon long-float-negative-epsilon) when (boundp sym) collect (symbol-value sym)) (list 0.0 1.0 -1.0 313123.13 283143.231 -314781.9 1.31283d2 834.13812D-45 8131238.1E14 -4618926.231e-2 -37818.131F3 81.318231f-19 1.31273s3 12361.12S-7 6124.124l0 13123.1L-23))) (defparameter *ratios* '(1/3 1/1000 1/1000000000000000 -10/3 -1000/7 -987129387912381/13612986912361 189729874978126783786123/1234678123487612347896123467851234671234)) (defparameter *complexes* '(#C(0.0 0.0) #C(1.0 0.0) #C(0.0 1.0) #C(1.0 1.0) #C(-1.0 -1.0) #C(1289713.12312 -9.12681271) #C(1.0D100 1.0D100) #C(-1.0D-100 -1.0D-100) #C(10.0s0 20.0s0) #C(100.0l0 200.0l0) #C(1.0s0 2.0f0) #C(1.0s0 3.0d0) #C(1.0s0 4.0l0) #C(1.0f0 5.0d0) #C(1.0f0 6.0l0) #C(1.0d0 7.0l0) #C(1.0f0 2.0s0) #C(1.0d0 3.0s0) #C(1.0l0 4.0s0) #C(1.0d0 5.0f0) #C(1.0l0 6.0f0) #C(1.0l0 7.0d0) #C(1/2 1/3) )) (defparameter *numbers* (append *integers* *floats* *ratios* *complexes*)) (defparameter *reals* (append *integers* *floats* *ratios*)) (defparameter *rationals* (append *integers* *ratios*)) (defun try-to-read-chars (&rest namelist) (declare (optimize safety)) (loop for name in namelist append (handler-case (list (read-from-string (concatenate 'string "\#\\" name))) (error () nil)))) (defparameter *characters* (remove-duplicates `(#\Newline #\Space ,@(try-to-read-chars "Rubout" "Page" "Tab" "Backspace" "Return" "Linefeed" "Null") #\a #\A #\0 #\9 #\. #\( #\) #\[ #\] ))) (defparameter *strings* (append (and (code-char 0) (list (make-string 1 :initial-element (code-char 0)) (make-string 10 :initial-element (code-char 0)))) (list "" "A" "a" "0" "abcdef" "~!@#$%^&*()_+`1234567890-=<,>.?/:;\"'{[}]|\\ abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWYXZ" (make-string 100000 :initial-element #\g) (let ((s (make-string 256))) (loop for i from 0 to 255 do (let ((c (code-char i))) (when c (setf (elt s i) c)))) s) ;; Specialized strings (make-array 3 :element-type 'character :displaced-to (make-array 5 :element-type 'character :initial-contents "abcde") :displaced-index-offset 1) (make-array 10 :initial-element #\x :fill-pointer 5 :element-type 'character) (make-array 10 :initial-element #\x :element-type 'base-char) (make-array 3 :initial-element #\y :adjustable t :element-type 'base-char) ))) (defparameter *conses* (list (list 'a 'b) (list nil) (list 1 2 3 4 5 6))) (defparameter *circular-conses* (list (let ((s (copy-list '(a b c d)))) (nconc s s) s) (let ((s (list nil))) (setf (car s) s) s) (let ((s (list nil))) (setf (car s) s) (setf (cdr s) s)))) (defparameter *booleans* '(nil t)) (defparameter *keywords* '(:a :b :|| :|a| :|1234|)) (defparameter *uninterned-symbols* (list '#:nil '#:t '#:foo '#:||)) (defparameter *cl-test-symbols* `(,(intern "a" :cl-test) ,(intern "" :cl-test) ,@(and (code-char 0) (list (intern (make-string 1 :initial-element (code-char 0)) :cl-test))) ,@(and (code-char 0) (let* ((s (make-string 10 :initial-element (code-char 0))) (s2 (copy-seq s)) (s3 (copy-seq s))) (setf (subseq s 3 4) "a") (setf (subseq s2 4 5) "a") (setf (subseq s3 4 5) "a") (setf (subseq s3 7 8) "b") (list (intern s :cl-test) (intern s2 :cl-test) (intern s3 :cl-test)))) )) (defparameter *cl-user-symbols* '(cl-user::foo cl-user::x cl-user::cons cl-user::lambda cl-user::*print-readably* cl-user::push)) (defparameter *symbols* (append *booleans* *keywords* *uninterned-symbols* *cl-test-symbols* *cl-user-symbols*)) (defparameter *array-dimensions* (loop for i from 0 to 8 collect (loop for j from 1 to i collect 2))) (defparameter *default-array-target* (make-array '(300))) (defparameter *arrays* (append (list (make-array '10)) (mapcar #'make-array *array-dimensions*) ;; typed arrays (loop for tp in '(fixnum float bit character base-char (signed-byte 8) (unsigned-byte 8)) for element in '(18 16.0f0 0 #\x #\y 127 200) append (loop for d in *array-dimensions* collect (make-array d :element-type tp :initial-element element))) ;; More typed arrays (loop for i from 1 to 64 append (list (make-array 10 :element-type `(unsigned-byte ,i) :initial-element 1) (make-array 10 :element-type `(signed-byte ,i) :initial-element 0))) ;; adjustable arrays (loop for d in *array-dimensions* collect (make-array d :adjustable t)) ;; Displaced arrays (loop for d in *array-dimensions* for i from 1 collect (make-array d :displaced-to *default-array-target* :displaced-index-offset i)) (list #() #* #*00000 #*1010101010101101 (make-array 10 :element-type 'bit :initial-contents '(0 1 1 0 1 1 1 1 0 1) :fill-pointer 8) (make-array 5 :element-type 'bit :displaced-to #*0111000110 :displaced-index-offset 3) (make-array 10 :element-type 'bit :initial-contents '(1 1 0 0 1 1 1 0 1 1) :adjustable t) ) ;; Integer arrays (list (make-array '(10) :element-type '(integer 0 (256)) :initial-contents '(8 9 10 11 12 1 2 3 4 5)) (make-array '(10) :element-type '(integer -128 (128)) :initial-contents '(8 9 -10 11 -12 1 -2 -3 4 5)) (make-array '(6) :element-type '(integer 0 (#.(ash 1 16))) :initial-contents '(5 9 100 1312 23432 87)) (make-array '(4) :element-type '(integer 0 (#.(ash 1 28))) :initial-contents '(100000 231213 8123712 19)) (make-array '(4) :element-type '(integer 0 (#.(ash 1 32))) :initial-contents '(#.(1- (ash 1 32)) 0 872312 10000000)) (make-array nil :element-type '(integer 0 (256)) :initial-element 14) (make-array '(2 2) :element-type '(integer 0 (256)) :initial-contents '((34 98)(14 119))) ) ;; Float arrays (list (make-array '(5) :element-type 'short-float :initial-contents '(1.0s0 2.0s0 3.0s0 4.0s0 5.0s0)) (make-array '(5) :element-type 'single-float :initial-contents '(1.0f0 2.0f0 3.0f0 4.0f0 5.0f0)) (make-array '(5) :element-type 'double-float :initial-contents '(1.0d0 2.0d0 3.0d0 4.0d0 5.0d0)) (make-array '(5) :element-type 'long-float :initial-contents '(1.0l0 2.0l0 3.0l0 4.0l0 5.0l0)) ) ;; The ever-popular NIL array (locally (declare (optimize safety)) (handler-case (list (make-array '(0) :element-type nil)) (error () nil))) ;; more kinds of arrays here later? )) (defparameter *hash-tables* (list (make-hash-table) (make-hash-table :test #'eq) (make-hash-table :test #'eql) (make-hash-table :test #'equal) #-(or CMU ECL) (make-hash-table :test #'equalp) )) (defparameter *pathnames* (locally (declare (optimize safety)) (loop for form in '((make-pathname :name "foo") (make-pathname :name "FOO" :case :common) (make-pathname :name "bar") (make-pathname :name "foo" :type "txt") (make-pathname :name "bar" :type "txt") (make-pathname :name "XYZ" :type "TXT" :case :common) (make-pathname :name nil) (make-pathname :name :wild) (make-pathname :name nil :type "txt") (make-pathname :name :wild :type "txt") (make-pathname :name :wild :type "TXT" :case :common) (make-pathname :name :wild :type "abc" :case :common) (make-pathname :directory :wild) (make-pathname :type :wild) (make-pathname :version :wild) (make-pathname :version :newest)) append (ignore-errors (eval `(list ,form)))))) (eval-when (:compile-toplevel :load-toplevel :execute) (locally (declare (optimize safety)) (ignore-errors (setf (logical-pathname-translations "CLTESTROOT") `(("**;*.*.*" ,(merge-pathnames "sandbox/" (make-pathname :directory '(:absolute :wild-inferiors) :name :wild :type :wild)))))) (ignore-errors (setf (logical-pathname-translations "CLTEST") `(("**;*.*.*" ,(merge-pathnames "sandbox/" (make-pathname :directory (append (pathname-directory (truename (make-pathname))) '(:wild-inferiors)) :name :wild :type :wild)))))) )) (defparameter *logical-pathnames* (locally (declare (optimize safety)) (append (ignore-errors (list (logical-pathname "CLTESTROOT:"))) ))) (defparameter *streams* (remove-duplicates (remove-if #'null (list *debug-io* *error-output* *query-io* *standard-input* *standard-output* *terminal-io* *trace-output*)))) (defparameter *readtables* (list *readtable* (copy-readtable))) (defstruct foo-structure x y z) (defstruct bar-structure x y z) (defparameter *structures* (list (make-foo-structure :x 1 :y 'a :z nil) (make-foo-structure :x 1 :y 'a :z nil) (make-bar-structure :x 1 :y 'a :z nil) )) (defun meaningless-user-function-for-universe (x y z) (list (+ x 1) (+ y 2) (+ z 3))) (defgeneric meaningless-user-generic-function-for-universe (x y z) #+(or (not :gcl) :ansi-cl) (:method ((x integer) (y integer) (z integer)) (+ x y z))) (eval-when (:load-toplevel :execute) (compile 'meaningless-user-function-for-universe) ;; Conditionalize to avoid a cmucl bug #-(or cmu gcl ecl) (compile 'meaningless-user-generic-function-for-universe) ) (defparameter *functions* (list #'cons #'car #'append #'values (macro-function 'cond) #'meaningless-user-function-for-universe #'meaningless-user-generic-function-for-universe #'(lambda (x) x) (compile nil '(lambda (x) x)))) (defparameter *methods* (list #+(or (not :gcl) :ansi-cl ) (find-method #'meaningless-user-generic-function-for-universe nil (mapcar #'find-class '(integer integer integer))) ;; Add more methods here )) (defparameter *random-states* (list (make-random-state))) (defparameter *universe* (remove-duplicates (append *symbols* *numbers* *characters* (mapcar #'copy-seq *strings*) *conses* *condition-objects* *package-objects* *arrays* *hash-tables* *pathnames* *logical-pathnames* *streams* *readtables* *structures* *functions* *random-states* *methods* nil))) (defparameter *mini-universe* (remove-duplicates (append (mapcar #'first (list *symbols* *numbers* *characters* (list (copy-seq (first *strings*))) *conses* *condition-objects* *package-objects* *arrays* *hash-tables* *pathnames* *logical-pathnames* *streams* *readtables* *structures* *functions* *random-states* *methods*)) '(;;; Others to fill in gaps 1.2s0 1.3f0 1.5d0 1.8l0 3/5 10000000000000000000000)))) (defparameter *classes* (remove-duplicates (mapcar #'class-of *universe*))) (defparameter *built-in-classes* (remove-if-not #'(lambda (x) (typep x 'built-in-class)) *classes*))
[ { "context": ";; AUTHOR\n;; Shilpi Goel <[email protected]>\n\n(in-package \"X86ISA\")\n\n;", "end": 24, "score": 0.9998883008956909, "start": 13, "tag": "NAME", "value": "Shilpi Goel" }, { "context": ";; AUTHOR\n;; Shilpi Goel <[email protected]>\n\n(in-package \"X86ISA\")\n\n;; =====================", "end": 47, "score": 0.9999311566352844, "start": 26, "tag": "EMAIL", "value": "[email protected]" } ]
books/projects/x86isa/machine/x86-register-readers-and-writers-raw.lsp
solswords/acl2
0
;; AUTHOR ;; Shilpi Goel <[email protected]> (in-package "X86ISA") ;; ====================================================================== ;; Undef Flg: (defun undef-flg$notinline (x86) (declare (xargs :mode :program :stobjs x86)) (when (or (equal (f-get-global 'in-prove-flg ACL2::*the-live-state*) t) (equal (f-get-global 'in-verify-flg ACL2::*the-live-state*) t)) (return-from X86ISA::undef-flg$notinline (X86ISA::undef-flg-logic x86))) ;; TO-DO@Shilpi: For now, I'm just returning 0 as the "undefined" ;; value for flags. (mv 0 x86) ;; (b* ((- (cw "~%undef-flg at PC: ~x0~%" (X86ISA::rip X86ISA::*the-live-x86*)))) ;; (mv 0 x86)) ) (defun undef-read$notinline (x86) (declare (xargs :mode :program :stobjs x86)) (when (or (equal (f-get-global 'in-prove-read ACL2::*the-live-state*) t) (equal (f-get-global 'in-verify-read ACL2::*the-live-state*) t)) (return-from X86ISA::undef-read$notinline (X86ISA::undef-read-logic x86))) ;; TO-DO@Shilpi: For now, I'm just returning 0 as the "undefined" ;; value. (mv 0 x86) ;; (b* ((- (cw "~%undef-read at PC: ~x0~%" (X86ISA::rip X86ISA::*the-live-x86*)))) ;; (mv 0 x86)) ) ;; Safe-!undef: ;; (defun safe-!undef$notinline (v x86) ;; (declare (xargs :mode :program :stobjs x86)) ;; (when (or (equal (f-get-global 'in-prove-flg ACL2::*the-live-state*) ;; t) ;; (equal (f-get-global 'in-verify-flg ;; ACL2::*the-live-state*) ;; t)) ;; (return-from X86ISA::safe-!undef$notinline ;; (X86ISA::!undef v x86))) ;; (er hard! 'safe-!undef ;; "Ill-advised attempt to call safe-!undef during top-level ~ ;; evaluation.")) ;; ======================================================================
9833
;; AUTHOR ;; <NAME> <<EMAIL>> (in-package "X86ISA") ;; ====================================================================== ;; Undef Flg: (defun undef-flg$notinline (x86) (declare (xargs :mode :program :stobjs x86)) (when (or (equal (f-get-global 'in-prove-flg ACL2::*the-live-state*) t) (equal (f-get-global 'in-verify-flg ACL2::*the-live-state*) t)) (return-from X86ISA::undef-flg$notinline (X86ISA::undef-flg-logic x86))) ;; TO-DO@Shilpi: For now, I'm just returning 0 as the "undefined" ;; value for flags. (mv 0 x86) ;; (b* ((- (cw "~%undef-flg at PC: ~x0~%" (X86ISA::rip X86ISA::*the-live-x86*)))) ;; (mv 0 x86)) ) (defun undef-read$notinline (x86) (declare (xargs :mode :program :stobjs x86)) (when (or (equal (f-get-global 'in-prove-read ACL2::*the-live-state*) t) (equal (f-get-global 'in-verify-read ACL2::*the-live-state*) t)) (return-from X86ISA::undef-read$notinline (X86ISA::undef-read-logic x86))) ;; TO-DO@Shilpi: For now, I'm just returning 0 as the "undefined" ;; value. (mv 0 x86) ;; (b* ((- (cw "~%undef-read at PC: ~x0~%" (X86ISA::rip X86ISA::*the-live-x86*)))) ;; (mv 0 x86)) ) ;; Safe-!undef: ;; (defun safe-!undef$notinline (v x86) ;; (declare (xargs :mode :program :stobjs x86)) ;; (when (or (equal (f-get-global 'in-prove-flg ACL2::*the-live-state*) ;; t) ;; (equal (f-get-global 'in-verify-flg ;; ACL2::*the-live-state*) ;; t)) ;; (return-from X86ISA::safe-!undef$notinline ;; (X86ISA::!undef v x86))) ;; (er hard! 'safe-!undef ;; "Ill-advised attempt to call safe-!undef during top-level ~ ;; evaluation.")) ;; ======================================================================
true
;; AUTHOR ;; PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> (in-package "X86ISA") ;; ====================================================================== ;; Undef Flg: (defun undef-flg$notinline (x86) (declare (xargs :mode :program :stobjs x86)) (when (or (equal (f-get-global 'in-prove-flg ACL2::*the-live-state*) t) (equal (f-get-global 'in-verify-flg ACL2::*the-live-state*) t)) (return-from X86ISA::undef-flg$notinline (X86ISA::undef-flg-logic x86))) ;; TO-DO@Shilpi: For now, I'm just returning 0 as the "undefined" ;; value for flags. (mv 0 x86) ;; (b* ((- (cw "~%undef-flg at PC: ~x0~%" (X86ISA::rip X86ISA::*the-live-x86*)))) ;; (mv 0 x86)) ) (defun undef-read$notinline (x86) (declare (xargs :mode :program :stobjs x86)) (when (or (equal (f-get-global 'in-prove-read ACL2::*the-live-state*) t) (equal (f-get-global 'in-verify-read ACL2::*the-live-state*) t)) (return-from X86ISA::undef-read$notinline (X86ISA::undef-read-logic x86))) ;; TO-DO@Shilpi: For now, I'm just returning 0 as the "undefined" ;; value. (mv 0 x86) ;; (b* ((- (cw "~%undef-read at PC: ~x0~%" (X86ISA::rip X86ISA::*the-live-x86*)))) ;; (mv 0 x86)) ) ;; Safe-!undef: ;; (defun safe-!undef$notinline (v x86) ;; (declare (xargs :mode :program :stobjs x86)) ;; (when (or (equal (f-get-global 'in-prove-flg ACL2::*the-live-state*) ;; t) ;; (equal (f-get-global 'in-verify-flg ;; ACL2::*the-live-state*) ;; t)) ;; (return-from X86ISA::safe-!undef$notinline ;; (X86ISA::!undef v x86))) ;; (er hard! 'safe-!undef ;; "Ill-advised attempt to call safe-!undef during top-level ~ ;; evaluation.")) ;; ======================================================================
[ { "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.9999229907989502, "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.9998950362205505, "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.ui)\n\n", "end": 134, "score": 0.9999268651008606, "start": 116, "tag": "EMAIL", "value": "[email protected]" } ]
ui/text-field.lisp
pupcraft/trial
0
#| 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.ui) (define-shader-entity text-field-cursor (vertex-entity) ((text-field :initarg :text-field :accessor text-field) (text-position :initform 0 :accessor text-position) (cursor-size :initform (vec4 0 0 0.5 1) :reader cursor-size)) (:default-initargs :text-field (error "TEXT-FIELD required.") :vertex-array (asset 'trial 'fullscreen-square))) (defmethod initialize-instance :after ((cursor text-field-cursor) &key text-field) (let* ((extent (extent (text-asset text-field))) (u (getf extent :t)) (b (getf extent :b))) (setf (vy (cursor-size cursor)) 0) (setf (vz (cursor-size cursor)) (/ (size (text-asset text-field)) (size (font (text-asset text-field))) 2)) (setf (vw (cursor-size cursor)) (/ (- u b) 2)))) (defmethod (setf text-position) :around (value (cursor text-field-cursor)) (call-next-method (min (length (text (text-field cursor))) (max 0 value)) cursor)) (defmethod (setf text-position) :after (value (cursor text-field-cursor)) (setf (vx (cursor-size cursor)) (getf (text-extent (text-asset (text-field cursor)) (subseq (text (text-field cursor)) 0 (text-position cursor))) :r))) (defmethod paint :before ((cursor text-field-cursor) target) (let ((size (cursor-size cursor))) (translate-by (vx size) (+ (vy size) (vw size)) 0) (scale-by (vz size) (vw size) 1))) (define-class-shader (text-field-cursor :fragment-shader) "out vec4 color; void main(){ color = vec4(0,0,0,1); }") (define-shader-entity text-field (highlightable-widget text-element control) ((cursor :accessor cursor)) (:default-initargs :align (list :left :center))) (defmethod initialize-instance :after ((text-field text-field) &key) (setf (cursor text-field) (make-instance 'text-field-cursor :text-field text-field)) (setf (text-position (cursor text-field)) (length (text text-field)))) (defmethod register-object-for-pass :after (pass (text-field text-field)) (register-object-for-pass pass (cursor text-field))) (defmethod paint :after ((text-field text-field) target) (paint (cursor text-field) target)) (defun string-remove-pos (string pos) (let ((new (make-array (1- (length string)) :element-type 'character))) (replace new string :end1 pos) (replace new string :start1 pos :start2 (1+ pos)) new)) (defun string-insert-pos (string pos stuff) (let ((new (make-array (+ (length string) (length stuff)) :element-type 'character))) (replace new string :end1 pos) (replace new stuff :start1 pos) (replace new string :start1 (+ pos (length stuff)) :start2 pos) new)) (defmethod handle ((event key-release) (text-field text-field)) (let ((key (key event)) (cursor (cursor text-field))) (with-accessors ((text-position text-position)) cursor (case key (:backspace (when (<= 1 text-position (length (text text-field))) (setf (text text-field) (string-remove-pos (text text-field) (1- text-position))) (decf text-position))) (:delete (when (< -1 text-position (length (text text-field))) (setf (text text-field) (string-remove-pos (text text-field) text-position)))) (:left (decf text-position)) (:right (incf text-position)) (:home (setf text-position 0)) (:end (setf text-position (length (text text-field)))))))) (defmethod handle ((event text-entered) (text-field text-field)) (setf (text text-field) (string-insert-pos (text text-field) (text-position (cursor text-field)) (text event))) (incf (text-position (cursor text-field)) (length (text event))))
55235
#| This file is a part of trial (c) 2017 Shirakumo http://tymoon.eu (<EMAIL>) Author: <NAME> <<EMAIL>> |# (in-package #:org.shirakumo.fraf.trial.ui) (define-shader-entity text-field-cursor (vertex-entity) ((text-field :initarg :text-field :accessor text-field) (text-position :initform 0 :accessor text-position) (cursor-size :initform (vec4 0 0 0.5 1) :reader cursor-size)) (:default-initargs :text-field (error "TEXT-FIELD required.") :vertex-array (asset 'trial 'fullscreen-square))) (defmethod initialize-instance :after ((cursor text-field-cursor) &key text-field) (let* ((extent (extent (text-asset text-field))) (u (getf extent :t)) (b (getf extent :b))) (setf (vy (cursor-size cursor)) 0) (setf (vz (cursor-size cursor)) (/ (size (text-asset text-field)) (size (font (text-asset text-field))) 2)) (setf (vw (cursor-size cursor)) (/ (- u b) 2)))) (defmethod (setf text-position) :around (value (cursor text-field-cursor)) (call-next-method (min (length (text (text-field cursor))) (max 0 value)) cursor)) (defmethod (setf text-position) :after (value (cursor text-field-cursor)) (setf (vx (cursor-size cursor)) (getf (text-extent (text-asset (text-field cursor)) (subseq (text (text-field cursor)) 0 (text-position cursor))) :r))) (defmethod paint :before ((cursor text-field-cursor) target) (let ((size (cursor-size cursor))) (translate-by (vx size) (+ (vy size) (vw size)) 0) (scale-by (vz size) (vw size) 1))) (define-class-shader (text-field-cursor :fragment-shader) "out vec4 color; void main(){ color = vec4(0,0,0,1); }") (define-shader-entity text-field (highlightable-widget text-element control) ((cursor :accessor cursor)) (:default-initargs :align (list :left :center))) (defmethod initialize-instance :after ((text-field text-field) &key) (setf (cursor text-field) (make-instance 'text-field-cursor :text-field text-field)) (setf (text-position (cursor text-field)) (length (text text-field)))) (defmethod register-object-for-pass :after (pass (text-field text-field)) (register-object-for-pass pass (cursor text-field))) (defmethod paint :after ((text-field text-field) target) (paint (cursor text-field) target)) (defun string-remove-pos (string pos) (let ((new (make-array (1- (length string)) :element-type 'character))) (replace new string :end1 pos) (replace new string :start1 pos :start2 (1+ pos)) new)) (defun string-insert-pos (string pos stuff) (let ((new (make-array (+ (length string) (length stuff)) :element-type 'character))) (replace new string :end1 pos) (replace new stuff :start1 pos) (replace new string :start1 (+ pos (length stuff)) :start2 pos) new)) (defmethod handle ((event key-release) (text-field text-field)) (let ((key (key event)) (cursor (cursor text-field))) (with-accessors ((text-position text-position)) cursor (case key (:backspace (when (<= 1 text-position (length (text text-field))) (setf (text text-field) (string-remove-pos (text text-field) (1- text-position))) (decf text-position))) (:delete (when (< -1 text-position (length (text text-field))) (setf (text text-field) (string-remove-pos (text text-field) text-position)))) (:left (decf text-position)) (:right (incf text-position)) (:home (setf text-position 0)) (:end (setf text-position (length (text text-field)))))))) (defmethod handle ((event text-entered) (text-field text-field)) (setf (text text-field) (string-insert-pos (text text-field) (text-position (cursor text-field)) (text event))) (incf (text-position (cursor text-field)) (length (text event))))
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.ui) (define-shader-entity text-field-cursor (vertex-entity) ((text-field :initarg :text-field :accessor text-field) (text-position :initform 0 :accessor text-position) (cursor-size :initform (vec4 0 0 0.5 1) :reader cursor-size)) (:default-initargs :text-field (error "TEXT-FIELD required.") :vertex-array (asset 'trial 'fullscreen-square))) (defmethod initialize-instance :after ((cursor text-field-cursor) &key text-field) (let* ((extent (extent (text-asset text-field))) (u (getf extent :t)) (b (getf extent :b))) (setf (vy (cursor-size cursor)) 0) (setf (vz (cursor-size cursor)) (/ (size (text-asset text-field)) (size (font (text-asset text-field))) 2)) (setf (vw (cursor-size cursor)) (/ (- u b) 2)))) (defmethod (setf text-position) :around (value (cursor text-field-cursor)) (call-next-method (min (length (text (text-field cursor))) (max 0 value)) cursor)) (defmethod (setf text-position) :after (value (cursor text-field-cursor)) (setf (vx (cursor-size cursor)) (getf (text-extent (text-asset (text-field cursor)) (subseq (text (text-field cursor)) 0 (text-position cursor))) :r))) (defmethod paint :before ((cursor text-field-cursor) target) (let ((size (cursor-size cursor))) (translate-by (vx size) (+ (vy size) (vw size)) 0) (scale-by (vz size) (vw size) 1))) (define-class-shader (text-field-cursor :fragment-shader) "out vec4 color; void main(){ color = vec4(0,0,0,1); }") (define-shader-entity text-field (highlightable-widget text-element control) ((cursor :accessor cursor)) (:default-initargs :align (list :left :center))) (defmethod initialize-instance :after ((text-field text-field) &key) (setf (cursor text-field) (make-instance 'text-field-cursor :text-field text-field)) (setf (text-position (cursor text-field)) (length (text text-field)))) (defmethod register-object-for-pass :after (pass (text-field text-field)) (register-object-for-pass pass (cursor text-field))) (defmethod paint :after ((text-field text-field) target) (paint (cursor text-field) target)) (defun string-remove-pos (string pos) (let ((new (make-array (1- (length string)) :element-type 'character))) (replace new string :end1 pos) (replace new string :start1 pos :start2 (1+ pos)) new)) (defun string-insert-pos (string pos stuff) (let ((new (make-array (+ (length string) (length stuff)) :element-type 'character))) (replace new string :end1 pos) (replace new stuff :start1 pos) (replace new string :start1 (+ pos (length stuff)) :start2 pos) new)) (defmethod handle ((event key-release) (text-field text-field)) (let ((key (key event)) (cursor (cursor text-field))) (with-accessors ((text-position text-position)) cursor (case key (:backspace (when (<= 1 text-position (length (text text-field))) (setf (text text-field) (string-remove-pos (text text-field) (1- text-position))) (decf text-position))) (:delete (when (< -1 text-position (length (text text-field))) (setf (text text-field) (string-remove-pos (text text-field) text-position)))) (:left (decf text-position)) (:right (incf text-position)) (:home (setf text-position 0)) (:end (setf text-position (length (text text-field)))))))) (defmethod handle ((event text-entered) (text-field text-field)) (setf (text text-field) (string-insert-pos (text text-field) (text-position (cursor text-field)) (text event))) (incf (text-position (cursor text-field)) (length (text event))))
[ { "context": "mental Test Lisp Language Experiments\"\n :author \"Peter Keller <[email protected]>\"\n :license \"MIT License\"\n", "end": 109, "score": 0.9998927116394043, "start": 97, "tag": "NAME", "value": "Peter Keller" }, { "context": "sp Language Experiments\"\n :author \"Peter Keller <[email protected]>\"\n :license \"MIT License\"\n :version \"0.0.1\"\n ", "end": 130, "score": 0.9999321699142456, "start": 111, "tag": "EMAIL", "value": "[email protected]" } ]
psilisp.asd
psilord/psilisp
1
(asdf:defsystem #:psilisp :description "Incremental Test Lisp Language Experiments" :author "Peter Keller <[email protected]>" :license "MIT License" :version "0.0.1" :serial t :depends-on (:cl-ppcre :alexandria) :components ((:file "package") (:file "base") ;; stuff used by all compilers. (:file "symtab") (:file "blsymtab") (:file "env") (:file "base-test") ;; Ghoulum's incremental lisp compiler (:file "c0") (:file "c0-test") ;; My first dialect to explore these topics: ;; alpha-conversion ;; free variables ;; mutable variable pass ;; closure conversion (:file "c1") (:file "c1-test-support")))
67776
(asdf:defsystem #:psilisp :description "Incremental Test Lisp Language Experiments" :author "<NAME> <<EMAIL>>" :license "MIT License" :version "0.0.1" :serial t :depends-on (:cl-ppcre :alexandria) :components ((:file "package") (:file "base") ;; stuff used by all compilers. (:file "symtab") (:file "blsymtab") (:file "env") (:file "base-test") ;; Ghoulum's incremental lisp compiler (:file "c0") (:file "c0-test") ;; My first dialect to explore these topics: ;; alpha-conversion ;; free variables ;; mutable variable pass ;; closure conversion (:file "c1") (:file "c1-test-support")))
true
(asdf:defsystem #:psilisp :description "Incremental Test Lisp Language Experiments" :author "PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>" :license "MIT License" :version "0.0.1" :serial t :depends-on (:cl-ppcre :alexandria) :components ((:file "package") (:file "base") ;; stuff used by all compilers. (:file "symtab") (:file "blsymtab") (:file "env") (:file "base-test") ;; Ghoulum's incremental lisp compiler (:file "c0") (:file "c0-test") ;; My first dialect to explore these topics: ;; alpha-conversion ;; free variables ;; mutable variable pass ;; closure conversion (:file "c1") (:file "c1-test-support")))
[ { "context": ";-*- Mode: Lisp -*-\n;;;; Author: Paul Dietz\n;;;; Created: Sat Apr 19 21:37:56 2003\n;;;; Cont", "end": 49, "score": 0.9998691082000732, "start": 39, "tag": "NAME", "value": "Paul Dietz" } ]
ansi-tests/subst.lsp
TeamSPoon/CYC_JRTL_with_CommonLisp_OLD
10
;-*- Mode: Lisp -*- ;;;; Author: Paul Dietz ;;;; Created: Sat Apr 19 21:37:56 2003 ;;;; Contains: Tests of SUBST (in-package :cl-test) (compile-and-load "cons-aux.lsp") (defvar *subst-tree-1* '(10 (30 20 10) (20 10) (10 20 30 40))) (deftest subst.1 (check-subst "Z" 30 (copy-tree *subst-tree-1*)) (10 ("Z" 20 10) (20 10) (10 20 "Z" 40))) (deftest subst.2 (check-subst "A" 0 (copy-tree *subst-tree-1*)) (10 (30 20 10) (20 10) (10 20 30 40))) (deftest subst.3 (check-subst "Z" 100 (copy-tree *subst-tree-1*) :test-not #'eql) "Z") (deftest subst.4 (check-subst 'grape 'dick '(melville wrote (moby dick))) (melville wrote (moby grape))) (deftest subst.5 (check-subst 'cha-cha-cha 'nil '(melville wrote (moby dick))) (melville wrote (moby dick . cha-cha-cha) . cha-cha-cha)) (deftest subst.6 (check-subst '(1 2) '(foo . bar) '((foo . baz) (foo . bar) (bar . foo) (baz foo . bar)) :test #'equal) ((foo . baz) (1 2) (bar . foo) (baz 1 2))) (deftest subst.7 (check-subst 'foo "aaa" '((1 . 2) (4 . 5) (6 7 8 9 10 (11 12))) :key #'(lambda (x) (if (and (numberp x) (evenp x)) "aaa" nil)) :test #'string=) ((1 . foo) (foo . 5) (foo 7 foo 9 foo (11 foo)))) (deftest subst.8 (check-subst 'foo nil '((1 . 2) (4 . 5) (6 7 8 9 10 (11 12))) :key #'(lambda (x) (if (and (numberp x) (evenp x)) (copy-seq "aaa") nil)) :test-not #'equal) ((1 . foo) (foo . 5) (foo 7 foo 9 foo (11 foo)))) (deftest subst.9 (check-subst 'a 'b (copy-tree '(a b c d a b)) :key nil) (a a c d a a)) (deftest subst.10 (check-subst 'x 10 (copy-tree '(1 2 10 20 30 4)) :test #'(lambda (x y) (and (realp x) (realp y) (< x y)))) (1 2 10 x x 4)) (deftest subst.11 (check-subst 'x 10 (copy-tree '(1 2 10 20 30 4)) :test-not #'(lambda (x y) (not (and (realp x) (realp y) (< x y))))) (1 2 10 x x 4)) (defharmless subset.test-and-test-not.1 (subst 'a 'b (list 'a 'b 'c 'd 'e) :test #'eq :test-not #'eq)) (defharmless subset.test-and-test-not.2 (subst 'a 'b (list 'a 'b 'c 'd 'e) :test-not #'eq :test #'eq)) ;;; Order of argument evaluation (deftest subst.order.1 (let ((i 0) v w x y z) (values (subst (progn (setf v (incf i)) 'b) (progn (setf w (incf i)) 'a) (progn (setf x (incf i)) (copy-tree '((10 a . a) a b c ((a)) z))) :key (progn (setf y (incf i)) #'identity) :test (progn (setf z (incf i)) #'eql)) i v w x y z)) ((10 b . b) b b c ((b)) z) 5 1 2 3 4 5) (deftest subst.order.2 (let ((i 0) v w x y z) (values (subst (progn (setf v (incf i)) 'b) (progn (setf w (incf i)) 'a) (progn (setf x (incf i)) (copy-tree '((10 a . a) a b c ((a)) z))) :test-not (progn (setf y (incf i)) (complement #'eql)) :key (progn (setf z (incf i)) #'identity) ) i v w x y z)) ((10 b . b) b b c ((b)) z) 5 1 2 3 4 5) ;;; Const fold tests (def-fold-test subst.fold.1 (subst 'a 'b '(a b c (a . b) . a))) ;;; Keyword tests for subst (deftest subst.allow-other-keys.1 (subst 'a 'b (list 'a 'b 'c) :bad t :allow-other-keys t) (a a c)) (deftest subst.allow-other-keys.2 (subst 'a 'b (list 'a 'b 'c) :allow-other-keys t) (a a c)) (deftest subst.allow-other-keys.3 (subst 'a 'b (list 'a 'b 'c) :allow-other-keys nil) (a a c)) (deftest subst.allow-other-keys.4 (subst 'a 'b (list 'a 'b 'c) :allow-other-keys t :bad t) (a a c)) (deftest subst.allow-other-keys.5 (subst 'a 'b (list 'a 'b 'c) :allow-other-keys t :allow-other-keys nil :bad t) (a a c)) (deftest subst.keywords.6 (subst 'a 'b (list 'a 'b 'c) :test #'eq :test (complement #'eq)) (a a c)) (deftest subst.error.1 (signals-error (subst) program-error) t) (deftest subst.error.2 (signals-error (subst 'a) program-error) t) (deftest subst.error.3 (signals-error (subst 'a 'b) program-error) t) (deftest subst.error.4 (signals-error (subst 'a 'b nil :foo nil) program-error) t) (deftest subst.error.5 (signals-error (subst 'a 'b nil :test) program-error) t) (deftest subst.error.6 (signals-error (subst 'a 'b nil 1) program-error) t) (deftest subst.error.7 (signals-error (subst 'a 'b nil :bad t :allow-other-keys nil) program-error) t) (deftest subst.error.8 (signals-error (subst 'a 'b (list 'a 'b) :test #'identity) program-error) t) (deftest subst.error.9 (signals-error (subst 'a 'b (list 'a 'b) :test-not #'identity) program-error) t) (deftest subst.error.10 (signals-error (subst 'a 'b (list 'a 'b) :key #'equal) program-error) t)
22436
;-*- Mode: Lisp -*- ;;;; Author: <NAME> ;;;; Created: Sat Apr 19 21:37:56 2003 ;;;; Contains: Tests of SUBST (in-package :cl-test) (compile-and-load "cons-aux.lsp") (defvar *subst-tree-1* '(10 (30 20 10) (20 10) (10 20 30 40))) (deftest subst.1 (check-subst "Z" 30 (copy-tree *subst-tree-1*)) (10 ("Z" 20 10) (20 10) (10 20 "Z" 40))) (deftest subst.2 (check-subst "A" 0 (copy-tree *subst-tree-1*)) (10 (30 20 10) (20 10) (10 20 30 40))) (deftest subst.3 (check-subst "Z" 100 (copy-tree *subst-tree-1*) :test-not #'eql) "Z") (deftest subst.4 (check-subst 'grape 'dick '(melville wrote (moby dick))) (melville wrote (moby grape))) (deftest subst.5 (check-subst 'cha-cha-cha 'nil '(melville wrote (moby dick))) (melville wrote (moby dick . cha-cha-cha) . cha-cha-cha)) (deftest subst.6 (check-subst '(1 2) '(foo . bar) '((foo . baz) (foo . bar) (bar . foo) (baz foo . bar)) :test #'equal) ((foo . baz) (1 2) (bar . foo) (baz 1 2))) (deftest subst.7 (check-subst 'foo "aaa" '((1 . 2) (4 . 5) (6 7 8 9 10 (11 12))) :key #'(lambda (x) (if (and (numberp x) (evenp x)) "aaa" nil)) :test #'string=) ((1 . foo) (foo . 5) (foo 7 foo 9 foo (11 foo)))) (deftest subst.8 (check-subst 'foo nil '((1 . 2) (4 . 5) (6 7 8 9 10 (11 12))) :key #'(lambda (x) (if (and (numberp x) (evenp x)) (copy-seq "aaa") nil)) :test-not #'equal) ((1 . foo) (foo . 5) (foo 7 foo 9 foo (11 foo)))) (deftest subst.9 (check-subst 'a 'b (copy-tree '(a b c d a b)) :key nil) (a a c d a a)) (deftest subst.10 (check-subst 'x 10 (copy-tree '(1 2 10 20 30 4)) :test #'(lambda (x y) (and (realp x) (realp y) (< x y)))) (1 2 10 x x 4)) (deftest subst.11 (check-subst 'x 10 (copy-tree '(1 2 10 20 30 4)) :test-not #'(lambda (x y) (not (and (realp x) (realp y) (< x y))))) (1 2 10 x x 4)) (defharmless subset.test-and-test-not.1 (subst 'a 'b (list 'a 'b 'c 'd 'e) :test #'eq :test-not #'eq)) (defharmless subset.test-and-test-not.2 (subst 'a 'b (list 'a 'b 'c 'd 'e) :test-not #'eq :test #'eq)) ;;; Order of argument evaluation (deftest subst.order.1 (let ((i 0) v w x y z) (values (subst (progn (setf v (incf i)) 'b) (progn (setf w (incf i)) 'a) (progn (setf x (incf i)) (copy-tree '((10 a . a) a b c ((a)) z))) :key (progn (setf y (incf i)) #'identity) :test (progn (setf z (incf i)) #'eql)) i v w x y z)) ((10 b . b) b b c ((b)) z) 5 1 2 3 4 5) (deftest subst.order.2 (let ((i 0) v w x y z) (values (subst (progn (setf v (incf i)) 'b) (progn (setf w (incf i)) 'a) (progn (setf x (incf i)) (copy-tree '((10 a . a) a b c ((a)) z))) :test-not (progn (setf y (incf i)) (complement #'eql)) :key (progn (setf z (incf i)) #'identity) ) i v w x y z)) ((10 b . b) b b c ((b)) z) 5 1 2 3 4 5) ;;; Const fold tests (def-fold-test subst.fold.1 (subst 'a 'b '(a b c (a . b) . a))) ;;; Keyword tests for subst (deftest subst.allow-other-keys.1 (subst 'a 'b (list 'a 'b 'c) :bad t :allow-other-keys t) (a a c)) (deftest subst.allow-other-keys.2 (subst 'a 'b (list 'a 'b 'c) :allow-other-keys t) (a a c)) (deftest subst.allow-other-keys.3 (subst 'a 'b (list 'a 'b 'c) :allow-other-keys nil) (a a c)) (deftest subst.allow-other-keys.4 (subst 'a 'b (list 'a 'b 'c) :allow-other-keys t :bad t) (a a c)) (deftest subst.allow-other-keys.5 (subst 'a 'b (list 'a 'b 'c) :allow-other-keys t :allow-other-keys nil :bad t) (a a c)) (deftest subst.keywords.6 (subst 'a 'b (list 'a 'b 'c) :test #'eq :test (complement #'eq)) (a a c)) (deftest subst.error.1 (signals-error (subst) program-error) t) (deftest subst.error.2 (signals-error (subst 'a) program-error) t) (deftest subst.error.3 (signals-error (subst 'a 'b) program-error) t) (deftest subst.error.4 (signals-error (subst 'a 'b nil :foo nil) program-error) t) (deftest subst.error.5 (signals-error (subst 'a 'b nil :test) program-error) t) (deftest subst.error.6 (signals-error (subst 'a 'b nil 1) program-error) t) (deftest subst.error.7 (signals-error (subst 'a 'b nil :bad t :allow-other-keys nil) program-error) t) (deftest subst.error.8 (signals-error (subst 'a 'b (list 'a 'b) :test #'identity) program-error) t) (deftest subst.error.9 (signals-error (subst 'a 'b (list 'a 'b) :test-not #'identity) program-error) t) (deftest subst.error.10 (signals-error (subst 'a 'b (list 'a 'b) :key #'equal) program-error) t)
true
;-*- Mode: Lisp -*- ;;;; Author: PI:NAME:<NAME>END_PI ;;;; Created: Sat Apr 19 21:37:56 2003 ;;;; Contains: Tests of SUBST (in-package :cl-test) (compile-and-load "cons-aux.lsp") (defvar *subst-tree-1* '(10 (30 20 10) (20 10) (10 20 30 40))) (deftest subst.1 (check-subst "Z" 30 (copy-tree *subst-tree-1*)) (10 ("Z" 20 10) (20 10) (10 20 "Z" 40))) (deftest subst.2 (check-subst "A" 0 (copy-tree *subst-tree-1*)) (10 (30 20 10) (20 10) (10 20 30 40))) (deftest subst.3 (check-subst "Z" 100 (copy-tree *subst-tree-1*) :test-not #'eql) "Z") (deftest subst.4 (check-subst 'grape 'dick '(melville wrote (moby dick))) (melville wrote (moby grape))) (deftest subst.5 (check-subst 'cha-cha-cha 'nil '(melville wrote (moby dick))) (melville wrote (moby dick . cha-cha-cha) . cha-cha-cha)) (deftest subst.6 (check-subst '(1 2) '(foo . bar) '((foo . baz) (foo . bar) (bar . foo) (baz foo . bar)) :test #'equal) ((foo . baz) (1 2) (bar . foo) (baz 1 2))) (deftest subst.7 (check-subst 'foo "aaa" '((1 . 2) (4 . 5) (6 7 8 9 10 (11 12))) :key #'(lambda (x) (if (and (numberp x) (evenp x)) "aaa" nil)) :test #'string=) ((1 . foo) (foo . 5) (foo 7 foo 9 foo (11 foo)))) (deftest subst.8 (check-subst 'foo nil '((1 . 2) (4 . 5) (6 7 8 9 10 (11 12))) :key #'(lambda (x) (if (and (numberp x) (evenp x)) (copy-seq "aaa") nil)) :test-not #'equal) ((1 . foo) (foo . 5) (foo 7 foo 9 foo (11 foo)))) (deftest subst.9 (check-subst 'a 'b (copy-tree '(a b c d a b)) :key nil) (a a c d a a)) (deftest subst.10 (check-subst 'x 10 (copy-tree '(1 2 10 20 30 4)) :test #'(lambda (x y) (and (realp x) (realp y) (< x y)))) (1 2 10 x x 4)) (deftest subst.11 (check-subst 'x 10 (copy-tree '(1 2 10 20 30 4)) :test-not #'(lambda (x y) (not (and (realp x) (realp y) (< x y))))) (1 2 10 x x 4)) (defharmless subset.test-and-test-not.1 (subst 'a 'b (list 'a 'b 'c 'd 'e) :test #'eq :test-not #'eq)) (defharmless subset.test-and-test-not.2 (subst 'a 'b (list 'a 'b 'c 'd 'e) :test-not #'eq :test #'eq)) ;;; Order of argument evaluation (deftest subst.order.1 (let ((i 0) v w x y z) (values (subst (progn (setf v (incf i)) 'b) (progn (setf w (incf i)) 'a) (progn (setf x (incf i)) (copy-tree '((10 a . a) a b c ((a)) z))) :key (progn (setf y (incf i)) #'identity) :test (progn (setf z (incf i)) #'eql)) i v w x y z)) ((10 b . b) b b c ((b)) z) 5 1 2 3 4 5) (deftest subst.order.2 (let ((i 0) v w x y z) (values (subst (progn (setf v (incf i)) 'b) (progn (setf w (incf i)) 'a) (progn (setf x (incf i)) (copy-tree '((10 a . a) a b c ((a)) z))) :test-not (progn (setf y (incf i)) (complement #'eql)) :key (progn (setf z (incf i)) #'identity) ) i v w x y z)) ((10 b . b) b b c ((b)) z) 5 1 2 3 4 5) ;;; Const fold tests (def-fold-test subst.fold.1 (subst 'a 'b '(a b c (a . b) . a))) ;;; Keyword tests for subst (deftest subst.allow-other-keys.1 (subst 'a 'b (list 'a 'b 'c) :bad t :allow-other-keys t) (a a c)) (deftest subst.allow-other-keys.2 (subst 'a 'b (list 'a 'b 'c) :allow-other-keys t) (a a c)) (deftest subst.allow-other-keys.3 (subst 'a 'b (list 'a 'b 'c) :allow-other-keys nil) (a a c)) (deftest subst.allow-other-keys.4 (subst 'a 'b (list 'a 'b 'c) :allow-other-keys t :bad t) (a a c)) (deftest subst.allow-other-keys.5 (subst 'a 'b (list 'a 'b 'c) :allow-other-keys t :allow-other-keys nil :bad t) (a a c)) (deftest subst.keywords.6 (subst 'a 'b (list 'a 'b 'c) :test #'eq :test (complement #'eq)) (a a c)) (deftest subst.error.1 (signals-error (subst) program-error) t) (deftest subst.error.2 (signals-error (subst 'a) program-error) t) (deftest subst.error.3 (signals-error (subst 'a 'b) program-error) t) (deftest subst.error.4 (signals-error (subst 'a 'b nil :foo nil) program-error) t) (deftest subst.error.5 (signals-error (subst 'a 'b nil :test) program-error) t) (deftest subst.error.6 (signals-error (subst 'a 'b nil 1) program-error) t) (deftest subst.error.7 (signals-error (subst 'a 'b nil :bad t :allow-other-keys nil) program-error) t) (deftest subst.error.8 (signals-error (subst 'a 'b (list 'a 'b) :test #'identity) program-error) t) (deftest subst.error.9 (signals-error (subst 'a 'b (list 'a 'b) :test-not #'identity) program-error) t) (deftest subst.error.10 (signals-error (subst 'a 'b (list 'a 'b) :key #'equal) program-error) t)
[ { "context": ";;;; Copyright (c) Frank James 2016 <[email protected]>\r\n;;;; This code is", "end": 30, "score": 0.999845027923584, "start": 19, "tag": "NAME", "value": "Frank James" }, { "context": ";;;; Copyright (c) Frank James 2016 <[email protected]>\r\n;;;; This code is licensed under the MIT licens", "end": 60, "score": 0.9999279379844666, "start": 37, "tag": "EMAIL", "value": "[email protected]" }, { "context": "eper game written in Common Lisp.\r\n\r\nCopyright (c) Frank James 2016.\r\n\"\r\n\t\t :caption \"About\"))\r\n (5 ;;", "end": 37482, "score": 0.9998083710670471, "start": 37471, "tag": "NAME", "value": "Frank James" } ]
examples/minesweeper/minesweeper.lisp
fjames86/ftw
48
;;;; Copyright (c) Frank James 2016 <[email protected]> ;;;; This code is licensed under the MIT license. ;;; Simple minesweeper game ;;; Things which could be done and are left as an exercise to the reader: ;;; 1. Adding icons/images instead of using text for the numbers, mines and flags. ;;; 2. Keeping a high-score list saved away e.g. in current user's home directory. ;;; 3. Writing a proper "about" dialog. ;;; 4. Dialog for entering arbitrary game sizes. ;;; 5. Automatically clicking on provable empty cells ;;; 6. Win detection ;;; 7. Automatically resizing main window to the size of the game board (defpackage #:ftw.minesweeper (:use #:cl #:cffi #:ftw) (:export #:minesweeper)) (in-package #:ftw.minesweeper) (defstruct minesweeper x y cells flags finished seconds) (defun cell (ms x y) (aref (minesweeper-cells ms) y x)) (defun (setf cell) (value ms x y) (setf (aref (minesweeper-cells ms) y x) value)) (defun set-flag (ms x y &optional set) (if set (pushnew :flag (cell ms x y)) (setf (cell ms x y) (remove :flag (cell ms x y))))) (defun flag-p (ms x y) (member :flag (cell ms x y))) (defun mine-p (ms x y) (member :mine (cell ms x y))) (defun mines (ms x y) (let ((m 0)) (do ((i (1- x) (1+ i))) ((> i (1+ x))) (do ((j (1- y) (1+ j))) ((> j (1+ y))) (when (and (>= i 0) (< i (minesweeper-x ms))) (when (and (>= j 0) (< j (minesweeper-y ms))) (unless (and (= i x) (= j y)) (when (mine-p ms i j) (incf m))))))) m)) (defvar *starting-mines* 10) (defvar *starting-x* 10) (defvar *starting-y* 10) (defvar *ms* nil) (defun random-game (&key x y mines) (unless x (setf x *starting-x*)) (unless y (setf y *starting-y*)) (unless mines (setf mines *starting-mines*)) (let ((ms (make-minesweeper :x x :y y :cells (make-array (list x y) :element-type t :initial-contents (let ((m mines)) (loop :for i :below x :collect (loop :for j :below y :collect (let ((left (- (* x y) (+ (* i y) j)))) (cond ((or (zerop left) (zerop m)) nil) ((<= left m) (decf m) (list :mine)) ((<= (random left) m) (decf m) (list :mine)) (t nil))))))) :flags mines :seconds 0))) ms)) (defun clicked-p (ms x y) (integerp (car (cell ms x y)))) (defun unclicked-neighbours (ms x y) (let ((neighbours nil)) (do ((i (1- x) (1+ i))) ((= i (+ x 2))) (do ((j (1- y) (1+ j))) ((= j (+ y 2))) (when (and (>= i 0) (< i (minesweeper-x ms)) (>= j 0) (< j (minesweeper-y ms)) (not (and (= i x) (= j y))) (not (clicked-p ms i j))) (push (list i j) neighbours)))) neighbours)) (defun click-provable-cells (ms x y) "If this location has a mine count of 0 then look at all the unclicked cells around this location and click those too. Repeat recursively." (when (= (mines ms x y) 0) (dolist (n (unclicked-neighbours ms x y)) (click-cell ms (first n) (second n))))) (defun click-cell (ms x y) (cond ((mine-p ms x y) :mine) (t (setf (cell ms x y) (list (mines ms x y))) (click-provable-cells ms x y) (cell ms x y)))) (defun resize-window (hwnd) "Set the window to the size required for the game" (let ((w (minesweeper-x *ms*)) (h (minesweeper-y *ms*))) (set-window-pos hwnd :top 0 0 (+ 100 (* w 25)) (+ 175 (* h 25)) '(:no-move)))) (defun game-won-p () "Returns true if all mines have a flag placed on them." (let ((mines 0) (correct 0)) (dotimes (i (minesweeper-x *ms*)) (dotimes (j (minesweeper-y *ms*)) (when (mine-p *ms* i j) (incf mines) (when (flag-p *ms* i j) (incf correct))))) (= mines correct))) ;; I made a little icon in gimp and exported it as a microsoft icon (*.ico) file. ;; Then I ran generate-icon-resource on that file. I pasted the output below. (defvar *MINE-ICON* (create-icon 32 32 1 32 (make-array 4224 :element-type '(unsigned-byte 8)) #(#x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #xFC #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x5F #x00 #x00 #x00 #xD5 #x00 #x00 #x00 #x3E #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x77 #x00 #x00 #x00 #xB6 #x00 #x00 #x00 #x5A #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #xE9 #x00 #x00 #x00 #xF3 #x00 #x00 #x00 #xF3 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #xAA #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x03 #x00 #x00 #x00 #x35 #x00 #x00 #x00 #x83 #x00 #x00 #x00 #xCA #x00 #x00 #x00 #xF5 #x00 #x00 #x00 #xF5 #x00 #x00 #x00 #xFF #x00 #x00 #x00 #x83 #x00 #x00 #x00 #x35 #x00 #x00 #x00 #x03 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x6C #x00 #x00 #x00 #x6C #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #xCE #x00 #x00 #x00 #x6C #x00 #x00 #x00 #x01 #x00 #x00 #x00 #x56 #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #x56 #x00 #x00 #x00 #x01 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x6C #x00 #x00 #x00 #xAA #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #xE4 #x00 #x00 #x00 #xC3 #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xC3 #x00 #x00 #x00 #xB0 #x00 #x00 #x00 #xAA #x00 #x00 #x00 #x6C #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x13 #x00 #x00 #x00 #xFA #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xF7 #x00 #x00 #x00 #x13 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x03 #x00 #x00 #x00 #xD3 #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xD3 #x00 #x00 #x00 #x03 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x6B #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #x6B #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x09 #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #x09 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x4A #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #x4A #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x9E #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #x9E #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x6F #x00 #x00 #x00 #xAE #x00 #x00 #x00 #xE0 #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x17 #x17 #x17 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xE0 #x00 #x00 #x00 #xDA #x00 #x00 #x00 #x53 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xF3 #x00 #x00 #x00 #xCA #x00 #x00 #x00 #xE9 #x00 #x00 #x00 #xFB #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x17 #x17 #x17 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x17 #x17 #x17 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFB #x00 #x00 #x00 #xD5 #x00 #x00 #x00 #xA3 #x00 #x00 #x00 #xFC #x00 #x00 #x00 #xFF #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #xAE #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xE0 #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x17 #x17 #x17 #xFF #x17 #x17 #x17 #xFF #x37 #x37 #x37 #xFF #x37 #x37 #x37 #xFF #x37 #x37 #x37 #xFF #x37 #x37 #x37 #xFF #x37 #x37 #x37 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xE0 #x00 #x00 #x00 #xDF #x00 #x00 #x00 #x98 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x9E #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x17 #x17 #x17 #xFF #x17 #x17 #x17 #xFF #x37 #x37 #x37 #xFF #x37 #x37 #x37 #xFF #x5B #x5B #x5B #xFF #x5B #x5B #x5B #xFF #x5B #x5B #x5B #xFF #x37 #x37 #x37 #xFF #x37 #x37 #x37 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #x9E #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x4A #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x37 #x37 #x37 #xFF #x5B #x5B #x5B #xFF #x5B #x5B #x5B #xFF #x5B #x5B #x5B #xFF #x5B #x5B #x5B #xFF #x5B #x5B #x5B #xFF #x5B #x5B #x5B #xFF #x37 #x37 #x37 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #x4A #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x09 #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x88 #x88 #x88 #xFF #x88 #x88 #x88 #xFF #x5B #x5B #x5B #xFF #x88 #x88 #x88 #xFF #x5B #x5B #x5B #xFF #x5B #x5B #x5B #xFF #x5B #x5B #x5B #xFF #x17 #x17 #x17 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #x09 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x6B #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x37 #x37 #x37 #xFF #x88 #x88 #x88 #xFF #x88 #x88 #x88 #xFF #x88 #x88 #x88 #xFF #x88 #x88 #x88 #xFF #x5B #x5B #x5B #xFF #x5B #x5B #x5B #xFF #x17 #x17 #x17 #xFF #x17 #x17 #x17 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #x6B #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x03 #x00 #x00 #x00 #xD3 #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x37 #x37 #x37 #xFF #x88 #x88 #x88 #xFF #x88 #x88 #x88 #xFF #xC7 #xC7 #xC7 #xFF #x5B #x5B #x5B #xFF #x37 #x37 #x37 #xFF #x17 #x17 #x17 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xD3 #x00 #x00 #x00 #x03 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x13 #x00 #x00 #x00 #xFC #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x37 #x37 #x37 #xFF #x88 #x88 #x88 #xFF #x49 #x49 #x49 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xF7 #x00 #x00 #x00 #x77 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #xAA #x00 #x00 #x00 #x76 #x00 #x00 #x00 #xC3 #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xC3 #x00 #x00 #x00 #xB0 #x00 #x00 #x00 #x6C #x00 #x00 #x00 #xAA #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x6C #x00 #x00 #x00 #x6C #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x01 #x00 #x00 #x00 #x56 #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #x56 #x00 #x00 #x00 #x01 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x6C #x00 #x00 #x00 #x6C #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x03 #x00 #x00 #x00 #x35 #x00 #x00 #x00 #x83 #x00 #x00 #x00 #xCA #x00 #x00 #x00 #xF5 #x00 #x00 #x00 #xF5 #x00 #x00 #x00 #xFF #x00 #x00 #x00 #x83 #x00 #x00 #x00 #x35 #x00 #x00 #x00 #x03 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x6C #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #xCC #x00 #x00 #x00 #xCC #x00 #x00 #x00 #x73 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #xC1 #x00 #x00 #x00 #xF3 #x00 #x00 #x00 #x98 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #xFF #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #xFF #xFF #xFF #xFF #xFF #xFF #x7F #xFF #xFF #xFE #x3F #xFF #xFF #xFE #x3F #xFF #xFF #xFE #x3F #xFF #xFD #xE0 #x07 #x3F #xFE #x00 #x01 #x3F #xFF #x00 #x00 #x3F #xFE #x00 #x00 #x7F #xFC #x00 #x00 #x3F #xFC #x00 #x00 #x3F #xF8 #x00 #x00 #x1F #xF8 #x00 #x00 #x1F #xF8 #x00 #x00 #x1F #xE0 #x00 #x00 #x07 #x80 #x00 #x00 #x01 #xE0 #x00 #x00 #x07 #xF8 #x00 #x00 #x1F #xF8 #x00 #x00 #x1F #xF8 #x00 #x00 #x1F #xFC #x00 #x00 #x3F #xFC #x00 #x00 #x3F #xFE #x00 #x00 #x7F #xFE #x00 #x00 #x3F #xFC #x80 #x01 #x3F #xFF #xE0 #x07 #xBF #xFF #xFE #x3F #xFF #xFF #xFE #x3F #xFF #xFF #xFE #x3F #xFF #xFF #xFF #x7F #xFF #xFF #xFF #xFF #xFF #xFF #xFF #xFF #xFF ))) (defwndproc minesweeper-wndproc (hwnd msg wparam lparam) (switch msg ((const +wm-create+) (setf *ms* (random-game)) (resize-window hwnd) ;; add menus (add-menu-bar hwnd `((:menu (:popup) :name "&Game" :children ((:item (:string) :name ,(format nil "&New~ACtrl+N" #\tab) :id 1) (:item (:separator)) (:item (:string) :name "Beginner" :id 6) (:item (:string) :name "Advanced" :id 7) (:item (:string) :name "Expert" :id 8) (:radio (6 8) :id 6) (:item (:separator)) (:item (:string) :name ,(format nil "&Quit~ACtrl+Q" #\tab) :id 2))) (:menu (:popup) :name "&Help" :children ((:item (:string) :name "&About" :id 3))))) (let ((right (getf (get-client-rect hwnd) :right 0))) (create-window :button :window-name "New" :styles (logior-consts +ws-visible+ +ws-child+ +bs-pushbutton+) :x (truncate right 2) :y 20 :width 45 :height 22 :parent hwnd :menu 5)) ;; create accelerator table (set-accelerator-table '((:keyn 1 :control :virtual-key) (:keyq 2 :control :virtual-key))) (set-timer :hwnd hwnd :elapse 1000 :replace-timer 4)) ((const +wm-paint+) (with-paint (hwnd hdc) (set-bk-mode hdc :transparent) ;; draw top region containing seconds and flag counter (destructuring-bind (&key (right 0) (bottom 0) &allow-other-keys) (get-client-rect hwnd) (draw-edge hdc (make-rect :left 10 :top 10 :right (- right 10) :bottom 50) :flags '(:left :right :top :bottom :adjust)) (text-out hdc (format nil "~A" (minesweeper-seconds *ms*)) 25 20) (text-out hdc (format nil "~A" (minesweeper-flags *ms*)) (- right 40) 20) (draw-edge hdc (make-rect :left 10 :top 70 :right (- right 10) :bottom (- bottom 5)) :flags '(:left :right :top :bottom :adjust)) (let ((xstart (- (truncate right 2) (* (truncate (minesweeper-x *ms*) 2) 25))) (ystart 85)) (dotimes (i (minesweeper-x *ms*)) (dotimes (j (minesweeper-y *ms*)) (draw-edge hdc (make-rect :left (+ xstart (* i 25)) :top (+ ystart (* j 25)) :right (+ xstart 25 (* i 25)) :bottom (+ ystart 25 (* j 25))) :inner-edge (if (or (clicked-p *ms* i j) (minesweeper-finished *ms*)) :sunk :raised) :outer-edge (if (or (clicked-p *ms* i j) (minesweeper-finished *ms*)) :sunk :raised) :flags '(:left :right :top :bottom :adjust)) (cond ((minesweeper-finished *ms*) (cond ((mine-p *ms* i j) (text-out hdc "M" (+ xstart 9 (* i 25)) (+ ystart 5 (* j 25)))) (t (let ((m (mines *ms* i j))) (unless (zerop m) (text-out hdc (format nil "~A" m) (+ xstart 9 (* i 25)) (+ ystart 5 (* j 25)))))))) (t (when (flag-p *ms* i j) (text-out hdc "F" (+ xstart 9 (* i 25)) (+ ystart 5 (* j 25)))) (when (clicked-p *ms* i j) (let ((m (mines *ms* i j))) (unless (zerop m) (text-out hdc (format nil "~A" m) (+ xstart 9 (* i 25)) (+ ystart 5 (* j 25)))))))))))))) ((const +wm-lbuttondown+) (destructuring-bind (&key (right 0) &allow-other-keys) (get-client-rect hwnd) (let* ((xstart (- (truncate right 2) (* (truncate (minesweeper-x *ms*) 2) 25))) (ystart 85) (x (loword lparam)) (y (hiword lparam)) (i (truncate (- x xstart) 25)) (j (truncate (- y ystart) 25))) (when (= (loword wparam) 1) (when (and (>= i 0) (< i (minesweeper-x *ms*)) (>= j 0) (< j (minesweeper-y *ms*))) (unless (flag-p *ms* i j) (when (eq (click-cell *ms* i j) :mine) (setf (minesweeper-finished *ms*) t)))))) (invalidate-rect hwnd nil t))) ((const +wm-rbuttondown+) (destructuring-bind (&key (right 0) &allow-other-keys) (get-client-rect hwnd) (let* ((xstart (- (truncate right 2) (* (truncate (minesweeper-x *ms*) 2) 25))) (ystart 85) (x (loword lparam)) (y (hiword lparam)) (i (truncate (- x xstart) 25)) (j (truncate (- y ystart) 25))) (when (= (loword wparam) 2) (when (and (>= i 0) (< i (minesweeper-x *ms*)) (>= j 0) (< j (minesweeper-y *ms*)) (not (clicked-p *ms* i j))) (cond ((flag-p *ms* i j) (set-flag *ms* i j nil) (incf (minesweeper-flags *ms*))) (t (when (> (minesweeper-flags *ms*) 0) (set-flag *ms* i j t) (decf (minesweeper-flags *ms*)) (when (game-won-p) (setf (minesweeper-finished *ms*) t) (message-box :hwnd hwnd :text "You won!" :caption "Win")))))))) (invalidate-rect hwnd nil t))) ((const +wm-command+) (switch (loword wparam) (1 ;; new (setf *ms* (random-game)) (resize-window hwnd) (invalidate-rect hwnd nil t)) (2 ;; quit (destroy-window hwnd)) (3 ;; about (message-box :hwnd hwnd :text "Simple minesweeper game written in Common Lisp. Copyright (c) Frank James 2016. " :caption "About")) (5 ;; new (setf *ms* (random-game)) (resize-window hwnd) (invalidate-rect hwnd nil t)) (6 ;; beginner (setf *starting-mines* 10 *starting-x* 10 *starting-y* 10) (check-menu-radio-item (get-menu hwnd) 6 8 6)) (7 ;; advanced (setf *starting-mines* 40 *starting-x* 14 *starting-y* 14) (check-menu-radio-item (get-menu hwnd) 6 8 7)) (8 ;; expert (setf *starting-mines* 99 *starting-x* 24 *starting-y* 24) (check-menu-radio-item (get-menu hwnd) 6 8 8)))) ((const +wm-timer+) (unless (minesweeper-finished *ms*) (incf (minesweeper-seconds *ms*))) (invalidate-rect hwnd (make-rect :right 50 :bottom 50) t)) ((const +wm-size+) (let ((btn (find-window "button" "New" hwnd))) (when btn (set-window-pos btn :top (- (truncate (getf (get-client-rect hwnd) :right 0) 2) 22) 20 45 22))) (invalidate-rect hwnd nil t)) ((const +wm-destroy+) (set-accelerator-table) (post-quit-message))) (default-window-proc hwnd msg wparam lparam)) (defun minesweeper () (default-message-loop (callback minesweeper-wndproc) :class-name "FTW_MINESWEEPER" :title "Minesweeper" :width 350 :height 425 :icon *mine-icon* :icon-small *mine-icon*))
54247
;;;; Copyright (c) <NAME> 2016 <<EMAIL>> ;;;; This code is licensed under the MIT license. ;;; Simple minesweeper game ;;; Things which could be done and are left as an exercise to the reader: ;;; 1. Adding icons/images instead of using text for the numbers, mines and flags. ;;; 2. Keeping a high-score list saved away e.g. in current user's home directory. ;;; 3. Writing a proper "about" dialog. ;;; 4. Dialog for entering arbitrary game sizes. ;;; 5. Automatically clicking on provable empty cells ;;; 6. Win detection ;;; 7. Automatically resizing main window to the size of the game board (defpackage #:ftw.minesweeper (:use #:cl #:cffi #:ftw) (:export #:minesweeper)) (in-package #:ftw.minesweeper) (defstruct minesweeper x y cells flags finished seconds) (defun cell (ms x y) (aref (minesweeper-cells ms) y x)) (defun (setf cell) (value ms x y) (setf (aref (minesweeper-cells ms) y x) value)) (defun set-flag (ms x y &optional set) (if set (pushnew :flag (cell ms x y)) (setf (cell ms x y) (remove :flag (cell ms x y))))) (defun flag-p (ms x y) (member :flag (cell ms x y))) (defun mine-p (ms x y) (member :mine (cell ms x y))) (defun mines (ms x y) (let ((m 0)) (do ((i (1- x) (1+ i))) ((> i (1+ x))) (do ((j (1- y) (1+ j))) ((> j (1+ y))) (when (and (>= i 0) (< i (minesweeper-x ms))) (when (and (>= j 0) (< j (minesweeper-y ms))) (unless (and (= i x) (= j y)) (when (mine-p ms i j) (incf m))))))) m)) (defvar *starting-mines* 10) (defvar *starting-x* 10) (defvar *starting-y* 10) (defvar *ms* nil) (defun random-game (&key x y mines) (unless x (setf x *starting-x*)) (unless y (setf y *starting-y*)) (unless mines (setf mines *starting-mines*)) (let ((ms (make-minesweeper :x x :y y :cells (make-array (list x y) :element-type t :initial-contents (let ((m mines)) (loop :for i :below x :collect (loop :for j :below y :collect (let ((left (- (* x y) (+ (* i y) j)))) (cond ((or (zerop left) (zerop m)) nil) ((<= left m) (decf m) (list :mine)) ((<= (random left) m) (decf m) (list :mine)) (t nil))))))) :flags mines :seconds 0))) ms)) (defun clicked-p (ms x y) (integerp (car (cell ms x y)))) (defun unclicked-neighbours (ms x y) (let ((neighbours nil)) (do ((i (1- x) (1+ i))) ((= i (+ x 2))) (do ((j (1- y) (1+ j))) ((= j (+ y 2))) (when (and (>= i 0) (< i (minesweeper-x ms)) (>= j 0) (< j (minesweeper-y ms)) (not (and (= i x) (= j y))) (not (clicked-p ms i j))) (push (list i j) neighbours)))) neighbours)) (defun click-provable-cells (ms x y) "If this location has a mine count of 0 then look at all the unclicked cells around this location and click those too. Repeat recursively." (when (= (mines ms x y) 0) (dolist (n (unclicked-neighbours ms x y)) (click-cell ms (first n) (second n))))) (defun click-cell (ms x y) (cond ((mine-p ms x y) :mine) (t (setf (cell ms x y) (list (mines ms x y))) (click-provable-cells ms x y) (cell ms x y)))) (defun resize-window (hwnd) "Set the window to the size required for the game" (let ((w (minesweeper-x *ms*)) (h (minesweeper-y *ms*))) (set-window-pos hwnd :top 0 0 (+ 100 (* w 25)) (+ 175 (* h 25)) '(:no-move)))) (defun game-won-p () "Returns true if all mines have a flag placed on them." (let ((mines 0) (correct 0)) (dotimes (i (minesweeper-x *ms*)) (dotimes (j (minesweeper-y *ms*)) (when (mine-p *ms* i j) (incf mines) (when (flag-p *ms* i j) (incf correct))))) (= mines correct))) ;; I made a little icon in gimp and exported it as a microsoft icon (*.ico) file. ;; Then I ran generate-icon-resource on that file. I pasted the output below. (defvar *MINE-ICON* (create-icon 32 32 1 32 (make-array 4224 :element-type '(unsigned-byte 8)) #(#x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #xFC #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x5F #x00 #x00 #x00 #xD5 #x00 #x00 #x00 #x3E #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x77 #x00 #x00 #x00 #xB6 #x00 #x00 #x00 #x5A #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #xE9 #x00 #x00 #x00 #xF3 #x00 #x00 #x00 #xF3 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #xAA #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x03 #x00 #x00 #x00 #x35 #x00 #x00 #x00 #x83 #x00 #x00 #x00 #xCA #x00 #x00 #x00 #xF5 #x00 #x00 #x00 #xF5 #x00 #x00 #x00 #xFF #x00 #x00 #x00 #x83 #x00 #x00 #x00 #x35 #x00 #x00 #x00 #x03 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x6C #x00 #x00 #x00 #x6C #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #xCE #x00 #x00 #x00 #x6C #x00 #x00 #x00 #x01 #x00 #x00 #x00 #x56 #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #x56 #x00 #x00 #x00 #x01 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x6C #x00 #x00 #x00 #xAA #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #xE4 #x00 #x00 #x00 #xC3 #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xC3 #x00 #x00 #x00 #xB0 #x00 #x00 #x00 #xAA #x00 #x00 #x00 #x6C #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x13 #x00 #x00 #x00 #xFA #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xF7 #x00 #x00 #x00 #x13 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x03 #x00 #x00 #x00 #xD3 #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xD3 #x00 #x00 #x00 #x03 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x6B #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #x6B #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x09 #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #x09 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x4A #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #x4A #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x9E #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #x9E #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x6F #x00 #x00 #x00 #xAE #x00 #x00 #x00 #xE0 #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x17 #x17 #x17 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xE0 #x00 #x00 #x00 #xDA #x00 #x00 #x00 #x53 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xF3 #x00 #x00 #x00 #xCA #x00 #x00 #x00 #xE9 #x00 #x00 #x00 #xFB #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x17 #x17 #x17 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x17 #x17 #x17 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFB #x00 #x00 #x00 #xD5 #x00 #x00 #x00 #xA3 #x00 #x00 #x00 #xFC #x00 #x00 #x00 #xFF #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #xAE #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xE0 #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x17 #x17 #x17 #xFF #x17 #x17 #x17 #xFF #x37 #x37 #x37 #xFF #x37 #x37 #x37 #xFF #x37 #x37 #x37 #xFF #x37 #x37 #x37 #xFF #x37 #x37 #x37 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xE0 #x00 #x00 #x00 #xDF #x00 #x00 #x00 #x98 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x9E #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x17 #x17 #x17 #xFF #x17 #x17 #x17 #xFF #x37 #x37 #x37 #xFF #x37 #x37 #x37 #xFF #x5B #x5B #x5B #xFF #x5B #x5B #x5B #xFF #x5B #x5B #x5B #xFF #x37 #x37 #x37 #xFF #x37 #x37 #x37 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #x9E #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x4A #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x37 #x37 #x37 #xFF #x5B #x5B #x5B #xFF #x5B #x5B #x5B #xFF #x5B #x5B #x5B #xFF #x5B #x5B #x5B #xFF #x5B #x5B #x5B #xFF #x5B #x5B #x5B #xFF #x37 #x37 #x37 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #x4A #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x09 #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x88 #x88 #x88 #xFF #x88 #x88 #x88 #xFF #x5B #x5B #x5B #xFF #x88 #x88 #x88 #xFF #x5B #x5B #x5B #xFF #x5B #x5B #x5B #xFF #x5B #x5B #x5B #xFF #x17 #x17 #x17 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #x09 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x6B #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x37 #x37 #x37 #xFF #x88 #x88 #x88 #xFF #x88 #x88 #x88 #xFF #x88 #x88 #x88 #xFF #x88 #x88 #x88 #xFF #x5B #x5B #x5B #xFF #x5B #x5B #x5B #xFF #x17 #x17 #x17 #xFF #x17 #x17 #x17 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #x6B #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x03 #x00 #x00 #x00 #xD3 #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x37 #x37 #x37 #xFF #x88 #x88 #x88 #xFF #x88 #x88 #x88 #xFF #xC7 #xC7 #xC7 #xFF #x5B #x5B #x5B #xFF #x37 #x37 #x37 #xFF #x17 #x17 #x17 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xD3 #x00 #x00 #x00 #x03 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x13 #x00 #x00 #x00 #xFC #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x37 #x37 #x37 #xFF #x88 #x88 #x88 #xFF #x49 #x49 #x49 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xF7 #x00 #x00 #x00 #x77 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #xAA #x00 #x00 #x00 #x76 #x00 #x00 #x00 #xC3 #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xC3 #x00 #x00 #x00 #xB0 #x00 #x00 #x00 #x6C #x00 #x00 #x00 #xAA #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x6C #x00 #x00 #x00 #x6C #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x01 #x00 #x00 #x00 #x56 #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #x56 #x00 #x00 #x00 #x01 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x6C #x00 #x00 #x00 #x6C #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x03 #x00 #x00 #x00 #x35 #x00 #x00 #x00 #x83 #x00 #x00 #x00 #xCA #x00 #x00 #x00 #xF5 #x00 #x00 #x00 #xF5 #x00 #x00 #x00 #xFF #x00 #x00 #x00 #x83 #x00 #x00 #x00 #x35 #x00 #x00 #x00 #x03 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x6C #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #xCC #x00 #x00 #x00 #xCC #x00 #x00 #x00 #x73 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #xC1 #x00 #x00 #x00 #xF3 #x00 #x00 #x00 #x98 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #xFF #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #xFF #xFF #xFF #xFF #xFF #xFF #x7F #xFF #xFF #xFE #x3F #xFF #xFF #xFE #x3F #xFF #xFF #xFE #x3F #xFF #xFD #xE0 #x07 #x3F #xFE #x00 #x01 #x3F #xFF #x00 #x00 #x3F #xFE #x00 #x00 #x7F #xFC #x00 #x00 #x3F #xFC #x00 #x00 #x3F #xF8 #x00 #x00 #x1F #xF8 #x00 #x00 #x1F #xF8 #x00 #x00 #x1F #xE0 #x00 #x00 #x07 #x80 #x00 #x00 #x01 #xE0 #x00 #x00 #x07 #xF8 #x00 #x00 #x1F #xF8 #x00 #x00 #x1F #xF8 #x00 #x00 #x1F #xFC #x00 #x00 #x3F #xFC #x00 #x00 #x3F #xFE #x00 #x00 #x7F #xFE #x00 #x00 #x3F #xFC #x80 #x01 #x3F #xFF #xE0 #x07 #xBF #xFF #xFE #x3F #xFF #xFF #xFE #x3F #xFF #xFF #xFE #x3F #xFF #xFF #xFF #x7F #xFF #xFF #xFF #xFF #xFF #xFF #xFF #xFF #xFF ))) (defwndproc minesweeper-wndproc (hwnd msg wparam lparam) (switch msg ((const +wm-create+) (setf *ms* (random-game)) (resize-window hwnd) ;; add menus (add-menu-bar hwnd `((:menu (:popup) :name "&Game" :children ((:item (:string) :name ,(format nil "&New~ACtrl+N" #\tab) :id 1) (:item (:separator)) (:item (:string) :name "Beginner" :id 6) (:item (:string) :name "Advanced" :id 7) (:item (:string) :name "Expert" :id 8) (:radio (6 8) :id 6) (:item (:separator)) (:item (:string) :name ,(format nil "&Quit~ACtrl+Q" #\tab) :id 2))) (:menu (:popup) :name "&Help" :children ((:item (:string) :name "&About" :id 3))))) (let ((right (getf (get-client-rect hwnd) :right 0))) (create-window :button :window-name "New" :styles (logior-consts +ws-visible+ +ws-child+ +bs-pushbutton+) :x (truncate right 2) :y 20 :width 45 :height 22 :parent hwnd :menu 5)) ;; create accelerator table (set-accelerator-table '((:keyn 1 :control :virtual-key) (:keyq 2 :control :virtual-key))) (set-timer :hwnd hwnd :elapse 1000 :replace-timer 4)) ((const +wm-paint+) (with-paint (hwnd hdc) (set-bk-mode hdc :transparent) ;; draw top region containing seconds and flag counter (destructuring-bind (&key (right 0) (bottom 0) &allow-other-keys) (get-client-rect hwnd) (draw-edge hdc (make-rect :left 10 :top 10 :right (- right 10) :bottom 50) :flags '(:left :right :top :bottom :adjust)) (text-out hdc (format nil "~A" (minesweeper-seconds *ms*)) 25 20) (text-out hdc (format nil "~A" (minesweeper-flags *ms*)) (- right 40) 20) (draw-edge hdc (make-rect :left 10 :top 70 :right (- right 10) :bottom (- bottom 5)) :flags '(:left :right :top :bottom :adjust)) (let ((xstart (- (truncate right 2) (* (truncate (minesweeper-x *ms*) 2) 25))) (ystart 85)) (dotimes (i (minesweeper-x *ms*)) (dotimes (j (minesweeper-y *ms*)) (draw-edge hdc (make-rect :left (+ xstart (* i 25)) :top (+ ystart (* j 25)) :right (+ xstart 25 (* i 25)) :bottom (+ ystart 25 (* j 25))) :inner-edge (if (or (clicked-p *ms* i j) (minesweeper-finished *ms*)) :sunk :raised) :outer-edge (if (or (clicked-p *ms* i j) (minesweeper-finished *ms*)) :sunk :raised) :flags '(:left :right :top :bottom :adjust)) (cond ((minesweeper-finished *ms*) (cond ((mine-p *ms* i j) (text-out hdc "M" (+ xstart 9 (* i 25)) (+ ystart 5 (* j 25)))) (t (let ((m (mines *ms* i j))) (unless (zerop m) (text-out hdc (format nil "~A" m) (+ xstart 9 (* i 25)) (+ ystart 5 (* j 25)))))))) (t (when (flag-p *ms* i j) (text-out hdc "F" (+ xstart 9 (* i 25)) (+ ystart 5 (* j 25)))) (when (clicked-p *ms* i j) (let ((m (mines *ms* i j))) (unless (zerop m) (text-out hdc (format nil "~A" m) (+ xstart 9 (* i 25)) (+ ystart 5 (* j 25)))))))))))))) ((const +wm-lbuttondown+) (destructuring-bind (&key (right 0) &allow-other-keys) (get-client-rect hwnd) (let* ((xstart (- (truncate right 2) (* (truncate (minesweeper-x *ms*) 2) 25))) (ystart 85) (x (loword lparam)) (y (hiword lparam)) (i (truncate (- x xstart) 25)) (j (truncate (- y ystart) 25))) (when (= (loword wparam) 1) (when (and (>= i 0) (< i (minesweeper-x *ms*)) (>= j 0) (< j (minesweeper-y *ms*))) (unless (flag-p *ms* i j) (when (eq (click-cell *ms* i j) :mine) (setf (minesweeper-finished *ms*) t)))))) (invalidate-rect hwnd nil t))) ((const +wm-rbuttondown+) (destructuring-bind (&key (right 0) &allow-other-keys) (get-client-rect hwnd) (let* ((xstart (- (truncate right 2) (* (truncate (minesweeper-x *ms*) 2) 25))) (ystart 85) (x (loword lparam)) (y (hiword lparam)) (i (truncate (- x xstart) 25)) (j (truncate (- y ystart) 25))) (when (= (loword wparam) 2) (when (and (>= i 0) (< i (minesweeper-x *ms*)) (>= j 0) (< j (minesweeper-y *ms*)) (not (clicked-p *ms* i j))) (cond ((flag-p *ms* i j) (set-flag *ms* i j nil) (incf (minesweeper-flags *ms*))) (t (when (> (minesweeper-flags *ms*) 0) (set-flag *ms* i j t) (decf (minesweeper-flags *ms*)) (when (game-won-p) (setf (minesweeper-finished *ms*) t) (message-box :hwnd hwnd :text "You won!" :caption "Win")))))))) (invalidate-rect hwnd nil t))) ((const +wm-command+) (switch (loword wparam) (1 ;; new (setf *ms* (random-game)) (resize-window hwnd) (invalidate-rect hwnd nil t)) (2 ;; quit (destroy-window hwnd)) (3 ;; about (message-box :hwnd hwnd :text "Simple minesweeper game written in Common Lisp. Copyright (c) <NAME> 2016. " :caption "About")) (5 ;; new (setf *ms* (random-game)) (resize-window hwnd) (invalidate-rect hwnd nil t)) (6 ;; beginner (setf *starting-mines* 10 *starting-x* 10 *starting-y* 10) (check-menu-radio-item (get-menu hwnd) 6 8 6)) (7 ;; advanced (setf *starting-mines* 40 *starting-x* 14 *starting-y* 14) (check-menu-radio-item (get-menu hwnd) 6 8 7)) (8 ;; expert (setf *starting-mines* 99 *starting-x* 24 *starting-y* 24) (check-menu-radio-item (get-menu hwnd) 6 8 8)))) ((const +wm-timer+) (unless (minesweeper-finished *ms*) (incf (minesweeper-seconds *ms*))) (invalidate-rect hwnd (make-rect :right 50 :bottom 50) t)) ((const +wm-size+) (let ((btn (find-window "button" "New" hwnd))) (when btn (set-window-pos btn :top (- (truncate (getf (get-client-rect hwnd) :right 0) 2) 22) 20 45 22))) (invalidate-rect hwnd nil t)) ((const +wm-destroy+) (set-accelerator-table) (post-quit-message))) (default-window-proc hwnd msg wparam lparam)) (defun minesweeper () (default-message-loop (callback minesweeper-wndproc) :class-name "FTW_MINESWEEPER" :title "Minesweeper" :width 350 :height 425 :icon *mine-icon* :icon-small *mine-icon*))
true
;;;; Copyright (c) PI:NAME:<NAME>END_PI 2016 <PI:EMAIL:<EMAIL>END_PI> ;;;; This code is licensed under the MIT license. ;;; Simple minesweeper game ;;; Things which could be done and are left as an exercise to the reader: ;;; 1. Adding icons/images instead of using text for the numbers, mines and flags. ;;; 2. Keeping a high-score list saved away e.g. in current user's home directory. ;;; 3. Writing a proper "about" dialog. ;;; 4. Dialog for entering arbitrary game sizes. ;;; 5. Automatically clicking on provable empty cells ;;; 6. Win detection ;;; 7. Automatically resizing main window to the size of the game board (defpackage #:ftw.minesweeper (:use #:cl #:cffi #:ftw) (:export #:minesweeper)) (in-package #:ftw.minesweeper) (defstruct minesweeper x y cells flags finished seconds) (defun cell (ms x y) (aref (minesweeper-cells ms) y x)) (defun (setf cell) (value ms x y) (setf (aref (minesweeper-cells ms) y x) value)) (defun set-flag (ms x y &optional set) (if set (pushnew :flag (cell ms x y)) (setf (cell ms x y) (remove :flag (cell ms x y))))) (defun flag-p (ms x y) (member :flag (cell ms x y))) (defun mine-p (ms x y) (member :mine (cell ms x y))) (defun mines (ms x y) (let ((m 0)) (do ((i (1- x) (1+ i))) ((> i (1+ x))) (do ((j (1- y) (1+ j))) ((> j (1+ y))) (when (and (>= i 0) (< i (minesweeper-x ms))) (when (and (>= j 0) (< j (minesweeper-y ms))) (unless (and (= i x) (= j y)) (when (mine-p ms i j) (incf m))))))) m)) (defvar *starting-mines* 10) (defvar *starting-x* 10) (defvar *starting-y* 10) (defvar *ms* nil) (defun random-game (&key x y mines) (unless x (setf x *starting-x*)) (unless y (setf y *starting-y*)) (unless mines (setf mines *starting-mines*)) (let ((ms (make-minesweeper :x x :y y :cells (make-array (list x y) :element-type t :initial-contents (let ((m mines)) (loop :for i :below x :collect (loop :for j :below y :collect (let ((left (- (* x y) (+ (* i y) j)))) (cond ((or (zerop left) (zerop m)) nil) ((<= left m) (decf m) (list :mine)) ((<= (random left) m) (decf m) (list :mine)) (t nil))))))) :flags mines :seconds 0))) ms)) (defun clicked-p (ms x y) (integerp (car (cell ms x y)))) (defun unclicked-neighbours (ms x y) (let ((neighbours nil)) (do ((i (1- x) (1+ i))) ((= i (+ x 2))) (do ((j (1- y) (1+ j))) ((= j (+ y 2))) (when (and (>= i 0) (< i (minesweeper-x ms)) (>= j 0) (< j (minesweeper-y ms)) (not (and (= i x) (= j y))) (not (clicked-p ms i j))) (push (list i j) neighbours)))) neighbours)) (defun click-provable-cells (ms x y) "If this location has a mine count of 0 then look at all the unclicked cells around this location and click those too. Repeat recursively." (when (= (mines ms x y) 0) (dolist (n (unclicked-neighbours ms x y)) (click-cell ms (first n) (second n))))) (defun click-cell (ms x y) (cond ((mine-p ms x y) :mine) (t (setf (cell ms x y) (list (mines ms x y))) (click-provable-cells ms x y) (cell ms x y)))) (defun resize-window (hwnd) "Set the window to the size required for the game" (let ((w (minesweeper-x *ms*)) (h (minesweeper-y *ms*))) (set-window-pos hwnd :top 0 0 (+ 100 (* w 25)) (+ 175 (* h 25)) '(:no-move)))) (defun game-won-p () "Returns true if all mines have a flag placed on them." (let ((mines 0) (correct 0)) (dotimes (i (minesweeper-x *ms*)) (dotimes (j (minesweeper-y *ms*)) (when (mine-p *ms* i j) (incf mines) (when (flag-p *ms* i j) (incf correct))))) (= mines correct))) ;; I made a little icon in gimp and exported it as a microsoft icon (*.ico) file. ;; Then I ran generate-icon-resource on that file. I pasted the output below. (defvar *MINE-ICON* (create-icon 32 32 1 32 (make-array 4224 :element-type '(unsigned-byte 8)) #(#x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #xFC #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x5F #x00 #x00 #x00 #xD5 #x00 #x00 #x00 #x3E #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x77 #x00 #x00 #x00 #xB6 #x00 #x00 #x00 #x5A #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #xE9 #x00 #x00 #x00 #xF3 #x00 #x00 #x00 #xF3 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #xAA #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x03 #x00 #x00 #x00 #x35 #x00 #x00 #x00 #x83 #x00 #x00 #x00 #xCA #x00 #x00 #x00 #xF5 #x00 #x00 #x00 #xF5 #x00 #x00 #x00 #xFF #x00 #x00 #x00 #x83 #x00 #x00 #x00 #x35 #x00 #x00 #x00 #x03 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x6C #x00 #x00 #x00 #x6C #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #xCE #x00 #x00 #x00 #x6C #x00 #x00 #x00 #x01 #x00 #x00 #x00 #x56 #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #x56 #x00 #x00 #x00 #x01 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x6C #x00 #x00 #x00 #xAA #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #xE4 #x00 #x00 #x00 #xC3 #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xC3 #x00 #x00 #x00 #xB0 #x00 #x00 #x00 #xAA #x00 #x00 #x00 #x6C #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x13 #x00 #x00 #x00 #xFA #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xF7 #x00 #x00 #x00 #x13 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x03 #x00 #x00 #x00 #xD3 #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xD3 #x00 #x00 #x00 #x03 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x6B #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #x6B #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x09 #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #x09 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x4A #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #x4A #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x9E #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #x9E #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x6F #x00 #x00 #x00 #xAE #x00 #x00 #x00 #xE0 #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x17 #x17 #x17 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xE0 #x00 #x00 #x00 #xDA #x00 #x00 #x00 #x53 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xF3 #x00 #x00 #x00 #xCA #x00 #x00 #x00 #xE9 #x00 #x00 #x00 #xFB #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x17 #x17 #x17 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x17 #x17 #x17 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFB #x00 #x00 #x00 #xD5 #x00 #x00 #x00 #xA3 #x00 #x00 #x00 #xFC #x00 #x00 #x00 #xFF #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #xAE #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xE0 #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x17 #x17 #x17 #xFF #x17 #x17 #x17 #xFF #x37 #x37 #x37 #xFF #x37 #x37 #x37 #xFF #x37 #x37 #x37 #xFF #x37 #x37 #x37 #xFF #x37 #x37 #x37 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xE0 #x00 #x00 #x00 #xDF #x00 #x00 #x00 #x98 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x9E #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x17 #x17 #x17 #xFF #x17 #x17 #x17 #xFF #x37 #x37 #x37 #xFF #x37 #x37 #x37 #xFF #x5B #x5B #x5B #xFF #x5B #x5B #x5B #xFF #x5B #x5B #x5B #xFF #x37 #x37 #x37 #xFF #x37 #x37 #x37 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #x9E #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x4A #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x37 #x37 #x37 #xFF #x5B #x5B #x5B #xFF #x5B #x5B #x5B #xFF #x5B #x5B #x5B #xFF #x5B #x5B #x5B #xFF #x5B #x5B #x5B #xFF #x5B #x5B #x5B #xFF #x37 #x37 #x37 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #x4A #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x09 #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x88 #x88 #x88 #xFF #x88 #x88 #x88 #xFF #x5B #x5B #x5B #xFF #x88 #x88 #x88 #xFF #x5B #x5B #x5B #xFF #x5B #x5B #x5B #xFF #x5B #x5B #x5B #xFF #x17 #x17 #x17 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #x09 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x6B #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x37 #x37 #x37 #xFF #x88 #x88 #x88 #xFF #x88 #x88 #x88 #xFF #x88 #x88 #x88 #xFF #x88 #x88 #x88 #xFF #x5B #x5B #x5B #xFF #x5B #x5B #x5B #xFF #x17 #x17 #x17 #xFF #x17 #x17 #x17 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #x6B #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x03 #x00 #x00 #x00 #xD3 #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x37 #x37 #x37 #xFF #x88 #x88 #x88 #xFF #x88 #x88 #x88 #xFF #xC7 #xC7 #xC7 #xFF #x5B #x5B #x5B #xFF #x37 #x37 #x37 #xFF #x17 #x17 #x17 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xD3 #x00 #x00 #x00 #x03 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x13 #x00 #x00 #x00 #xFC #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x37 #x37 #x37 #xFF #x88 #x88 #x88 #xFF #x49 #x49 #x49 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xF7 #x00 #x00 #x00 #x77 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #xAA #x00 #x00 #x00 #x76 #x00 #x00 #x00 #xC3 #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xC3 #x00 #x00 #x00 #xB0 #x00 #x00 #x00 #x6C #x00 #x00 #x00 #xAA #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x6C #x00 #x00 #x00 #x6C #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x01 #x00 #x00 #x00 #x56 #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #x56 #x00 #x00 #x00 #x01 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x6C #x00 #x00 #x00 #x6C #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x03 #x00 #x00 #x00 #x35 #x00 #x00 #x00 #x83 #x00 #x00 #x00 #xCA #x00 #x00 #x00 #xF5 #x00 #x00 #x00 #xF5 #x00 #x00 #x00 #xFF #x00 #x00 #x00 #x83 #x00 #x00 #x00 #x35 #x00 #x00 #x00 #x03 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x6C #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #xFF #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #xCC #x00 #x00 #x00 #xCC #x00 #x00 #x00 #x73 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #xC1 #x00 #x00 #x00 #xF3 #x00 #x00 #x00 #x98 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #xFF #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #x00 #xFF #xFF #xFF #xFF #xFF #xFF #x7F #xFF #xFF #xFE #x3F #xFF #xFF #xFE #x3F #xFF #xFF #xFE #x3F #xFF #xFD #xE0 #x07 #x3F #xFE #x00 #x01 #x3F #xFF #x00 #x00 #x3F #xFE #x00 #x00 #x7F #xFC #x00 #x00 #x3F #xFC #x00 #x00 #x3F #xF8 #x00 #x00 #x1F #xF8 #x00 #x00 #x1F #xF8 #x00 #x00 #x1F #xE0 #x00 #x00 #x07 #x80 #x00 #x00 #x01 #xE0 #x00 #x00 #x07 #xF8 #x00 #x00 #x1F #xF8 #x00 #x00 #x1F #xF8 #x00 #x00 #x1F #xFC #x00 #x00 #x3F #xFC #x00 #x00 #x3F #xFE #x00 #x00 #x7F #xFE #x00 #x00 #x3F #xFC #x80 #x01 #x3F #xFF #xE0 #x07 #xBF #xFF #xFE #x3F #xFF #xFF #xFE #x3F #xFF #xFF #xFE #x3F #xFF #xFF #xFF #x7F #xFF #xFF #xFF #xFF #xFF #xFF #xFF #xFF #xFF ))) (defwndproc minesweeper-wndproc (hwnd msg wparam lparam) (switch msg ((const +wm-create+) (setf *ms* (random-game)) (resize-window hwnd) ;; add menus (add-menu-bar hwnd `((:menu (:popup) :name "&Game" :children ((:item (:string) :name ,(format nil "&New~ACtrl+N" #\tab) :id 1) (:item (:separator)) (:item (:string) :name "Beginner" :id 6) (:item (:string) :name "Advanced" :id 7) (:item (:string) :name "Expert" :id 8) (:radio (6 8) :id 6) (:item (:separator)) (:item (:string) :name ,(format nil "&Quit~ACtrl+Q" #\tab) :id 2))) (:menu (:popup) :name "&Help" :children ((:item (:string) :name "&About" :id 3))))) (let ((right (getf (get-client-rect hwnd) :right 0))) (create-window :button :window-name "New" :styles (logior-consts +ws-visible+ +ws-child+ +bs-pushbutton+) :x (truncate right 2) :y 20 :width 45 :height 22 :parent hwnd :menu 5)) ;; create accelerator table (set-accelerator-table '((:keyn 1 :control :virtual-key) (:keyq 2 :control :virtual-key))) (set-timer :hwnd hwnd :elapse 1000 :replace-timer 4)) ((const +wm-paint+) (with-paint (hwnd hdc) (set-bk-mode hdc :transparent) ;; draw top region containing seconds and flag counter (destructuring-bind (&key (right 0) (bottom 0) &allow-other-keys) (get-client-rect hwnd) (draw-edge hdc (make-rect :left 10 :top 10 :right (- right 10) :bottom 50) :flags '(:left :right :top :bottom :adjust)) (text-out hdc (format nil "~A" (minesweeper-seconds *ms*)) 25 20) (text-out hdc (format nil "~A" (minesweeper-flags *ms*)) (- right 40) 20) (draw-edge hdc (make-rect :left 10 :top 70 :right (- right 10) :bottom (- bottom 5)) :flags '(:left :right :top :bottom :adjust)) (let ((xstart (- (truncate right 2) (* (truncate (minesweeper-x *ms*) 2) 25))) (ystart 85)) (dotimes (i (minesweeper-x *ms*)) (dotimes (j (minesweeper-y *ms*)) (draw-edge hdc (make-rect :left (+ xstart (* i 25)) :top (+ ystart (* j 25)) :right (+ xstart 25 (* i 25)) :bottom (+ ystart 25 (* j 25))) :inner-edge (if (or (clicked-p *ms* i j) (minesweeper-finished *ms*)) :sunk :raised) :outer-edge (if (or (clicked-p *ms* i j) (minesweeper-finished *ms*)) :sunk :raised) :flags '(:left :right :top :bottom :adjust)) (cond ((minesweeper-finished *ms*) (cond ((mine-p *ms* i j) (text-out hdc "M" (+ xstart 9 (* i 25)) (+ ystart 5 (* j 25)))) (t (let ((m (mines *ms* i j))) (unless (zerop m) (text-out hdc (format nil "~A" m) (+ xstart 9 (* i 25)) (+ ystart 5 (* j 25)))))))) (t (when (flag-p *ms* i j) (text-out hdc "F" (+ xstart 9 (* i 25)) (+ ystart 5 (* j 25)))) (when (clicked-p *ms* i j) (let ((m (mines *ms* i j))) (unless (zerop m) (text-out hdc (format nil "~A" m) (+ xstart 9 (* i 25)) (+ ystart 5 (* j 25)))))))))))))) ((const +wm-lbuttondown+) (destructuring-bind (&key (right 0) &allow-other-keys) (get-client-rect hwnd) (let* ((xstart (- (truncate right 2) (* (truncate (minesweeper-x *ms*) 2) 25))) (ystart 85) (x (loword lparam)) (y (hiword lparam)) (i (truncate (- x xstart) 25)) (j (truncate (- y ystart) 25))) (when (= (loword wparam) 1) (when (and (>= i 0) (< i (minesweeper-x *ms*)) (>= j 0) (< j (minesweeper-y *ms*))) (unless (flag-p *ms* i j) (when (eq (click-cell *ms* i j) :mine) (setf (minesweeper-finished *ms*) t)))))) (invalidate-rect hwnd nil t))) ((const +wm-rbuttondown+) (destructuring-bind (&key (right 0) &allow-other-keys) (get-client-rect hwnd) (let* ((xstart (- (truncate right 2) (* (truncate (minesweeper-x *ms*) 2) 25))) (ystart 85) (x (loword lparam)) (y (hiword lparam)) (i (truncate (- x xstart) 25)) (j (truncate (- y ystart) 25))) (when (= (loword wparam) 2) (when (and (>= i 0) (< i (minesweeper-x *ms*)) (>= j 0) (< j (minesweeper-y *ms*)) (not (clicked-p *ms* i j))) (cond ((flag-p *ms* i j) (set-flag *ms* i j nil) (incf (minesweeper-flags *ms*))) (t (when (> (minesweeper-flags *ms*) 0) (set-flag *ms* i j t) (decf (minesweeper-flags *ms*)) (when (game-won-p) (setf (minesweeper-finished *ms*) t) (message-box :hwnd hwnd :text "You won!" :caption "Win")))))))) (invalidate-rect hwnd nil t))) ((const +wm-command+) (switch (loword wparam) (1 ;; new (setf *ms* (random-game)) (resize-window hwnd) (invalidate-rect hwnd nil t)) (2 ;; quit (destroy-window hwnd)) (3 ;; about (message-box :hwnd hwnd :text "Simple minesweeper game written in Common Lisp. Copyright (c) PI:NAME:<NAME>END_PI 2016. " :caption "About")) (5 ;; new (setf *ms* (random-game)) (resize-window hwnd) (invalidate-rect hwnd nil t)) (6 ;; beginner (setf *starting-mines* 10 *starting-x* 10 *starting-y* 10) (check-menu-radio-item (get-menu hwnd) 6 8 6)) (7 ;; advanced (setf *starting-mines* 40 *starting-x* 14 *starting-y* 14) (check-menu-radio-item (get-menu hwnd) 6 8 7)) (8 ;; expert (setf *starting-mines* 99 *starting-x* 24 *starting-y* 24) (check-menu-radio-item (get-menu hwnd) 6 8 8)))) ((const +wm-timer+) (unless (minesweeper-finished *ms*) (incf (minesweeper-seconds *ms*))) (invalidate-rect hwnd (make-rect :right 50 :bottom 50) t)) ((const +wm-size+) (let ((btn (find-window "button" "New" hwnd))) (when btn (set-window-pos btn :top (- (truncate (getf (get-client-rect hwnd) :right 0) 2) 22) 20 45 22))) (invalidate-rect hwnd nil t)) ((const +wm-destroy+) (set-accelerator-table) (post-quit-message))) (default-window-proc hwnd msg wparam lparam)) (defun minesweeper () (default-message-loop (callback minesweeper-wndproc) :class-name "FTW_MINESWEEPER" :title "Minesweeper" :width 350 :height 425 :icon *mine-icon* :icon-small *mine-icon*))
[ { "context": " |\n;;; Copyright (c) 2021, Sentot Kromodimoeljo, William Pase, |\n;;; Mark Saaltink, D", "end": 194, "score": 0.9998644590377808, "start": 174, "tag": "NAME", "value": "Sentot Kromodimoeljo" }, { "context": " |\n;;; Copyright (c) 2021, Sentot Kromodimoeljo, William Pase, |\n;;; Mark Saaltink, Dan Craigen and", "end": 208, "score": 0.9998290538787842, "start": 196, "tag": "NAME", "value": "William Pase" }, { "context": "tot Kromodimoeljo, William Pase, |\n;;; Mark Saaltink, Dan Craigen and Irwin Meisels. ", "end": 241, "score": 0.9998257160186768, "start": 228, "tag": "NAME", "value": "Mark Saaltink" }, { "context": "jo, William Pase, |\n;;; Mark Saaltink, Dan Craigen and Irwin Meisels. |\n;;; Al", "end": 254, "score": 0.9998383522033691, "start": 243, "tag": "NAME", "value": "Dan Craigen" }, { "context": ", |\n;;; Mark Saaltink, Dan Craigen and Irwin Meisels. |\n;;; All Rights Reserved.", "end": 272, "score": 0.999855637550354, "start": 259, "tag": "NAME", "value": "Irwin Meisels" } ]
sources/dnf.lisp
sentot/ZK
0
;;;====================================================================== ;;; | ;;; Copyright (c) 2021, Sentot Kromodimoeljo, William Pase, | ;;; Mark Saaltink, Dan Craigen and Irwin Meisels. | ;;; All Rights Reserved. | ;;; | ;;; Redistribution and use in source and binary forms, with or without | ;;; modification, are permitted provided 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. | ;;; | ;;; 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 HOLDERS AND | ;;; CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, | ;;; SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT | ;;; LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF | ;;; USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED | ;;; AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT | ;;; LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING | ;;; IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF | ;;; THE POSSIBILITY OF SUCH DAMAGE. | ;;; | ;;;====================================================================== (in-package "ZK") ;;; =============== Conjunctive/Disjunctive Normal Forms =============== ;;; Code to do CNF/DNF using the Minato-Morreale technique. For our ;;; purposes, the technique is more than good enough. The BDD is based ;;; on Sentot's BDD implementation for a symbolic model checker. (defconstant bdd-hash-table-size 131072) (defconstant bdd-hash-table-mask (1- bdd-hash-table-size)) (defconstant recache-threshold 262144) (defconstant hash-multiplier 5) (defconstant second-hash-multiplier 3) (defvar *atom-list* nil) (defvar *bdd-entries* (make-array 8192 :initial-element nil)) (defvar *bdd-entries-size* 0) (defsubst push-bdd-entry (bdd) (setf (aref *bdd-entries* *bdd-entries-size*) bdd) (let ((result *bdd-entries-size*)) (setq *bdd-entries-size* (fixnum-op + *bdd-entries-size* 1)) result)) (defsubst bdd-entry (index) (aref *bdd-entries* index)) (defsubst pop-bdd-entry () (setf (aref *bdd-entries* *bdd-entries-size*) nil) (setq *bdd-entries-size* (fixnum-op - *bdd-entries-size* 1))) (defvar *atom-array* (vector)) ;;; The *if-hash-table* plays a vital role in ensuring that the BDD ;;; structures are shared. ;;; Each element of *if-hash-table* is a list of entries. ;;; Each entry is of the "if" form: (id test-id left-bdd right-bdd). (defvar *if-hash-table* (make-array bdd-hash-table-size :initial-element nil)) (defvar *if-count* 0) (defvar *recaching* nil) ;;; The *not-hash-table* also plays a vital role in ensuring that ;;; the BDD structures are shared. ;;; Each element of *not-hash-table* is a list of entries. ;;; Each entry is of the "not" form: (id unsigned-bdd), ;;; where the unsigned-bdd represents an "unsigned" formula. (defvar *not-hash-table* (make-array bdd-hash-table-size :initial-element nil)) ;;; The next two tables are for memoizing subfunction operations. ;;; The tables are not vital in that deleting entries in the ;;; tables does not effect the correct operation of the BDD. (defvar *sub0-hash-table* (make-array bdd-hash-table-size :initial-element nil)) (defvar *sub1-hash-table* (make-array bdd-hash-table-size :initial-element nil)) ;;; The *and-hash-table* is also for memoizing only: (defvar *and-hash-table* (make-array bdd-hash-table-size :initial-element nil)) ;;; The *recache-table* plays a vital role in ensuring the ;;; correct operation of the "garbage collector". (defvar *recache-table* (make-array bdd-hash-table-size :initial-element nil)) (defvar *next-id* 2) (defvar *number-of-atoms* 0) (defvar *bdd-zero* 0) (defparameter *bdd-one* (list 1 0)) (defsubst bdd-id (formula) (if (atom formula) formula (car formula))) (defsubst bdd-negated-p (formula) (and (consp formula) (= (length formula) 2))) (defsubst bdd-top (formula) (cond ((atom formula) formula) ((atom (second formula)) (second formula)) (t (second (second formula))))) ;;; Hash consing and memoizing ;;; Haven't tried to "optimize" the hashing function to get a good ;;; distribution, except for *not-hash-table*. (defun lookup-memo-for-and (left-id right-id) ;; andop is commutative, so normalize arguments to low, high (let ((low-id (fixnum-op min left-id right-id)) (high-id (fixnum-op max left-id right-id))) (loop for x in (unsafe-aref *and-hash-table* (fixnum-op logand (fixnum-op + (fixnum-op * low-id hash-multiplier) high-id) bdd-hash-table-mask)) when (and (fixnum-rel = low-id (caar x)) (fixnum-rel = high-id (cdar x))) return (cdr x)))) (defsubst memoize-and (left-id right-id result) ;; andop is commutative, so normalize arguments to low, high (let ((low-id (fixnum-op min left-id right-id)) (high-id (fixnum-op max left-id right-id))) (let ((index (fixnum-op logand (fixnum-op + (fixnum-op * low-id hash-multiplier) high-id) bdd-hash-table-mask))) (setf (unsafe-aref *and-hash-table* index) (cons (cons (cons low-id high-id) result) (unsafe-aref *and-hash-table* index)))))) ;;; "nots" are not really memoized, but rather, they are hash-consed ;;; (to use J Moore's terminology). (defsubst lookup-memo-for-not (formula) (let ((id (bdd-id formula))) (loop for x in (unsafe-aref *not-hash-table* (fixnum-op logand id bdd-hash-table-mask)) when (eq (second x) formula) return x))) (defsubst memoize-not (formula result) (let* ((id (bdd-id formula)) (index (fixnum-op logand id bdd-hash-table-mask))) (setf (unsafe-aref *not-hash-table* index) (cons result (unsafe-aref *not-hash-table* index))))) (defsubst lookup-memo-for-sub0 (var formula) (let ((id (bdd-id formula))) (loop for x in (unsafe-aref *sub0-hash-table* (fixnum-op logand (fixnum-op + (fixnum-op * var hash-multiplier) id) bdd-hash-table-mask)) when (and (fixnum-rel = var (caar x)) (fixnum-rel = id (cdar x))) return (cdr x)))) (defsubst memoize-sub0 (var formula result) (let ((id (bdd-id formula))) (let ((index (fixnum-op logand (fixnum-op + (fixnum-op * var hash-multiplier) id) bdd-hash-table-mask))) (setf (unsafe-aref *sub0-hash-table* index) (cons (cons (cons var id) result) (unsafe-aref *sub0-hash-table* index)))))) (defsubst lookup-memo-for-sub1 (var formula) (let ((id (bdd-id formula))) (loop for x in (unsafe-aref *sub1-hash-table* (fixnum-op logand (fixnum-op + (fixnum-op * var hash-multiplier) id) bdd-hash-table-mask)) when (and (fixnum-rel = var (caar x)) (fixnum-rel = id (cdar x))) return (cdr x)))) (defsubst memoize-sub1 (var formula result) (let ((id (bdd-id formula))) (let ((index (fixnum-op logand (fixnum-op + (fixnum-op * var hash-multiplier) id) bdd-hash-table-mask))) (setf (unsafe-aref *sub1-hash-table* index) (cons (cons (cons var id) result) (unsafe-aref *sub1-hash-table* index)))))) ;;; Reconstruction of bdds after "garbage collection" are really ;;; "hash-consing" operations. (defsubst lookup-memo-for-recache (formula) (let ((id (bdd-id formula))) (loop for x in (unsafe-aref *recache-table* (fixnum-op logand id bdd-hash-table-mask)) when (fixnum-rel = id (car x)) return (cdr x)))) (defsubst memoize-recache (id formula) (let ((index (fixnum-op logand id bdd-hash-table-mask))) (setf (unsafe-aref *recache-table* index) (cons (cons id formula) (unsafe-aref *recache-table* index))))) ;;; The top level function for "garbage collection": (defun bdd-clear-and-recache () ;(format t "~%Clearing and starting new cache~%") (dotimes (i bdd-hash-table-size) (setf (aref *if-hash-table* i) nil) (setf (aref *recache-table* i) nil) (setf (aref *not-hash-table* i) nil) (setf (aref *sub0-hash-table* i) nil) (setf (aref *sub1-hash-table* i) nil) (setf (aref *and-hash-table* i) nil)) (setq *if-count* 0) (setq *next-id* (+ *number-of-atoms* 2)) (let ((*recaching* t)) (let ((results (loop for i from 0 to (- *bdd-entries-size* 1) do (setf (aref *bdd-entries* i) (bdd-recache (aref *bdd-entries* i)))))) (dotimes (i bdd-hash-table-size) (setf (aref *recache-table* i) nil)) results))) ;;; Function to create the negation of a BDD node. (defsubst bdd-negate (formula) (cond ((eq formula *bdd-zero*) *bdd-one*) ((eq formula *bdd-one*) *bdd-zero*) ((and (consp formula) (= (length formula) 2)) (second formula)) (t (or (lookup-memo-for-not formula) (let ((result (list *next-id* formula))) (setq *next-id* (+ *next-id* 1)) (memoize-not formula result) result))))) ;;; Function to create an "if" node in a BDD. (defun bdd-make-if (test left right) (cond ((equal left right) left) ((and (consp right) (= (length right) 2)) (let ((negated-left (bdd-negate left)) (negated-right (bdd-negate right))) (let ((index (fixnum-op logand (fixnum-op + (fixnum-op * (bdd-id test) hash-multiplier) (fixnum-op + (fixnum-op * (bdd-id negated-left) second-hash-multiplier) (bdd-id negated-right))) bdd-hash-table-mask))) (bdd-negate (or (loop for x in (unsafe-aref *if-hash-table* index) when (and (eq test (if-test x)) (eq negated-left (if-left x)) (eq negated-right (if-right x))) return x) (let ((need-to-recache (fixnum-op logand recache-threshold *if-count*))) (cond ((= need-to-recache 0) (let ((if-form (list *next-id* test negated-left negated-right))) (unless *recaching* (setq *if-count* (+ *if-count* 1))) (setq *next-id* (+ *next-id* 1)) (setf (unsafe-aref *if-hash-table* index) (cons if-form (unsafe-aref *if-hash-table* index))) if-form)) (t (let ((left-index (push-bdd-entry negated-left)) (right-index (push-bdd-entry negated-right))) (bdd-clear-and-recache) (let ((if-form (list *next-id* test (bdd-entry left-index) (bdd-entry right-index))) (index (fixnum-op logand (fixnum-op + (fixnum-op * (bdd-id test) hash-multiplier) (fixnum-op + (fixnum-op * (bdd-id (bdd-entry left-index)) second-hash-multiplier) (bdd-id (bdd-entry right-index)))) bdd-hash-table-mask))) (pop-bdd-entry) (pop-bdd-entry) (unless *recaching* (setq *if-count* (+ *if-count* 1))) (setq *next-id* (+ *next-id* 1)) (setf (unsafe-aref *if-hash-table* index) (cons if-form (unsafe-aref *if-hash-table* index))) if-form)))))))))) (t (let ((index (fixnum-op logand (fixnum-op + (fixnum-op * (bdd-id test) hash-multiplier) (fixnum-op + (fixnum-op * (bdd-id left) second-hash-multiplier) (bdd-id right))) bdd-hash-table-mask))) (or (loop for x in (unsafe-aref *if-hash-table* index) when (and (eq test (if-test x)) (eq left (if-left x)) (eq right (if-right x))) return x) (let ((need-to-recache (fixnum-op logand recache-threshold *if-count*))) (cond ((= need-to-recache 0) (let ((if-form (list *next-id* test left right))) (unless *recaching* (setq *if-count* (+ *if-count* 1))) (setq *next-id* (+ *next-id* 1)) (setf (unsafe-aref *if-hash-table* index) (cons if-form (unsafe-aref *if-hash-table* index))) if-form)) (t (let ((left-index (push-bdd-entry left)) (right-index (push-bdd-entry right))) (bdd-clear-and-recache) (let ((result (list *next-id* test (bdd-entry left-index) (bdd-entry right-index))) (index (fixnum-op logand (fixnum-op + (fixnum-op * (bdd-id test) hash-multiplier) (fixnum-op + (fixnum-op * (bdd-id (bdd-entry left-index)) second-hash-multiplier) (bdd-id (bdd-entry right-index)))) bdd-hash-table-mask))) (pop-bdd-entry) (pop-bdd-entry) (unless *recaching* (setq *if-count* (+ *if-count* 1))) (setq *next-id* (+ *next-id* 1)) (setf (unsafe-aref *if-hash-table* index) (cons result (unsafe-aref *if-hash-table* index))) result)))))))))) ;;; Function to "reconstruct" a BDD node after "garbage collection". (defun bdd-recache (formula) (cond ((or (eq formula *bdd-zero*) (eq formula *bdd-one*)) formula) (t (or (lookup-memo-for-recache formula) (cond ((= (length formula) 2) (let ((result (bdd-negate (bdd-recache (second formula))))) (memoize-recache (bdd-id formula) result) result)) (t (let ((result (bdd-make-if (if-test formula) (bdd-recache (if-left formula)) (bdd-recache (if-right formula))))) (memoize-recache (bdd-id formula) result) result))))))) ;;; =========== The "merge-sorting" functions ============ ;;; All boolean connectives are converted to use the "and" ;;; operation and negation (instead of "nand" or "nor"). (defsubst andop-constant (formula negated1 negated2) (cond ((not negated1) *bdd-zero*) (negated2 (bdd-negate formula)) (t formula))) (defsubst complementary (formula1 formula2) (or (and (consp formula1) (= (length formula1) 2) (eq (second formula1) formula2)) (and (consp formula2) (= (length formula2) 2) (eq (second formula2) formula1)))) (defsubst bdd-unnegated (formula) (if (bdd-negated-p formula) (second formula) formula)) (defsubst bdd-compute-sense (formula negated) (if (bdd-negated-p formula) (not negated) negated)) (defun andop-aux (formula1 formula2 negated1 negated2) (cond ((eq formula1 *bdd-zero*) (andop-constant formula2 negated1 negated2)) ((eq formula2 *bdd-zero*) (andop-constant formula1 negated2 negated1)) ((eq formula1 formula2) (if negated1 (if negated2 (bdd-negate formula1) *bdd-zero*) (if negated2 *bdd-zero* formula1))) (t (let ((expr1 (if negated1 (bdd-negate formula1) formula1)) (expr2 (if negated2 (bdd-negate formula2) formula2))) (or (lookup-memo-for-and (bdd-id expr1) (bdd-id expr2)) (let ((expr1-index (push-bdd-entry expr1)) (expr2-index (push-bdd-entry expr2))) (let ((result (cond ((= (if-test formula1) (if-test formula2)) (let ((left1 (bdd-unnegated (if-left formula1))) (left2 (bdd-unnegated (if-left formula2))) (neg1 (bdd-compute-sense (if-left formula1) negated1)) (neg2 (bdd-compute-sense (if-left formula2) negated2))) ;; Note that a right branch is never a negation (let ((right1-index (push-bdd-entry (if-right formula1))) (right2-index (push-bdd-entry (if-right formula2))) (left-index (push-bdd-entry (andop-aux left1 left2 neg1 neg2)))) (let ((right-result (andop-aux (bdd-entry right1-index) (bdd-entry right2-index) negated1 negated2))) (let ((left-result (bdd-entry left-index))) (dotimes (i 3) (pop-bdd-entry)) (bdd-make-if (if-test formula1) left-result right-result)))))) ((< (if-test formula1) (if-test formula2)) (let ((left1 (bdd-unnegated (if-left formula1))) (neg1 (bdd-compute-sense (if-left formula1) negated1))) (let ((right1-index (push-bdd-entry (if-right formula1))) (formula2-index (push-bdd-entry formula2)) (left-index (push-bdd-entry (andop-aux left1 formula2 neg1 negated2)))) (let ((right-result (andop-aux (bdd-entry right1-index) (bdd-entry formula2-index) negated1 negated2))) (let ((left-result (bdd-entry left-index))) (dotimes (i 3) (pop-bdd-entry)) (bdd-make-if (if-test formula1) left-result right-result)))))) (t (let ((left2 (bdd-unnegated (if-left formula2))) (neg2 (bdd-compute-sense (if-left formula2) negated2))) (let ((formula1-index (push-bdd-entry formula1)) (right2-index (push-bdd-entry (if-right formula2))) (left-index (push-bdd-entry (andop-aux formula1 left2 negated1 neg2)))) (let ((right-result (andop-aux (bdd-entry formula1-index) (bdd-entry right2-index) negated1 negated2))) (let ((left-result (bdd-entry left-index))) (dotimes (i 3) (pop-bdd-entry)) (bdd-make-if (if-test formula2) left-result right-result))))))))) (memoize-and (bdd-id (bdd-entry expr1-index)) (bdd-id (bdd-entry expr2-index)) result) (dotimes (i 2) (pop-bdd-entry)) result))))))) (defun andop (formula1 formula2) (andop-aux (bdd-unnegated formula1) (bdd-unnegated formula2) (bdd-negated-p formula1) (bdd-negated-p formula2))) (defsubst orop (formula1 formula2) (bdd-negate (andop (bdd-negate formula1) (bdd-negate formula2)))) ;;; ================ Interface ================= (defun reset-bdd () (setq *atom-list* nil) (setq *atom-array* (vector)) (setq *next-id* 2) (setq *number-of-atoms* 0) (setq *if-count* 0) (dotimes (i bdd-hash-table-size) (setf (aref *if-hash-table* i) nil) (setf (aref *recache-table* i) nil) (setf (aref *not-hash-table* i) nil) (setf (aref *sub0-hash-table* i) nil) (setf (aref *sub1-hash-table* i) nil) (setf (aref *and-hash-table* i) nil))) (defvar *var-scores* (vector)) (defvar *initial-order* nil) (defun compute-input-scores (circuit &optional (unit 1.0)) (cond ((null circuit) nil) ((atom circuit) (incf (aref *var-scores* (- circuit 2)) unit)) (t (let ((u (/ unit (length circuit)))) (loop for c in circuit do (compute-input-scores c u)))))) (defun remove-from-circuit (element circuit) (cond ((null circuit) nil) ((atom circuit) (cond ((= element circuit) nil) (t circuit))) (t (loop for c in circuit for result = (remove-from-circuit element c) unless (null result) collect result)))) (defun construct-circuit-representation (formula) (cond ((or (and-p formula) (or-p formula)) (loop for arg in (cdr formula) for result = (construct-circuit-representation arg) unless (null result) collect result)) ((implies-p formula) (let ((left-result (construct-circuit-representation (implies-left formula))) (right-result (construct-circuit-representation (implies-right formula)))) (cond ((null left-result) right-result) ((null right-result) left-result) (t (list left-result right-result))))) ((not-p formula) (construct-circuit-representation (not-expr formula))) ((if-p formula) (let ((left-result (cond ((and-p (if-left formula)) (construct-circuit-representation (list* 'and (if-test formula) (cdr (if-left formula))))) (t (construct-circuit-representation (make-and (if-test formula) (if-left formula)))))) (right-result (cond ((and-p (if-right formula)) (construct-circuit-representation (list* 'and (if-test formula) (cdr (if-right formula))))) (t (construct-circuit-representation (make-and (if-test formula) (if-right formula))))))) (cond ((null left-result) right-result) ((null right-result) left-result) (t (list left-result right-result))))) ((not (or (true-p formula) (false-p formula))) (bdd-integrate-atomic formula)))) ;;; The initial order here is essentially Minato's DWA. (defun construct-initial-order (formula) (setq *initial-order* nil) (let ((circuit (construct-circuit-representation formula))) (setq *number-of-atoms* (length *atom-list*)) (setq *atom-array* (make-array *number-of-atoms* :initial-contents (reverse *atom-list*))) (setq *var-scores* (make-array *number-of-atoms* :initial-element 0)) (loop while (not (null circuit)) do (progn (compute-input-scores circuit) (let ((champ 0) (champ-score (aref *var-scores* 0))) (loop for i from 1 to (- *number-of-atoms* 1) when (> (aref *var-scores* i) champ-score) do (setq champ-score (aref *var-scores* (setq champ i)))) (push (aref *atom-array* champ) *initial-order*) (setq circuit (remove-from-circuit (+ champ 2) circuit)) (loop for i from 0 to (- *number-of-atoms* 1) do (setf (aref *var-scores* i) 0))))) (let ((result (reverse *initial-order*))) (setq *initial-order* nil) (setq *atom-list* nil) (setq *atom-array* (vector)) (setq *var-scores* (vector)) result))) (defvar *input-order* nil) (defun construct-input-order (formula) (let ((*input-order* nil)) (construct-input-order-aux formula) (reverse *input-order*))) (defun construct-input-order-aux (formula) (cond ((or (and-p formula) (or-p formula)) (loop for arg in (cdr formula) do (construct-input-order-aux arg))) ((implies-p formula) (construct-input-order-aux (implies-left formula)) (construct-input-order-aux (implies-right formula))) ((not-p formula) (construct-input-order-aux (not-expr formula))) ((if-p formula) (construct-input-order-aux (if-test formula)) (construct-input-order-aux (if-left formula)) (construct-input-order-aux (if-right formula))) ((not (or (true-p formula) (false-p formula) (member-equal formula *input-order*))) (push formula *input-order*)))) ;;; ============== Integrating formulas into the BDD =============== (defun set-expression (formula) (bdd-integrate-atoms formula) (setq *number-of-atoms* (length *atom-list*)) (setq *atom-array* (make-array *number-of-atoms* :initial-contents (reverse *atom-list*))) (setq *next-id* (+ *number-of-atoms* 2)) ;; By now, all atoms have been integrated. (bdd-integrate-formula formula)) (defun set-expression-with-reorder (formula) (let ((initial-bdd-index (push-bdd-entry (set-expression formula)))) (bdd-clear-and-recache) (let ((list-of-literals nil) (initial-bdd (bdd-entry initial-bdd-index))) (pop-bdd-entry) (dolist (var (bdd-choose-order initial-bdd)) (push (aref *atom-array* (- var 2)) list-of-literals)) (reset-bdd) (dolist (l list-of-literals) (bdd-integrate-atomic l)) (set-expression formula)))) ;;; We assume that all atoms have been integrated when this is called. (defun bdd-integrate-formula (formula) (cond ((true-p formula) *bdd-one*) ((false-p formula) *bdd-zero*) ((if-p formula) (let ((test-index (push-bdd-entry (bdd-integrate-formula (if-test formula)))) (left-index (push-bdd-entry (bdd-integrate-formula (if-left formula)))) (right-index (push-bdd-entry (bdd-integrate-formula (if-right formula))))) (let ((first-index (push-bdd-entry (bdd-negate (andop (bdd-entry test-index) (bdd-entry left-index))))) (second-result (bdd-negate (andop (bdd-negate (bdd-entry test-index)) (bdd-entry right-index))))) (let ((first-result (bdd-entry first-index))) (dotimes (i 4) (pop-bdd-entry)) (bdd-negate (andop first-result second-result)))))) ((not-p formula) (bdd-negate (bdd-integrate-formula (second formula)))) ((and-p formula) (let ((first-index (push-bdd-entry (bdd-integrate-formula (second formula)))) (second-result (bdd-integrate-formula (third formula)))) (let ((first-result (bdd-entry first-index))) (pop-bdd-entry) (andop first-result second-result)))) ((or-p formula) (let ((first-index (push-bdd-entry (bdd-integrate-formula (second formula)))) (second-result (bdd-integrate-formula (third formula)))) (let ((first-result (bdd-entry first-index))) (pop-bdd-entry) (orop first-result second-result)))) ((implies-p formula) (let ((first-index (push-bdd-entry (bdd-integrate-formula (second formula)))) (second-result (bdd-integrate-formula (third formula)))) (let ((first-result (bdd-entry first-index))) (pop-bdd-entry) (bdd-negate (andop first-result (bdd-negate second-result)))))) (t ;; Atoms have been integrated, so bdd-integrate-atomic will ;; not have any side effects. (bdd-make-if (bdd-integrate-atomic formula) *bdd-one* *bdd-zero*)))) (defun bdd-integrate-atomic (formula) (let ((tail (member-equal formula *atom-list*))) (cond (tail (+ (length tail) 1)) (t (push formula *atom-list*) (+ (length *atom-list*) 1))))) (defun bool-connective-p (formula) (or (and-p formula) (or-p formula) (implies-p formula))) (defun bdd-integrate-atoms (formula) (cond ((or (true-p formula) (false-p formula)) nil) ((if-p formula) (bdd-integrate-atoms (if-test formula)) (bdd-integrate-atoms (if-left formula)) (bdd-integrate-atoms (if-right formula))) ((not-p formula) (bdd-integrate-atoms (second formula))) ((bool-connective-p formula) (bdd-integrate-atoms (second formula)) (bdd-integrate-atoms (third formula))) (t (bdd-integrate-atomic formula)))) ;;; Some more BDD operations (defun bdd-subfunction0 (var formula) (cond ((or (eq formula *bdd-zero*) (eq formula *bdd-one*)) formula) ((bdd-negated-p formula) (bdd-negate (bdd-subfunction0 var (second formula)))) (t (or (lookup-memo-for-sub0 var formula) (let* ((formula-index (push-bdd-entry formula)) (result (cond ((= (if-test formula) var) (if-right formula)) ((< (if-test formula) var) (bdd-make-if (if-test formula) (bdd-subfunction0 var (if-left formula)) (bdd-subfunction0 var (if-right (bdd-entry formula-index))))) (t formula)))) (memoize-sub0 var (bdd-entry formula-index) result) (pop-bdd-entry) result))))) (defun bdd-subfunction1 (var formula) (cond ((or (eq formula *bdd-zero*) (eq formula *bdd-one*)) formula) ((bdd-negated-p formula) (bdd-negate (bdd-subfunction1 var (second formula)))) (t (or (lookup-memo-for-sub1 var formula) (let* ((formula-index (push-bdd-entry formula)) (result (cond ((= (if-test formula) var) (if-left formula)) ((< (if-test formula) var) (bdd-make-if (if-test formula) (bdd-subfunction1 var (if-left formula)) (bdd-subfunction1 var (if-right (bdd-entry formula-index))))) (t formula)))) (memoize-sub1 var (bdd-entry formula-index) result) (pop-bdd-entry) result))))) (defsubst bdd-var (formula) (cond ((or (eq formula *bdd-zero*) (eq formula *bdd-one*)) 1000000) ((bdd-negated-p formula) (if-test (second formula))) (t (if-test formula)))) (defun bdd-compute-subfunctions (var set-indices) (let ((result-indices nil)) (dolist (s-index set-indices) (let ((sub0 (bdd-unnegated (bdd-subfunction0 var (bdd-entry s-index))))) (unless (loop for r-index in result-indices when (eq sub0 (bdd-entry r-index)) return t) (push (push-bdd-entry sub0) result-indices))) (let ((sub1 (bdd-unnegated (bdd-subfunction1 var (bdd-entry s-index))))) (unless (loop for r-index in result-indices when (eq sub1 (bdd-entry r-index)) return t) (push (push-bdd-entry sub1) result-indices)))) (let ((result (loop for r-index in result-indices collect (bdd-entry r-index)))) (dotimes (i (length result-indices)) (pop-bdd-entry)) result))) (defun bdd-choose-order-aux (set-indices result) (let ((minvar (bdd-var (bdd-entry (car set-indices))))) (dolist (s-index set-indices) (when (< (bdd-var (bdd-entry s-index)) minvar) (setq minvar (bdd-var (bdd-entry s-index))))) (cond ((> minvar *number-of-atoms*) (dotimes (i (length set-indices)) (pop-bdd-entry)) result) (t (let ((champ-indices (loop for c in (bdd-compute-subfunctions minvar set-indices) collect (push-bdd-entry c))) (champvar minvar)) (loop for var from 2 to (+ *number-of-atoms* 1) do (unless (or (eq var champvar) (member-eq var result)) (let ((chal (bdd-compute-subfunctions var set-indices))) (when (< (length chal) (length champ-indices)) (dotimes (i (length champ-indices)) (pop-bdd-entry)) (setq champ-indices (loop for c in chal collect (push-bdd-entry c))) (setq champvar var))))) (let ((champ (loop for c-index in champ-indices collect (bdd-entry c-index)))) (dotimes (i (length champ)) (pop-bdd-entry)) (dotimes (i (length set-indices)) (pop-bdd-entry)) (setq champ-indices (loop for c in champ collect (push-bdd-entry c))) (bdd-choose-order-aux champ-indices (cons champvar result)))))))) (defun bdd-choose-order (formula) (unless (or (eq formula *bdd-zero*) (eq formula *bdd-one*)) (let* ((var (bdd-var formula)) (formula-index (push-bdd-entry formula)) (subfunctions (bdd-compute-subfunctions var (list formula-index)))) (pop-bdd-entry) (let ((subfunction-indices (loop for s in subfunctions collect (push-bdd-entry s)))) (bdd-choose-order-aux subfunction-indices (list var)))))) ;;; ================= ZBDD ================== (defconstant zbdd-hash-table-size 65536) (defconstant zbdd-hash-table-mask (1- zbdd-hash-table-size)) (defvar *zbdd-next-id* 0) (defvar *zbdd-hash-table* (make-array zbdd-hash-table-size :initial-element nil)) (defun zbdd-make-if (test left right) (cond ((equal left 0) right) (t (let ((test-id (bdd-id test)) (left-id (bdd-id left)) (right-id (bdd-id right))) (let ((index (fixnum-op logand (fixnum-op + (fixnum-op * test-id hash-multiplier) (fixnum-op + (fixnum-op * left-id second-hash-multiplier) right-id)) zbdd-hash-table-mask))) (or (loop for x in (unsafe-aref *zbdd-hash-table* index) when (let ((u (car x))) (and (fixnum-rel = (first u) test-id) (fixnum-rel = (second u) left-id) (fixnum-rel = (third u) right-id))) return (cdr x)) (let ((result (list *zbdd-next-id* test left right))) (setq *zbdd-next-id* (fixnum-op + *zbdd-next-id* 1)) (setf (unsafe-aref *zbdd-hash-table* index) (cons (cons (list test-id left-id right-id) result) (unsafe-aref *zbdd-hash-table* index))) result))))))) ;;; Returns subset of formula such that var = 1 (defun zbdd-subset1 (formula var) (cond ((< var (bdd-top formula)) 0) ((= var (bdd-top formula)) (if-left formula)) (t (zbdd-make-if (if-test formula) (zbdd-subset1 (if-left formula) var) (zbdd-subset1 (if-right formula) var))))) ;;; Returns subset of formula such that var = 0 (defun zbdd-subset0 (formula var) (cond ((< var (bdd-top formula)) formula) ((= var (bdd-top formula)) (if-right formula)) (t (zbdd-make-if (if-test formula) (zbdd-subset0 (if-left formula) var) (zbdd-subset0 (if-right formula) var))))) ;;; Returns formula with var inverted (defun zbdd-change (formula var) (cond ((or (atom formula) (< var (bdd-top formula))) (zbdd-make-if var formula 0)) ((= var (bdd-top formula)) (zbdd-make-if var (if-right formula) (if-left formula))) (t (zbdd-make-if (if-test formula) (zbdd-change (if-left formula) var) (zbdd-change (if-right formula) var))))) ;;; Union (defun zbdd-union (formula1 formula2) (cond ((equal formula1 0) formula2) ((equal formula2 0) formula1) ((equal formula1 formula2) formula1) ((< (bdd-top formula1) (bdd-top formula2)) (zbdd-make-if (if-test formula1) (if-left formula1) (zbdd-union (if-right formula1) formula2))) ((= (bdd-top formula1) (bdd-top formula2)) (zbdd-make-if (if-test formula1) (zbdd-union (if-left formula1) (if-left formula2)) (zbdd-union (if-right formula1) (if-right formula2)))) (t (zbdd-make-if (if-test formula2) (if-left formula2) (zbdd-union formula1 (if-right formula2)))))) ;;; Intersection (defun zbdd-inter (formula1 formula2) (cond ((equal formula1 0) 0) ((equal formula2 0) 0) ((equal formula1 formula2) formula1) ((< (bdd-top formula1) (bdd-top formula2)) (zbdd-inter (if-right formula1) formula2)) ((= (bdd-top formula1) (bdd-top formula2)) (zbdd-make-if (if-test formula1) (zbdd-inter (if-left formula1) (if-left formula2)) (zbdd-inter (if-right formula1) (if-right formula2)))) (t (zbdd-inter formula1 (if-right formula2))))) ;;; Difference (defun zbdd-diff (formula1 formula2) (cond ((equal formula1 0) 0) ((equal formula2 0) formula1) ((equal formula1 formula2) 0) ((< (bdd-top formula1) (bdd-top formula2)) (zbdd-make-if (if-test formula1) (if-left formula1) (zbdd-diff (if-right formula1) formula2))) ((= (bdd-top formula1) (bdd-top formula2)) (zbdd-make-if (if-test formula1) (zbdd-diff (if-left formula1) (if-left formula2)) (zbdd-diff (if-right formula1) (if-right formula2)))) (t (zbdd-diff formula1 (if-right formula2))))) (defun reset-zbdd () (setq *zbdd-next-id* 0) (dotimes (i zbdd-hash-table-size) (setf (aref *zbdd-hash-table* i) nil))) (defsubst zbdd-atom (atom) (- (* 2 atom) 2)) (defun zbdd-complement-atom (atom) (- (* 2 atom) 1)) (defun zbdd-complemented-p (atom) (= (mod atom 2) 1)) (defun zbdd-print-atom (atom) (let ((atomic-formula (aref *atom-array* (floor (- atom 2) 2)))) (if (zbdd-complemented-p atom) (make-not atomic-formula) atomic-formula))) ;;; ================ New ISOP using ZBDDs =================== ;;; Uses Minato-Morreale algorithm. (defvar *isop-hash-table* (make-array zbdd-hash-table-size :initial-element nil)) (defun reset-new-isop () (setq *zbdd-next-id* 0) (dotimes (i zbdd-hash-table-size) (setf (aref *zbdd-hash-table* i) nil) (setf (aref *isop-hash-table* i) nil))) (defun setup-new-isop () (setq *zbdd-next-id* (+ (* 2 *number-of-atoms*) 2))) (defun memoize-isop (floor-id ceiling-id result) (let ((index (fixnum-op logand (fixnum-op + (fixnum-op * hash-multiplier floor-id) ceiling-id) zbdd-hash-table-mask))) (setf (unsafe-aref *isop-hash-table* index) (cons (cons (cons floor-id ceiling-id) result) (unsafe-aref *isop-hash-table* index))))) (defun lookup-memo-for-isop (floor ceiling) (let ((floor-id (bdd-id floor)) (ceiling-id (bdd-id ceiling))) (loop for x in (unsafe-aref *isop-hash-table* (fixnum-op logand (fixnum-op + (fixnum-op * hash-multiplier floor-id) ceiling-id) zbdd-hash-table-mask)) when (and (fixnum-rel = floor-id (caar x)) (fixnum-rel = ceiling-id (cdar x))) return (cdr x)))) (defun new-isop (flr ceil) (cond ((eq flr *bdd-zero*) (list *bdd-zero* 0)) ((eq ceil *bdd-one*) (list *bdd-one* 1)) (t (or (lookup-memo-for-isop flr ceil) (let ((flr-expr (if (bdd-negated-p flr) (second flr) flr)) (neg-flr (if (bdd-negated-p flr) t nil)) (ceil-expr (if (bdd-negated-p ceil) (second ceil) ceil)) (neg-ceil (if (bdd-negated-p ceil) t nil)) (flr-index (push-bdd-entry flr)) (ceil-index (push-bdd-entry ceil))) (let ((result (cond ((= (if-test flr-expr) (if-test ceil-expr)) (new-isop-aux (if-test flr-expr) (if neg-flr (bdd-negate (if-left flr-expr)) (if-left flr-expr)) (if neg-ceil (bdd-negate (if-left ceil-expr)) (if-left ceil-expr)) (if neg-flr (bdd-negate (if-right flr-expr)) (if-right flr-expr)) (if neg-ceil (bdd-negate (if-right ceil-expr)) (if-right ceil-expr)))) ((< (if-test flr-expr) (if-test ceil-expr)) (new-isop-aux (if-test flr-expr) (if neg-flr (bdd-negate (if-left flr-expr)) (if-left flr-expr)) ceil (if neg-flr (bdd-negate (if-right flr-expr)) (if-right flr-expr)) ceil)) (t (new-isop-aux (if-test ceil-expr) flr (if neg-ceil (bdd-negate (if-left ceil-expr)) (if-left ceil-expr)) flr (if neg-ceil (bdd-negate (if-right ceil-expr)) (if-right ceil-expr))))))) (memoize-isop (bdd-id (bdd-entry flr-index)) (bdd-id (bdd-entry ceil-index)) result) (pop-bdd-entry) (pop-bdd-entry) result)))))) (defun new-isop-aux (test left-floor left-ceiling right-floor right-ceiling) (let ((left-floor-index (push-bdd-entry left-floor)) (left-ceiling-index (push-bdd-entry left-ceiling)) (right-floor-index (push-bdd-entry right-floor)) (right-ceiling-index (push-bdd-entry right-ceiling)) (first-index (push-bdd-entry (andop left-floor (bdd-negate right-ceiling))))) (let ((second-index (push-bdd-entry (andop (bdd-entry right-floor-index) (bdd-negate (bdd-entry left-ceiling-index)))))) (let* ((left (new-isop (bdd-entry first-index) (bdd-entry left-ceiling-index))) (left-index (push-bdd-entry (first left))) (right (new-isop (bdd-entry second-index) (bdd-entry right-ceiling-index))) (right-index (push-bdd-entry (first right)))) (let ((leftdpflr-index (push-bdd-entry (andop (bdd-entry left-floor-index) (bdd-negate (bdd-entry left-index))))) (rightdpflr (andop (bdd-entry right-floor-index) (bdd-negate (bdd-entry right-index))))) (let ((leftdpflr (bdd-entry leftdpflr-index))) (pop-bdd-entry) (let ((floor-index (push-bdd-entry (orop (andop leftdpflr (bdd-entry right-ceiling-index)) (andop rightdpflr (bdd-entry left-ceiling-index))))) (ceiling-index (push-bdd-entry (andop (bdd-entry left-ceiling-index) (bdd-entry right-ceiling-index))))) (let* ((dontcare (new-isop (bdd-entry floor-index) (bdd-entry ceiling-index))) (dontcare-index (push-bdd-entry (first dontcare))) (res1-index (push-bdd-entry (andop (bdd-make-if test *bdd-one* *bdd-zero*) (bdd-entry left-index)))) (res2 (andop (bdd-make-if test *bdd-zero* *bdd-one*) (bdd-entry right-index))) (result-bdd (orop (orop (bdd-entry res1-index) res2) (bdd-entry dontcare-index)))) (dotimes (i 12) (pop-bdd-entry)) (list result-bdd (zbdd-union (zbdd-union (zbdd-change (second left) (zbdd-atom test)) (zbdd-change (second right) (zbdd-complement-atom test))) (second dontcare))))))))))) (defun new-ipos (flr ceil) (cond ((equal ceil *bdd-one*) (list *bdd-one* 0)) ((equal flr *bdd-zero*) (list *bdd-zero* 1)) (t (or (lookup-memo-for-isop flr ceil) (let ((flr-expr (if (bdd-negated-p flr) (second flr) flr)) (neg-flr (if (bdd-negated-p flr) t nil)) (ceil-expr (if (bdd-negated-p ceil) (second ceil) ceil)) (neg-ceil (if (bdd-negated-p ceil) t nil)) (flr-index (push-bdd-entry flr)) (ceil-index (push-bdd-entry ceil))) (let ((result (cond ((= (if-test flr-expr) (if-test ceil-expr)) (new-ipos-aux (if-test flr-expr) (if neg-flr (bdd-negate (if-left flr-expr)) (if-left flr-expr)) (if neg-ceil (bdd-negate (if-left ceil-expr)) (if-left ceil-expr)) (if neg-flr (bdd-negate (if-right flr-expr)) (if-right flr-expr)) (if neg-ceil (bdd-negate (if-right ceil-expr)) (if-right ceil-expr)))) ((< (if-test flr-expr) (if-test ceil-expr)) (new-ipos-aux (if-test flr-expr) (if neg-flr (bdd-negate (if-left flr-expr)) (if-left flr-expr)) ceil (if neg-flr (bdd-negate (if-right flr-expr)) (if-right flr-expr)) ceil)) (t (new-ipos-aux (if-test ceil-expr) flr (if neg-ceil (bdd-negate (if-left ceil-expr)) (if-left ceil-expr)) flr (if neg-ceil (bdd-negate (if-right ceil-expr)) (if-right ceil-expr))))))) (memoize-isop (bdd-id (bdd-entry flr-index)) (bdd-id (bdd-entry ceil-index)) result) (pop-bdd-entry) (pop-bdd-entry) result)))))) (defun new-ipos-aux (test left-floor left-ceiling right-floor right-ceiling) (let ((left-floor-index (push-bdd-entry left-floor)) (left-ceiling-index (push-bdd-entry left-ceiling)) (right-floor-index (push-bdd-entry right-floor)) (right-ceiling-index (push-bdd-entry right-ceiling)) (first-index (push-bdd-entry (orop left-ceiling (bdd-negate right-floor))))) (let ((second-index (push-bdd-entry (orop (bdd-entry right-ceiling-index) (bdd-negate (bdd-entry left-floor-index)))))) (let* ((left (new-ipos (bdd-entry left-floor-index) (bdd-entry first-index))) (left-index (push-bdd-entry (first left))) (right (new-ipos (bdd-entry right-floor-index) (bdd-entry second-index))) (right-index (push-bdd-entry (first right)))) (let ((leftdpceil-index (push-bdd-entry (orop (bdd-entry left-ceiling-index) (bdd-negate (bdd-entry left-index))))) (rightdpceil (orop (bdd-entry right-ceiling-index) (bdd-negate (bdd-entry right-index))))) (let ((leftdpceil (bdd-entry leftdpceil-index))) (pop-bdd-entry) (let ((floor-index (push-bdd-entry (orop (bdd-entry left-floor-index) (bdd-entry right-floor-index)))) (ceiling-index (push-bdd-entry (andop (orop leftdpceil (bdd-entry right-floor-index)) (orop rightdpceil (bdd-entry left-floor-index)))))) (let* ((dontcare (new-ipos (bdd-entry floor-index) (bdd-entry ceiling-index))) (dontcare-index (push-bdd-entry (first dontcare))) (res1-index (push-bdd-entry (orop (bdd-make-if test *bdd-one* *bdd-zero*) (bdd-entry right-index)))) (res2 (orop (bdd-make-if test *bdd-zero* *bdd-one*) (bdd-entry left-index))) (result-bdd (andop (andop (bdd-entry res1-index) res2) (bdd-entry dontcare-index)))) (dotimes (i 12) (pop-bdd-entry)) (list result-bdd (zbdd-union (zbdd-change (second right) (zbdd-atom test)) (zbdd-union (zbdd-change (second left) (zbdd-complement-atom test)) (second dontcare)))))))))))) (defvar *zbdd-cube-set* nil) (defun zbdd-to-cube-set (zbdd) (setq *zbdd-cube-set* nil) (zbdd-to-cube-set-aux zbdd nil) *zbdd-cube-set*) (defun zbdd-to-cube-set-aux (zbdd path) (cond ((equal zbdd 1) (push path *zbdd-cube-set*)) ((equal zbdd 0)) (t (zbdd-to-cube-set-aux (if-left zbdd) (cons (if-test zbdd) path)) (zbdd-to-cube-set-aux (if-right zbdd) path)))) (defun prop-weight (formula order) (cond ((not-p formula) (length (member-equal (not-expr formula) order))) (t (length (member-equal formula order))))) (defun insert-into-collection (pair collection) (cond ((or (null collection) (> (car pair) (caar collection))) (cons pair collection)) (t (cons (car collection) (insert-into-collection pair (cdr collection)))))) (defun prop-rearrange (formula order) (cond ((and-p formula) (let ((collected nil)) (loop for expr in (cdr formula) do (let ((r (prop-rearrange expr order))) (setq collected (insert-into-collection (cons (prop-weight r order) r) collected)))) (cons 'and (loop for r in collected collect (cdr r))))) ((or-p formula) (let ((collected nil)) (loop for expr in (cdr formula) do (let ((r (prop-rearrange expr order))) (setq collected (insert-into-collection (cons (prop-weight r order) r) collected)))) (cons 'or (loop for r in collected collect (cdr r))))) ((not-p formula) (make-not (prop-rearrange (not-expr formula) order))) ((implies-p formula) (make-implies (prop-rearrange (implies-left formula) order) (prop-rearrange (implies-right formula) order))) ((if-p formula) (make-if (prop-rearrange (if-test formula) order) (prop-rearrange (if-left formula) order) (prop-rearrange (if-right formula) order))) (t formula))) ;;; ============ Top level functions for DNF and CNF =============== (defun dnf (formula) (let* ((initial-order (construct-initial-order formula)) (input-order (construct-input-order formula)) (rearranged (prop-rearrange formula initial-order))) (loop for atom in initial-order do (bdd-integrate-atomic atom)) (let ((internal-formula (set-expression (without-proof-logging (expand-proposition rearranged nil))))) (let ((internal-formula-index (push-bdd-entry internal-formula))) (bdd-clear-and-recache) (setq internal-formula (bdd-entry internal-formula-index)) (pop-bdd-entry) (setup-new-isop) (let* ((result (new-isop internal-formula internal-formula)) (cube-set (zbdd-to-cube-set (second result))) (result-formula (cond ((null cube-set) *false*) ((= (length cube-set) 1) (dnf-aux (first cube-set))) (t (let ((result nil)) (loop for disjunct in cube-set do (push (dnf-aux disjunct) result)) (cons 'or result)))))) (reset-new-isop) (reset-bdd) (prop-rearrange result-formula input-order)))))) (defun dnf-aux (result) (cond ((null result) *true*) ((= (length result) 1) (zbdd-print-atom (first result))) (t (let ((res nil)) (loop for conjunct in result do (push (zbdd-print-atom conjunct) res)) (cons 'and res))))) (defun cnf (formula) (let* ((initial-order (construct-initial-order formula)) (input-order (construct-input-order formula)) (rearranged (prop-rearrange formula initial-order))) (loop for atom in initial-order do (bdd-integrate-atomic atom)) (let ((internal-formula (set-expression (without-proof-logging (expand-proposition rearranged nil))))) (let ((internal-formula-index (push-bdd-entry internal-formula))) (bdd-clear-and-recache) (setq internal-formula (bdd-entry internal-formula-index)) (pop-bdd-entry) (setup-new-isop) (let* ((result (new-ipos internal-formula internal-formula)) (cube-set (zbdd-to-cube-set (second result))) (result-formula (cond ((null cube-set) *true*) ((= (length cube-set) 1) (cnf-aux (first cube-set))) (t (let ((result nil)) (loop for disjunct in cube-set do (push (cnf-aux disjunct) result)) (cons 'and result)))))) (reset-new-isop) (reset-bdd) (prop-rearrange result-formula input-order)))))) (defun cnf-aux (result) (cond ((null result) *false*) ((= (length result) 1) (zbdd-print-atom (first result))) (t (let ((res nil)) (loop for disjunct in result do (push (zbdd-print-atom disjunct) res)) (cons 'or res)))))
66239
;;;====================================================================== ;;; | ;;; Copyright (c) 2021, <NAME>, <NAME>, | ;;; <NAME>, <NAME> and <NAME>. | ;;; All Rights Reserved. | ;;; | ;;; Redistribution and use in source and binary forms, with or without | ;;; modification, are permitted provided 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. | ;;; | ;;; 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 HOLDERS AND | ;;; CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, | ;;; SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT | ;;; LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF | ;;; USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED | ;;; AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT | ;;; LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING | ;;; IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF | ;;; THE POSSIBILITY OF SUCH DAMAGE. | ;;; | ;;;====================================================================== (in-package "ZK") ;;; =============== Conjunctive/Disjunctive Normal Forms =============== ;;; Code to do CNF/DNF using the Minato-Morreale technique. For our ;;; purposes, the technique is more than good enough. The BDD is based ;;; on Sentot's BDD implementation for a symbolic model checker. (defconstant bdd-hash-table-size 131072) (defconstant bdd-hash-table-mask (1- bdd-hash-table-size)) (defconstant recache-threshold 262144) (defconstant hash-multiplier 5) (defconstant second-hash-multiplier 3) (defvar *atom-list* nil) (defvar *bdd-entries* (make-array 8192 :initial-element nil)) (defvar *bdd-entries-size* 0) (defsubst push-bdd-entry (bdd) (setf (aref *bdd-entries* *bdd-entries-size*) bdd) (let ((result *bdd-entries-size*)) (setq *bdd-entries-size* (fixnum-op + *bdd-entries-size* 1)) result)) (defsubst bdd-entry (index) (aref *bdd-entries* index)) (defsubst pop-bdd-entry () (setf (aref *bdd-entries* *bdd-entries-size*) nil) (setq *bdd-entries-size* (fixnum-op - *bdd-entries-size* 1))) (defvar *atom-array* (vector)) ;;; The *if-hash-table* plays a vital role in ensuring that the BDD ;;; structures are shared. ;;; Each element of *if-hash-table* is a list of entries. ;;; Each entry is of the "if" form: (id test-id left-bdd right-bdd). (defvar *if-hash-table* (make-array bdd-hash-table-size :initial-element nil)) (defvar *if-count* 0) (defvar *recaching* nil) ;;; The *not-hash-table* also plays a vital role in ensuring that ;;; the BDD structures are shared. ;;; Each element of *not-hash-table* is a list of entries. ;;; Each entry is of the "not" form: (id unsigned-bdd), ;;; where the unsigned-bdd represents an "unsigned" formula. (defvar *not-hash-table* (make-array bdd-hash-table-size :initial-element nil)) ;;; The next two tables are for memoizing subfunction operations. ;;; The tables are not vital in that deleting entries in the ;;; tables does not effect the correct operation of the BDD. (defvar *sub0-hash-table* (make-array bdd-hash-table-size :initial-element nil)) (defvar *sub1-hash-table* (make-array bdd-hash-table-size :initial-element nil)) ;;; The *and-hash-table* is also for memoizing only: (defvar *and-hash-table* (make-array bdd-hash-table-size :initial-element nil)) ;;; The *recache-table* plays a vital role in ensuring the ;;; correct operation of the "garbage collector". (defvar *recache-table* (make-array bdd-hash-table-size :initial-element nil)) (defvar *next-id* 2) (defvar *number-of-atoms* 0) (defvar *bdd-zero* 0) (defparameter *bdd-one* (list 1 0)) (defsubst bdd-id (formula) (if (atom formula) formula (car formula))) (defsubst bdd-negated-p (formula) (and (consp formula) (= (length formula) 2))) (defsubst bdd-top (formula) (cond ((atom formula) formula) ((atom (second formula)) (second formula)) (t (second (second formula))))) ;;; Hash consing and memoizing ;;; Haven't tried to "optimize" the hashing function to get a good ;;; distribution, except for *not-hash-table*. (defun lookup-memo-for-and (left-id right-id) ;; andop is commutative, so normalize arguments to low, high (let ((low-id (fixnum-op min left-id right-id)) (high-id (fixnum-op max left-id right-id))) (loop for x in (unsafe-aref *and-hash-table* (fixnum-op logand (fixnum-op + (fixnum-op * low-id hash-multiplier) high-id) bdd-hash-table-mask)) when (and (fixnum-rel = low-id (caar x)) (fixnum-rel = high-id (cdar x))) return (cdr x)))) (defsubst memoize-and (left-id right-id result) ;; andop is commutative, so normalize arguments to low, high (let ((low-id (fixnum-op min left-id right-id)) (high-id (fixnum-op max left-id right-id))) (let ((index (fixnum-op logand (fixnum-op + (fixnum-op * low-id hash-multiplier) high-id) bdd-hash-table-mask))) (setf (unsafe-aref *and-hash-table* index) (cons (cons (cons low-id high-id) result) (unsafe-aref *and-hash-table* index)))))) ;;; "nots" are not really memoized, but rather, they are hash-consed ;;; (to use J Moore's terminology). (defsubst lookup-memo-for-not (formula) (let ((id (bdd-id formula))) (loop for x in (unsafe-aref *not-hash-table* (fixnum-op logand id bdd-hash-table-mask)) when (eq (second x) formula) return x))) (defsubst memoize-not (formula result) (let* ((id (bdd-id formula)) (index (fixnum-op logand id bdd-hash-table-mask))) (setf (unsafe-aref *not-hash-table* index) (cons result (unsafe-aref *not-hash-table* index))))) (defsubst lookup-memo-for-sub0 (var formula) (let ((id (bdd-id formula))) (loop for x in (unsafe-aref *sub0-hash-table* (fixnum-op logand (fixnum-op + (fixnum-op * var hash-multiplier) id) bdd-hash-table-mask)) when (and (fixnum-rel = var (caar x)) (fixnum-rel = id (cdar x))) return (cdr x)))) (defsubst memoize-sub0 (var formula result) (let ((id (bdd-id formula))) (let ((index (fixnum-op logand (fixnum-op + (fixnum-op * var hash-multiplier) id) bdd-hash-table-mask))) (setf (unsafe-aref *sub0-hash-table* index) (cons (cons (cons var id) result) (unsafe-aref *sub0-hash-table* index)))))) (defsubst lookup-memo-for-sub1 (var formula) (let ((id (bdd-id formula))) (loop for x in (unsafe-aref *sub1-hash-table* (fixnum-op logand (fixnum-op + (fixnum-op * var hash-multiplier) id) bdd-hash-table-mask)) when (and (fixnum-rel = var (caar x)) (fixnum-rel = id (cdar x))) return (cdr x)))) (defsubst memoize-sub1 (var formula result) (let ((id (bdd-id formula))) (let ((index (fixnum-op logand (fixnum-op + (fixnum-op * var hash-multiplier) id) bdd-hash-table-mask))) (setf (unsafe-aref *sub1-hash-table* index) (cons (cons (cons var id) result) (unsafe-aref *sub1-hash-table* index)))))) ;;; Reconstruction of bdds after "garbage collection" are really ;;; "hash-consing" operations. (defsubst lookup-memo-for-recache (formula) (let ((id (bdd-id formula))) (loop for x in (unsafe-aref *recache-table* (fixnum-op logand id bdd-hash-table-mask)) when (fixnum-rel = id (car x)) return (cdr x)))) (defsubst memoize-recache (id formula) (let ((index (fixnum-op logand id bdd-hash-table-mask))) (setf (unsafe-aref *recache-table* index) (cons (cons id formula) (unsafe-aref *recache-table* index))))) ;;; The top level function for "garbage collection": (defun bdd-clear-and-recache () ;(format t "~%Clearing and starting new cache~%") (dotimes (i bdd-hash-table-size) (setf (aref *if-hash-table* i) nil) (setf (aref *recache-table* i) nil) (setf (aref *not-hash-table* i) nil) (setf (aref *sub0-hash-table* i) nil) (setf (aref *sub1-hash-table* i) nil) (setf (aref *and-hash-table* i) nil)) (setq *if-count* 0) (setq *next-id* (+ *number-of-atoms* 2)) (let ((*recaching* t)) (let ((results (loop for i from 0 to (- *bdd-entries-size* 1) do (setf (aref *bdd-entries* i) (bdd-recache (aref *bdd-entries* i)))))) (dotimes (i bdd-hash-table-size) (setf (aref *recache-table* i) nil)) results))) ;;; Function to create the negation of a BDD node. (defsubst bdd-negate (formula) (cond ((eq formula *bdd-zero*) *bdd-one*) ((eq formula *bdd-one*) *bdd-zero*) ((and (consp formula) (= (length formula) 2)) (second formula)) (t (or (lookup-memo-for-not formula) (let ((result (list *next-id* formula))) (setq *next-id* (+ *next-id* 1)) (memoize-not formula result) result))))) ;;; Function to create an "if" node in a BDD. (defun bdd-make-if (test left right) (cond ((equal left right) left) ((and (consp right) (= (length right) 2)) (let ((negated-left (bdd-negate left)) (negated-right (bdd-negate right))) (let ((index (fixnum-op logand (fixnum-op + (fixnum-op * (bdd-id test) hash-multiplier) (fixnum-op + (fixnum-op * (bdd-id negated-left) second-hash-multiplier) (bdd-id negated-right))) bdd-hash-table-mask))) (bdd-negate (or (loop for x in (unsafe-aref *if-hash-table* index) when (and (eq test (if-test x)) (eq negated-left (if-left x)) (eq negated-right (if-right x))) return x) (let ((need-to-recache (fixnum-op logand recache-threshold *if-count*))) (cond ((= need-to-recache 0) (let ((if-form (list *next-id* test negated-left negated-right))) (unless *recaching* (setq *if-count* (+ *if-count* 1))) (setq *next-id* (+ *next-id* 1)) (setf (unsafe-aref *if-hash-table* index) (cons if-form (unsafe-aref *if-hash-table* index))) if-form)) (t (let ((left-index (push-bdd-entry negated-left)) (right-index (push-bdd-entry negated-right))) (bdd-clear-and-recache) (let ((if-form (list *next-id* test (bdd-entry left-index) (bdd-entry right-index))) (index (fixnum-op logand (fixnum-op + (fixnum-op * (bdd-id test) hash-multiplier) (fixnum-op + (fixnum-op * (bdd-id (bdd-entry left-index)) second-hash-multiplier) (bdd-id (bdd-entry right-index)))) bdd-hash-table-mask))) (pop-bdd-entry) (pop-bdd-entry) (unless *recaching* (setq *if-count* (+ *if-count* 1))) (setq *next-id* (+ *next-id* 1)) (setf (unsafe-aref *if-hash-table* index) (cons if-form (unsafe-aref *if-hash-table* index))) if-form)))))))))) (t (let ((index (fixnum-op logand (fixnum-op + (fixnum-op * (bdd-id test) hash-multiplier) (fixnum-op + (fixnum-op * (bdd-id left) second-hash-multiplier) (bdd-id right))) bdd-hash-table-mask))) (or (loop for x in (unsafe-aref *if-hash-table* index) when (and (eq test (if-test x)) (eq left (if-left x)) (eq right (if-right x))) return x) (let ((need-to-recache (fixnum-op logand recache-threshold *if-count*))) (cond ((= need-to-recache 0) (let ((if-form (list *next-id* test left right))) (unless *recaching* (setq *if-count* (+ *if-count* 1))) (setq *next-id* (+ *next-id* 1)) (setf (unsafe-aref *if-hash-table* index) (cons if-form (unsafe-aref *if-hash-table* index))) if-form)) (t (let ((left-index (push-bdd-entry left)) (right-index (push-bdd-entry right))) (bdd-clear-and-recache) (let ((result (list *next-id* test (bdd-entry left-index) (bdd-entry right-index))) (index (fixnum-op logand (fixnum-op + (fixnum-op * (bdd-id test) hash-multiplier) (fixnum-op + (fixnum-op * (bdd-id (bdd-entry left-index)) second-hash-multiplier) (bdd-id (bdd-entry right-index)))) bdd-hash-table-mask))) (pop-bdd-entry) (pop-bdd-entry) (unless *recaching* (setq *if-count* (+ *if-count* 1))) (setq *next-id* (+ *next-id* 1)) (setf (unsafe-aref *if-hash-table* index) (cons result (unsafe-aref *if-hash-table* index))) result)))))))))) ;;; Function to "reconstruct" a BDD node after "garbage collection". (defun bdd-recache (formula) (cond ((or (eq formula *bdd-zero*) (eq formula *bdd-one*)) formula) (t (or (lookup-memo-for-recache formula) (cond ((= (length formula) 2) (let ((result (bdd-negate (bdd-recache (second formula))))) (memoize-recache (bdd-id formula) result) result)) (t (let ((result (bdd-make-if (if-test formula) (bdd-recache (if-left formula)) (bdd-recache (if-right formula))))) (memoize-recache (bdd-id formula) result) result))))))) ;;; =========== The "merge-sorting" functions ============ ;;; All boolean connectives are converted to use the "and" ;;; operation and negation (instead of "nand" or "nor"). (defsubst andop-constant (formula negated1 negated2) (cond ((not negated1) *bdd-zero*) (negated2 (bdd-negate formula)) (t formula))) (defsubst complementary (formula1 formula2) (or (and (consp formula1) (= (length formula1) 2) (eq (second formula1) formula2)) (and (consp formula2) (= (length formula2) 2) (eq (second formula2) formula1)))) (defsubst bdd-unnegated (formula) (if (bdd-negated-p formula) (second formula) formula)) (defsubst bdd-compute-sense (formula negated) (if (bdd-negated-p formula) (not negated) negated)) (defun andop-aux (formula1 formula2 negated1 negated2) (cond ((eq formula1 *bdd-zero*) (andop-constant formula2 negated1 negated2)) ((eq formula2 *bdd-zero*) (andop-constant formula1 negated2 negated1)) ((eq formula1 formula2) (if negated1 (if negated2 (bdd-negate formula1) *bdd-zero*) (if negated2 *bdd-zero* formula1))) (t (let ((expr1 (if negated1 (bdd-negate formula1) formula1)) (expr2 (if negated2 (bdd-negate formula2) formula2))) (or (lookup-memo-for-and (bdd-id expr1) (bdd-id expr2)) (let ((expr1-index (push-bdd-entry expr1)) (expr2-index (push-bdd-entry expr2))) (let ((result (cond ((= (if-test formula1) (if-test formula2)) (let ((left1 (bdd-unnegated (if-left formula1))) (left2 (bdd-unnegated (if-left formula2))) (neg1 (bdd-compute-sense (if-left formula1) negated1)) (neg2 (bdd-compute-sense (if-left formula2) negated2))) ;; Note that a right branch is never a negation (let ((right1-index (push-bdd-entry (if-right formula1))) (right2-index (push-bdd-entry (if-right formula2))) (left-index (push-bdd-entry (andop-aux left1 left2 neg1 neg2)))) (let ((right-result (andop-aux (bdd-entry right1-index) (bdd-entry right2-index) negated1 negated2))) (let ((left-result (bdd-entry left-index))) (dotimes (i 3) (pop-bdd-entry)) (bdd-make-if (if-test formula1) left-result right-result)))))) ((< (if-test formula1) (if-test formula2)) (let ((left1 (bdd-unnegated (if-left formula1))) (neg1 (bdd-compute-sense (if-left formula1) negated1))) (let ((right1-index (push-bdd-entry (if-right formula1))) (formula2-index (push-bdd-entry formula2)) (left-index (push-bdd-entry (andop-aux left1 formula2 neg1 negated2)))) (let ((right-result (andop-aux (bdd-entry right1-index) (bdd-entry formula2-index) negated1 negated2))) (let ((left-result (bdd-entry left-index))) (dotimes (i 3) (pop-bdd-entry)) (bdd-make-if (if-test formula1) left-result right-result)))))) (t (let ((left2 (bdd-unnegated (if-left formula2))) (neg2 (bdd-compute-sense (if-left formula2) negated2))) (let ((formula1-index (push-bdd-entry formula1)) (right2-index (push-bdd-entry (if-right formula2))) (left-index (push-bdd-entry (andop-aux formula1 left2 negated1 neg2)))) (let ((right-result (andop-aux (bdd-entry formula1-index) (bdd-entry right2-index) negated1 negated2))) (let ((left-result (bdd-entry left-index))) (dotimes (i 3) (pop-bdd-entry)) (bdd-make-if (if-test formula2) left-result right-result))))))))) (memoize-and (bdd-id (bdd-entry expr1-index)) (bdd-id (bdd-entry expr2-index)) result) (dotimes (i 2) (pop-bdd-entry)) result))))))) (defun andop (formula1 formula2) (andop-aux (bdd-unnegated formula1) (bdd-unnegated formula2) (bdd-negated-p formula1) (bdd-negated-p formula2))) (defsubst orop (formula1 formula2) (bdd-negate (andop (bdd-negate formula1) (bdd-negate formula2)))) ;;; ================ Interface ================= (defun reset-bdd () (setq *atom-list* nil) (setq *atom-array* (vector)) (setq *next-id* 2) (setq *number-of-atoms* 0) (setq *if-count* 0) (dotimes (i bdd-hash-table-size) (setf (aref *if-hash-table* i) nil) (setf (aref *recache-table* i) nil) (setf (aref *not-hash-table* i) nil) (setf (aref *sub0-hash-table* i) nil) (setf (aref *sub1-hash-table* i) nil) (setf (aref *and-hash-table* i) nil))) (defvar *var-scores* (vector)) (defvar *initial-order* nil) (defun compute-input-scores (circuit &optional (unit 1.0)) (cond ((null circuit) nil) ((atom circuit) (incf (aref *var-scores* (- circuit 2)) unit)) (t (let ((u (/ unit (length circuit)))) (loop for c in circuit do (compute-input-scores c u)))))) (defun remove-from-circuit (element circuit) (cond ((null circuit) nil) ((atom circuit) (cond ((= element circuit) nil) (t circuit))) (t (loop for c in circuit for result = (remove-from-circuit element c) unless (null result) collect result)))) (defun construct-circuit-representation (formula) (cond ((or (and-p formula) (or-p formula)) (loop for arg in (cdr formula) for result = (construct-circuit-representation arg) unless (null result) collect result)) ((implies-p formula) (let ((left-result (construct-circuit-representation (implies-left formula))) (right-result (construct-circuit-representation (implies-right formula)))) (cond ((null left-result) right-result) ((null right-result) left-result) (t (list left-result right-result))))) ((not-p formula) (construct-circuit-representation (not-expr formula))) ((if-p formula) (let ((left-result (cond ((and-p (if-left formula)) (construct-circuit-representation (list* 'and (if-test formula) (cdr (if-left formula))))) (t (construct-circuit-representation (make-and (if-test formula) (if-left formula)))))) (right-result (cond ((and-p (if-right formula)) (construct-circuit-representation (list* 'and (if-test formula) (cdr (if-right formula))))) (t (construct-circuit-representation (make-and (if-test formula) (if-right formula))))))) (cond ((null left-result) right-result) ((null right-result) left-result) (t (list left-result right-result))))) ((not (or (true-p formula) (false-p formula))) (bdd-integrate-atomic formula)))) ;;; The initial order here is essentially Minato's DWA. (defun construct-initial-order (formula) (setq *initial-order* nil) (let ((circuit (construct-circuit-representation formula))) (setq *number-of-atoms* (length *atom-list*)) (setq *atom-array* (make-array *number-of-atoms* :initial-contents (reverse *atom-list*))) (setq *var-scores* (make-array *number-of-atoms* :initial-element 0)) (loop while (not (null circuit)) do (progn (compute-input-scores circuit) (let ((champ 0) (champ-score (aref *var-scores* 0))) (loop for i from 1 to (- *number-of-atoms* 1) when (> (aref *var-scores* i) champ-score) do (setq champ-score (aref *var-scores* (setq champ i)))) (push (aref *atom-array* champ) *initial-order*) (setq circuit (remove-from-circuit (+ champ 2) circuit)) (loop for i from 0 to (- *number-of-atoms* 1) do (setf (aref *var-scores* i) 0))))) (let ((result (reverse *initial-order*))) (setq *initial-order* nil) (setq *atom-list* nil) (setq *atom-array* (vector)) (setq *var-scores* (vector)) result))) (defvar *input-order* nil) (defun construct-input-order (formula) (let ((*input-order* nil)) (construct-input-order-aux formula) (reverse *input-order*))) (defun construct-input-order-aux (formula) (cond ((or (and-p formula) (or-p formula)) (loop for arg in (cdr formula) do (construct-input-order-aux arg))) ((implies-p formula) (construct-input-order-aux (implies-left formula)) (construct-input-order-aux (implies-right formula))) ((not-p formula) (construct-input-order-aux (not-expr formula))) ((if-p formula) (construct-input-order-aux (if-test formula)) (construct-input-order-aux (if-left formula)) (construct-input-order-aux (if-right formula))) ((not (or (true-p formula) (false-p formula) (member-equal formula *input-order*))) (push formula *input-order*)))) ;;; ============== Integrating formulas into the BDD =============== (defun set-expression (formula) (bdd-integrate-atoms formula) (setq *number-of-atoms* (length *atom-list*)) (setq *atom-array* (make-array *number-of-atoms* :initial-contents (reverse *atom-list*))) (setq *next-id* (+ *number-of-atoms* 2)) ;; By now, all atoms have been integrated. (bdd-integrate-formula formula)) (defun set-expression-with-reorder (formula) (let ((initial-bdd-index (push-bdd-entry (set-expression formula)))) (bdd-clear-and-recache) (let ((list-of-literals nil) (initial-bdd (bdd-entry initial-bdd-index))) (pop-bdd-entry) (dolist (var (bdd-choose-order initial-bdd)) (push (aref *atom-array* (- var 2)) list-of-literals)) (reset-bdd) (dolist (l list-of-literals) (bdd-integrate-atomic l)) (set-expression formula)))) ;;; We assume that all atoms have been integrated when this is called. (defun bdd-integrate-formula (formula) (cond ((true-p formula) *bdd-one*) ((false-p formula) *bdd-zero*) ((if-p formula) (let ((test-index (push-bdd-entry (bdd-integrate-formula (if-test formula)))) (left-index (push-bdd-entry (bdd-integrate-formula (if-left formula)))) (right-index (push-bdd-entry (bdd-integrate-formula (if-right formula))))) (let ((first-index (push-bdd-entry (bdd-negate (andop (bdd-entry test-index) (bdd-entry left-index))))) (second-result (bdd-negate (andop (bdd-negate (bdd-entry test-index)) (bdd-entry right-index))))) (let ((first-result (bdd-entry first-index))) (dotimes (i 4) (pop-bdd-entry)) (bdd-negate (andop first-result second-result)))))) ((not-p formula) (bdd-negate (bdd-integrate-formula (second formula)))) ((and-p formula) (let ((first-index (push-bdd-entry (bdd-integrate-formula (second formula)))) (second-result (bdd-integrate-formula (third formula)))) (let ((first-result (bdd-entry first-index))) (pop-bdd-entry) (andop first-result second-result)))) ((or-p formula) (let ((first-index (push-bdd-entry (bdd-integrate-formula (second formula)))) (second-result (bdd-integrate-formula (third formula)))) (let ((first-result (bdd-entry first-index))) (pop-bdd-entry) (orop first-result second-result)))) ((implies-p formula) (let ((first-index (push-bdd-entry (bdd-integrate-formula (second formula)))) (second-result (bdd-integrate-formula (third formula)))) (let ((first-result (bdd-entry first-index))) (pop-bdd-entry) (bdd-negate (andop first-result (bdd-negate second-result)))))) (t ;; Atoms have been integrated, so bdd-integrate-atomic will ;; not have any side effects. (bdd-make-if (bdd-integrate-atomic formula) *bdd-one* *bdd-zero*)))) (defun bdd-integrate-atomic (formula) (let ((tail (member-equal formula *atom-list*))) (cond (tail (+ (length tail) 1)) (t (push formula *atom-list*) (+ (length *atom-list*) 1))))) (defun bool-connective-p (formula) (or (and-p formula) (or-p formula) (implies-p formula))) (defun bdd-integrate-atoms (formula) (cond ((or (true-p formula) (false-p formula)) nil) ((if-p formula) (bdd-integrate-atoms (if-test formula)) (bdd-integrate-atoms (if-left formula)) (bdd-integrate-atoms (if-right formula))) ((not-p formula) (bdd-integrate-atoms (second formula))) ((bool-connective-p formula) (bdd-integrate-atoms (second formula)) (bdd-integrate-atoms (third formula))) (t (bdd-integrate-atomic formula)))) ;;; Some more BDD operations (defun bdd-subfunction0 (var formula) (cond ((or (eq formula *bdd-zero*) (eq formula *bdd-one*)) formula) ((bdd-negated-p formula) (bdd-negate (bdd-subfunction0 var (second formula)))) (t (or (lookup-memo-for-sub0 var formula) (let* ((formula-index (push-bdd-entry formula)) (result (cond ((= (if-test formula) var) (if-right formula)) ((< (if-test formula) var) (bdd-make-if (if-test formula) (bdd-subfunction0 var (if-left formula)) (bdd-subfunction0 var (if-right (bdd-entry formula-index))))) (t formula)))) (memoize-sub0 var (bdd-entry formula-index) result) (pop-bdd-entry) result))))) (defun bdd-subfunction1 (var formula) (cond ((or (eq formula *bdd-zero*) (eq formula *bdd-one*)) formula) ((bdd-negated-p formula) (bdd-negate (bdd-subfunction1 var (second formula)))) (t (or (lookup-memo-for-sub1 var formula) (let* ((formula-index (push-bdd-entry formula)) (result (cond ((= (if-test formula) var) (if-left formula)) ((< (if-test formula) var) (bdd-make-if (if-test formula) (bdd-subfunction1 var (if-left formula)) (bdd-subfunction1 var (if-right (bdd-entry formula-index))))) (t formula)))) (memoize-sub1 var (bdd-entry formula-index) result) (pop-bdd-entry) result))))) (defsubst bdd-var (formula) (cond ((or (eq formula *bdd-zero*) (eq formula *bdd-one*)) 1000000) ((bdd-negated-p formula) (if-test (second formula))) (t (if-test formula)))) (defun bdd-compute-subfunctions (var set-indices) (let ((result-indices nil)) (dolist (s-index set-indices) (let ((sub0 (bdd-unnegated (bdd-subfunction0 var (bdd-entry s-index))))) (unless (loop for r-index in result-indices when (eq sub0 (bdd-entry r-index)) return t) (push (push-bdd-entry sub0) result-indices))) (let ((sub1 (bdd-unnegated (bdd-subfunction1 var (bdd-entry s-index))))) (unless (loop for r-index in result-indices when (eq sub1 (bdd-entry r-index)) return t) (push (push-bdd-entry sub1) result-indices)))) (let ((result (loop for r-index in result-indices collect (bdd-entry r-index)))) (dotimes (i (length result-indices)) (pop-bdd-entry)) result))) (defun bdd-choose-order-aux (set-indices result) (let ((minvar (bdd-var (bdd-entry (car set-indices))))) (dolist (s-index set-indices) (when (< (bdd-var (bdd-entry s-index)) minvar) (setq minvar (bdd-var (bdd-entry s-index))))) (cond ((> minvar *number-of-atoms*) (dotimes (i (length set-indices)) (pop-bdd-entry)) result) (t (let ((champ-indices (loop for c in (bdd-compute-subfunctions minvar set-indices) collect (push-bdd-entry c))) (champvar minvar)) (loop for var from 2 to (+ *number-of-atoms* 1) do (unless (or (eq var champvar) (member-eq var result)) (let ((chal (bdd-compute-subfunctions var set-indices))) (when (< (length chal) (length champ-indices)) (dotimes (i (length champ-indices)) (pop-bdd-entry)) (setq champ-indices (loop for c in chal collect (push-bdd-entry c))) (setq champvar var))))) (let ((champ (loop for c-index in champ-indices collect (bdd-entry c-index)))) (dotimes (i (length champ)) (pop-bdd-entry)) (dotimes (i (length set-indices)) (pop-bdd-entry)) (setq champ-indices (loop for c in champ collect (push-bdd-entry c))) (bdd-choose-order-aux champ-indices (cons champvar result)))))))) (defun bdd-choose-order (formula) (unless (or (eq formula *bdd-zero*) (eq formula *bdd-one*)) (let* ((var (bdd-var formula)) (formula-index (push-bdd-entry formula)) (subfunctions (bdd-compute-subfunctions var (list formula-index)))) (pop-bdd-entry) (let ((subfunction-indices (loop for s in subfunctions collect (push-bdd-entry s)))) (bdd-choose-order-aux subfunction-indices (list var)))))) ;;; ================= ZBDD ================== (defconstant zbdd-hash-table-size 65536) (defconstant zbdd-hash-table-mask (1- zbdd-hash-table-size)) (defvar *zbdd-next-id* 0) (defvar *zbdd-hash-table* (make-array zbdd-hash-table-size :initial-element nil)) (defun zbdd-make-if (test left right) (cond ((equal left 0) right) (t (let ((test-id (bdd-id test)) (left-id (bdd-id left)) (right-id (bdd-id right))) (let ((index (fixnum-op logand (fixnum-op + (fixnum-op * test-id hash-multiplier) (fixnum-op + (fixnum-op * left-id second-hash-multiplier) right-id)) zbdd-hash-table-mask))) (or (loop for x in (unsafe-aref *zbdd-hash-table* index) when (let ((u (car x))) (and (fixnum-rel = (first u) test-id) (fixnum-rel = (second u) left-id) (fixnum-rel = (third u) right-id))) return (cdr x)) (let ((result (list *zbdd-next-id* test left right))) (setq *zbdd-next-id* (fixnum-op + *zbdd-next-id* 1)) (setf (unsafe-aref *zbdd-hash-table* index) (cons (cons (list test-id left-id right-id) result) (unsafe-aref *zbdd-hash-table* index))) result))))))) ;;; Returns subset of formula such that var = 1 (defun zbdd-subset1 (formula var) (cond ((< var (bdd-top formula)) 0) ((= var (bdd-top formula)) (if-left formula)) (t (zbdd-make-if (if-test formula) (zbdd-subset1 (if-left formula) var) (zbdd-subset1 (if-right formula) var))))) ;;; Returns subset of formula such that var = 0 (defun zbdd-subset0 (formula var) (cond ((< var (bdd-top formula)) formula) ((= var (bdd-top formula)) (if-right formula)) (t (zbdd-make-if (if-test formula) (zbdd-subset0 (if-left formula) var) (zbdd-subset0 (if-right formula) var))))) ;;; Returns formula with var inverted (defun zbdd-change (formula var) (cond ((or (atom formula) (< var (bdd-top formula))) (zbdd-make-if var formula 0)) ((= var (bdd-top formula)) (zbdd-make-if var (if-right formula) (if-left formula))) (t (zbdd-make-if (if-test formula) (zbdd-change (if-left formula) var) (zbdd-change (if-right formula) var))))) ;;; Union (defun zbdd-union (formula1 formula2) (cond ((equal formula1 0) formula2) ((equal formula2 0) formula1) ((equal formula1 formula2) formula1) ((< (bdd-top formula1) (bdd-top formula2)) (zbdd-make-if (if-test formula1) (if-left formula1) (zbdd-union (if-right formula1) formula2))) ((= (bdd-top formula1) (bdd-top formula2)) (zbdd-make-if (if-test formula1) (zbdd-union (if-left formula1) (if-left formula2)) (zbdd-union (if-right formula1) (if-right formula2)))) (t (zbdd-make-if (if-test formula2) (if-left formula2) (zbdd-union formula1 (if-right formula2)))))) ;;; Intersection (defun zbdd-inter (formula1 formula2) (cond ((equal formula1 0) 0) ((equal formula2 0) 0) ((equal formula1 formula2) formula1) ((< (bdd-top formula1) (bdd-top formula2)) (zbdd-inter (if-right formula1) formula2)) ((= (bdd-top formula1) (bdd-top formula2)) (zbdd-make-if (if-test formula1) (zbdd-inter (if-left formula1) (if-left formula2)) (zbdd-inter (if-right formula1) (if-right formula2)))) (t (zbdd-inter formula1 (if-right formula2))))) ;;; Difference (defun zbdd-diff (formula1 formula2) (cond ((equal formula1 0) 0) ((equal formula2 0) formula1) ((equal formula1 formula2) 0) ((< (bdd-top formula1) (bdd-top formula2)) (zbdd-make-if (if-test formula1) (if-left formula1) (zbdd-diff (if-right formula1) formula2))) ((= (bdd-top formula1) (bdd-top formula2)) (zbdd-make-if (if-test formula1) (zbdd-diff (if-left formula1) (if-left formula2)) (zbdd-diff (if-right formula1) (if-right formula2)))) (t (zbdd-diff formula1 (if-right formula2))))) (defun reset-zbdd () (setq *zbdd-next-id* 0) (dotimes (i zbdd-hash-table-size) (setf (aref *zbdd-hash-table* i) nil))) (defsubst zbdd-atom (atom) (- (* 2 atom) 2)) (defun zbdd-complement-atom (atom) (- (* 2 atom) 1)) (defun zbdd-complemented-p (atom) (= (mod atom 2) 1)) (defun zbdd-print-atom (atom) (let ((atomic-formula (aref *atom-array* (floor (- atom 2) 2)))) (if (zbdd-complemented-p atom) (make-not atomic-formula) atomic-formula))) ;;; ================ New ISOP using ZBDDs =================== ;;; Uses Minato-Morreale algorithm. (defvar *isop-hash-table* (make-array zbdd-hash-table-size :initial-element nil)) (defun reset-new-isop () (setq *zbdd-next-id* 0) (dotimes (i zbdd-hash-table-size) (setf (aref *zbdd-hash-table* i) nil) (setf (aref *isop-hash-table* i) nil))) (defun setup-new-isop () (setq *zbdd-next-id* (+ (* 2 *number-of-atoms*) 2))) (defun memoize-isop (floor-id ceiling-id result) (let ((index (fixnum-op logand (fixnum-op + (fixnum-op * hash-multiplier floor-id) ceiling-id) zbdd-hash-table-mask))) (setf (unsafe-aref *isop-hash-table* index) (cons (cons (cons floor-id ceiling-id) result) (unsafe-aref *isop-hash-table* index))))) (defun lookup-memo-for-isop (floor ceiling) (let ((floor-id (bdd-id floor)) (ceiling-id (bdd-id ceiling))) (loop for x in (unsafe-aref *isop-hash-table* (fixnum-op logand (fixnum-op + (fixnum-op * hash-multiplier floor-id) ceiling-id) zbdd-hash-table-mask)) when (and (fixnum-rel = floor-id (caar x)) (fixnum-rel = ceiling-id (cdar x))) return (cdr x)))) (defun new-isop (flr ceil) (cond ((eq flr *bdd-zero*) (list *bdd-zero* 0)) ((eq ceil *bdd-one*) (list *bdd-one* 1)) (t (or (lookup-memo-for-isop flr ceil) (let ((flr-expr (if (bdd-negated-p flr) (second flr) flr)) (neg-flr (if (bdd-negated-p flr) t nil)) (ceil-expr (if (bdd-negated-p ceil) (second ceil) ceil)) (neg-ceil (if (bdd-negated-p ceil) t nil)) (flr-index (push-bdd-entry flr)) (ceil-index (push-bdd-entry ceil))) (let ((result (cond ((= (if-test flr-expr) (if-test ceil-expr)) (new-isop-aux (if-test flr-expr) (if neg-flr (bdd-negate (if-left flr-expr)) (if-left flr-expr)) (if neg-ceil (bdd-negate (if-left ceil-expr)) (if-left ceil-expr)) (if neg-flr (bdd-negate (if-right flr-expr)) (if-right flr-expr)) (if neg-ceil (bdd-negate (if-right ceil-expr)) (if-right ceil-expr)))) ((< (if-test flr-expr) (if-test ceil-expr)) (new-isop-aux (if-test flr-expr) (if neg-flr (bdd-negate (if-left flr-expr)) (if-left flr-expr)) ceil (if neg-flr (bdd-negate (if-right flr-expr)) (if-right flr-expr)) ceil)) (t (new-isop-aux (if-test ceil-expr) flr (if neg-ceil (bdd-negate (if-left ceil-expr)) (if-left ceil-expr)) flr (if neg-ceil (bdd-negate (if-right ceil-expr)) (if-right ceil-expr))))))) (memoize-isop (bdd-id (bdd-entry flr-index)) (bdd-id (bdd-entry ceil-index)) result) (pop-bdd-entry) (pop-bdd-entry) result)))))) (defun new-isop-aux (test left-floor left-ceiling right-floor right-ceiling) (let ((left-floor-index (push-bdd-entry left-floor)) (left-ceiling-index (push-bdd-entry left-ceiling)) (right-floor-index (push-bdd-entry right-floor)) (right-ceiling-index (push-bdd-entry right-ceiling)) (first-index (push-bdd-entry (andop left-floor (bdd-negate right-ceiling))))) (let ((second-index (push-bdd-entry (andop (bdd-entry right-floor-index) (bdd-negate (bdd-entry left-ceiling-index)))))) (let* ((left (new-isop (bdd-entry first-index) (bdd-entry left-ceiling-index))) (left-index (push-bdd-entry (first left))) (right (new-isop (bdd-entry second-index) (bdd-entry right-ceiling-index))) (right-index (push-bdd-entry (first right)))) (let ((leftdpflr-index (push-bdd-entry (andop (bdd-entry left-floor-index) (bdd-negate (bdd-entry left-index))))) (rightdpflr (andop (bdd-entry right-floor-index) (bdd-negate (bdd-entry right-index))))) (let ((leftdpflr (bdd-entry leftdpflr-index))) (pop-bdd-entry) (let ((floor-index (push-bdd-entry (orop (andop leftdpflr (bdd-entry right-ceiling-index)) (andop rightdpflr (bdd-entry left-ceiling-index))))) (ceiling-index (push-bdd-entry (andop (bdd-entry left-ceiling-index) (bdd-entry right-ceiling-index))))) (let* ((dontcare (new-isop (bdd-entry floor-index) (bdd-entry ceiling-index))) (dontcare-index (push-bdd-entry (first dontcare))) (res1-index (push-bdd-entry (andop (bdd-make-if test *bdd-one* *bdd-zero*) (bdd-entry left-index)))) (res2 (andop (bdd-make-if test *bdd-zero* *bdd-one*) (bdd-entry right-index))) (result-bdd (orop (orop (bdd-entry res1-index) res2) (bdd-entry dontcare-index)))) (dotimes (i 12) (pop-bdd-entry)) (list result-bdd (zbdd-union (zbdd-union (zbdd-change (second left) (zbdd-atom test)) (zbdd-change (second right) (zbdd-complement-atom test))) (second dontcare))))))))))) (defun new-ipos (flr ceil) (cond ((equal ceil *bdd-one*) (list *bdd-one* 0)) ((equal flr *bdd-zero*) (list *bdd-zero* 1)) (t (or (lookup-memo-for-isop flr ceil) (let ((flr-expr (if (bdd-negated-p flr) (second flr) flr)) (neg-flr (if (bdd-negated-p flr) t nil)) (ceil-expr (if (bdd-negated-p ceil) (second ceil) ceil)) (neg-ceil (if (bdd-negated-p ceil) t nil)) (flr-index (push-bdd-entry flr)) (ceil-index (push-bdd-entry ceil))) (let ((result (cond ((= (if-test flr-expr) (if-test ceil-expr)) (new-ipos-aux (if-test flr-expr) (if neg-flr (bdd-negate (if-left flr-expr)) (if-left flr-expr)) (if neg-ceil (bdd-negate (if-left ceil-expr)) (if-left ceil-expr)) (if neg-flr (bdd-negate (if-right flr-expr)) (if-right flr-expr)) (if neg-ceil (bdd-negate (if-right ceil-expr)) (if-right ceil-expr)))) ((< (if-test flr-expr) (if-test ceil-expr)) (new-ipos-aux (if-test flr-expr) (if neg-flr (bdd-negate (if-left flr-expr)) (if-left flr-expr)) ceil (if neg-flr (bdd-negate (if-right flr-expr)) (if-right flr-expr)) ceil)) (t (new-ipos-aux (if-test ceil-expr) flr (if neg-ceil (bdd-negate (if-left ceil-expr)) (if-left ceil-expr)) flr (if neg-ceil (bdd-negate (if-right ceil-expr)) (if-right ceil-expr))))))) (memoize-isop (bdd-id (bdd-entry flr-index)) (bdd-id (bdd-entry ceil-index)) result) (pop-bdd-entry) (pop-bdd-entry) result)))))) (defun new-ipos-aux (test left-floor left-ceiling right-floor right-ceiling) (let ((left-floor-index (push-bdd-entry left-floor)) (left-ceiling-index (push-bdd-entry left-ceiling)) (right-floor-index (push-bdd-entry right-floor)) (right-ceiling-index (push-bdd-entry right-ceiling)) (first-index (push-bdd-entry (orop left-ceiling (bdd-negate right-floor))))) (let ((second-index (push-bdd-entry (orop (bdd-entry right-ceiling-index) (bdd-negate (bdd-entry left-floor-index)))))) (let* ((left (new-ipos (bdd-entry left-floor-index) (bdd-entry first-index))) (left-index (push-bdd-entry (first left))) (right (new-ipos (bdd-entry right-floor-index) (bdd-entry second-index))) (right-index (push-bdd-entry (first right)))) (let ((leftdpceil-index (push-bdd-entry (orop (bdd-entry left-ceiling-index) (bdd-negate (bdd-entry left-index))))) (rightdpceil (orop (bdd-entry right-ceiling-index) (bdd-negate (bdd-entry right-index))))) (let ((leftdpceil (bdd-entry leftdpceil-index))) (pop-bdd-entry) (let ((floor-index (push-bdd-entry (orop (bdd-entry left-floor-index) (bdd-entry right-floor-index)))) (ceiling-index (push-bdd-entry (andop (orop leftdpceil (bdd-entry right-floor-index)) (orop rightdpceil (bdd-entry left-floor-index)))))) (let* ((dontcare (new-ipos (bdd-entry floor-index) (bdd-entry ceiling-index))) (dontcare-index (push-bdd-entry (first dontcare))) (res1-index (push-bdd-entry (orop (bdd-make-if test *bdd-one* *bdd-zero*) (bdd-entry right-index)))) (res2 (orop (bdd-make-if test *bdd-zero* *bdd-one*) (bdd-entry left-index))) (result-bdd (andop (andop (bdd-entry res1-index) res2) (bdd-entry dontcare-index)))) (dotimes (i 12) (pop-bdd-entry)) (list result-bdd (zbdd-union (zbdd-change (second right) (zbdd-atom test)) (zbdd-union (zbdd-change (second left) (zbdd-complement-atom test)) (second dontcare)))))))))))) (defvar *zbdd-cube-set* nil) (defun zbdd-to-cube-set (zbdd) (setq *zbdd-cube-set* nil) (zbdd-to-cube-set-aux zbdd nil) *zbdd-cube-set*) (defun zbdd-to-cube-set-aux (zbdd path) (cond ((equal zbdd 1) (push path *zbdd-cube-set*)) ((equal zbdd 0)) (t (zbdd-to-cube-set-aux (if-left zbdd) (cons (if-test zbdd) path)) (zbdd-to-cube-set-aux (if-right zbdd) path)))) (defun prop-weight (formula order) (cond ((not-p formula) (length (member-equal (not-expr formula) order))) (t (length (member-equal formula order))))) (defun insert-into-collection (pair collection) (cond ((or (null collection) (> (car pair) (caar collection))) (cons pair collection)) (t (cons (car collection) (insert-into-collection pair (cdr collection)))))) (defun prop-rearrange (formula order) (cond ((and-p formula) (let ((collected nil)) (loop for expr in (cdr formula) do (let ((r (prop-rearrange expr order))) (setq collected (insert-into-collection (cons (prop-weight r order) r) collected)))) (cons 'and (loop for r in collected collect (cdr r))))) ((or-p formula) (let ((collected nil)) (loop for expr in (cdr formula) do (let ((r (prop-rearrange expr order))) (setq collected (insert-into-collection (cons (prop-weight r order) r) collected)))) (cons 'or (loop for r in collected collect (cdr r))))) ((not-p formula) (make-not (prop-rearrange (not-expr formula) order))) ((implies-p formula) (make-implies (prop-rearrange (implies-left formula) order) (prop-rearrange (implies-right formula) order))) ((if-p formula) (make-if (prop-rearrange (if-test formula) order) (prop-rearrange (if-left formula) order) (prop-rearrange (if-right formula) order))) (t formula))) ;;; ============ Top level functions for DNF and CNF =============== (defun dnf (formula) (let* ((initial-order (construct-initial-order formula)) (input-order (construct-input-order formula)) (rearranged (prop-rearrange formula initial-order))) (loop for atom in initial-order do (bdd-integrate-atomic atom)) (let ((internal-formula (set-expression (without-proof-logging (expand-proposition rearranged nil))))) (let ((internal-formula-index (push-bdd-entry internal-formula))) (bdd-clear-and-recache) (setq internal-formula (bdd-entry internal-formula-index)) (pop-bdd-entry) (setup-new-isop) (let* ((result (new-isop internal-formula internal-formula)) (cube-set (zbdd-to-cube-set (second result))) (result-formula (cond ((null cube-set) *false*) ((= (length cube-set) 1) (dnf-aux (first cube-set))) (t (let ((result nil)) (loop for disjunct in cube-set do (push (dnf-aux disjunct) result)) (cons 'or result)))))) (reset-new-isop) (reset-bdd) (prop-rearrange result-formula input-order)))))) (defun dnf-aux (result) (cond ((null result) *true*) ((= (length result) 1) (zbdd-print-atom (first result))) (t (let ((res nil)) (loop for conjunct in result do (push (zbdd-print-atom conjunct) res)) (cons 'and res))))) (defun cnf (formula) (let* ((initial-order (construct-initial-order formula)) (input-order (construct-input-order formula)) (rearranged (prop-rearrange formula initial-order))) (loop for atom in initial-order do (bdd-integrate-atomic atom)) (let ((internal-formula (set-expression (without-proof-logging (expand-proposition rearranged nil))))) (let ((internal-formula-index (push-bdd-entry internal-formula))) (bdd-clear-and-recache) (setq internal-formula (bdd-entry internal-formula-index)) (pop-bdd-entry) (setup-new-isop) (let* ((result (new-ipos internal-formula internal-formula)) (cube-set (zbdd-to-cube-set (second result))) (result-formula (cond ((null cube-set) *true*) ((= (length cube-set) 1) (cnf-aux (first cube-set))) (t (let ((result nil)) (loop for disjunct in cube-set do (push (cnf-aux disjunct) result)) (cons 'and result)))))) (reset-new-isop) (reset-bdd) (prop-rearrange result-formula input-order)))))) (defun cnf-aux (result) (cond ((null result) *false*) ((= (length result) 1) (zbdd-print-atom (first result))) (t (let ((res nil)) (loop for disjunct in result do (push (zbdd-print-atom disjunct) res)) (cons 'or res)))))
true
;;;====================================================================== ;;; | ;;; Copyright (c) 2021, 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. | ;;; All Rights Reserved. | ;;; | ;;; Redistribution and use in source and binary forms, with or without | ;;; modification, are permitted provided 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. | ;;; | ;;; 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 HOLDERS AND | ;;; CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, | ;;; SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT | ;;; LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF | ;;; USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED | ;;; AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT | ;;; LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING | ;;; IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF | ;;; THE POSSIBILITY OF SUCH DAMAGE. | ;;; | ;;;====================================================================== (in-package "ZK") ;;; =============== Conjunctive/Disjunctive Normal Forms =============== ;;; Code to do CNF/DNF using the Minato-Morreale technique. For our ;;; purposes, the technique is more than good enough. The BDD is based ;;; on Sentot's BDD implementation for a symbolic model checker. (defconstant bdd-hash-table-size 131072) (defconstant bdd-hash-table-mask (1- bdd-hash-table-size)) (defconstant recache-threshold 262144) (defconstant hash-multiplier 5) (defconstant second-hash-multiplier 3) (defvar *atom-list* nil) (defvar *bdd-entries* (make-array 8192 :initial-element nil)) (defvar *bdd-entries-size* 0) (defsubst push-bdd-entry (bdd) (setf (aref *bdd-entries* *bdd-entries-size*) bdd) (let ((result *bdd-entries-size*)) (setq *bdd-entries-size* (fixnum-op + *bdd-entries-size* 1)) result)) (defsubst bdd-entry (index) (aref *bdd-entries* index)) (defsubst pop-bdd-entry () (setf (aref *bdd-entries* *bdd-entries-size*) nil) (setq *bdd-entries-size* (fixnum-op - *bdd-entries-size* 1))) (defvar *atom-array* (vector)) ;;; The *if-hash-table* plays a vital role in ensuring that the BDD ;;; structures are shared. ;;; Each element of *if-hash-table* is a list of entries. ;;; Each entry is of the "if" form: (id test-id left-bdd right-bdd). (defvar *if-hash-table* (make-array bdd-hash-table-size :initial-element nil)) (defvar *if-count* 0) (defvar *recaching* nil) ;;; The *not-hash-table* also plays a vital role in ensuring that ;;; the BDD structures are shared. ;;; Each element of *not-hash-table* is a list of entries. ;;; Each entry is of the "not" form: (id unsigned-bdd), ;;; where the unsigned-bdd represents an "unsigned" formula. (defvar *not-hash-table* (make-array bdd-hash-table-size :initial-element nil)) ;;; The next two tables are for memoizing subfunction operations. ;;; The tables are not vital in that deleting entries in the ;;; tables does not effect the correct operation of the BDD. (defvar *sub0-hash-table* (make-array bdd-hash-table-size :initial-element nil)) (defvar *sub1-hash-table* (make-array bdd-hash-table-size :initial-element nil)) ;;; The *and-hash-table* is also for memoizing only: (defvar *and-hash-table* (make-array bdd-hash-table-size :initial-element nil)) ;;; The *recache-table* plays a vital role in ensuring the ;;; correct operation of the "garbage collector". (defvar *recache-table* (make-array bdd-hash-table-size :initial-element nil)) (defvar *next-id* 2) (defvar *number-of-atoms* 0) (defvar *bdd-zero* 0) (defparameter *bdd-one* (list 1 0)) (defsubst bdd-id (formula) (if (atom formula) formula (car formula))) (defsubst bdd-negated-p (formula) (and (consp formula) (= (length formula) 2))) (defsubst bdd-top (formula) (cond ((atom formula) formula) ((atom (second formula)) (second formula)) (t (second (second formula))))) ;;; Hash consing and memoizing ;;; Haven't tried to "optimize" the hashing function to get a good ;;; distribution, except for *not-hash-table*. (defun lookup-memo-for-and (left-id right-id) ;; andop is commutative, so normalize arguments to low, high (let ((low-id (fixnum-op min left-id right-id)) (high-id (fixnum-op max left-id right-id))) (loop for x in (unsafe-aref *and-hash-table* (fixnum-op logand (fixnum-op + (fixnum-op * low-id hash-multiplier) high-id) bdd-hash-table-mask)) when (and (fixnum-rel = low-id (caar x)) (fixnum-rel = high-id (cdar x))) return (cdr x)))) (defsubst memoize-and (left-id right-id result) ;; andop is commutative, so normalize arguments to low, high (let ((low-id (fixnum-op min left-id right-id)) (high-id (fixnum-op max left-id right-id))) (let ((index (fixnum-op logand (fixnum-op + (fixnum-op * low-id hash-multiplier) high-id) bdd-hash-table-mask))) (setf (unsafe-aref *and-hash-table* index) (cons (cons (cons low-id high-id) result) (unsafe-aref *and-hash-table* index)))))) ;;; "nots" are not really memoized, but rather, they are hash-consed ;;; (to use J Moore's terminology). (defsubst lookup-memo-for-not (formula) (let ((id (bdd-id formula))) (loop for x in (unsafe-aref *not-hash-table* (fixnum-op logand id bdd-hash-table-mask)) when (eq (second x) formula) return x))) (defsubst memoize-not (formula result) (let* ((id (bdd-id formula)) (index (fixnum-op logand id bdd-hash-table-mask))) (setf (unsafe-aref *not-hash-table* index) (cons result (unsafe-aref *not-hash-table* index))))) (defsubst lookup-memo-for-sub0 (var formula) (let ((id (bdd-id formula))) (loop for x in (unsafe-aref *sub0-hash-table* (fixnum-op logand (fixnum-op + (fixnum-op * var hash-multiplier) id) bdd-hash-table-mask)) when (and (fixnum-rel = var (caar x)) (fixnum-rel = id (cdar x))) return (cdr x)))) (defsubst memoize-sub0 (var formula result) (let ((id (bdd-id formula))) (let ((index (fixnum-op logand (fixnum-op + (fixnum-op * var hash-multiplier) id) bdd-hash-table-mask))) (setf (unsafe-aref *sub0-hash-table* index) (cons (cons (cons var id) result) (unsafe-aref *sub0-hash-table* index)))))) (defsubst lookup-memo-for-sub1 (var formula) (let ((id (bdd-id formula))) (loop for x in (unsafe-aref *sub1-hash-table* (fixnum-op logand (fixnum-op + (fixnum-op * var hash-multiplier) id) bdd-hash-table-mask)) when (and (fixnum-rel = var (caar x)) (fixnum-rel = id (cdar x))) return (cdr x)))) (defsubst memoize-sub1 (var formula result) (let ((id (bdd-id formula))) (let ((index (fixnum-op logand (fixnum-op + (fixnum-op * var hash-multiplier) id) bdd-hash-table-mask))) (setf (unsafe-aref *sub1-hash-table* index) (cons (cons (cons var id) result) (unsafe-aref *sub1-hash-table* index)))))) ;;; Reconstruction of bdds after "garbage collection" are really ;;; "hash-consing" operations. (defsubst lookup-memo-for-recache (formula) (let ((id (bdd-id formula))) (loop for x in (unsafe-aref *recache-table* (fixnum-op logand id bdd-hash-table-mask)) when (fixnum-rel = id (car x)) return (cdr x)))) (defsubst memoize-recache (id formula) (let ((index (fixnum-op logand id bdd-hash-table-mask))) (setf (unsafe-aref *recache-table* index) (cons (cons id formula) (unsafe-aref *recache-table* index))))) ;;; The top level function for "garbage collection": (defun bdd-clear-and-recache () ;(format t "~%Clearing and starting new cache~%") (dotimes (i bdd-hash-table-size) (setf (aref *if-hash-table* i) nil) (setf (aref *recache-table* i) nil) (setf (aref *not-hash-table* i) nil) (setf (aref *sub0-hash-table* i) nil) (setf (aref *sub1-hash-table* i) nil) (setf (aref *and-hash-table* i) nil)) (setq *if-count* 0) (setq *next-id* (+ *number-of-atoms* 2)) (let ((*recaching* t)) (let ((results (loop for i from 0 to (- *bdd-entries-size* 1) do (setf (aref *bdd-entries* i) (bdd-recache (aref *bdd-entries* i)))))) (dotimes (i bdd-hash-table-size) (setf (aref *recache-table* i) nil)) results))) ;;; Function to create the negation of a BDD node. (defsubst bdd-negate (formula) (cond ((eq formula *bdd-zero*) *bdd-one*) ((eq formula *bdd-one*) *bdd-zero*) ((and (consp formula) (= (length formula) 2)) (second formula)) (t (or (lookup-memo-for-not formula) (let ((result (list *next-id* formula))) (setq *next-id* (+ *next-id* 1)) (memoize-not formula result) result))))) ;;; Function to create an "if" node in a BDD. (defun bdd-make-if (test left right) (cond ((equal left right) left) ((and (consp right) (= (length right) 2)) (let ((negated-left (bdd-negate left)) (negated-right (bdd-negate right))) (let ((index (fixnum-op logand (fixnum-op + (fixnum-op * (bdd-id test) hash-multiplier) (fixnum-op + (fixnum-op * (bdd-id negated-left) second-hash-multiplier) (bdd-id negated-right))) bdd-hash-table-mask))) (bdd-negate (or (loop for x in (unsafe-aref *if-hash-table* index) when (and (eq test (if-test x)) (eq negated-left (if-left x)) (eq negated-right (if-right x))) return x) (let ((need-to-recache (fixnum-op logand recache-threshold *if-count*))) (cond ((= need-to-recache 0) (let ((if-form (list *next-id* test negated-left negated-right))) (unless *recaching* (setq *if-count* (+ *if-count* 1))) (setq *next-id* (+ *next-id* 1)) (setf (unsafe-aref *if-hash-table* index) (cons if-form (unsafe-aref *if-hash-table* index))) if-form)) (t (let ((left-index (push-bdd-entry negated-left)) (right-index (push-bdd-entry negated-right))) (bdd-clear-and-recache) (let ((if-form (list *next-id* test (bdd-entry left-index) (bdd-entry right-index))) (index (fixnum-op logand (fixnum-op + (fixnum-op * (bdd-id test) hash-multiplier) (fixnum-op + (fixnum-op * (bdd-id (bdd-entry left-index)) second-hash-multiplier) (bdd-id (bdd-entry right-index)))) bdd-hash-table-mask))) (pop-bdd-entry) (pop-bdd-entry) (unless *recaching* (setq *if-count* (+ *if-count* 1))) (setq *next-id* (+ *next-id* 1)) (setf (unsafe-aref *if-hash-table* index) (cons if-form (unsafe-aref *if-hash-table* index))) if-form)))))))))) (t (let ((index (fixnum-op logand (fixnum-op + (fixnum-op * (bdd-id test) hash-multiplier) (fixnum-op + (fixnum-op * (bdd-id left) second-hash-multiplier) (bdd-id right))) bdd-hash-table-mask))) (or (loop for x in (unsafe-aref *if-hash-table* index) when (and (eq test (if-test x)) (eq left (if-left x)) (eq right (if-right x))) return x) (let ((need-to-recache (fixnum-op logand recache-threshold *if-count*))) (cond ((= need-to-recache 0) (let ((if-form (list *next-id* test left right))) (unless *recaching* (setq *if-count* (+ *if-count* 1))) (setq *next-id* (+ *next-id* 1)) (setf (unsafe-aref *if-hash-table* index) (cons if-form (unsafe-aref *if-hash-table* index))) if-form)) (t (let ((left-index (push-bdd-entry left)) (right-index (push-bdd-entry right))) (bdd-clear-and-recache) (let ((result (list *next-id* test (bdd-entry left-index) (bdd-entry right-index))) (index (fixnum-op logand (fixnum-op + (fixnum-op * (bdd-id test) hash-multiplier) (fixnum-op + (fixnum-op * (bdd-id (bdd-entry left-index)) second-hash-multiplier) (bdd-id (bdd-entry right-index)))) bdd-hash-table-mask))) (pop-bdd-entry) (pop-bdd-entry) (unless *recaching* (setq *if-count* (+ *if-count* 1))) (setq *next-id* (+ *next-id* 1)) (setf (unsafe-aref *if-hash-table* index) (cons result (unsafe-aref *if-hash-table* index))) result)))))))))) ;;; Function to "reconstruct" a BDD node after "garbage collection". (defun bdd-recache (formula) (cond ((or (eq formula *bdd-zero*) (eq formula *bdd-one*)) formula) (t (or (lookup-memo-for-recache formula) (cond ((= (length formula) 2) (let ((result (bdd-negate (bdd-recache (second formula))))) (memoize-recache (bdd-id formula) result) result)) (t (let ((result (bdd-make-if (if-test formula) (bdd-recache (if-left formula)) (bdd-recache (if-right formula))))) (memoize-recache (bdd-id formula) result) result))))))) ;;; =========== The "merge-sorting" functions ============ ;;; All boolean connectives are converted to use the "and" ;;; operation and negation (instead of "nand" or "nor"). (defsubst andop-constant (formula negated1 negated2) (cond ((not negated1) *bdd-zero*) (negated2 (bdd-negate formula)) (t formula))) (defsubst complementary (formula1 formula2) (or (and (consp formula1) (= (length formula1) 2) (eq (second formula1) formula2)) (and (consp formula2) (= (length formula2) 2) (eq (second formula2) formula1)))) (defsubst bdd-unnegated (formula) (if (bdd-negated-p formula) (second formula) formula)) (defsubst bdd-compute-sense (formula negated) (if (bdd-negated-p formula) (not negated) negated)) (defun andop-aux (formula1 formula2 negated1 negated2) (cond ((eq formula1 *bdd-zero*) (andop-constant formula2 negated1 negated2)) ((eq formula2 *bdd-zero*) (andop-constant formula1 negated2 negated1)) ((eq formula1 formula2) (if negated1 (if negated2 (bdd-negate formula1) *bdd-zero*) (if negated2 *bdd-zero* formula1))) (t (let ((expr1 (if negated1 (bdd-negate formula1) formula1)) (expr2 (if negated2 (bdd-negate formula2) formula2))) (or (lookup-memo-for-and (bdd-id expr1) (bdd-id expr2)) (let ((expr1-index (push-bdd-entry expr1)) (expr2-index (push-bdd-entry expr2))) (let ((result (cond ((= (if-test formula1) (if-test formula2)) (let ((left1 (bdd-unnegated (if-left formula1))) (left2 (bdd-unnegated (if-left formula2))) (neg1 (bdd-compute-sense (if-left formula1) negated1)) (neg2 (bdd-compute-sense (if-left formula2) negated2))) ;; Note that a right branch is never a negation (let ((right1-index (push-bdd-entry (if-right formula1))) (right2-index (push-bdd-entry (if-right formula2))) (left-index (push-bdd-entry (andop-aux left1 left2 neg1 neg2)))) (let ((right-result (andop-aux (bdd-entry right1-index) (bdd-entry right2-index) negated1 negated2))) (let ((left-result (bdd-entry left-index))) (dotimes (i 3) (pop-bdd-entry)) (bdd-make-if (if-test formula1) left-result right-result)))))) ((< (if-test formula1) (if-test formula2)) (let ((left1 (bdd-unnegated (if-left formula1))) (neg1 (bdd-compute-sense (if-left formula1) negated1))) (let ((right1-index (push-bdd-entry (if-right formula1))) (formula2-index (push-bdd-entry formula2)) (left-index (push-bdd-entry (andop-aux left1 formula2 neg1 negated2)))) (let ((right-result (andop-aux (bdd-entry right1-index) (bdd-entry formula2-index) negated1 negated2))) (let ((left-result (bdd-entry left-index))) (dotimes (i 3) (pop-bdd-entry)) (bdd-make-if (if-test formula1) left-result right-result)))))) (t (let ((left2 (bdd-unnegated (if-left formula2))) (neg2 (bdd-compute-sense (if-left formula2) negated2))) (let ((formula1-index (push-bdd-entry formula1)) (right2-index (push-bdd-entry (if-right formula2))) (left-index (push-bdd-entry (andop-aux formula1 left2 negated1 neg2)))) (let ((right-result (andop-aux (bdd-entry formula1-index) (bdd-entry right2-index) negated1 negated2))) (let ((left-result (bdd-entry left-index))) (dotimes (i 3) (pop-bdd-entry)) (bdd-make-if (if-test formula2) left-result right-result))))))))) (memoize-and (bdd-id (bdd-entry expr1-index)) (bdd-id (bdd-entry expr2-index)) result) (dotimes (i 2) (pop-bdd-entry)) result))))))) (defun andop (formula1 formula2) (andop-aux (bdd-unnegated formula1) (bdd-unnegated formula2) (bdd-negated-p formula1) (bdd-negated-p formula2))) (defsubst orop (formula1 formula2) (bdd-negate (andop (bdd-negate formula1) (bdd-negate formula2)))) ;;; ================ Interface ================= (defun reset-bdd () (setq *atom-list* nil) (setq *atom-array* (vector)) (setq *next-id* 2) (setq *number-of-atoms* 0) (setq *if-count* 0) (dotimes (i bdd-hash-table-size) (setf (aref *if-hash-table* i) nil) (setf (aref *recache-table* i) nil) (setf (aref *not-hash-table* i) nil) (setf (aref *sub0-hash-table* i) nil) (setf (aref *sub1-hash-table* i) nil) (setf (aref *and-hash-table* i) nil))) (defvar *var-scores* (vector)) (defvar *initial-order* nil) (defun compute-input-scores (circuit &optional (unit 1.0)) (cond ((null circuit) nil) ((atom circuit) (incf (aref *var-scores* (- circuit 2)) unit)) (t (let ((u (/ unit (length circuit)))) (loop for c in circuit do (compute-input-scores c u)))))) (defun remove-from-circuit (element circuit) (cond ((null circuit) nil) ((atom circuit) (cond ((= element circuit) nil) (t circuit))) (t (loop for c in circuit for result = (remove-from-circuit element c) unless (null result) collect result)))) (defun construct-circuit-representation (formula) (cond ((or (and-p formula) (or-p formula)) (loop for arg in (cdr formula) for result = (construct-circuit-representation arg) unless (null result) collect result)) ((implies-p formula) (let ((left-result (construct-circuit-representation (implies-left formula))) (right-result (construct-circuit-representation (implies-right formula)))) (cond ((null left-result) right-result) ((null right-result) left-result) (t (list left-result right-result))))) ((not-p formula) (construct-circuit-representation (not-expr formula))) ((if-p formula) (let ((left-result (cond ((and-p (if-left formula)) (construct-circuit-representation (list* 'and (if-test formula) (cdr (if-left formula))))) (t (construct-circuit-representation (make-and (if-test formula) (if-left formula)))))) (right-result (cond ((and-p (if-right formula)) (construct-circuit-representation (list* 'and (if-test formula) (cdr (if-right formula))))) (t (construct-circuit-representation (make-and (if-test formula) (if-right formula))))))) (cond ((null left-result) right-result) ((null right-result) left-result) (t (list left-result right-result))))) ((not (or (true-p formula) (false-p formula))) (bdd-integrate-atomic formula)))) ;;; The initial order here is essentially Minato's DWA. (defun construct-initial-order (formula) (setq *initial-order* nil) (let ((circuit (construct-circuit-representation formula))) (setq *number-of-atoms* (length *atom-list*)) (setq *atom-array* (make-array *number-of-atoms* :initial-contents (reverse *atom-list*))) (setq *var-scores* (make-array *number-of-atoms* :initial-element 0)) (loop while (not (null circuit)) do (progn (compute-input-scores circuit) (let ((champ 0) (champ-score (aref *var-scores* 0))) (loop for i from 1 to (- *number-of-atoms* 1) when (> (aref *var-scores* i) champ-score) do (setq champ-score (aref *var-scores* (setq champ i)))) (push (aref *atom-array* champ) *initial-order*) (setq circuit (remove-from-circuit (+ champ 2) circuit)) (loop for i from 0 to (- *number-of-atoms* 1) do (setf (aref *var-scores* i) 0))))) (let ((result (reverse *initial-order*))) (setq *initial-order* nil) (setq *atom-list* nil) (setq *atom-array* (vector)) (setq *var-scores* (vector)) result))) (defvar *input-order* nil) (defun construct-input-order (formula) (let ((*input-order* nil)) (construct-input-order-aux formula) (reverse *input-order*))) (defun construct-input-order-aux (formula) (cond ((or (and-p formula) (or-p formula)) (loop for arg in (cdr formula) do (construct-input-order-aux arg))) ((implies-p formula) (construct-input-order-aux (implies-left formula)) (construct-input-order-aux (implies-right formula))) ((not-p formula) (construct-input-order-aux (not-expr formula))) ((if-p formula) (construct-input-order-aux (if-test formula)) (construct-input-order-aux (if-left formula)) (construct-input-order-aux (if-right formula))) ((not (or (true-p formula) (false-p formula) (member-equal formula *input-order*))) (push formula *input-order*)))) ;;; ============== Integrating formulas into the BDD =============== (defun set-expression (formula) (bdd-integrate-atoms formula) (setq *number-of-atoms* (length *atom-list*)) (setq *atom-array* (make-array *number-of-atoms* :initial-contents (reverse *atom-list*))) (setq *next-id* (+ *number-of-atoms* 2)) ;; By now, all atoms have been integrated. (bdd-integrate-formula formula)) (defun set-expression-with-reorder (formula) (let ((initial-bdd-index (push-bdd-entry (set-expression formula)))) (bdd-clear-and-recache) (let ((list-of-literals nil) (initial-bdd (bdd-entry initial-bdd-index))) (pop-bdd-entry) (dolist (var (bdd-choose-order initial-bdd)) (push (aref *atom-array* (- var 2)) list-of-literals)) (reset-bdd) (dolist (l list-of-literals) (bdd-integrate-atomic l)) (set-expression formula)))) ;;; We assume that all atoms have been integrated when this is called. (defun bdd-integrate-formula (formula) (cond ((true-p formula) *bdd-one*) ((false-p formula) *bdd-zero*) ((if-p formula) (let ((test-index (push-bdd-entry (bdd-integrate-formula (if-test formula)))) (left-index (push-bdd-entry (bdd-integrate-formula (if-left formula)))) (right-index (push-bdd-entry (bdd-integrate-formula (if-right formula))))) (let ((first-index (push-bdd-entry (bdd-negate (andop (bdd-entry test-index) (bdd-entry left-index))))) (second-result (bdd-negate (andop (bdd-negate (bdd-entry test-index)) (bdd-entry right-index))))) (let ((first-result (bdd-entry first-index))) (dotimes (i 4) (pop-bdd-entry)) (bdd-negate (andop first-result second-result)))))) ((not-p formula) (bdd-negate (bdd-integrate-formula (second formula)))) ((and-p formula) (let ((first-index (push-bdd-entry (bdd-integrate-formula (second formula)))) (second-result (bdd-integrate-formula (third formula)))) (let ((first-result (bdd-entry first-index))) (pop-bdd-entry) (andop first-result second-result)))) ((or-p formula) (let ((first-index (push-bdd-entry (bdd-integrate-formula (second formula)))) (second-result (bdd-integrate-formula (third formula)))) (let ((first-result (bdd-entry first-index))) (pop-bdd-entry) (orop first-result second-result)))) ((implies-p formula) (let ((first-index (push-bdd-entry (bdd-integrate-formula (second formula)))) (second-result (bdd-integrate-formula (third formula)))) (let ((first-result (bdd-entry first-index))) (pop-bdd-entry) (bdd-negate (andop first-result (bdd-negate second-result)))))) (t ;; Atoms have been integrated, so bdd-integrate-atomic will ;; not have any side effects. (bdd-make-if (bdd-integrate-atomic formula) *bdd-one* *bdd-zero*)))) (defun bdd-integrate-atomic (formula) (let ((tail (member-equal formula *atom-list*))) (cond (tail (+ (length tail) 1)) (t (push formula *atom-list*) (+ (length *atom-list*) 1))))) (defun bool-connective-p (formula) (or (and-p formula) (or-p formula) (implies-p formula))) (defun bdd-integrate-atoms (formula) (cond ((or (true-p formula) (false-p formula)) nil) ((if-p formula) (bdd-integrate-atoms (if-test formula)) (bdd-integrate-atoms (if-left formula)) (bdd-integrate-atoms (if-right formula))) ((not-p formula) (bdd-integrate-atoms (second formula))) ((bool-connective-p formula) (bdd-integrate-atoms (second formula)) (bdd-integrate-atoms (third formula))) (t (bdd-integrate-atomic formula)))) ;;; Some more BDD operations (defun bdd-subfunction0 (var formula) (cond ((or (eq formula *bdd-zero*) (eq formula *bdd-one*)) formula) ((bdd-negated-p formula) (bdd-negate (bdd-subfunction0 var (second formula)))) (t (or (lookup-memo-for-sub0 var formula) (let* ((formula-index (push-bdd-entry formula)) (result (cond ((= (if-test formula) var) (if-right formula)) ((< (if-test formula) var) (bdd-make-if (if-test formula) (bdd-subfunction0 var (if-left formula)) (bdd-subfunction0 var (if-right (bdd-entry formula-index))))) (t formula)))) (memoize-sub0 var (bdd-entry formula-index) result) (pop-bdd-entry) result))))) (defun bdd-subfunction1 (var formula) (cond ((or (eq formula *bdd-zero*) (eq formula *bdd-one*)) formula) ((bdd-negated-p formula) (bdd-negate (bdd-subfunction1 var (second formula)))) (t (or (lookup-memo-for-sub1 var formula) (let* ((formula-index (push-bdd-entry formula)) (result (cond ((= (if-test formula) var) (if-left formula)) ((< (if-test formula) var) (bdd-make-if (if-test formula) (bdd-subfunction1 var (if-left formula)) (bdd-subfunction1 var (if-right (bdd-entry formula-index))))) (t formula)))) (memoize-sub1 var (bdd-entry formula-index) result) (pop-bdd-entry) result))))) (defsubst bdd-var (formula) (cond ((or (eq formula *bdd-zero*) (eq formula *bdd-one*)) 1000000) ((bdd-negated-p formula) (if-test (second formula))) (t (if-test formula)))) (defun bdd-compute-subfunctions (var set-indices) (let ((result-indices nil)) (dolist (s-index set-indices) (let ((sub0 (bdd-unnegated (bdd-subfunction0 var (bdd-entry s-index))))) (unless (loop for r-index in result-indices when (eq sub0 (bdd-entry r-index)) return t) (push (push-bdd-entry sub0) result-indices))) (let ((sub1 (bdd-unnegated (bdd-subfunction1 var (bdd-entry s-index))))) (unless (loop for r-index in result-indices when (eq sub1 (bdd-entry r-index)) return t) (push (push-bdd-entry sub1) result-indices)))) (let ((result (loop for r-index in result-indices collect (bdd-entry r-index)))) (dotimes (i (length result-indices)) (pop-bdd-entry)) result))) (defun bdd-choose-order-aux (set-indices result) (let ((minvar (bdd-var (bdd-entry (car set-indices))))) (dolist (s-index set-indices) (when (< (bdd-var (bdd-entry s-index)) minvar) (setq minvar (bdd-var (bdd-entry s-index))))) (cond ((> minvar *number-of-atoms*) (dotimes (i (length set-indices)) (pop-bdd-entry)) result) (t (let ((champ-indices (loop for c in (bdd-compute-subfunctions minvar set-indices) collect (push-bdd-entry c))) (champvar minvar)) (loop for var from 2 to (+ *number-of-atoms* 1) do (unless (or (eq var champvar) (member-eq var result)) (let ((chal (bdd-compute-subfunctions var set-indices))) (when (< (length chal) (length champ-indices)) (dotimes (i (length champ-indices)) (pop-bdd-entry)) (setq champ-indices (loop for c in chal collect (push-bdd-entry c))) (setq champvar var))))) (let ((champ (loop for c-index in champ-indices collect (bdd-entry c-index)))) (dotimes (i (length champ)) (pop-bdd-entry)) (dotimes (i (length set-indices)) (pop-bdd-entry)) (setq champ-indices (loop for c in champ collect (push-bdd-entry c))) (bdd-choose-order-aux champ-indices (cons champvar result)))))))) (defun bdd-choose-order (formula) (unless (or (eq formula *bdd-zero*) (eq formula *bdd-one*)) (let* ((var (bdd-var formula)) (formula-index (push-bdd-entry formula)) (subfunctions (bdd-compute-subfunctions var (list formula-index)))) (pop-bdd-entry) (let ((subfunction-indices (loop for s in subfunctions collect (push-bdd-entry s)))) (bdd-choose-order-aux subfunction-indices (list var)))))) ;;; ================= ZBDD ================== (defconstant zbdd-hash-table-size 65536) (defconstant zbdd-hash-table-mask (1- zbdd-hash-table-size)) (defvar *zbdd-next-id* 0) (defvar *zbdd-hash-table* (make-array zbdd-hash-table-size :initial-element nil)) (defun zbdd-make-if (test left right) (cond ((equal left 0) right) (t (let ((test-id (bdd-id test)) (left-id (bdd-id left)) (right-id (bdd-id right))) (let ((index (fixnum-op logand (fixnum-op + (fixnum-op * test-id hash-multiplier) (fixnum-op + (fixnum-op * left-id second-hash-multiplier) right-id)) zbdd-hash-table-mask))) (or (loop for x in (unsafe-aref *zbdd-hash-table* index) when (let ((u (car x))) (and (fixnum-rel = (first u) test-id) (fixnum-rel = (second u) left-id) (fixnum-rel = (third u) right-id))) return (cdr x)) (let ((result (list *zbdd-next-id* test left right))) (setq *zbdd-next-id* (fixnum-op + *zbdd-next-id* 1)) (setf (unsafe-aref *zbdd-hash-table* index) (cons (cons (list test-id left-id right-id) result) (unsafe-aref *zbdd-hash-table* index))) result))))))) ;;; Returns subset of formula such that var = 1 (defun zbdd-subset1 (formula var) (cond ((< var (bdd-top formula)) 0) ((= var (bdd-top formula)) (if-left formula)) (t (zbdd-make-if (if-test formula) (zbdd-subset1 (if-left formula) var) (zbdd-subset1 (if-right formula) var))))) ;;; Returns subset of formula such that var = 0 (defun zbdd-subset0 (formula var) (cond ((< var (bdd-top formula)) formula) ((= var (bdd-top formula)) (if-right formula)) (t (zbdd-make-if (if-test formula) (zbdd-subset0 (if-left formula) var) (zbdd-subset0 (if-right formula) var))))) ;;; Returns formula with var inverted (defun zbdd-change (formula var) (cond ((or (atom formula) (< var (bdd-top formula))) (zbdd-make-if var formula 0)) ((= var (bdd-top formula)) (zbdd-make-if var (if-right formula) (if-left formula))) (t (zbdd-make-if (if-test formula) (zbdd-change (if-left formula) var) (zbdd-change (if-right formula) var))))) ;;; Union (defun zbdd-union (formula1 formula2) (cond ((equal formula1 0) formula2) ((equal formula2 0) formula1) ((equal formula1 formula2) formula1) ((< (bdd-top formula1) (bdd-top formula2)) (zbdd-make-if (if-test formula1) (if-left formula1) (zbdd-union (if-right formula1) formula2))) ((= (bdd-top formula1) (bdd-top formula2)) (zbdd-make-if (if-test formula1) (zbdd-union (if-left formula1) (if-left formula2)) (zbdd-union (if-right formula1) (if-right formula2)))) (t (zbdd-make-if (if-test formula2) (if-left formula2) (zbdd-union formula1 (if-right formula2)))))) ;;; Intersection (defun zbdd-inter (formula1 formula2) (cond ((equal formula1 0) 0) ((equal formula2 0) 0) ((equal formula1 formula2) formula1) ((< (bdd-top formula1) (bdd-top formula2)) (zbdd-inter (if-right formula1) formula2)) ((= (bdd-top formula1) (bdd-top formula2)) (zbdd-make-if (if-test formula1) (zbdd-inter (if-left formula1) (if-left formula2)) (zbdd-inter (if-right formula1) (if-right formula2)))) (t (zbdd-inter formula1 (if-right formula2))))) ;;; Difference (defun zbdd-diff (formula1 formula2) (cond ((equal formula1 0) 0) ((equal formula2 0) formula1) ((equal formula1 formula2) 0) ((< (bdd-top formula1) (bdd-top formula2)) (zbdd-make-if (if-test formula1) (if-left formula1) (zbdd-diff (if-right formula1) formula2))) ((= (bdd-top formula1) (bdd-top formula2)) (zbdd-make-if (if-test formula1) (zbdd-diff (if-left formula1) (if-left formula2)) (zbdd-diff (if-right formula1) (if-right formula2)))) (t (zbdd-diff formula1 (if-right formula2))))) (defun reset-zbdd () (setq *zbdd-next-id* 0) (dotimes (i zbdd-hash-table-size) (setf (aref *zbdd-hash-table* i) nil))) (defsubst zbdd-atom (atom) (- (* 2 atom) 2)) (defun zbdd-complement-atom (atom) (- (* 2 atom) 1)) (defun zbdd-complemented-p (atom) (= (mod atom 2) 1)) (defun zbdd-print-atom (atom) (let ((atomic-formula (aref *atom-array* (floor (- atom 2) 2)))) (if (zbdd-complemented-p atom) (make-not atomic-formula) atomic-formula))) ;;; ================ New ISOP using ZBDDs =================== ;;; Uses Minato-Morreale algorithm. (defvar *isop-hash-table* (make-array zbdd-hash-table-size :initial-element nil)) (defun reset-new-isop () (setq *zbdd-next-id* 0) (dotimes (i zbdd-hash-table-size) (setf (aref *zbdd-hash-table* i) nil) (setf (aref *isop-hash-table* i) nil))) (defun setup-new-isop () (setq *zbdd-next-id* (+ (* 2 *number-of-atoms*) 2))) (defun memoize-isop (floor-id ceiling-id result) (let ((index (fixnum-op logand (fixnum-op + (fixnum-op * hash-multiplier floor-id) ceiling-id) zbdd-hash-table-mask))) (setf (unsafe-aref *isop-hash-table* index) (cons (cons (cons floor-id ceiling-id) result) (unsafe-aref *isop-hash-table* index))))) (defun lookup-memo-for-isop (floor ceiling) (let ((floor-id (bdd-id floor)) (ceiling-id (bdd-id ceiling))) (loop for x in (unsafe-aref *isop-hash-table* (fixnum-op logand (fixnum-op + (fixnum-op * hash-multiplier floor-id) ceiling-id) zbdd-hash-table-mask)) when (and (fixnum-rel = floor-id (caar x)) (fixnum-rel = ceiling-id (cdar x))) return (cdr x)))) (defun new-isop (flr ceil) (cond ((eq flr *bdd-zero*) (list *bdd-zero* 0)) ((eq ceil *bdd-one*) (list *bdd-one* 1)) (t (or (lookup-memo-for-isop flr ceil) (let ((flr-expr (if (bdd-negated-p flr) (second flr) flr)) (neg-flr (if (bdd-negated-p flr) t nil)) (ceil-expr (if (bdd-negated-p ceil) (second ceil) ceil)) (neg-ceil (if (bdd-negated-p ceil) t nil)) (flr-index (push-bdd-entry flr)) (ceil-index (push-bdd-entry ceil))) (let ((result (cond ((= (if-test flr-expr) (if-test ceil-expr)) (new-isop-aux (if-test flr-expr) (if neg-flr (bdd-negate (if-left flr-expr)) (if-left flr-expr)) (if neg-ceil (bdd-negate (if-left ceil-expr)) (if-left ceil-expr)) (if neg-flr (bdd-negate (if-right flr-expr)) (if-right flr-expr)) (if neg-ceil (bdd-negate (if-right ceil-expr)) (if-right ceil-expr)))) ((< (if-test flr-expr) (if-test ceil-expr)) (new-isop-aux (if-test flr-expr) (if neg-flr (bdd-negate (if-left flr-expr)) (if-left flr-expr)) ceil (if neg-flr (bdd-negate (if-right flr-expr)) (if-right flr-expr)) ceil)) (t (new-isop-aux (if-test ceil-expr) flr (if neg-ceil (bdd-negate (if-left ceil-expr)) (if-left ceil-expr)) flr (if neg-ceil (bdd-negate (if-right ceil-expr)) (if-right ceil-expr))))))) (memoize-isop (bdd-id (bdd-entry flr-index)) (bdd-id (bdd-entry ceil-index)) result) (pop-bdd-entry) (pop-bdd-entry) result)))))) (defun new-isop-aux (test left-floor left-ceiling right-floor right-ceiling) (let ((left-floor-index (push-bdd-entry left-floor)) (left-ceiling-index (push-bdd-entry left-ceiling)) (right-floor-index (push-bdd-entry right-floor)) (right-ceiling-index (push-bdd-entry right-ceiling)) (first-index (push-bdd-entry (andop left-floor (bdd-negate right-ceiling))))) (let ((second-index (push-bdd-entry (andop (bdd-entry right-floor-index) (bdd-negate (bdd-entry left-ceiling-index)))))) (let* ((left (new-isop (bdd-entry first-index) (bdd-entry left-ceiling-index))) (left-index (push-bdd-entry (first left))) (right (new-isop (bdd-entry second-index) (bdd-entry right-ceiling-index))) (right-index (push-bdd-entry (first right)))) (let ((leftdpflr-index (push-bdd-entry (andop (bdd-entry left-floor-index) (bdd-negate (bdd-entry left-index))))) (rightdpflr (andop (bdd-entry right-floor-index) (bdd-negate (bdd-entry right-index))))) (let ((leftdpflr (bdd-entry leftdpflr-index))) (pop-bdd-entry) (let ((floor-index (push-bdd-entry (orop (andop leftdpflr (bdd-entry right-ceiling-index)) (andop rightdpflr (bdd-entry left-ceiling-index))))) (ceiling-index (push-bdd-entry (andop (bdd-entry left-ceiling-index) (bdd-entry right-ceiling-index))))) (let* ((dontcare (new-isop (bdd-entry floor-index) (bdd-entry ceiling-index))) (dontcare-index (push-bdd-entry (first dontcare))) (res1-index (push-bdd-entry (andop (bdd-make-if test *bdd-one* *bdd-zero*) (bdd-entry left-index)))) (res2 (andop (bdd-make-if test *bdd-zero* *bdd-one*) (bdd-entry right-index))) (result-bdd (orop (orop (bdd-entry res1-index) res2) (bdd-entry dontcare-index)))) (dotimes (i 12) (pop-bdd-entry)) (list result-bdd (zbdd-union (zbdd-union (zbdd-change (second left) (zbdd-atom test)) (zbdd-change (second right) (zbdd-complement-atom test))) (second dontcare))))))))))) (defun new-ipos (flr ceil) (cond ((equal ceil *bdd-one*) (list *bdd-one* 0)) ((equal flr *bdd-zero*) (list *bdd-zero* 1)) (t (or (lookup-memo-for-isop flr ceil) (let ((flr-expr (if (bdd-negated-p flr) (second flr) flr)) (neg-flr (if (bdd-negated-p flr) t nil)) (ceil-expr (if (bdd-negated-p ceil) (second ceil) ceil)) (neg-ceil (if (bdd-negated-p ceil) t nil)) (flr-index (push-bdd-entry flr)) (ceil-index (push-bdd-entry ceil))) (let ((result (cond ((= (if-test flr-expr) (if-test ceil-expr)) (new-ipos-aux (if-test flr-expr) (if neg-flr (bdd-negate (if-left flr-expr)) (if-left flr-expr)) (if neg-ceil (bdd-negate (if-left ceil-expr)) (if-left ceil-expr)) (if neg-flr (bdd-negate (if-right flr-expr)) (if-right flr-expr)) (if neg-ceil (bdd-negate (if-right ceil-expr)) (if-right ceil-expr)))) ((< (if-test flr-expr) (if-test ceil-expr)) (new-ipos-aux (if-test flr-expr) (if neg-flr (bdd-negate (if-left flr-expr)) (if-left flr-expr)) ceil (if neg-flr (bdd-negate (if-right flr-expr)) (if-right flr-expr)) ceil)) (t (new-ipos-aux (if-test ceil-expr) flr (if neg-ceil (bdd-negate (if-left ceil-expr)) (if-left ceil-expr)) flr (if neg-ceil (bdd-negate (if-right ceil-expr)) (if-right ceil-expr))))))) (memoize-isop (bdd-id (bdd-entry flr-index)) (bdd-id (bdd-entry ceil-index)) result) (pop-bdd-entry) (pop-bdd-entry) result)))))) (defun new-ipos-aux (test left-floor left-ceiling right-floor right-ceiling) (let ((left-floor-index (push-bdd-entry left-floor)) (left-ceiling-index (push-bdd-entry left-ceiling)) (right-floor-index (push-bdd-entry right-floor)) (right-ceiling-index (push-bdd-entry right-ceiling)) (first-index (push-bdd-entry (orop left-ceiling (bdd-negate right-floor))))) (let ((second-index (push-bdd-entry (orop (bdd-entry right-ceiling-index) (bdd-negate (bdd-entry left-floor-index)))))) (let* ((left (new-ipos (bdd-entry left-floor-index) (bdd-entry first-index))) (left-index (push-bdd-entry (first left))) (right (new-ipos (bdd-entry right-floor-index) (bdd-entry second-index))) (right-index (push-bdd-entry (first right)))) (let ((leftdpceil-index (push-bdd-entry (orop (bdd-entry left-ceiling-index) (bdd-negate (bdd-entry left-index))))) (rightdpceil (orop (bdd-entry right-ceiling-index) (bdd-negate (bdd-entry right-index))))) (let ((leftdpceil (bdd-entry leftdpceil-index))) (pop-bdd-entry) (let ((floor-index (push-bdd-entry (orop (bdd-entry left-floor-index) (bdd-entry right-floor-index)))) (ceiling-index (push-bdd-entry (andop (orop leftdpceil (bdd-entry right-floor-index)) (orop rightdpceil (bdd-entry left-floor-index)))))) (let* ((dontcare (new-ipos (bdd-entry floor-index) (bdd-entry ceiling-index))) (dontcare-index (push-bdd-entry (first dontcare))) (res1-index (push-bdd-entry (orop (bdd-make-if test *bdd-one* *bdd-zero*) (bdd-entry right-index)))) (res2 (orop (bdd-make-if test *bdd-zero* *bdd-one*) (bdd-entry left-index))) (result-bdd (andop (andop (bdd-entry res1-index) res2) (bdd-entry dontcare-index)))) (dotimes (i 12) (pop-bdd-entry)) (list result-bdd (zbdd-union (zbdd-change (second right) (zbdd-atom test)) (zbdd-union (zbdd-change (second left) (zbdd-complement-atom test)) (second dontcare)))))))))))) (defvar *zbdd-cube-set* nil) (defun zbdd-to-cube-set (zbdd) (setq *zbdd-cube-set* nil) (zbdd-to-cube-set-aux zbdd nil) *zbdd-cube-set*) (defun zbdd-to-cube-set-aux (zbdd path) (cond ((equal zbdd 1) (push path *zbdd-cube-set*)) ((equal zbdd 0)) (t (zbdd-to-cube-set-aux (if-left zbdd) (cons (if-test zbdd) path)) (zbdd-to-cube-set-aux (if-right zbdd) path)))) (defun prop-weight (formula order) (cond ((not-p formula) (length (member-equal (not-expr formula) order))) (t (length (member-equal formula order))))) (defun insert-into-collection (pair collection) (cond ((or (null collection) (> (car pair) (caar collection))) (cons pair collection)) (t (cons (car collection) (insert-into-collection pair (cdr collection)))))) (defun prop-rearrange (formula order) (cond ((and-p formula) (let ((collected nil)) (loop for expr in (cdr formula) do (let ((r (prop-rearrange expr order))) (setq collected (insert-into-collection (cons (prop-weight r order) r) collected)))) (cons 'and (loop for r in collected collect (cdr r))))) ((or-p formula) (let ((collected nil)) (loop for expr in (cdr formula) do (let ((r (prop-rearrange expr order))) (setq collected (insert-into-collection (cons (prop-weight r order) r) collected)))) (cons 'or (loop for r in collected collect (cdr r))))) ((not-p formula) (make-not (prop-rearrange (not-expr formula) order))) ((implies-p formula) (make-implies (prop-rearrange (implies-left formula) order) (prop-rearrange (implies-right formula) order))) ((if-p formula) (make-if (prop-rearrange (if-test formula) order) (prop-rearrange (if-left formula) order) (prop-rearrange (if-right formula) order))) (t formula))) ;;; ============ Top level functions for DNF and CNF =============== (defun dnf (formula) (let* ((initial-order (construct-initial-order formula)) (input-order (construct-input-order formula)) (rearranged (prop-rearrange formula initial-order))) (loop for atom in initial-order do (bdd-integrate-atomic atom)) (let ((internal-formula (set-expression (without-proof-logging (expand-proposition rearranged nil))))) (let ((internal-formula-index (push-bdd-entry internal-formula))) (bdd-clear-and-recache) (setq internal-formula (bdd-entry internal-formula-index)) (pop-bdd-entry) (setup-new-isop) (let* ((result (new-isop internal-formula internal-formula)) (cube-set (zbdd-to-cube-set (second result))) (result-formula (cond ((null cube-set) *false*) ((= (length cube-set) 1) (dnf-aux (first cube-set))) (t (let ((result nil)) (loop for disjunct in cube-set do (push (dnf-aux disjunct) result)) (cons 'or result)))))) (reset-new-isop) (reset-bdd) (prop-rearrange result-formula input-order)))))) (defun dnf-aux (result) (cond ((null result) *true*) ((= (length result) 1) (zbdd-print-atom (first result))) (t (let ((res nil)) (loop for conjunct in result do (push (zbdd-print-atom conjunct) res)) (cons 'and res))))) (defun cnf (formula) (let* ((initial-order (construct-initial-order formula)) (input-order (construct-input-order formula)) (rearranged (prop-rearrange formula initial-order))) (loop for atom in initial-order do (bdd-integrate-atomic atom)) (let ((internal-formula (set-expression (without-proof-logging (expand-proposition rearranged nil))))) (let ((internal-formula-index (push-bdd-entry internal-formula))) (bdd-clear-and-recache) (setq internal-formula (bdd-entry internal-formula-index)) (pop-bdd-entry) (setup-new-isop) (let* ((result (new-ipos internal-formula internal-formula)) (cube-set (zbdd-to-cube-set (second result))) (result-formula (cond ((null cube-set) *true*) ((= (length cube-set) 1) (cnf-aux (first cube-set))) (t (let ((result nil)) (loop for disjunct in cube-set do (push (cnf-aux disjunct) result)) (cons 'and result)))))) (reset-new-isop) (reset-bdd) (prop-rearrange result-formula input-order)))))) (defun cnf-aux (result) (cond ((null result) *false*) ((= (length result) 1) (zbdd-print-atom (first result))) (t (let ((res nil)) (loop for disjunct in result do (push (zbdd-print-atom disjunct) res)) (cons 'or res)))))
[ { "context": "; DEALINGS IN THE SOFTWARE.\n;\n; Original author: Sol Swords <[email protected]>\n\n(in-package \"SV\")\n(includ", "end": 1419, "score": 0.9998676180839539, "start": 1409, "tag": "NAME", "value": "Sol Swords" }, { "context": "IN THE SOFTWARE.\n;\n; Original author: Sol Swords <[email protected]>\n\n(in-package \"SV\")\n(include-book \"eval\")\n(includ", "end": 1441, "score": 0.9999316334724426, "start": 1421, "tag": "EMAIL", "value": "[email protected]" } ]
books/centaur/sv/svex/symbolic.lisp
mayankmanj/acl2
305
; SV - Symbolic Vector Hardware Analysis Framework ; Copyright (C) 2014-2015 Centaur Technology ; ; Contact: ; Centaur Technology Formal Verification Group ; 7600-C N. Capital of Texas Highway, Suite 300, Austin, TX 78731, USA. ; http://www.centtech.com/ ; ; License: (An MIT/X11-style license) ; ; Permission is hereby granted, free of charge, to any person obtaining a ; copy of this software and associated documentation files (the "Software"), ; to deal in the Software without restriction, including without limitation ; the rights to use, copy, modify, merge, publish, distribute, sublicense, ; and/or sell copies of the Software, and to permit persons to whom the ; Software is furnished to do so, subject to the following conditions: ; ; The above copyright notice and this permission notice shall be included in ; all copies or substantial portions of the Software. ; ; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR ; IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, ; FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE ; AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER ; LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING ; FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER ; DEALINGS IN THE SOFTWARE. ; ; Original author: Sol Swords <[email protected]> (in-package "SV") (include-book "eval") (include-book "a4vec-ops") (include-book "rewrite") (include-book "lists") (include-book "env-ops") (include-book "centaur/gl/gl-mbe" :dir :system) (include-book "centaur/gl/def-gl-rewrite" :dir :system) (local (include-book "arithmetic/top-with-meta" :dir :system)) (local (include-book "centaur/bitops/ihsext-basics" :dir :system)) (local (include-book "std/alists/alist-keys" :dir :System)) (local (include-book "centaur/bitops/equal-by-logbitp" :dir :system)) (local (include-book "clause-processors/just-expand" :dir :system)) (local (std::add-default-post-define-hook :fix)) (local (std::deflist svarlist-p (x) (svar-p x) :true-listp t :elementp-of-nil nil)) (local (defthm true-listp-nthcdr (implies (true-listp x) (true-listp (nthcdr n x))) :hints(("Goal" :in-theory (e/d (nthcdr) (acl2::cdr-nthcdr)) :induct (nthcdr n x))) :rule-classes :type-prescription)) (local (defthm nthcdr-of-append-equal-len (implies (equal (nfix n) (len x)) (equal (nthcdr n (append x y)) y)) :hints(("Goal" :in-theory (e/d (nthcdr) (acl2::cdr-nthcdr)) :induct (nthcdr n x))))) (local (defthm take-of-append-equal-len (implies (equal (nfix n) (len x)) (equal (take n (append x y)) (list-fix x))) :hints(("Goal" :in-theory (e/d (acl2::take)) :induct (nthcdr n x))))) (local (in-theory (disable double-containment))) (local (defthm 3vec-p-of-4vec-mask (implies (3vec-p x) (3vec-p (4vec-mask mask x))) :hints(("Goal" :in-theory (enable 4vec-mask 3vec-p)) (acl2::logbitp-reasoning)))) (local (defthm true-listp-of-scdr (implies (true-listp x) (true-listp (gl::scdr x))) :hints(("Goal" :in-theory (enable gl::scdr))) :rule-classes :type-prescription)) (local (in-theory (disable gl::s-endp-of-bfr-scons aig-list->s))) (local (defthm aig-list->s-open-quote (implies (syntaxp (quotep x)) (equal (aig-list->s x env) (B* (((MV FIRST REST GL::END) (GL::FIRST/REST/END X))) (IF GL::END (GL::BOOL->SIGN (AIG-EVAL FIRST ENV)) (BITOPS::LOGCONS (BOOL->BIT (AIG-EVAL FIRST ENV)) (AIG-LIST->S REST ENV)))))) :hints(("Goal" :in-theory (enable aig-list->s))))) (local (defthm aig-list->s-of-bfr-snorm (equal (aig-list->s (gl::bfr-snorm x) env) (aig-list->s x env)) :hints(("Goal" :in-theory (enable aig-list->s gl::bfr-snorm))))) (local (defthm aig-list->s-of-bfr-scons (equal (aig-list->s (gl::bfr-scons a b) env) (bitops::logcons (bool->bit (aig-eval a env)) (aig-list->s b env))) :hints(("Goal" :expand ((aig-list->s (gl::bfr-scons a b) env) (aig-list->s b env)) :in-theory (enable gl::s-endp-of-bfr-scons) :do-not-induct t)))) (defxdoc bit-blasting :parents (expressions) :short "We implement an efficient translation from @(see svex) expressions into @(see acl2::aig)s, to support symbolic simulation with @(see acl2::gl).") (local (xdoc::set-default-parents bit-blasting)) (defalist svex-a4vec-env :key-type svar :val-type a4vec) (define svex-a4vec-env-eval ((x svex-a4vec-env-p) env) :returns (xx svex-env-p) :measure (len (svex-a4vec-env-fix x)) (b* ((x (svex-a4vec-env-fix x))) (if (atom x) nil (cons (cons (svar-fix (caar x)) (a4vec-eval (cdar x) env)) (svex-a4vec-env-eval (cdr x) env)))) /// (defret alist-keys-of-svex-a4vec-env-eval (equal (alist-keys xx) (alist-keys (svex-a4vec-env-fix x))) :hints(("Goal" :in-theory (enable svex-a4vec-env-fix alist-keys))))) (define a4veclist-nth ((n natp) (x a4veclist-p)) :returns (elt a4vec-p) :guard-hints (("goal" :in-theory (enable nth a4veclist-p))) (mbe :logic (if (< (nfix n) (len x)) (a4vec-fix (nth n x)) (a4vec-x)) :exec (or (nth n x) (a4vec-x))) /// (defthm a4veclist-nth-out-of-bounds (implies (<= (len x) (nfix n)) (equal (a4veclist-nth n x) (a4vec-x)))) (defthm a4veclist-nth-in-of-bounds (implies (< (nfix n) (len x)) (equal (a4veclist-nth n x) (a4vec-fix (nth n x)))))) (define svexlist-nth ((n natp) (x svexlist-p)) :returns (elt svex-p) :guard-hints (("goal" :in-theory (enable nth svexlist-p))) (mbe :logic (if (< (nfix n) (len x)) (svex-fix (nth n x)) (svex-x)) :exec (or (nth n x) (svex-x))) /// (defthm svexlist-nth-out-of-bounds (implies (<= (len x) (nfix n)) (equal (svexlist-nth n x) (svex-x)))) (defthm svexlist-nth-in-of-bounds (implies (< (nfix n) (len x)) (equal (svexlist-nth n x) (svex-fix (nth n x)))))) (local (defthm nth-of-svexlist-eval (equal (nth n (svexlist-eval x env)) (and (< (nfix n) (len x)) (svex-eval (nth n x) env))) :hints(("Goal" :in-theory (enable nth svexlist-eval) :induct (nth n x))))) (local (defthm nth-of-a4veclist-eval (equal (nth n (a4veclist-eval x env)) (and (< (nfix n) (len x)) (a4vec-eval (nth n x) env))) :hints(("Goal" :in-theory (enable nth a4veclist-eval) :induct (nth n x))))) (define maybe-a3vec-fix ((v (a4vec-p v)) (x svex-p)) :returns (vv a4vec-p) (if (3valued-syntaxp (svex-fix x)) (a4vec-fix v) (a3vec-fix v)) /// (local (defthm nth-under-iff-when-a4veclist-p (implies (a4veclist-p x) (iff (nth n x) (< (nfix n) (len x)))) :hints(("Goal" :in-theory (enable a4veclist-p nth))))) (local (defthm nth-out-of-bounds (implies (<= (len x) (nfix n)) (not (nth n x))) :hints(("Goal" :in-theory (enable nth))))) (defthm maybe-a3vec-fix-when-implies (implies (case-split (implies (3valued-syntaxp x) (3vec-p (a4vec-eval v env)))) (equal (a4vec-eval (maybe-a3vec-fix v x) env) (3vec-fix (a4vec-eval v env))))) (defthm maybe-a3vec-fix-of-nths (implies (equal (a4veclist-eval vals env) (svexlist-eval x (svex-a4vec-env-eval a4env env))) (equal (a4vec-eval (maybe-a3vec-fix (nth n vals) (nth n x)) env) (3vec-fix (a4vec-eval (nth n vals) env)))) :hints(("Goal" :in-theory (e/d (a4veclist-nth) (nth-of-svexlist-eval) (nth-of-a4veclist-eval)) :use ((:instance nth-of-svexlist-eval (env (svex-a4vec-env-eval a4env env))) (:instance nth-of-a4veclist-eval))))) (defthm maybe-a3vec-fix-of-a3vec (implies (a4vec-syntactic-3vec-p v) (equal (maybe-a3vec-fix v x) (a4vec-fix v))) :hints(("Goal" :in-theory (enable a3vec-fix))))) ;; (define 4vmask-nth ((n natp) (x 4vmasklist-p)) ;; :returns (mask 4vmask-p :rule-classes (:rewrite :type-prescription)) ;; (b* ((x (4vmasklist-fix x))) ;; (if (< (lnfix n) (len x)) ;; (4vmask-fix (nth n x)) ;; -1))) ;; (define maybe-a4vec-fix ((v (or (a4vec-p v) (not v)))) ;; :returns (vv a4vec-p) ;; (if v (a4vec-fix v) (a4vec-x))) (defconst *svex-aig-op-table* ;; fn name, non-3vec-fixing function, args (with notation for 3vec-fixed ones and masks) '((id a4vec-fix (x) "identity function") (bitsel a4vec-bit-extract (index x) "bit select") (unfloat a4vec-fix ((3v x)) "change Z bits to Xes") (bitnot a3vec-bitnot ((3v x)) "bitwise negation") (onp a4vec-onset (x) "bitwise onset") (offp a4vec-offset (x) "bitwise offset") (bitand a3vec-bitand ((3v x) (3v y)) "bitwise AND") (bitor a3vec-bitor ((3v x) (3v y)) "bitwise OR") (bitxor a3vec-bitxor ((3v x) (3v y)) "bitwise XOR") (res a4vec-res (x y) "resolve (short together)") (resand a4vec-resand (x y) "resolve wired AND") (resor a4vec-resor (x y) "resolve wired OR") (override a4vec-override (x y) "resolve different strengths") (uand a3vec-reduction-and ((3v x)) "unary (reduction) AND") (uor a3vec-reduction-or ((3v x)) "unary (reduction) OR") (uxor a4vec-parity (x) "reduction XOR, i.e. parity") (zerox a4vec-zero-ext (width x (mask m)) "zero extend") (signx a4vec-sign-ext (width x (mask m)) "sign extend") (concat a4vec-concat (width x y (mask m)) "concatenate at a given bit width") (partsel a4vec-part-select (lsb width in (mask m)) "part select") (partinst a4vec-part-install (lsb width in val (mask m)) "part install") (blkrev a4vec-rev-blocks (width blksz x) "reverse block order") (rsh a4vec-rsh (shift x (mask m)) "right shift") (lsh a4vec-lsh (shift x (mask m)) "left shift") (+ a4vec-plus (x y) "addition") (b- a4vec-minus (x y) "subtraction") (u- a4vec-uminus (x) "unary minus") (xdet a4vec-xdet (x) "x detect") (countones a4vec-countones (x) "count of set bits") (onehot a4vec-onehot (x) "one-hot check") (onehot0 a4vec-onehot0 (x) "one-hot check (zero-hot allowed)") (* a4vec-times (x y) "multiplication") (/ a4vec-quotient (x y) "division") (% a4vec-remainder (x y) "modulus") (< a4vec-< (x y) "less than") (clog2 a4vec-clog2 (x) "ceiling of log2") (pow a4vec-pow (x y) "exponentiation") (== a3vec-== ((3v x) (3v y)) "equality") (=== a4vec-=== (x y) "case equality") (===* a4vec-===* (x y) "modified case equality") (==? a4vec-wildeq (x y) "wildcard equality") (safer-==? a4vec-wildeq-safe (x y) "wildcard equality (monotonic version)") (==?? a4vec-symwildeq (x y) "symmetric wildcard equality") (? a3vec-? ((3v test) (3vp then) (3vp else)) "if-then-else") (?* a3vec-?* ((3v test) (3vp then) (3vp else)) "if-then-else") (bit? a3vec-bit? ((3v test) (3vp then) (3vp else)) "bitwise if-then-else") (?! a4vec-?! (test them else) "procedural if-then-else") (bit?! a4vec-bit?! ((3v test) (3vp then) (3vp else)) "bitwise if-then-else"))) #|| (loop for lst in sv::*svex-aig-op-table* do (let ((fn (cadr lst))) (unless (eq fn 'sv::a4vec-fix) (profile-fn fn)))) ||# (defun svex-apply-aig-collect-args (n restargs argsvar svvar maskvar ;; argmasks-var ) (let* ((n (nfix n))) (if (atom restargs) nil (append (if (consp (car restargs)) (case (caar restargs) (3v `((maybe-a3vec-fix ;; (a4vec-mask (4vmask-nth ,n ,argmasks-var) (a4veclist-nth ,n ,argsvar) (svexlist-nth ,n ,svvar)))) (3vp `(;; (a4vec-mask (4vmask-nth ,n ,argmasks-var) (a4veclist-nth ,n ,argsvar) (3valued-syntaxp (svexlist-nth ,n ,svvar)))) (mask `(,maskvar)) (t (prog2$ (er hard? 'svex-apply-aig-collect-args "bad formal expr") `((a4veclist-nth ,n ,argsvar))))) `((a4veclist-nth ,n ,argsvar))) (svex-apply-aig-collect-args (+ 1 n) (cdr restargs) argsvar svvar maskvar ;; argmasks-var ))))) ;; (defun svex-apply-aig-uses-argmasks (args) ;; (if (atom args) ;; nil ;; (or (and (consp (car args)) ;; (or (eq (caar args) '3v) ;; (eq (caar args) '3vp))) ;; (svex-apply-aig-uses-argmasks (cdr args))))) (defun svex-apply-aig-cases-fn (argsvar svvar maskvar optable) (b* (((when (atom optable)) '((otherwise (a4vec-x)))) ((list sym fn args) (car optable)) (acc-args (svex-apply-aig-collect-args 0 args argsvar svvar maskvar ;; 'tmp-argmasks )) (call `(,fn . ,acc-args)) (full ;; (if (svex-apply-aig-uses-argmasks args) ;; `(let ((tmp-argmasks (svex-argmasks ,maskvar ',sym ,svvar))) ;; ,call) call)) (cons `(,sym ,full) (svex-apply-aig-cases-fn argsvar svvar maskvar (cdr optable))))) (defmacro svex-apply-aig-cases (fn args svex mask) `(case ,fn . ,(svex-apply-aig-cases-fn args svex mask *svex-aig-op-table*))) (defthm svex-p-when-nth (implies (and (svexlist-p x) (nth n x)) (svex-p (nth n x))) :hints(("Goal" :in-theory (enable nth svexlist-p)))) (defthm a4vec-p-when-nth (implies (and (a4veclist-p x) (nth n x)) (a4vec-p (nth n x))) :hints(("Goal" :in-theory (enable nth svexlist-p)))) ;; (defthm a4vec-eval-of-maybe-a4vec-fix-nth-out-of-bounds ;; (implies (<= (len x) (nfix n)) ;; (equal (a4vec-eval (maybe-a4vec-fix (nth n x)) env) ;; (4vec-x))) ;; :hints(("Goal" :in-theory (enable maybe-a4vec-fix nth)))) (local (in-theory (disable nth))) (local (defthm 4vec-bit?!-of-3vec-fix (equal (4vec-bit?! (3vec-fix test) then else) (4vec-bit?! test then else)) :hints(("Goal" :in-theory (enable 4vec-bit?! 3vec-fix))))) (define svex-apply-aig ((fn fnsym-p) (args a4veclist-p) (terms svexlist-p) (mask 4vmask-p)) :prepwork ((local (Defthm 4veclist-nth-safe-of-a4veclist-eval (equal (a4vec-eval (a4veclist-nth n x) aigenv) (4veclist-nth-safe n (a4veclist-eval x aigenv))) :hints(("Goal" :in-theory (enable a4veclist-eval a4veclist-nth 4veclist-nth-safe))))) (local (defun ind (n vals x) (if (zp n) (list vals x) (ind (1- n) (cdr vals) (cdr x))))) (local (defthm 3vec-p-when-3valued-syntaxp-nth (implies (and (EQUAL (A4VECLIST-EVAL VALS AIGENV) (SVEXLIST-EVAL X (SVEX-A4VEC-ENV-EVAL A4ENV AIGENV))) (3valued-syntaxp (svexlist-nth n x))) (3vec-p (a4vec-eval (nth n vals) aigenv))) :hints(("Goal" :in-theory (enable a4veclist-eval svexlist-eval svexlist-nth nth) :induct (ind n vals x) :expand ((a4veclist-eval vals aigenv) (:free (env) (svexlist-eval x env)))) (and stable-under-simplificationp '(:use ((:instance 3vec-p-of-eval-when-3valued-syntaxp (x (car x)) (env (svex-a4vec-env-eval a4env aigenv))))))))) (local (encapsulate nil (local (defun ind2 (n masks vals x) (if (zp n) (list masks vals x) (ind2 (1- n) (cdr masks) (cdr vals) (cdr x))))) ;; BOZO do we need this? ;; (defthm 4vmask-of-nths ;; (implies (equal (len masks) (len vecs)) ;; (equal (4vec-mask (4vmask-nth n masks) ;; (4veclist-nth-safe n vecs)) ;; (4veclist-nth-safe n (4veclist-mask masks vecs)))) ;; :hints(("Goal" :in-theory (enable 4vmask-nth 4veclist-nth-safe 4veclist-mask nth ;; 4vmasklist-fix) ;; :induct (ind2 n masks vecs nil)))) (defthm svex-eval-of-nth-rev (equal (svex-eval (nth n x) env) (4veclist-nth-safe n (svexlist-eval x env)))) (in-theory (disable svex-eval-of-nth 4veclist-nth-safe-of-svexlist-eval)) (local (defthm 3vec-p-of-eval-by-equal (implies (and (equal x (svex-eval y env)) (3valued-syntaxp y)) (3vec-p x)))) (local (defthm 3vec-p-of-eval-by-equal-with-mask (implies (and (equal x (4vec-mask mask (svex-eval y env))) (3valued-syntaxp y)) (3vec-p x)))) (defthm 4veclist-masked-idempotent (implies (equal x (4veclist-mask masks y)) (equal (4veclist-mask masks x) x))) (defthm dumb (implies (and (EQUAL (A4VECLIST-EVAL VALS AIGENV) (4VECLIST-MASK masks (SVEXLIST-EVAL X (SVEX-A4VEC-ENV-EVAL A4ENV AIGENV)))) (3valued-syntaxp (svexlist-nth n x))) (3vec-p (4veclist-nth-safe n (a4veclist-eval vals aigenv))) ;; (3vec-p (4vec-mask (4vmask-nth n masks) ;; (a4vec-eval (a4veclist-nth n vals) aigenv))) ) :hints (("goal" :in-theory (e/d (nth len 4veclist-nth-safe a4veclist-eval 4veclist-mask svexlist-eval a4veclist-eval svexlist-nth) (4veclist-nth-safe-of-a4veclist-eval)) :expand ((:free (env) (svexlist-eval x env)) (a4veclist-eval vals aigenv) (:free (a b) (4veclist-mask masks (cons a b)))) :induct (ind2 n masks vals x)))) ))) :verbosep t :guard-debug t :returns (res a4vec-p) (b* ((fn (fnsym-fix fn)) (args (a4veclist-fix args)) (res (svex-apply-aig-cases fn args terms mask))) ;; ;; This cleverly masks out any bits of the result that we don't care about, ;; ;; replacing them with Xes. This might be a great way to get a lot more ;; ;; constant propagation... (a4vec-mask mask res)) /// (defthm svex-apply-aig-correct (implies (and (fnsym-p fn) (bind-free '((a4env . env)) (a4env)) (equal (a4veclist-eval vals aigenv) (4veclist-mask argmasks (svexlist-eval x (svex-a4vec-env-eval a4env aigenv)))) (svex-argmasks-okp (svex-call fn x) mask argmasks)) (equal (a4vec-eval (svex-apply-aig fn vals x mask) aigenv) (4vec-mask mask (svex-apply fn (svexlist-eval x (svex-a4vec-env-eval a4env aigenv)))))) :hints(("Goal" :in-theory (disable len-of-4veclist-mask svex-apply-aig) ;; Establish that (len vals) = (len x). :use ((:instance len-of-4veclist-mask (masks (svex-argmasks mask fn x)) (values (a4veclist-eval vals aigenv))) (:instance len-of-4veclist-mask (masks (svex-argmasks mask fn x)) (values (svexlist-eval x (svex-a4vec-env-eval a4env aigenv)))))) (and stable-under-simplificationp '( :in-theory (e/d (svex-apply svexlist-eval ;; 4veclist-nth-safe ;; 4veclist-mask 4veclist-mask? 4vec-bitnot 4vec-bitand 4vec-bitor 4vec-bitxor-redef 4vec-reduction-and 4vec-reduction-or 4vec-? 4vec-?* 4vec-bit? 4vec-==) (;; len-of-svexlist-eval ;; len-of-a4veclist-eval ;; len-of-4veclist-mask svex-argmasks-correct svex-argmasks-remove-mask)) :use ;; ((:instance len-of-svexlist-eval ;; (env (svex-a4vec-env-eval a4env aigenv))) ;; (:instance len-of-a4veclist-eval ;; (x vals) (env aigenv))) ((:instance svex-argmasks-okp-necc (x (svex-call fn x)) (vals (a4veclist-eval vals aigenv)) (env (svex-a4vec-env-eval a4env aigenv))) ;; (:instance svex-argmasks-remove-mask ;; (fn fn) ;; (args x) ;; (env (svex-a4vec-env-eval a4env aigenv))) ) :do-not-induct t :do-not '(fertilize generalize eliminate-destructors) ))) :otf-flg t)) (defalist svex-aig-memotable :key-type svex :val-type a4vec) (defthm a4vec-p-of-svex-a4vec-env-lookup (implies (and (svex-a4vec-env-p x) (hons-assoc-equal k x)) (a4vec-p (cdr (hons-assoc-equal k x))))) (defthm a4vec-p-of-svex-aig-memotable-lookup (implies (and (svex-aig-memotable-p x) (hons-assoc-equal k x)) (a4vec-p (cdr (hons-assoc-equal k x))))) ;; (SVEX->A4VEC ;; '(RSH (? (< 0 (* 32 (B- (CONCAT 16 CNST 0) 0))) (* 32 (B- (CONCAT 16 CNST 0) 0)) 0) '(-71265535176078871931497435759850128999 . 269016831744859591531877171671918082457)) ;; (make-fast-alist `((cnst ,(acl2::numlist 0 2 16) . ,(acl2::numlist 1 2 16)))) ;; nil) (define svex-is-const-concat ((x svex-p)) :returns (is-concat) :guard-hints (("goal" :in-theory (enable nth))) (svex-case x :call (and (eq x.fn 'concat) (eql (len x.args) 3) (let ((arg1 (mbe :logic (nth 0 x.args) :exec (car x.args)))) (svex-case arg1 :quote))) :otherwise nil)) (define svex-const-concat-args ((x svex-p)) :guard (svex-is-const-concat x) :guard-hints (("goal" :expand ((:free (n) (nth n (svex-call->args x))) (:free (n) (nth n (cdr (svex-call->args x)))) (:free (n) (nth n (cddr (svex-call->args x))))))) :prepwork ((local (in-theory (enable svex-is-const-concat)))) :returns (mv (width 4vec-p) (lsbs svex-p) (msbs svex-p)) (b* (((svex-call x))) (mv (svex-quote->val (mbe :logic (svex-fix (nth 0 x.args)) :exec (first x.args))) (mbe :logic (svex-fix (nth 1 x.args)) :exec (second x.args)) (mbe :logic (svex-fix (nth 2 x.args)) :exec (third x.args)))) /// (local (defthm nth-when-n-too-big (implies (<= (len x) (nfix n)) (equal (nth n x) nil)) :hints(("Goal" :in-theory (enable nth))))) (local (defthm 4vec-zero-ext-is-concat (equal (4vec-zero-ext n x) (4vec-concat n x 0)) :hints(("Goal" :in-theory (enable 4vec-zero-ext 4vec-concat))))) (defretd svex-const-concat-args-correct-rw (implies (svex-is-const-concat x) (equal (svex-eval x env) (4vec-concat width (svex-eval lsbs env) (svex-eval msbs env)))) :hints(("Goal" :in-theory (enable svex-apply svexlist-eval)))) (local (defthm svex-count-of-nth (<= (svex-count (nth n x)) (svexlist-count x)) :hints(("Goal" :in-theory (enable nth svexlist-count))) :rule-classes :linear)) (local (defthm svex-count-of-svexlist-nth (<= (svex-count (svexlist-nth n x)) (svexlist-count x)) :hints(("Goal" :in-theory (enable svexlist-nth))) :rule-classes :linear)) (defret svex-count-of-svex-const-concat-args-lsbs (implies (svex-is-const-concat x) (< (svex-count lsbs) (svex-count x))) :rule-classes :linear) (defret svex-count-of-svex-const-concat-args-msbs (implies (svex-is-const-concat x) (< (svex-count msbs) (svex-count x))) :hints ((and stable-under-simplificationp '(:expand ((svex-count x))))) :rule-classes :linear)) (progn (local (defthm 4vec-zero-ext-of-4vec-mask? (equal (4vec-zero-ext w (4vec-mask? mask x y)) (4vec-mask? (if (and (2vec-p w) (<= 0 (2vec->val w))) (sparseint-concatenate (2vec->val w) (4vmask-fix mask) 0) mask) (4vec-zero-ext w x) (4vec-zero-ext w y))) :hints(("Goal" :in-theory (enable 4vec-mask? 4vec-bit? 3vec-bit? 4vec-zero-ext)) (logbitp-reasoning)))) (local (defthm 4vec-zero-ext-of-equal-4vec-mask? (implies (equal z (4vec-mask? mask x y)) (equal (4vec-zero-ext w z) (4vec-mask? (if (and (2vec-p w) (<= 0 (2vec->val w))) (sparseint-concatenate (2vec->val w) (4vmask-fix mask) 0) mask) (4vec-zero-ext w x) (4vec-zero-ext w y)))))) (local (defthm 4vec-zero-ext-of-zero-ext (equal (4vec-zero-ext w (4vec-zero-ext w x)) (4vec-zero-ext w x)) :hints(("Goal" :in-theory (enable 4vec-zero-ext)))))) (defines svex->a4vec ;; Self-memoized version of svex-eval, for GL :verify-guards nil :ruler-extenders :all (define svex->a4vec ((x svex-p) (env svex-a4vec-env-p) (masks svex-mask-alist-p)) :returns (res a4vec-p) :measure (two-nats-measure (svex-count x) 1) (b* ((env (svex-a4vec-env-fix env))) (svex-case x :quote (b* ((mask (svex-mask-lookup x masks))) (4vec->a4vec (4vec-mask mask x.val))) :var (let ((look (hons-get x.name env)) (mask (svex-mask-lookup x masks))) (a4vec-mask mask (if look (cdr look) (a4vec-x)))) :call (b* ((x (svex-fix x)) ((when (svex-is-const-concat x)) (b* (((mv upper lower) (svex-concat->a4vec x env masks)) (mask (svex-mask-lookup x masks))) (a4vec-mask mask (a4vec upper lower)))) (args (svexlist->a4vec x.args env masks)) (mask (svex-mask-lookup x masks))) (svex-apply-aig x.fn args x.args mask))))) (define svexlist->a4vec ((x svexlist-p) (env svex-a4vec-env-p) (masks svex-mask-alist-p)) :returns (res a4veclist-p) :measure (two-nats-measure (svexlist-count x) 0) (if (atom x) nil (cons (svex->a4vec (car x) env masks) (svexlist->a4vec (cdr x) env masks)))) (define svex-concat->a4vec ((x svex-p) (env svex-a4vec-env-p) (masks svex-mask-alist-p)) :returns (mv (upper true-listp) (lower true-listp)) :measure (two-nats-measure (svex-count x) (if (svex-is-const-concat x) 0 2)) (b* (((unless (svex-is-const-concat x)) (b* ((res (svex->a4vec x env masks))) (mv (a4vec->upper res) (a4vec->lower res)))) ((mv width lsbs msbs) (svex-const-concat-args x)) ((unless (and (2vec-p width) (natp (2vec->val width)))) (mv (a4vec->upper (a4vec-x)) (a4vec->lower (a4vec-x)))) (width (2vec->val width)) (mask (svex-mask-lookup x masks)) ((unless (sparseint-test-bitand (sparseint-concatenate width 0 -1) mask)) (svex-concat->a4vec lsbs env masks)) ((mv upper2 lower2) (svex-concat->a4vec msbs env masks))) (svex-concat->a4vec-lower lsbs width upper2 lower2 env masks))) (define svex-concat->a4vec-lower ((x svex-p) (width natp) (upper-acc true-listp) (lower-acc true-listp) (env svex-a4vec-env-p) (masks svex-mask-alist-p)) :returns (mv (upper true-listp) (lower true-listp)) :measure (two-nats-measure (svex-count x) (if (svex-is-const-concat x) 0 2)) (b* ((upper-acc (llist-fix upper-acc)) (lower-acc (llist-fix lower-acc)) ((When (zp width)) (mv upper-acc lower-acc)) ((unless (svex-is-const-concat x)) (b* ((res (svex->a4vec x env masks))) (mv (aig-logapp-nss width (a4vec->upper res) upper-acc) (aig-logapp-nss width (a4vec->lower res) lower-acc)))) ((mv sub-width lsbs msbs) (svex-const-concat-args x)) ((unless (and (2vec-p sub-width) (natp (2vec->val sub-width)))) (mv (aig-logapp-nss width (a4vec->upper (a4vec-x)) upper-acc) (aig-logapp-nss width (a4vec->lower (a4vec-x)) lower-acc))) (sub-width (2vec->val sub-width)) (lsbs-width (min width sub-width)) (msbs-width (- width lsbs-width)) ((mv upper-acc lower-acc) (svex-concat->a4vec-lower msbs msbs-width upper-acc lower-acc env masks))) (svex-concat->a4vec-lower lsbs lsbs-width upper-acc lower-acc env masks))) /// (verify-guards svex->a4vec :guard-debug t) (local (in-theory (disable svex->a4vec svexlist->a4vec))) (encapsulate nil (local (defthm lookup-in-svex-a4vec-env-eval-lemma (implies (svex-a4vec-env-p env) (equal (hons-assoc-equal k (svex-a4vec-env-eval env aigenv)) (and (hons-assoc-equal k env) (cons k (a4vec-eval (cdr (hons-assoc-equal k env)) aigenv))))) :hints(("Goal" :in-theory (enable svex-a4vec-env-eval svex-a4vec-env-p) :induct (svex-a4vec-env-eval env aigenv) :do-not-induct t)) :rule-classes nil)) (defthm lookup-in-svex-a4vec-env-eval (equal (hons-assoc-equal k (svex-a4vec-env-eval env aigenv)) (and (hons-assoc-equal k (svex-a4vec-env-fix env)) (cons k (a4vec-eval (cdr (hons-assoc-equal k (svex-a4vec-env-fix env))) aigenv)))) :hints(("Goal" :use ((:instance lookup-in-svex-a4vec-env-eval-lemma (env (svex-a4vec-env-fix env)))))))) (defthm svex-env-lookup-in-svex-a4vec-env-eval (equal (svex-env-lookup k (svex-a4vec-env-eval env aigenv)) (if (hons-assoc-equal (svar-fix k) (svex-a4vec-env-fix env)) (a4vec-eval (cdr (hons-assoc-equal (svar-fix k) (svex-a4vec-env-fix env))) aigenv) (4vec-x))) :hints(("Goal" :in-theory (enable svex-env-lookup)))) ;; (local (defthm svex-apply-aig-correct-rw ;; (implies (and (fnsym-p fn) ;; (bind-free '((a4env . env)) (a4env)) ;; (equal (a4veclist-eval vals aigenv) ;; (4veclist-mask argmasks (svexlist-eval x (svex-a4vec-env-eval a4env aigenv)))) ;; (svex-argmasks-okp (svex-call fn x) mask argmasks)) ;; (equal (a4vec-eval (svex-apply-aig fn vals x mask) aigenv) ;; (4vec-mask mask (svex-apply fn (svexlist-eval x (svex-a4vec-env-eval a4env aigenv)))))) (local (in-theory (enable svex-mask-alist-complete-necc))) (local (defthm 4vec-concat-when-not-2vec (implies (not (equal (4vec->upper width) (4vec->lower width))) (equal (4vec-concat width x y) (4vec-x))) :hints(("Goal" :in-theory (enable 4vec-concat))))) (local (defthm 4vec-concat-when-not-natp (implies (< (4vec->lower width) 0) (equal (4vec-concat width x y) (4vec-x))) :hints(("Goal" :in-theory (enable 4vec-concat))))) (local (defthm 4vec-mask-idempotence-rw (implies (equal y (4vec-mask mask x)) (equal (4vec-mask mask y) y)))) (local (defthm 4vec-concat-when-width-0 (implies (and (equal 0 (4vec->upper width)) (equal 0 (4vec->lower width))) (equal (4vec-concat width x y) (4vec-fix y))) :hints(("Goal" :in-theory (enable 4vec-concat))))) (local (define 4vec-change-all-bits ((x 4vec-p)) :returns (new-x 4vec-p) (4vec (lognot (4vec->upper x)) (lognot (4vec->lower x))))) (local (encapsulate nil (local (in-theory (disable* (:rules-of-class :linear :here) bitops::logand-natp-type-2 bitops::logand-natp-type-1 bitops::logior-natp-type bitops::lognot-negp bitops::lognot-natp member-svex-mask-alist-keys acl2::loghead-identity))) (defthm mask-of-bit?-logand-lognot (implies (4vmask-p mask) (equal (4vec-mask mask (4vec-bit? (2vec (logand a (lognot (sparseint-val mask)))) x y)) (4vec-mask mask y))) :hints(("Goal" :in-theory (e/d* (4vec-mask 4vec-bit? 3vec-bit?))) (logbitp-reasoning))) (defthm mask-of-bit?-logand-lognot2 (implies (4vmask-p mask) (equal (4vec-mask mask (4vec-bit? (2vec (logand (lognot (sparseint-val mask)) a)) x y)) (4vec-mask mask y))) :hints(("Goal" :in-theory (e/d* (4vec-mask 4vec-bit? 3vec-bit?))) (logbitp-reasoning))) (defthm argmasks-okp-for-const-concat-implies-lsb-mask-subsumes-outer (b* (((mv width lsbs msbs) (svex-const-concat-args x))) (implies (and (svex-is-const-concat x) (svex-mask-alist-complete masks) (2vec-p width) (<= (nfix w) (2vec->val width))) (4vmask-subsumes (sparseint-concatenate w (svex-mask-lookup lsbs masks) 0) (sparseint-concatenate w (svex-mask-lookup x masks) 0)))) :hints (("goal" :use ((:instance svex-mask-alist-complete-necc (y x) (mask-al masks)) (:instance svex-argmasks-okp-necc (vals (b* (((mv width lsbs msbs) (svex-const-concat-args x))) (list width (4vec-bit? (2vec (logandc1 (sparseint-val (svex-mask-lookup lsbs masks)) (sparseint-val (svex-mask-lookup x masks)))) (4vec-change-all-bits (svex-eval lsbs env)) (svex-eval lsbs env)) (svex-eval msbs env)))) (mask (svex-mask-lookup x masks)) (argmasks (svex-argmasks-lookup (svex-call->args x) masks)))) :in-theory (enable svex-argmasks-lookup svex-apply 4vmask-subsumes svexlist-eval 4veclist-mask len nth) :expand ((svex-is-const-concat x) (svex-const-concat-args x) (len (svex-call->args x)) (len (cdr (svex-call->args x))) (len (cddr (svex-call->args x))) (len (cdddr (svex-call->args x))) (:free (n) (nth n (svex-call->args x))) (:free (n) (nth n (cdr (svex-call->args x)))) (:free (n) (nth n (cddr (svex-call->args x)))) (:free (n) (nth n (cdddr (svex-call->args x)))))) (and stable-under-simplificationp '(:in-theory (enable 4vec-mask 4vec-bit? 3vec-bit? 4vec-change-all-bits 4vec-concat))) (logbitp-reasoning :add-hints (:in-theory (enable* logbitp-case-splits)) :simp-hint (:in-theory (enable* logbitp-case-splits))) ) :otf-flg t) (local (in-theory (disable iff not))) (defthm argmasks-okp-for-const-concat-implies-msb-mask-subsumes-outer (b* (((mv width lsbs msbs) (svex-const-concat-args x))) (implies (and (svex-is-const-concat x) (svex-mask-alist-complete masks) (2vec-p width) (<= 0 (2vec->val width))) (4vmask-subsumes (svex-mask-lookup msbs masks) (sparseint-rightshift (4vec->lower width) (svex-mask-lookup x masks))))) :hints (("goal" :use ((:instance svex-mask-alist-complete-necc (y x) (mask-al masks)) (:instance svex-argmasks-okp-necc (vals (b* (((mv width lsbs msbs) (svex-const-concat-args x))) (list width (svex-eval lsbs env) (4vec-bit? (2vec (logandc1 (sparseint-val (svex-mask-lookup msbs masks)) (logtail (2vec->val width) (sparseint-val (svex-mask-lookup x masks))))) (4vec-change-all-bits (svex-eval msbs env)) (svex-eval msbs env))))) (mask (svex-mask-lookup x masks)) (argmasks (svex-argmasks-lookup (svex-call->args x) masks)))) :in-theory (enable svex-argmasks-lookup svex-apply 4vmask-subsumes svexlist-eval 4veclist-mask len nth) :expand ((svex-is-const-concat x) (svex-const-concat-args x) (len (svex-call->args x)) (len (cdr (svex-call->args x))) (len (cddr (svex-call->args x))) (len (cdddr (svex-call->args x))) (:free (n) (nth n (svex-call->args x))) (:free (n) (nth n (cdr (svex-call->args x)))) (:free (n) (nth n (cddr (svex-call->args x)))) (:free (n) (nth n (cdddr (svex-call->args x)))))) (and stable-under-simplificationp '(:in-theory (enable 4vec-mask 4vec-bit? 3vec-bit? 4vec-change-all-bits 4vec-concat))) (logbitp-reasoning :add-hints (:in-theory (enable* logbitp-case-splits)) :simp-hint (:in-theory (enable* logbitp-case-splits))) ) :otf-flg t) (defthm argmasks-okp-for-const-concat-implies-lsb-mask-subsumes-outer-when-tail-0 (b* (((mv width lsbs msbs) (svex-const-concat-args x))) (implies (and (svex-is-const-concat x) (svex-mask-alist-complete masks) (2vec-p width) (<= 0 (2vec->val width)) (equal 0 (logtail (2vec->val width) (sparseint-val (svex-mask-lookup x masks))))) (4vmask-subsumes (svex-mask-lookup lsbs masks) (svex-mask-lookup x masks)))) :hints (("goal" :use ((:instance argmasks-okp-for-const-concat-implies-lsb-mask-subsumes-outer (w (2vec->val (mv-nth 0 (svex-const-concat-args x)))))) :in-theory (e/d (4vmask-subsumes) (argmasks-okp-for-const-concat-implies-lsb-mask-subsumes-outer))) (logbitp-reasoning :prune-examples nil) ) :otf-flg t))) (local (defthmd 4vec-mask-over-4vec-zero-ext (implies (and (2vec-p width) (<= 0 (2vec->val width))) (equal (4vec-mask mask (4vec-zero-ext width x)) (4vec-concat width (4vec-mask mask x) (4vec-mask (sparseint-rightshift (2vec->val width) (4vmask-fix mask)) 0)))) :hints(("Goal" :in-theory (enable 4vec-mask 4vec-zero-ext 4vec-concat)) (logbitp-reasoning :prune-examples nil)))) (local (defthmd 4vec-mask-over-4vec-concat (implies (and (2vec-p width) (<= 0 (2vec->val width))) (equal (4vec-mask mask (4vec-concat width x y)) (4vec-concat width (4vec-mask mask x) (4vec-mask (sparseint-rightshift (2vec->val width) (4vmask-fix mask)) y)))) :hints(("Goal" :in-theory (enable 4vec-mask 4vec-concat)) (logbitp-reasoning :prune-examples nil)))) (local (defthmd 4vec-concat-of-4vec-mask-identity (implies (and (equal mask1 (4vmask-fix mask)) (2vec-p w) (<= 0 (2vec->val w)) (equal w1 (2vec->val w))) (equal (4vec-concat w (4vec-mask mask x) (4vec-mask (sparseint-rightshift w1 mask1) (4vec-rsh w x))) (4vec-mask mask x))) :hints(("Goal" :in-theory (enable 4vec-mask 4vec-concat 4vec-rsh 4vec-shift-core)) (logbitp-reasoning :prune-examples nil)))) (local (defthmd 4vec-concat-of-equal-4vec-conct (implies (and (equal x (4vec-concat w a b)) (2vec-p w) (<= 0 (2vec->val w))) (equal (4vec-concat w x y) (4vec-concat w a y))))) (local (defthm min-gte-zero (implies (and (<= 0 x) (<= 0 y)) (<= 0 (min x y))))) (local (defthm 2vec-of-4vec-acc (implies (2vec-p x) (and (equal (2vec (4vec->lower x)) (4vec-fix x)) (equal (2vec (4vec->upper x)) (4vec-fix x)))) :hints(("Goal" :in-theory (enable 2vec))))) (local (defthmd 4vec-concat-identity (implies (and (2vec-p w) (<= 0 (2vec->val w))) (equal (4vec-concat w x (4vec-rsh w x)) (4vec-fix x))) :hints(("Goal" :in-theory (enable 4vec-concat 4vec-rsh 4vec-shift-core)) (logbitp-reasoning :prune-examples nil)))) (local (defthmd equal-of-4vec-concat2 (implies (and (2vec-p w) (<= 0 (2vec->val w))) (equal (equal (4vec-concat w x y) z) (and (4vec-p z) (equal (4vec-zero-ext w x) (4vec-zero-ext w z)) (equal (4vec-fix y) (4vec-rsh w z))))) :hints(("Goal" :in-theory (enable 4vec-concat 4vec-zero-ext 4vec-rsh 4vec-shift-core)) (logbitp-reasoning)) :otf-flg t)) (local (defthm 4vec-zero-ext-of-concat (implies (and (2vec-p w1) (2vec-p w2) (<= 0 (2vec->val w1)) (<= (2vec->val w1) (2vec->val w2))) (equal (4vec-zero-ext w1 (4vec-concat w2 x y)) (4vec-zero-ext w1 x))) :hints(("Goal" :in-theory (enable 4vec-zero-ext 4vec-concat))))) (local (defthm 4vec-rsh-of-4vec-mask (implies (and (2vec-p shift) (<= 0 (2vec->val shift))) (equal (4vec-rsh shift (4vec-mask mask x)) (4vec-mask (sparseint-rightshift (2vec->val shift) (4vmask-fix mask)) (4vec-rsh shift x)))) :hints(("Goal" :in-theory (enable 4vec-mask 4vec-rsh 4vec-shift-core))))) (local (defthm equal-zero-ext-of-mask (implies (and (2vec-p w) (<= 0 (2vec->val w))) (equal (equal (4vec-zero-ext w (4vec-mask m x)) (4vec-zero-ext w (4vec-mask m y))) (equal (4vec-mask (sparseint-concatenate (2vec->val w) (4vmask-fix m) 0) x) (4vec-mask (sparseint-concatenate (2vec->val w) (4vmask-fix m) 0) y)))) :hints(("Goal" :in-theory (enable 4vec-zero-ext 4vec-mask)) (logbitp-reasoning)))) (local (defthmd 4vec-mask-of-4vec-concat-under-mask (implies (and (equal (logtail (2vec->val width) (sparseint-val (4vmask-fix mask))) 0) (2vec-p width) (<= 0 (2vec->val width))) (equal (4vec-mask mask (4vec-concat width x y)) (4vec-mask mask x))) :hints(("Goal" :in-theory (enable 4vec-mask 4vec-concat)) (logbitp-reasoning :prune-examples nil)))) (local (defthmd 4vec-concat-of-4vec (equal (4vec (logapp w a b) (logapp w c d)) (4vec-concat (2vec (nfix w)) (4vec a c) (4vec b d))) :hints(("Goal" :in-theory (enable 4vec-concat))))) (local (defthmd 4vec-zero-ext-of-4vec (equal (4vec (loghead w a) (loghead w c)) (4vec-zero-ext (2vec (nfix w)) (4vec a c))) :hints(("Goal" :in-theory (enable 4vec-zero-ext))))) (local (defthmd 4vec-zero-ext-of-4vec/0 (equal (4vec (loghead w a) 0) (4vec-zero-ext (2vec (nfix w)) (4vec a 0))) :hints(("Goal" :in-theory (enable 4vec-zero-ext))))) (local (defthmd 4vec-of-aig-list->s-of-upper/lower (equal (4vec (aig-list->s (a4vec->upper x) env) (aig-list->s (a4vec->lower x) env)) (a4vec-eval x env)) :hints(("Goal" :in-theory (enable a4vec-eval))))) (local (defthm aig-list->s-of-list-fix (equal (aig-list->s (list-fix x) env) (aig-list->s x env)) :hints(("Goal" :in-theory (enable aig-list->s))))) (local (defthm 4vec-mask-of-loghead-4vec-mask (implies (equal mask1 (4vmask-fix mask)) (Equal (4vec-mask (sparseint-concatenate n mask1 0) (4vec-mask mask x)) (4vec-mask (sparseint-concatenate n mask1 0) x))) :hints(("Goal" :in-theory (enable 4vec-mask)) (logbitp-reasoning)))) (local (defun aig-logapp-nss-ind (w1 w2 x y) (declare (xargs :measure (nfix w1))) (if (or (zp w1) (zp w2)) (list x y) (aig-logapp-nss-ind (1- w1) (1- w2) (gl::scdr x) y)))) (local (defthm aig-logapp-nss-of-nfix (Equal (aig-logapp-nss (nfix w) x y) (aig-logapp-nss w x y)) :hints(("Goal" :in-theory (enable aig-logapp-nss))))) (local (defthm aig-logapp-nss-of-list-fix (Equal (aig-logapp-nss w (list-fix x) y) (aig-logapp-nss w x y)) :hints(("Goal" :in-theory (enable aig-logapp-nss))))) (local (defthm aig-logapp-nss-of-snorm (Equal (aig-logapp-nss w (gl::bfr-snorm x) y) (aig-logapp-nss w x y)) :hints(("Goal" :in-theory (enable aig-logapp-nss))))) (local (defthm aig-logapp-nss-of-aig-logapp-nss (equal (aig-logapp-nss w1 (aig-logapp-nss w2 x y) z) (let* ((wa (min (nfix w1) (nfix w2))) (wb (- (nfix w1) wa))) (aig-logapp-nss wa x (aig-logapp-nss wb y z)))) :hints(("Goal" :in-theory (enable aig-logapp-nss) :induct (aig-logapp-nss-ind w1 w2 x y) :expand ((:free (x y) (aig-logapp-nss w1 x y)) (:free (x y) (aig-logapp-nss w2 x y))))))) (local (defthm aig-logapp-nss-when-zp (implies (zp w) (equal (aig-logapp-nss w x y) (list-fix y))) :hints(("Goal" :in-theory (enable aig-logapp-nss))))) (local (defun-sk svex-concat->a4vec-lower-acc-elim-correct (x width env masks) (forall (upper-acc lower-acc) (implies (syntaxp (not (and (equal upper-acc ''nil) (equal lower-acc ''nil)))) (b* (((mv upper-impl lower-impl) (svex-concat->a4vec-lower x width upper-acc lower-acc env masks)) ((mv upper-spec lower-spec) (svex-concat->a4vec-lower x width nil nil env masks))) (and (equal upper-impl (aig-logapp-nss width upper-spec (list-fix upper-acc))) (equal lower-impl (aig-logapp-nss width lower-spec (list-fix lower-acc))))))) :rewrite :direct)) (local (in-theory (disable svex-concat->a4vec-lower-acc-elim-correct))) (local (std::defret-mutual svex-concat->a4vec-lower-acc-elim-lemma (defret svex-concat->a4vec-lower-acc-elim-lemma (svex-concat->a4vec-lower-acc-elim-correct x width env masks) :hints ((and stable-under-simplificationp `(:expand (,(car (last clause)) (:free (upper-acc lower-acc) <call>))))) :fn svex-concat->a4vec-lower :rule-classes nil) :skip-others t)) (defthm svex-concat->a4vec-lower-acc-elim (implies (syntaxp (not (and (equal upper-acc ''nil) (equal lower-acc ''nil)))) (b* (((mv upper-impl lower-impl) (svex-concat->a4vec-lower x width upper-acc lower-acc env masks)) ((mv upper-spec lower-spec) (svex-concat->a4vec-lower x width nil nil env masks))) (and (equal upper-impl (aig-logapp-nss width upper-spec (list-fix upper-acc))) (equal lower-impl (aig-logapp-nss width lower-spec (list-fix lower-acc)))))) :hints (("goal" :use svex-concat->a4vec-lower-acc-elim-lemma))) ;; (define svex-concat->a4vec-lower-zero ((x svex-p) ;; (width natp) ;; (env svex-a4vec-env-p) ;; (masks svex-mask-alist-p) ;; (memo svex-aig-memotable-p)) ;; :returns (mv (upper true-listp) ;; (lower true-listp) ;; (memo1 svex-aig-memotable-p)) ;; :measure (svex-count x) ;; :hooks nil ;; :verify-guards nil ;; (b* ((memo (svex-aig-memotable-fix memo)) ;; ((When (zp width)) ;; (mv nil nil memo)) ;; ((unless (svex-is-const-concat x)) ;; (b* (((mv res memo) (svex->a4vec x env masks memo))) ;; (mv (aig-logapp-nss width (a4vec->upper res) nil) ;; (aig-logapp-nss width (a4vec->lower res) nil) ;; memo))) ;; ((mv sub-width lsbs msbs) ;; (svex-const-concat-args x)) ;; ((unless (and (2vec-p sub-width) (natp (2vec->val sub-width)))) ;; (mv (aig-logapp-nss width (a4vec->upper (a4vec-x)) nil) ;; (aig-logapp-nss width (a4vec->lower (a4vec-x)) nil) ;; (svex-aig-memotable-fix memo))) ;; (sub-width (2vec->val sub-width)) ;; (lsbs-width (min width sub-width)) ;; (msbs-width (- width lsbs-width)) ;; ((mv upper2 lower2 memo) ;; (svex-concat->a4vec-lower-zero msbs msbs-width env masks memo)) ;; ((mv upper1 lower1 memo) ;; (svex-concat->a4vec-lower-zero lsbs lsbs-width env masks memo))) ;; (mv (aig-logapp-nss lsbs-width upper1 upper2) ;; (aig-logapp-nss lsbs-width lower1 lower2) ;; memo)) ;; /// ;; (defthm-svex->a4vec-flag ;; (defthm svex-concat->a4vec-lower-in-terms-of-zero ;; (b* (((mv upper-impl lower-impl memo-impl) ;; (svex-concat->a4vec-lower x width upper-acc lower-acc env masks memo)) ;; ((mv upper-spec lower-spec memo-spec) ;; (svex-concat->a4vec-lower-zero x width env masks memo))) ;; (and (equal memo-impl memo-spec) ;; (equal upper-impl (aig-logapp-nss width upper-spec (list-fix upper-acc))) ;; (equal lower-impl (aig-logapp-nss width lower-spec (list-fix lower-acc))))) ;; :flag svex-concat->a4vec-lower ;; :hints ('(:expand ((svex-concat->a4vec-lower x width upper-acc lower-acc env masks memo) ;; (svex-concat->a4vec-lower-zero x width env masks memo))))) ;; :skip-others t)) (local (defthm 4vec-mask-of-loghead-zero-ext (implies (natp width) (equal (4vec-mask (sparseint-concatenate width mask 0) (4vec-zero-ext (2vec width) x)) (4vec-mask (sparseint-concatenate width mask 0) x))) :hints(("Goal" :in-theory (enable 4vec-mask 4vec-zero-ext)) (logbitp-reasoning)))) (local (defthm 4vec-mask-zero-ext-mask (equal (4vec-mask mask (4vec-zero-ext w (4vec-mask mask x))) (4vec-mask mask (4vec-zero-ext w x))) :hints(("Goal" :in-theory (enable 4vec-mask 4vec-zero-ext)) (logbitp-reasoning)))) (local (defthm 4vec-zero-ext-0 (equal (4vec-zero-ext 0 x) 0) :hints(("Goal" :in-theory (enable 4vec-zero-ext))))) ;; (local (Defthm 4vec-zero-ext-of-zp ;; (equal (4vec-zero-ext (2vec width) x) 0)) ;; :hints(("Goal" :in-theory (enable* 4vec-zero-ext ;; ihsext-recursive-redefs)))) (local (defthm 4vec-concat-0 (equal (4vec-concat width x 0) (4vec-zero-ext width x)) :hints(("Goal" :in-theory (enable 4vec-concat 4vec-zero-ext))))) (local (defthm 4vec-of-equal-upper-lower (implies (and (equal a (4vec->upper x)) (equal b (4vec->lower x))) (equal (4vec a b) (4vec-fix x))))) (local (defthm 4vec-mask?-of-4vec-mask?-when-subsumes (implies (4vmask-subsumes m1 m2) (equal (4vec-mask? m2 a (4vec-mask? m1 a b)) (4vec-mask? m1 a b))) :hints(("Goal" :in-theory (enable 4vec-mask? 4vec-bit? 3vec-bit? 4vmask-subsumes)) (logbitp-reasoning)))) (local (defthm zero-ext-of-zero-ext (implies (and (2vec-p a) (2vec-p b) (<= 0 (2vec->val a)) (<= (2vec->val a) (2vec->val b))) (and (equal (4vec-zero-ext a (4vec-zero-ext b x)) (4vec-zero-ext a x)) (equal (4vec-zero-ext b (4vec-zero-ext a x)) (4vec-zero-ext a x)))) :hints(("Goal" :in-theory (enable 4vec-zero-ext))))) (local (Defthm 4vec-rsh-of-4vec-mask? (implies (and (2vec-p sh) (<= 0 (2vec->val sh))) (equal (4vec-rsh sh (4vec-mask? mask a b)) (4vec-mask? (sparseint-rightshift (2vec->val sh) (4vmask-fix mask)) (4vec-rsh sh a) (4vec-rsh sh b)))) :hints(("Goal" :in-theory (enable 4vec-rsh 4vec-shift-core 4vec-mask? 4vec-bit? 3vec-bit?))))) (local (defthm 4vec-rsh-of-4vec-zero-ext (implies (and (2vec-p a) (2vec-p b) (<= 0 (2vec->val a)) (<= (2vec->val a) (2vec->val b))) (and (equal (4vec-rsh a (4vec-zero-ext b x)) (4vec-zero-ext (2vec (- (2vec->val b) (2vec->val a))) (4vec-rsh a x))) (equal (4vec-rsh b (4vec-zero-ext a x)) 0))) :hints(("Goal" :in-theory (enable 4vec-rsh 4vec-shift-core 4vec-zero-ext)) (and stable-under-simplificationp '(:in-theory (enable* ihsext-recursive-redefs)))))) (local (defthm 4vmask-subsumes-of-loghead (implies (and (4vmask-subsumes a b) (4vmask-p a) (4vmask-p b)) (4vmask-subsumes (sparseint-concatenate w a 0) (sparseint-concatenate w b 0))) :hints(("Goal" :in-theory (enable 4vmask-subsumes)) (logbitp-reasoning)))) (local (defthm 4vec-mask?-of-concat-same (implies (and (2vec-p w) (<= 0 (2vec->val w))) (equal (4vec-mask? mask (4vec-concat w a b) (4vec-concat w c d)) (4vec-concat w (4vec-mask? (sparseint-concatenate (2vec->val w) (4vmask-fix mask) 0) (4vec-zero-ext w a) (4vec-zero-ext w c)) (4vec-mask? (sparseint-rightshift (2vec->val w) (4vmask-fix mask)) b d)))) :hints(("Goal" :in-theory (enable 4vec-mask? 4vec-bit? 3vec-bit? 4vec-concat 4vec-zero-ext)) (logbitp-reasoning)))) (local (defthm 4vec-mask?-of-concat-when-logtail-0 (implies (and (equal 0 (logtail (2vec->val w) (sparseint-val (4vmask-fix mask)))) (2vec-p w) (<= 0 (2vec->val w))) (equal (4vec-mask? mask (4vec-concat w a b) c) (4vec-mask? mask a c))) :hints(("Goal" :in-theory (enable 4vec-mask? 4vec-bit? 3vec-bit? 4vec-concat)) (logbitp-reasoning :prune-examples nil)))) ;; (local (defthm 4vec-mask?-of-zero-ext-when-logtail-0 ;; (implies (and (equal 0 (logtail (2vec->val w) (sparseint-val (4vmask-fix mask)))) ;; (2vec-p w) (<= 0 (2vec->val w))) ;; (equal (4vec-mask? mask (4vec-zero-ext w a) c) ;; (4vec-mask? mask a c))) ;; :hints(("Goal" :in-theory (enable 4vec-mask? 4vec-bit? 3vec-bit? 4vec-zero-ext)) ;; (logbitp-reasoning :prune-examples nil)))) ;; (local (defthm 4vec-mask?-of-zero-ext-when-logtail-0-2 ;; (implies (and (equal 0 (logtail (2vec->val w) (sparseint-val (4vmask-fix mask)))) ;; (2vec-p w) (<= 0 (2vec->val w))) ;; (equal (4vec-mask? mask a (4vec-zero-ext w c)) ;; (4vec-mask? mask a c))) ;; :hints(("Goal" :in-theory (enable 4vec-mask? 4vec-bit? 3vec-bit? 4vec-zero-ext)) ;; (logbitp-reasoning :prune-examples nil)))) (local (defthm 4veclist-mask?-of-conses (equal (4veclist-mask? (cons c1 c2) (cons t1 t2) (cons f1 f2)) (cons (4vec-mask? c1 t1 f1) (4veclist-mask? c2 t2 f2))) :hints(("Goal" :in-theory (enable 4veclist-mask?))))) (local (progn (defcong 4vmask-equal equal (4vec-mask? mask a b) 1 :hints(("Goal" :in-theory (enable 4vec-mask?)))) (defthm sparseint-concatenate-self-under-4vmask-equal (4vmask-equal (sparseint-concatenate width (sparseint-concatenate width a b) c) (sparseint-concatenate width a c)) :hints(("Goal" :in-theory (enable bitops::logapp-right-assoc)))) (defcong sparseint-equal 4vmask-equal (sparseint-concatenate width a b) 2) (defcong sparseint-equal 4vmask-equal (sparseint-concatenate width a b) 3) (defthm sparseint-equal-rightshift-0 (sparseint-equal (sparseint-rightshift 0 x) x)))) (local (defthm logand-ash-neg1-equal-0 (implies (natp n) (equal (equal 0 (logand (ash -1 n) x)) (equal 0 (logtail n x)))) :hints ((logbitp-reasoning :prune-examples nil)))) (local (defthm loghead-when-width-zp (implies (zp width) (equal (loghead width x) 0)))) (local (defthm 4vec-mask-of-4vec-mask?-when-subsumes (implies (4vmask-subsumes m1 m2) (equal (4vec-mask m2 (4vec-mask? m1 b c)) (4vec-mask m2 b))) :hints(("Goal" :in-theory (enable 4vec-mask? 4vec-mask 4vec-bit? 3vec-bit? 4vmask-subsumes)) (logbitp-reasoning)))) ;; (local (defthm 4vec-zero-ext-to-concat ;; (equal (4vec-zero-ext w x) ;; (4vec-concat w x 0)))) ;; (local (in-theory (disable 4vec-concat-0))) (std::defret-mutual svex->a4vec-correct (defret svex->a4vec-correct (implies (svex-mask-alist-complete masks) (equal (a4vec-eval res aigenv) (4vec-mask (svex-mask-lookup x masks) (svex-eval x (svex-a4vec-env-eval env aigenv))))) :hints ('(:expand (<call> (:free (env) (svex-eval x env))))) :fn svex->a4vec) (defret svexlist->a4vec-correct (implies (svex-mask-alist-complete masks) (equal (a4veclist-eval res aigenv) (4veclist-mask (svex-argmasks-lookup x masks) (svexlist-eval x (svex-a4vec-env-eval env aigenv))))) :hints ('(:expand (<call> (:free (env) (svexlist-eval x env)) (a4veclist-eval nil aigenv) (svex-argmasks-lookup x masks) (:free (a b) (a4veclist-eval (cons a b) aigenv))) :in-theory (enable 4veclist-mask))) :fn svexlist->a4vec) (defret svex-concat->a4vec-correct (implies (svex-mask-alist-complete masks) (4vec-mask-equiv (a4vec-eval (a4vec upper lower) aigenv) (svex-eval x (svex-a4vec-env-eval env aigenv)) (svex-mask-lookup x masks))) :hints ((acl2::just-expand ((:free (x) (hide x))) :last-only t :lambdasp t) '(:expand (<call>) :in-theory (e/d (svex-const-concat-args-correct-rw 4vec-concat-of-4vec)))) :fn svex-concat->a4vec) (defret svex-concat->a4vec-lower-correct :pre-bind ((lower-acc nil) (upper-acc nil)) (implies (svex-mask-alist-complete masks) (let ((ans (a4vec-eval (a4vec upper lower) aigenv))) (equal ans (4vec-zero-ext (2vec (nfix width)) (4vec-mask? (svex-mask-lookup x masks) (svex-eval x (svex-a4vec-env-eval env aigenv)) (hide ans)))))) :hints ((acl2::just-expand ((:free (x) (hide x))) :last-only t :lambdasp t) '(:expand ((svex-concat->a4vec-lower x width nil nil env masks)) :in-theory (e/d (svex-const-concat-args-correct-rw 4vec-concat-of-4vec 4vec-zero-ext-of-4vec 4vec-zero-ext-of-4vec/0 4vec-of-aig-list->s-of-upper/lower ;; 4vec-mask-over-4vec-concat ;; 4vec-mask-over-4vec-zero-ext ) (BITOPS::LOGAPP-OF-I-0 a4vec-eval-of-var))) (and stable-under-simplificationp '(:in-theory (e/d (equal-of-4vec-concat2 4vec-mask-of-4vec-concat-under-mask svex-const-concat-args-correct-rw 4vec-concat-of-4vec 4vec-zero-ext-of-4vec 4vec-zero-ext-of-4vec/0 4vec-of-aig-list->s-of-upper/lower) (a4vec-eval-of-var)) :do-not-induct t))) :fn svex-concat->a4vec-lower) ) (std::defret-mutual svexlist->a4vec-true-listp (defret svexlist->a4vec-true-listp (true-listp res) :hints ('(:expand (<call>))) :fn svexlist->a4vec) :skip-others t) (std::defret-mutual len-of-svexlist->a4vec (defret len-of-svexlist->a4vec (equal (len res) (len x)) :hints ('(:expand (<call>))) :fn svexlist->a4vec) :skip-others t) (deffixequiv-mutual svex->a4vec)) (define svex->a4vec-memotable-correctp ((memo svex-aig-memotable-p) (env svex-a4vec-env-p) (masks svex-mask-alist-p)) (if (atom memo) t (and (or (not (mbt (consp (car memo)))) (equal (svex->a4vec (caar memo) env masks) (a4vec-fix (cdar memo)))) (svex->a4vec-memotable-correctp (cdr memo) env masks))) /// (defthm svex->a4vec-memotable-correctp-implies-lookup (implies (and (svex->a4vec-memotable-correctp memo env masks) (hons-assoc-equal x memo)) (a4vec-equiv (cdr (hons-assoc-equal x memo)) (svex->a4vec x env masks)))) (defthm svex->a4vec-memotable-correctp-implies-lookup-fix (implies (and (svex->a4vec-memotable-correctp memo env masks) (hons-assoc-equal x (svex-aig-memotable-fix memo))) (equal (cdr (hons-assoc-equal x (svex-aig-memotable-fix memo))) (svex->a4vec x env masks))) :hints(("Goal" :in-theory (enable svex-aig-memotable-fix)))) (defthm svex->a4vec-memotable-correctp-of-cons (implies (and (svex->a4vec-memotable-correctp memo env masks) (a4vec-equiv val (svex->a4vec x env masks))) (svex->a4vec-memotable-correctp (cons (cons x val) memo) env masks))) (defthm svex->a4vec-memotable-correctp-of-nil (svex->a4vec-memotable-correctp nil env masks)) (local (in-theory (enable svex-aig-memotable-fix)))) (defines svex->a4vec-memo ;; Self-memoized version of svex-eval, for GL :verify-guards nil :ruler-extenders :all (define svex->a4vec-memo ((x svex-p) (env svex-a4vec-env-p) (masks svex-mask-alist-p) (memo svex-aig-memotable-p)) :returns (mv (res a4vec-p) (memo1 svex-aig-memotable-p)) :measure (two-nats-measure (svex-count x) 1) (b* ((memo (svex-aig-memotable-fix memo)) (env (svex-a4vec-env-fix env))) (svex-case x :quote (b* ((mask (svex-mask-lookup x masks))) (mv (4vec->a4vec (4vec-mask mask x.val)) memo)) :var (mv (let ((look (hons-get x.name env)) (mask (svex-mask-lookup x masks))) (a4vec-mask mask (if look (cdr look) (a4vec-x)))) memo) :call (b* ((x (svex-fix x)) (look (hons-get x memo)) ((when look) (mv (cdr look) memo)) ((mv res memo) (b* (((when (svex-is-const-concat x)) (b* (((mv upper lower memo) (svex-concat->a4vec-memo x env masks memo)) (mask (svex-mask-lookup x masks))) (mv (a4vec-mask mask (a4vec upper lower)) memo))) ((mv args memo) (svexlist->a4vec-memo x.args env masks memo)) (mask (svex-mask-lookup x masks)) (res (svex-apply-aig x.fn args x.args mask))) (mv res memo))) (memo (hons-acons x res memo))) (mv res memo))))) (define svexlist->a4vec-memo ((x svexlist-p) (env svex-a4vec-env-p) (masks svex-mask-alist-p) (memo svex-aig-memotable-p)) :returns (mv (res a4veclist-p) (memo1 svex-aig-memotable-p)) :measure (two-nats-measure (svexlist-count x) 0) (b* (((when (atom x)) (mv nil (svex-aig-memotable-fix memo))) ((mv first memo) (svex->a4vec-memo (car x) env masks memo)) ((mv rest memo) (svexlist->a4vec-memo (cdr x) env masks memo))) (mv (cons first rest) memo))) (define svex-concat->a4vec-memo ((x svex-p) (env svex-a4vec-env-p) (masks svex-mask-alist-p) (memo svex-aig-memotable-p)) :returns (mv (upper true-listp) (lower true-listp) (memo1 svex-aig-memotable-p)) :measure (two-nats-measure (svex-count x) (if (svex-is-const-concat x) 0 2)) (b* (((unless (svex-is-const-concat x)) (b* (((mv res memo) (svex->a4vec-memo x env masks memo))) (mv (a4vec->upper res) (a4vec->lower res) memo))) ((mv width lsbs msbs) (svex-const-concat-args x)) ((unless (and (2vec-p width) (natp (2vec->val width)))) (mv (a4vec->upper (a4vec-x)) (a4vec->lower (a4vec-x)) (svex-aig-memotable-fix memo))) (width (2vec->val width)) (mask (svex-mask-lookup x masks)) ((unless (sparseint-test-bitand (sparseint-concatenate width 0 -1) mask)) (svex-concat->a4vec-memo lsbs env masks memo)) ((mv upper2 lower2 memo) (svex-concat->a4vec-memo msbs env masks memo))) (svex-concat->a4vec-memo-lower lsbs width upper2 lower2 env masks memo))) (define svex-concat->a4vec-memo-lower ((x svex-p) (width natp) (upper-acc true-listp) (lower-acc true-listp) (env svex-a4vec-env-p) (masks svex-mask-alist-p) (memo svex-aig-memotable-p)) :returns (mv (upper true-listp) (lower true-listp) (memo1 svex-aig-memotable-p)) :measure (two-nats-measure (svex-count x) (if (svex-is-const-concat x) 0 2)) (b* ((upper-acc (llist-fix upper-acc)) (lower-acc (llist-fix lower-acc)) (memo (svex-aig-memotable-fix memo)) ((When (zp width)) (mv upper-acc lower-acc memo)) ((unless (svex-is-const-concat x)) (b* (((mv res memo) (svex->a4vec-memo x env masks memo))) (mv (aig-logapp-nss width (a4vec->upper res) upper-acc) (aig-logapp-nss width (a4vec->lower res) lower-acc) memo))) ((mv sub-width lsbs msbs) (svex-const-concat-args x)) ((unless (and (2vec-p sub-width) (natp (2vec->val sub-width)))) (mv (aig-logapp-nss width (a4vec->upper (a4vec-x)) upper-acc) (aig-logapp-nss width (a4vec->lower (a4vec-x)) lower-acc) (svex-aig-memotable-fix memo))) (sub-width (2vec->val sub-width)) (lsbs-width (min width sub-width)) (msbs-width (- width lsbs-width)) ((mv upper-acc lower-acc memo) (svex-concat->a4vec-memo-lower msbs msbs-width upper-acc lower-acc env masks memo))) (svex-concat->a4vec-memo-lower lsbs lsbs-width upper-acc lower-acc env masks memo))) /// (verify-guards svex->a4vec-memo :guard-debug t) (local (in-theory (disable svex-concat->a4vec-lower-acc-elim))) (std::defret-mutual svex->a4vec-memo-correct (defret svex->a4vec-memo-correct (implies (svex->a4vec-memotable-correctp memo env masks) (and (equal res (svex->a4vec x env masks)) (svex->a4vec-memotable-correctp memo1 env masks))) :hints ('(:expand (<call> (svex->a4vec x env masks)))) :fn svex->a4vec-memo) (defret svexlist->a4vec-memo-correct (implies (svex->a4vec-memotable-correctp memo env masks) (and (equal res (svexlist->a4vec x env masks)) (svex->a4vec-memotable-correctp memo1 env masks))) :hints ('(:expand (<call> (svexlist->a4vec x env masks)))) :fn svexlist->a4vec-memo) (defret svex-concat->a4vec-memo-correct (implies (svex->a4vec-memotable-correctp memo env masks) (b* (((mv upper-spec lower-spec) (svex-concat->a4vec x env masks))) (and (equal upper upper-spec) (equal lower lower-spec) (svex->a4vec-memotable-correctp memo1 env masks)))) :hints ('(:expand (<call> (svex-concat->a4vec x env masks)))) :fn svex-concat->a4vec-memo) (defret svex-concat->a4vec-memo-lower-correct (implies (svex->a4vec-memotable-correctp memo env masks) (b* (((mv upper-spec lower-spec) (svex-concat->a4vec-lower x width upper-acc lower-acc env masks))) (and (equal upper upper-spec) (equal lower lower-spec) (svex->a4vec-memotable-correctp memo1 env masks)))) :hints ('(:expand ((:free (width) <call>) (:free (width) (svex-concat->a4vec-lower x width upper-acc lower-acc env masks))))) :fn svex-concat->a4vec-memo-lower)) (deffixequiv-mutual svex->a4vec-memo)) (define svexlist->a4vec-nrev ((x svexlist-p) (env svex-a4vec-env-p) (masks svex-mask-alist-p) (memo svex-aig-memotable-p) (acl2::nrev)) :returns (mv (new-nrev) (memo1 svex-aig-memotable-p)) (if (atom x) (b* ((acl2::nrev (acl2::nrev-fix acl2::nrev))) (mv acl2::nrev (svex-aig-memotable-fix memo))) (b* (((mv first memo) (svex->a4vec-memo (car x) env masks memo)) (acl2::nrev (acl2::nrev-push first acl2::nrev))) (svexlist->a4vec-nrev (cdr x) env masks memo acl2::nrev))) /// (defret svexlist->a4vec-nrev-removal (b* (((mv out-spec memo1-spec) (svexlist->a4vec-memo x env masks memo))) (and (equal new-nrev (append acl2::nrev out-spec)) (equal memo1 memo1-spec))) :hints(("Goal" :induct t :expand ((svexlist->a4vec-memo x env masks memo)))))) (define svexlist->a4vec-top ((x svexlist-p) (env svex-a4vec-env-p) (masks svex-mask-alist-p)) ;; note: env must be fast ;; :prepwork ((local (defthm svexlist->a4vec-decomp ;; (equal (list (mv-nth 0 (svexlist->a4vec x env masks memo)) ;; (mv-nth 1 (svexlist->a4vec x env masks memo))) ;; (svexlist->a4vec x env masks memo)) ;; :hints (("goal" :expand ((svexlist->a4vec x env masks memo))))))) :enabled t (mbe :logic (svexlist->a4vec x env masks) :exec (b* (((mv res memo) (with-local-stobj acl2::nrev (mv-let (res memo acl2::nrev) (b* (((mv acl2::nrev memo) (svexlist->a4vec-nrev x env masks nil acl2::nrev)) ((mv res acl2::nrev) (acl2::nrev-finish acl2::nrev))) (mv res memo acl2::nrev)) (mv res memo))))) (fast-alist-free memo) res))) ;; There are a few possible approaches to generating the a4vec-env to use in ;; building AIGs. Basically, we're going to generate a pair of Boolean ;; variables for each bit that matters (mask-wise) in x; the masks for the ;; variables of x must be finite so that we can determine which bits matter. ;; (The don't-care bits will be assigned X.) ;; But there are still a few options: ;; 1. Always assign AIG variables to every care bit of every variable. This ;; has the advantage that the input and output to svexlist->a4vec is always ;; identical for a given svexlist, so we can memoize, which may improve ;; performance if we run several simulations with the same svex but different ;; environments. But the complete set of variables might be overkill, ;; e.g. svtvs have lots of variables for don't-care inputs and initial ;; states. ;; 2. Assign AIG variables to the care bits of all the variables bound in the ;; environment. This could still allow good memoization as long as the same ;; variables are going to be assigned basically all the time. We can extract ;; and sort the variables so that the order of the bindings doesn't matter. ;; 3. In between 1 and 2: Take a list of variables as an extra argument, ;; ignored in the logic, which should be a superset of the variables in the ;; environment; only generate AIG vars for these variables. This care list ;; could be provided e.g. by the SVTV. This has the advantage over 2 that ;; memoization still works if different subsets of the care variables are ;; used in different runs. ;; The implementations of 1,2,3 would be quite similar and could basically ;; all be based on 3. ;; 4. More extreme than 2, more difficult to implement, and little chance of ;; memoization working: in the symbolic environment provided, we only really ;; need AIG variables for non-constant bits. So ignore masks and just ;; produce an a4vec environment that replicates the constants assigned in env ;; and generates AIG variables for the non-constant bits. This would mean ;; we'd need to get a hold of the symbolic environment, which probably would ;; mean we'd need a symbolic counterpart function, not just an alternate ;; definition. ;; The following implements option 3 above. We provide the svexlist and the ;; list of care vars. The function returns the a4veclist and the a4vec-env. (define nat-bool-listp (x) (if (atom x) (eq x nil) (and (or (natp (car x)) (booleanp (car x))) (nat-bool-listp (cdr x)))) /// (defthm nat-bool-listp-of-aig-sterm (implies (or (booleanp x) (natp x)) (nat-bool-listp (aig-sterm x))) :hints(("Goal" :in-theory (enable gl::bfr-sterm)))) (defthm nat-bool-listp-of-aig-scons (implies (and (or (booleanp x) (natp x)) (nat-bool-listp y)) (nat-bool-listp (aig-scons x y))) :hints(("Goal" :in-theory (enable gl::bfr-scons)))) (defthm nat-bool-listp-of-list-fix (implies (nat-bool-listp x) (nat-bool-listp (list-fix x))))) (define nat-bool-list-nats ((x nat-bool-listp)) :prepwork ((local (in-theory (enable nat-bool-listp)))) (if (atom x) nil (if (booleanp (car x)) (nat-bool-list-nats (cdr x)) (cons (lnfix (car x)) (nat-bool-list-nats (cdr x))))) /// (defthm nat-bool-list-nats-of-list-fix (equal (nat-bool-list-nats (list-fix x)) (nat-bool-list-nats x))) (defthm nat-bool-list-nats-of-aig-sterm (equal (nat-bool-list-nats (aig-sterm x)) (if (booleanp x) nil (list (nfix x)))) :hints(("Goal" :in-theory (enable gl::bfr-sterm)))) (defthm nat-bool-list-nats-of-aig-scons-bool (implies (booleanp x) (equal (nat-bool-list-nats (aig-scons x y)) (nat-bool-list-nats y))) :hints(("Goal" :in-theory (enable gl::bfr-scons)))) (defthm nat-bool-list-nats-of-aig-scons-nat (implies (and (natp x) (not (member x (nat-bool-list-nats y)))) (equal (nat-bool-list-nats (aig-scons x y)) (cons x (nat-bool-list-nats y)))) :hints(("Goal" :in-theory (enable gl::bfr-scons))))) (define nat-bool-list-lower-boundp ((bound natp) (x nat-bool-listp)) :prepwork ((local (in-theory (enable nat-bool-listp)))) (if (atom x) t (and (or (booleanp (car x)) (<= (lnfix bound) (lnfix (car x)))) (nat-bool-list-lower-boundp bound (cdr x)))) /// (defthm nat-bool-list-lower-boundp-of-list-fix (equal (nat-bool-list-lower-boundp bound (list-fix x)) (nat-bool-list-lower-boundp bound x))) (defthm nat-bool-list-nonmember-by-lower-bound (implies (and (nat-bool-list-lower-boundp bound x) (< v (nfix bound)) (nat-bool-listp x)) (not (member v (nat-bool-list-nats x)))) :hints(("Goal" :in-theory (enable nat-bool-list-nats)))) (Defthm nat-bool-list-lower-boundp-lower (implies (and (nat-bool-list-lower-boundp bound x) (<= (nfix n) (nfix bound))) (nat-bool-list-lower-boundp n x)))) (define nat-bool-list-upper-boundp ((bound natp) (x nat-bool-listp)) :prepwork ((local (in-theory (enable nat-bool-listp)))) (if (atom x) t (and (or (booleanp (car x)) (< (lnfix (car x)) (lnfix bound))) (nat-bool-list-upper-boundp bound (cdr x)))) /// (defthm nat-bool-list-upper-boundp-of-list-fix (equal (nat-bool-list-upper-boundp bound (list-fix x)) (nat-bool-list-upper-boundp bound x))) (defthm nat-bool-list-nonmember-by-upper-bound (implies (and (nat-bool-list-upper-boundp bound x) (<= (nfix bound) v) (nat-bool-listp x)) (not (member v (nat-bool-list-nats x)))) :hints(("Goal" :in-theory (enable nat-bool-list-nats)))) (defthm nat-bool-list-no-intersection-by-bounds (implies (and (nat-bool-list-upper-boundp bound0 x0) (nat-bool-list-lower-boundp bound1 x1) (<= (nfix bound0) (nfix bound1)) (nat-bool-listp x0) (nat-bool-listp x1)) (not (intersectp (nat-bool-list-nats x0) (nat-bool-list-nats x1)))) :hints(("Goal" :in-theory (e/d (intersectp-equal nat-bool-listp nat-bool-list-nats) (acl2::intersectp-equal-commute))))) (Defthm nat-bool-list-upper-boundp-higher (implies (and (nat-bool-list-upper-boundp bound x) (<= (nfix bound) (nfix n))) (nat-bool-list-upper-boundp n x)))) (define nat-bool-a4vec-p ((x a4vec-p)) (b* (((a4vec x) x)) (and (nat-bool-listp x.upper) (nat-bool-listp x.lower))) /// (deffixtype nba4vec :pred nat-bool-a4vec-p! :fix a4vec-fix :equiv a4vec-equiv)) (defmacro nat-bool-a4vec-p! (x) `(and (a4vec-p ,x) (nat-bool-a4vec-p ,x))) (define nat-bool-a4vec-vars ((x nat-bool-a4vec-p!)) :prepwork ((local (in-theory (enable nat-bool-a4vec-p)))) (b* (((a4vec x) x)) (append (nat-bool-list-nats x.upper) (nat-bool-list-nats x.lower)))) (define nat-bool-a4vec-lower-boundp ((bound natp) (x nat-bool-a4vec-p!)) :prepwork ((local (in-theory (enable nat-bool-a4vec-p)))) (b* (((a4vec x) x)) (and (nat-bool-list-lower-boundp bound x.upper) (nat-bool-list-lower-boundp bound x.lower))) /// (defthm nat-bool-a4vec-vars-nonmember-by-lower-bound (implies (and (nat-bool-a4vec-lower-boundp bound x) (< v (nfix bound)) (nat-bool-a4vec-p x)) (not (member v (nat-bool-a4vec-vars x)))) :hints(("Goal" :in-theory (enable nat-bool-a4vec-vars nat-bool-a4vec-p nat-bool-list-nonmember-by-lower-bound)))) (Defthm nat-bool-a4vec-lower-boundp-lower (implies (and (nat-bool-a4vec-lower-boundp bound x) (<= (nfix n) (nfix bound))) (nat-bool-a4vec-lower-boundp n x)))) (define nat-bool-a4vec-upper-boundp ((bound natp) (x nat-bool-a4vec-p!)) :prepwork ((local (in-theory (enable nat-bool-a4vec-p)))) (b* (((a4vec x) x)) (and (nat-bool-list-upper-boundp bound x.upper) (nat-bool-list-upper-boundp bound x.lower))) /// (defthm nat-bool-a4vec-vars-nonmember-by-upper-bound (implies (and (nat-bool-a4vec-upper-boundp bound x) (<= (nfix bound) v) (nat-bool-a4vec-p x)) (not (member v (nat-bool-a4vec-vars x)))) :hints(("Goal" :in-theory (enable nat-bool-a4vec-vars nat-bool-a4vec-p nat-bool-list-nonmember-by-upper-bound)))) (defthm nat-bool-a4vec-no-intersection-by-bounds (implies (and (nat-bool-a4vec-upper-boundp bound0 x0) (nat-bool-a4vec-lower-boundp bound1 x1) (<= (nfix bound0) (nfix bound1)) (nat-bool-a4vec-p x0) (nat-bool-a4vec-p x1)) (not (intersectp (nat-bool-a4vec-vars x0) (nat-bool-a4vec-vars x1)))) :hints(("Goal" :in-theory (e/d (intersectp-equal nat-bool-a4vec-p nat-bool-a4vec-vars nat-bool-a4vec-upper-boundp nat-bool-a4vec-lower-boundp) (acl2::intersectp-equal-commute))))) (Defthm nat-bool-a4vec-upper-boundp-higher (implies (and (nat-bool-a4vec-upper-boundp bound x) (<= (nfix bound) (nfix n))) (nat-bool-a4vec-upper-boundp n x)))) (define nat-bool-a4env-p ((x svex-a4vec-env-p)) :prepwork ((local (in-theory (enable svex-a4vec-env-fix)))) (if (atom x) t (and (if (mbt (consp (car x))) (nat-bool-a4vec-p (cdar x)) t) (nat-bool-a4env-p (cdr x)))) /// (deffixtype nba4env :pred nat-bool-a4env-p! :fix svex-a4vec-env-fix :equiv svex-a4vec-env-equiv)) (defmacro nat-bool-a4env-p! (x) `(and (svex-a4vec-env-p ,x) (nat-bool-a4env-p ,x))) (define nat-bool-a4env-vars ((x nat-bool-a4env-p!)) :prepwork ((local (in-theory (enable nat-bool-a4env-p svex-a4vec-env-fix)))) (if (atom x) nil (append (and (mbt (consp (car x))) (nat-bool-a4vec-vars (cdar x))) (nat-bool-a4env-vars (cdr x))))) (define nat-bool-a4env-lower-boundp ((bound natp) (x nat-bool-a4env-p!)) :prepwork ((local (in-theory (enable nat-bool-a4env-p svex-a4vec-env-fix)))) (if (atom x) t (and (if (mbt (consp (car x))) (nat-bool-a4vec-lower-boundp bound (cdar x)) t) (nat-bool-a4env-lower-boundp bound (cdr x)))) /// (defthm nat-bool-a4env-vars-nonmember-by-lower-bound (implies (and (nat-bool-a4env-lower-boundp bound x) (< v (nfix bound)) (nat-bool-a4env-p x)) (not (member v (nat-bool-a4env-vars x)))) :hints(("Goal" :in-theory (enable nat-bool-a4env-vars nat-bool-a4env-p nat-bool-list-nonmember-by-lower-bound)))) (Defthm nat-bool-a4env-lower-boundp-lower (implies (and (nat-bool-a4env-lower-boundp bound x) (<= (nfix n) (nfix bound))) (nat-bool-a4env-lower-boundp n x)))) (define nat-bool-a4env-upper-boundp ((bound natp) (x nat-bool-a4env-p!)) :prepwork ((local (in-theory (enable nat-bool-a4env-p svex-a4vec-env-fix)))) (if (atom x) t (and (if (mbt (consp (car x))) (nat-bool-a4vec-upper-boundp bound (cdar x)) t) (nat-bool-a4env-upper-boundp bound (cdr x)))) /// (defthm nat-bool-a4env-vars-nonmember-by-upper-bound (implies (and (nat-bool-a4env-upper-boundp bound x) (<= (nfix bound) v) (nat-bool-a4env-p x)) (not (member v (nat-bool-a4env-vars x)))) :hints(("Goal" :in-theory (enable nat-bool-a4env-vars nat-bool-a4env-p nat-bool-list-nonmember-by-upper-bound)))) (defthm nat-bool-a4vec/env-no-intersection-by-bounds (implies (and (nat-bool-a4vec-upper-boundp bound0 x0) (nat-bool-a4env-lower-boundp bound1 x1) (<= (nfix bound0) (nfix bound1)) (nat-bool-a4vec-p x0) (nat-bool-a4env-p x1)) (not (intersectp (nat-bool-a4vec-vars x0) (nat-bool-a4env-vars x1)))) :hints(("Goal" :in-theory (e/d (intersectp-equal nat-bool-a4env-p nat-bool-a4env-lower-boundp) (acl2::intersectp-equal-commute)) :expand ((nat-bool-a4env-vars x1)) :induct (nat-bool-a4env-lower-boundp bound1 x1)))) (defthm nat-bool-a4env-no-intersection-by-bounds (implies (and (nat-bool-a4env-upper-boundp bound0 x0) (nat-bool-a4env-lower-boundp bound1 x1) (<= (nfix bound0) (nfix bound1)) (nat-bool-a4env-p x0) (nat-bool-a4env-p x1)) (not (intersectp (nat-bool-a4env-vars x0) (nat-bool-a4env-vars x1)))) :hints(("Goal" :in-theory (e/d (intersectp-equal nat-bool-a4env-p nat-bool-a4env-vars nat-bool-a4env-upper-boundp nat-bool-a4env-lower-boundp) (acl2::intersectp-equal-commute))))) (defthm nat-bool-a4env-a4vec-no-intersection-by-bounds (implies (and (nat-bool-a4env-upper-boundp bound0 x0) (nat-bool-a4vec-lower-boundp bound1 x1) (<= (nfix bound0) (nfix bound1)) (nat-bool-a4env-p x0) (nat-bool-a4vec-p x1)) (not (intersectp (nat-bool-a4env-vars x0) (nat-bool-a4vec-vars x1)))) :hints(("Goal" :in-theory (e/d (intersectp-equal nat-bool-a4env-p nat-bool-a4env-vars nat-bool-a4env-upper-boundp nat-bool-a4env-lower-boundp) (acl2::intersectp-equal-commute))))) (Defthm nat-bool-a4env-upper-boundp-higher (implies (and (nat-bool-a4env-upper-boundp bound x) (<= (nfix bound) (nfix n))) (nat-bool-a4env-upper-boundp n x)))) (local (defthm logcount-of-logand (implies (natp y) (<= (logcount (logand x y)) (logcount y))) :hints(("Goal" :in-theory (e/d* (bitops::logcount** bitops::logand** bitops::ihsext-inductions)))) :rule-classes :linear)) (define sparseint-nfix ((x sparseint-p)) :guard (not (sparseint-< x 0)) :returns (new-x sparseint-p) :inline t (mbe :logic (if (sparseint-< x 0) 0 (sparseint-fix x)) :exec x) /// (defret <fn>-correct (equal (sparseint-val new-x) (nfix (sparseint-val x))))) (define 4vmask-to-a4vec-varcount ((mask 4vmask-p) (boolmask integerp)) :guard (not (sparseint-< mask 0)) :returns (count natp :rule-classes :type-prescription) (b* ((mask (sparseint-nfix (4vmask-fix mask)))) (- (* 2 (sparseint-bitcount mask)) (sparseint-bitcount (sparseint-bitand mask (int-to-sparseint boolmask)))))) (local (defcong sparseint-equal sparseint-equal (sparseint-nfix x) 1)) (local (defthm integer-length-posp (implies (posp x) (posp (integer-length x))) :hints(("Goal" :in-theory (enable* ihsext-recursive-redefs ihsext-inductions))) :rule-classes :type-prescription)) (define 4vmask-to-a4vec-rec ((mask 4vmask-p) (boolmask integerp) (nextvar natp)) :guard (not (sparseint-< mask 0)) :returns (mv (upper nat-bool-listp) (lower nat-bool-listp)) :verify-guards nil :measure (sparseint-length (sparseint-nfix mask)) :hints(("Goal" :in-theory (enable bitops::integer-length** 4vmask-fix))) (b* ((mask (sparseint-nfix (4vmask-fix mask))) (nextvar (lnfix nextvar)) ((when (sparseint-equal mask 0)) (mv (aig-sterm t) (aig-sterm nil))) ((mv ubit0 ubit1 nextvar) (if (eql 1 (sparseint-bit 0 mask)) (if (logbitp 0 boolmask) (mv nextvar nextvar (+ 1 nextvar)) (mv nextvar (1+ nextvar) (+ 2 nextvar))) (mv t nil nextvar))) ((mv rest-upper rest-lower) (4vmask-to-a4vec-rec (sparseint-rightshift 1 mask) (logcdr boolmask) nextvar))) (mv (aig-scons ubit0 rest-upper) (aig-scons ubit1 rest-lower))) /// ;; (defthm 4vmask-to-a4vec-rec-nextvar ;; (equal (mv-nth 2 (4vmask-to-a4vec-rec mask nextvar)) ;; (+ (* 2 (logcount (nfix mask))) (nfix nextvar))) ;; :hints(("Goal" :in-theory (enable bitops::logcount**)))) (defret true-listp-of-<fn>-upper (true-listp upper) :rule-classes :type-prescription) (defret true-listp-of-<fn>-lower (true-listp lower) :rule-classes :type-prescription) (verify-guards 4vmask-to-a4vec-rec) (defthm 4vmask-to-a4vec-rec-lower-bounds (and (nat-bool-list-lower-boundp nextvar (mv-nth 0 (4vmask-to-a4vec-rec mask boolmask nextvar))) (nat-bool-list-lower-boundp nextvar (mv-nth 1 (4vmask-to-a4vec-rec mask boolmask nextvar)))) :hints(("Goal" :in-theory (enable nat-bool-list-lower-boundp gl::bfr-scons))) :rule-classes ((:forward-chaining :trigger-terms ((4vmask-to-a4vec-rec mask boolmask nextvar))))) (defthm 4vmask-to-a4vec-rec-upper-bounds (and (nat-bool-list-upper-boundp (+ (nfix nextvar) (4vmask-to-a4vec-varcount mask boolmask)) (mv-nth 0 (4vmask-to-a4vec-rec mask boolmask nextvar))) (nat-bool-list-upper-boundp (+ (nfix nextvar) (4vmask-to-a4vec-varcount mask boolmask)) (mv-nth 1 (4vmask-to-a4vec-rec mask boolmask nextvar)))) :hints(("Goal" :in-theory (enable gl::bfr-scons 4vmask-to-a4vec-varcount bitops::logand** bitops::logbitp** bitops::logcount**) :induct (4vmask-to-a4vec-rec mask boolmask nextvar) :expand ((:free (bound a b) (nat-bool-list-upper-boundp bound (cons a b))) (:free (bound) (nat-bool-list-upper-boundp bound nil)) (:free (x) (logtail 1 x))) :do-not-induct t)) :rule-classes ((:forward-chaining :trigger-terms ((4vmask-to-a4vec-rec mask boolmask nextvar))))) ;; (defthm 4vmask-to-a4vec-rec-no-duplicate-vars ;; (b* (((mv upper lower) ;; (4vmask-to-a4vec-rec mask boolmask nextvar))) ;; (and (no-duplicatesp (nat-bool-list-nats upper)) ;; (no-duplicatesp (nat-bool-list-nats lower)) ;; (not (intersectp (nat-bool-list-nats upper) ;; (nat-bool-list-nats lower))))) ;; :hints(("Goal" :in-theory (enable nat-bool-list-nats ;; intersectp-equal)))) (defthm member-4vmask-to-a4vec-rec-vars ;; not a good rewrite rule but useful for the next phase (iff (member v (append (nat-bool-list-nats (mv-nth 0 (4vmask-to-a4vec-rec mask boolmask nextvar))) (nat-bool-list-nats (mv-nth 1 (4vmask-to-a4vec-rec mask boolmask nextvar))))) (and (natp v) (<= (nfix nextvar) v) (< v (+ (nfix nextvar) (4vmask-to-a4vec-varcount mask boolmask))))) :hints(("Goal" :in-theory (enable nat-bool-list-nats 4vmask-to-a4vec-varcount bitops::logand** bitops::logcount** bitops::logbitp**) :induct (4vmask-to-a4vec-rec mask boolmask nextvar)) (and stable-under-simplificationp '(:expand ((logcount (sparseint-val (4vmask-fix mask))) (:free (x) (logtail 1 x)))))) :rule-classes nil)) ;; (defthm eval-4vmask-to-a4vec-rec-cons-greater ;; (b* (((mv ?err upper lower nextvar1) ;; (4vmask-to-a4vec-rec mask nextvar))) ;; (implies (<= nextvar1 var) ;; (and (equal (aig-list->s upper (cons (cons var val) env)) ;; (aig-list->s upper env)) ;; (equal (aig-list->s lower (cons (cons var val) env)) ;; (aig-list->s lower env)))))) ;; (defthm eval-4vmask-to-a4vec-rec-cons-lesser ;; (b* (((mv ?err upper lower ?nextvar1) ;; (4vmask-to-a4vec-rec mask nextvar))) ;; (implies (< var (nfix nextvar)) ;; (and (equal (aig-list->s upper (cons (cons var val) env)) ;; (aig-list->s upper env)) ;; (equal (aig-list->s lower (cons (cons var val) env)) ;; (aig-list->s lower env))))))) (define 4vmask-to-a4vec-rec-env ((mask 4vmask-p) (boolmask integerp) (upper integerp) (lower integerp) (nextvar natp)) :guard (not (sparseint-< mask 0)) :returns (env "environment for the resulting 4vmask") :measure (sparseint-length (sparseint-nfix (4vmask-fix mask))) :hints(("Goal" :in-theory (enable bitops::integer-length** 4vmask-fix))) (b* ((mask (sparseint-nfix (4vmask-fix mask))) (nextvar (lnfix nextvar)) ((when (sparseint-equal mask 0)) nil) (rest-env (4vmask-to-a4vec-rec-env (sparseint-rightshift 1 mask) (logcdr boolmask) (logcdr upper) (logcdr lower) (if (eql 1 (sparseint-bit 0 mask)) (if (logbitp 0 boolmask) (+ 1 nextvar) (+ 2 nextvar)) nextvar)))) (if (eql 1 (sparseint-bit 0 mask)) (cons (cons nextvar (logbitp 0 upper)) (if (logbitp 0 boolmask) rest-env (cons (cons (1+ nextvar) (logbitp 0 lower)) rest-env))) rest-env)) /// (defthm key-exists-in-4vmask-to-a4vec-rec-env (iff (hons-assoc-equal v (4vmask-to-a4vec-rec-env mask boolmask upper lower nextvar)) (and (natp v) (<= (nfix nextvar) v) (< v (+ (nfix nextvar) (4vmask-to-a4vec-varcount mask boolmask))))) :hints(("Goal" :in-theory (enable bitops::logcount** bitops::logbitp** 4vmask-to-a4vec-varcount bitops::logand**) :do-not-induct t :induct (4vmask-to-a4vec-rec-env mask boolmask upper lower nextvar)) (and stable-under-simplificationp '(:expand ((:free (x) (logtail 1 x)) (logcount (sparseint-val (4vmask-fix mask)))))))) (defthm nat-bool-aig-list->s-of-cons-nonmember (implies (and (nat-bool-listp x) (not (member n (nat-bool-list-nats x)))) (equal (aig-list->s x (cons (cons n v) env)) (aig-list->s x env))) :hints(("Goal" :in-theory (enable aig-list->s nat-bool-listp nat-bool-list-nats gl::scdr gl::s-endp) :induct (aig-list->s x env) :expand ((:Free (env) (aig-list->s x env)))))) (local (defthm equal-nfix-plus-1 (not (equal x (+ 1 (nfix x)))) :hints(("Goal" :in-theory (enable nfix))))) (defthm eval-4vmask-to-a4vec-rec-with-env (b* (((mv uppera lowera) (4vmask-to-a4vec-rec mask boolmask nextvar)) (env (4vmask-to-a4vec-rec-env mask boolmask upper lower nextvar))) (and (equal (logand (nfix (sparseint-val (4vmask-fix mask))) (aig-list->s uppera env)) (logand (nfix (sparseint-val (4vmask-fix mask))) upper)) (implies (eql 0 (logand boolmask (logxor upper lower))) (equal (logand (nfix (sparseint-val (4vmask-fix mask))) (aig-list->s lowera env)) (logand (nfix (sparseint-val (4vmask-fix mask))) lower))))) :hints(("Goal" :in-theory (enable 4vmask-to-a4vec-rec bitops::logand** bitops::logxor** bitops::logbitp** 4vmask-fix) :induct (4vmask-to-a4vec-rec-env mask boolmask upper lower nextvar) :expand ((:free (x) (logtail 1 x)))) (and stable-under-simplificationp '(:in-theory (enable bitops::b-xor))) (and stable-under-simplificationp '(:in-theory (enable nfix)))))) (define 4vec-boolmaskp ((x 4vec-p) (mask integerp)) (b* (((4vec x) x)) (eql 0 (logand mask (logxor x.upper x.lower))))) (define 4vmask-to-a4vec ((mask 4vmask-p) (boolmask integerp) (nextvar natp)) :guard (not (sparseint-< mask 0)) :returns (res nat-bool-a4vec-p! :hints(("Goal" :in-theory (enable nat-bool-a4vec-p)))) :prepwork ((local (defthm true-listp-when-nat-bool-listp (implies (nat-bool-listp x) (true-listp x)) :hints(("Goal" :in-theory (enable nat-bool-listp)))))) (b* (((mv upper lower) (4vmask-to-a4vec-rec mask boolmask nextvar))) (a4vec upper lower)) /// ;; (defthm 4vmask-to-a4vec-nextvar ;; (equal (mv-nth 1 (4vmask-to-a4vec mask nextvar)) ;; (+ (* 2 (logcount (nfix mask))) (nfix nextvar)))) (defthm member-vars-of-4vmask-to-a4vec (iff (member v (nat-bool-a4vec-vars (4vmask-to-a4vec mask boolmask nextvar))) (and (natp v) (<= (nfix nextvar) v) (< v (+ (nfix nextvar) (4vmask-to-a4vec-varcount mask boolmask))))) :hints (("goal" :use member-4vmask-to-a4vec-rec-vars :in-theory (enable nat-bool-a4vec-vars)))) (defthm 4vmask-to-a4vec-lower-bounds (nat-bool-a4vec-lower-boundp nextvar (4vmask-to-a4vec mask boolmask nextvar)) :hints(("Goal" :in-theory (enable nat-bool-a4vec-lower-boundp))) :rule-classes ((:forward-chaining :trigger-terms ((4vmask-to-a4vec mask boolmask nextvar))))) (defthm 4vmask-to-a4vec-upper-bounds (nat-bool-a4vec-upper-boundp (+ (nfix nextvar) (4vmask-to-a4vec-varcount mask boolmask)) (4vmask-to-a4vec mask boolmask nextvar)) :hints(("Goal" :in-theory (enable nat-bool-a4vec-upper-boundp))) :rule-classes ((:forward-chaining :trigger-terms ((4vmask-to-a4vec mask boolmask nextvar)))))) (define 4vmask-to-a4vec-env ((mask 4vmask-p) (boolmask integerp) (val 4vec-p) (nextvar natp)) :guard (not (sparseint-< mask 0)) :returns env :prepwork ((local (defthm true-listp-when-nat-bool-listp (implies (nat-bool-listp x) (true-listp x)) :hints(("Goal" :in-theory (enable nat-bool-listp)))))) (4vmask-to-a4vec-rec-env mask boolmask (4vec->upper val) (4vec->lower val) nextvar) /// (defthm key-exists-in-4vmask-to-a4vec-env (iff (hons-assoc-equal v (4vmask-to-a4vec-env mask boolmask val nextvar)) (and (natp v) (<= (nfix nextvar) v) (< v (+ (nfix nextvar) (4vmask-to-a4vec-varcount mask boolmask)))))) (local (defthm mask-lemma (IMPLIES (AND (EQUAL (LOGAND mask a) (LOGAND b mask))) (EQUAL (LOGIOR b (lognot mask)) (LOGIOR (LOGNOT mask) a))) :hints ((bitops::logbitp-reasoning)))) (defthm eval-4vmask-to-a4vec-with-env (b* ((vala (4vmask-to-a4vec mask boolmask nextvar)) (env (4vmask-to-a4vec-env mask boolmask val nextvar))) (implies (and (4vec-boolmaskp val boolmask) (4vmask-p mask) (natp (sparseint-val mask))) (equal (4vec-mask mask (a4vec-eval vala env)) (4vec-mask mask val)))) :hints(("Goal" :in-theory (e/d (4vmask-to-a4vec 4vec-boolmaskp 4vmask-fix 4vec-mask a4vec-eval) (eval-4vmask-to-a4vec-rec-with-env)) :use ((:instance eval-4vmask-to-a4vec-rec-with-env (upper (4vec->upper val)) (lower (4vec->lower val))))) ;; (bitops::logbitp-reasoning) ;; (and stable-under-simplificationp ;; '(:bdd (:vars nil))) )) ;; (defthm eval-4vmask-to-a4vec-with-env-mask-natp ;; (b* ((vala (4vmask-to-a4vec mask boolmask nextvar)) ;; (env (4vmask-to-a4vec-env mask boolmask val nextvar))) ;; (implies (and (4vec-boolmaskp val boolmask)) ;; (equal (4vec-mask mask (a4vec-eval vala env)) ;; (4vec-mask mask val)))) ;; :hints (("Goal" :use eval-4vmask-to-a4vec-with-env ;; :in-theory (disable eval-4vmask-to-a4vec-with-env)))) ) (local (in-theory (disable PICK-A-POINT-SUBSET-STRATEGY))) (define svex-maskbits-for-vars ((vars svarlist-p) (masks svex-mask-alist-p) (boolmasks svar-boolmasks-p)) :prepwork ((local (in-theory (enable svarlist-p svarlist-fix)))) :returns (incr natp :rule-classes :type-prescription) (b* (((when (atom vars)) 0) (mask (svex-mask-lookup (svex-var (car vars)) masks)) (boolmask (svar-boolmasks-lookup (car vars) boolmasks)) ((when (sparseint-< mask 0)) 0)) (+ (4vmask-to-a4vec-varcount mask boolmask) (svex-maskbits-for-vars (cdr vars) masks boolmasks)))) (define svex-maskbits-ok ((vars svarlist-p) (masks svex-mask-alist-p)) :prepwork ((local (in-theory (enable svarlist-p svarlist-fix)))) (b* (((when (atom vars)) t) (mask (svex-mask-lookup (svex-var (car vars)) masks)) ((when (sparseint-< mask 0)) nil)) (svex-maskbits-ok (cdr vars) masks))) (define svex-varmasks->a4env-rec ((vars svarlist-p) (masks svex-mask-alist-p) (boolmasks svar-boolmasks-p) (nextvar natp) (acc nat-bool-a4env-p!)) :prepwork ((local (in-theory (enable svarlist-p svarlist-fix nat-bool-a4env-p svex-mask-alist-fix svex-a4vec-env-fix)))) :returns (mv (err "some mask was negative" (iff err (not (svex-maskbits-ok vars masks))) :hints(("Goal" :in-theory (enable svex-maskbits-ok)))) (a4env nat-bool-a4env-p! :hyp (nat-bool-a4env-p! acc)) (nextvar1 (equal nextvar1 (+ (nfix nextvar) (svex-maskbits-for-vars vars masks boolmasks))) :hints(("Goal" :in-theory (enable svex-maskbits-for-vars))))) (b* ((acc (svex-a4vec-env-fix acc)) ((when (atom vars)) (mv nil acc (lnfix nextvar))) (mask (svex-mask-lookup (svex-var (car vars)) masks)) ((when (sparseint-< mask 0)) (mv (msg "Negative mask: ~x0~%" (svar-fix (car vars))) acc (lnfix nextvar))) (boolmask (svar-boolmasks-lookup (car vars) boolmasks)) (a4vec (4vmask-to-a4vec mask boolmask nextvar)) (nextvar (+ (lnfix nextvar) (4vmask-to-a4vec-varcount mask boolmask)))) (svex-varmasks->a4env-rec (cdr vars) masks boolmasks nextvar (cons (cons (svar-fix (car vars)) a4vec) acc))) /// (local (defun-sk svex-varmasks->a4env-rec-accumulator-elim-correct (vars masks boolmasks nextvar) (forall acc (implies (syntaxp (not (equal acc ''nil))) (b* (((mv err1 a4env1 nextvar1) (svex-varmasks->a4env-rec vars masks boolmasks nextvar acc)) ((mv err2 a4env2 nextvar2) (svex-varmasks->a4env-rec vars masks boolmasks nextvar nil))) (and (equal err1 err2) (equal a4env1 (append a4env2 (svex-a4vec-env-fix acc))) (equal nextvar1 nextvar2))))) :rewrite :direct)) (local (in-theory (disable svex-varmasks->a4env-rec-accumulator-elim-correct))) (local (defthmd svex-varmasks->a4env-rec-accumulator-elim-lemma (svex-varmasks->a4env-rec-accumulator-elim-correct vars masks boolmasks nextvar) :hints (("goal" :induct (svex-varmasks->a4env-rec vars masks boolmasks nextvar acc)) (and stable-under-simplificationp `(:expand (,(car (last clause)) (:free (acc) (svex-varmasks->a4env-rec vars masks boolmasks nextvar acc)))))))) (defthmd svex-varmasks->a4env-rec-accumulator-elim (implies (syntaxp (not (equal acc ''nil))) (b* (((mv err1 a4env1 nextvar1) (svex-varmasks->a4env-rec vars masks boolmasks nextvar acc)) ((mv err2 a4env2 nextvar2) (svex-varmasks->a4env-rec vars masks boolmasks nextvar nil))) (and (equal err1 err2) (equal a4env1 (append a4env2 (svex-a4vec-env-fix acc))) (equal nextvar1 nextvar2)))) :hints (("goal" :use svex-varmasks->a4env-rec-accumulator-elim-lemma))) (defthm member-vars-of-svex-varmasks->a4env-rec (iff (member v (nat-bool-a4env-vars (mv-nth 1 (svex-varmasks->a4env-rec vars masks boolmasks nextvar acc)))) (or (member v (nat-bool-a4env-vars acc)) (and (natp v) (<= (nfix nextvar) v) (< v (+ (nfix nextvar) (svex-maskbits-for-vars vars masks boolmasks)))))) :hints(("Goal" :in-theory (enable svex-maskbits-for-vars nat-bool-a4env-vars)))) (defthm svex-varmasks->a4env-rec-lower-bounds (implies (and (nat-bool-a4env-lower-boundp bound acc) (<= (nfix bound) (nfix nextvar))) (nat-bool-a4env-lower-boundp bound (mv-nth 1 (svex-varmasks->a4env-rec vars masks boolmasks nextvar acc)))) :hints(("Goal" :in-theory (enable nat-bool-a4env-lower-boundp)))) (defthm svex-varmasks->a4env-rec-upper-bounds (implies (and (nat-bool-a4env-upper-boundp bound acc) (<= (+ (nfix nextvar) (svex-maskbits-for-vars vars masks boolmasks)) (nfix bound))) (nat-bool-a4env-upper-boundp bound (mv-nth 1 (svex-varmasks->a4env-rec vars masks boolmasks nextvar acc)))) :hints(("Goal" :in-theory (enable nat-bool-a4env-upper-boundp svex-maskbits-for-vars)))) (defret key-exists-in-svex-varmasks->a4env-rec (implies (not err) (iff (hons-assoc-equal v a4env) (or (member v (svarlist-fix vars)) (hons-assoc-equal v (svex-a4vec-env-fix acc)))))) (defret alist-keys-of-svex-varmasks->a4env-rec (implies (not err) (equal (alist-keys a4env) (append (rev (svarlist-fix vars)) (alist-keys (svex-a4vec-env-fix acc))))) :hints(("Goal" :in-theory (enable svex-maskbits-ok))))) ;; (defsection svex-envs-masks-partly-equiv ;; (defquant svex-envs-masks-partly-equiv (vars masks env1 env2) ;; (forall v ;; (implies (not (member (svar-fix v) (svarlist-fix vars))) ;; (equal (4vec-mask (svex-mask-lookup (svex-var v) masks) ;; (svex-env-lookup v env1)) ;; (4vec-mask (svex-mask-lookup (svex-var v) masks) ;; (svex-env-lookup v env2))))) ;; :rewrite :direct) ;; (defexample svex-envs-masks-partly-equiv-example ;; :pattern (equal (4vec-mask (svex-mask-lookup (svex-var v) masks) ;; val1) ;; (4vec-mask mask2 val2)) ;; :templates (v) ;; :instance-rulename svex-envs-masks-partly-equiv-instancing)) (defsection svex-envs-mask-equiv-on-vars (defquant svex-envs-mask-equiv-on-vars (vars masks env1 env2) (forall v (implies (member (svar-fix v) (svarlist-fix vars)) (equal (4vec-mask (svex-mask-lookup (svex-var v) masks) (svex-env-lookup v env1)) (4vec-mask (svex-mask-lookup (svex-var v) masks) (svex-env-lookup v env2))))) :rewrite :direct) (defexample svex-envs-mask-equiv-on-vars-example :pattern (equal (4vec-mask (svex-mask-lookup (svex-var v) masks) val1) (4vec-mask mask2 val2)) :templates (v) :instance-rulename svex-envs-mask-equiv-on-vars-instancing) (local (defexample svex-envs-mask-equiv-on-vars-mask-look-example :pattern (svex-mask-lookup (svex-var var) masks) :templates (var) :instance-rulename svex-envs-mask-equiv-on-vars-instancing)) (local (defexample svex-envs-mask-equiv-on-vars-env-look-example :pattern (svex-env-lookup var env) :templates (var) :instance-rulename svex-envs-mask-equiv-on-vars-instancing)) (local (defexample svex-argmasks-okp-example :pattern (equal (4vec-mask mask (svex-apply fn (svexlist-eval args env1))) (4vec-mask mask (svex-apply fn (svexlist-eval args env2)))) :templates (env1 (svexlist-eval args env2)) :instance-rulename svex-argmasks-okp-instancing)) (local (acl2::def-witness-ruleset svex-mask-alist-reasoning '(svex-mask-alist-complete-witnessing svex-mask-alist-complete-instancing svex-mask-alist-complete-example svex-mask-alist-partly-complete-witnessing svex-mask-alist-partly-complete-instancing svex-mask-alist-partly-complete-example))) (local (acl2::def-witness-ruleset svex-env-reasoning '(svex-envs-mask-equiv-on-vars-instancing svex-envs-mask-equiv-on-vars-witnessing svex-envs-mask-equiv-on-vars-mask-look-example svex-envs-mask-equiv-on-vars-env-look-example svex-mask-alist-reasoning SVEX-ARGMASKS-OKP-WITNESSING SVEX-ARGMASKS-OKP-INSTANCING SVEX-ARGMASKS-OKP-EXAMPLE ))) (defthm-svex-eval-flag (defthm svex-eval-of-mask-equiv-on-vars-envs (implies (and (svex-mask-alist-complete masks) (svex-envs-mask-equiv-on-vars vars masks env1 env2) (subsetp-equal (intersection-equal (svex-vars x) (union-equal (alist-keys (svex-env-fix env1)) (alist-keys (svex-env-fix env2)))) (svarlist-fix vars))) (equal (equal (4vec-mask (svex-mask-lookup x masks) (svex-eval x env1)) (4vec-mask (svex-mask-lookup x masks) (svex-eval x env2))) t)) :hints ('(:expand ((:free (env) (svex-eval x env)) (svex-vars x)) :do-not-induct t) (witness :ruleset svex-env-reasoning) (witness :ruleset svex-env-reasoning) (set-reasoning) (and stable-under-simplificationp '(:in-theory (enable svex-env-lookup))) ;; (and stable-under-simplificationp ;; '(:use ((:instance svex-argmasks-okp-necc ;; (mask (svex-mask-lookup x masks)) ;; (argmasks (svex-argmasks-lookup ;; (svex-call->args x) masks)) ;; (env env1) ;; (vals (svexlist-eval (svex-call->args x) env2)))))) ) :flag expr) (defthm svexlist-eval-of-mask-equiv-on-vars-envs (implies (and (svex-mask-alist-complete masks) (svex-envs-mask-equiv-on-vars vars masks env1 env2) (subsetp-equal (intersection-equal (svexlist-vars x) (union-equal (alist-keys (svex-env-fix env1)) (alist-keys (svex-env-fix env2)))) (svarlist-fix vars))) (equal (equal (4veclist-mask (svex-argmasks-lookup x masks) (svexlist-eval x env1)) (4veclist-mask (svex-argmasks-lookup x masks) (svexlist-eval x env2))) t)) :hints ('(:expand ((:free (env) (svexlist-eval x env)) (svexlist-vars x) (svex-argmasks-lookup x masks)))) :flag list)) ) (local (defthm hons-assoc-equal-of-append (equal (hons-assoc-equal k (append a b)) (or (hons-assoc-equal k a) (hons-assoc-equal k b))))) (defthm aig-list->s-of-append-when-first-superset (implies (and (nat-bool-listp x) (subsetp (nat-bool-list-nats x) (alist-keys env))) (equal (aig-list->s x (append env rest)) (aig-list->s x env))) :hints(("Goal" :in-theory (e/d* (aig-list->s nat-bool-listp nat-bool-list-nats gl::scdr gl::s-endp) ((:rules-of-class :type-prescription :here))) :induct (aig-list->s x env) :expand ((:free (env) (aig-list->s x env)))))) (defthm a4vec-eval-of-append-when-first-superset (implies (and (nat-bool-a4vec-p x) (subsetp (nat-bool-a4vec-vars x) (alist-keys env))) (equal (a4vec-eval x (append env rest)) (a4vec-eval x env))) :hints(("Goal" :in-theory (enable a4vec-eval nat-bool-a4vec-p nat-bool-a4vec-vars)))) (defthm aig-list->s-of-append-when-first-not-intersect (implies (and (nat-bool-listp x) (not (intersectp (nat-bool-list-nats x) (alist-keys prev)))) (equal (aig-list->s x (append prev env)) (aig-list->s x env))) :hints(("Goal" :in-theory (e/d* (aig-list->s nat-bool-listp nat-bool-list-nats gl::scdr gl::s-endp) ((:rules-of-class :type-prescription :here))) :induct (aig-list->s x env) :expand ((:free (env) (aig-list->s x env)))))) (defthm a4vec-eval-of-append-when-first-not-intersect (implies (and (nat-bool-a4vec-p x) (not (intersectp (nat-bool-a4vec-vars x) (alist-keys prev)))) (equal (a4vec-eval x (append prev env)) (a4vec-eval x env))) :hints(("Goal" :in-theory (enable a4vec-eval nat-bool-a4vec-p nat-bool-a4vec-vars)))) (defthm nat-bool-a4vec-p-of-nat-bool-a4env (implies (and (nat-bool-a4env-p x) (hons-assoc-equal k x)) (nat-bool-a4vec-p (cdr (hons-assoc-equal k x)))) :hints(("Goal" :in-theory (enable nat-bool-a4env-p)))) ;; (define svex-env-lookup-nofix (x env) ;; (or (cdr (hons-get x env)) (4vec-x)) ;; /// ;; (defthm svex-env-lookup-nofix-when-right-types ;; (implies (and (svar-p x) ;; (svex-env-p env)) ;; (equal (svex-env-lookup-nofix x env) ;; (svex-env-lookup x env))) ;; :hints(("Goal" :in-theory (enable svex-env-lookup ;; svex-env-p)))) ;; ;; (local (defthm lookup-in-svex-env-fix-when-svar-p ;; ;; (implies (and (svar-p x) ;; ;; (not (cdr (hons-assoc-equal x env)))) ;; ;; (4vec-equiv (cdr (hons-assoc-equal x (svex-env-fix env))) ;; ;; (4vec-x))) ;; ;; :hints(("Goal" :in-theory (enable svex-env-fix))))) ;; (defthm svex-env-lookup-nofix-when-right-types-weak ;; (implies (svar-p x) ;; (4vec-equiv (svex-env-lookup-nofix x env) ;; (svex-env-lookup x env))) ;; :hints(("Goal" :in-theory (enable svex-env-lookup svex-env-fix))))) (define svex-mask-alist-extract-vars ((x svex-mask-alist-p)) :returns (new-x svex-mask-alist-p) :hooks nil (if (atom x) nil (if (and (mbt (svex-p (caar x))) (eq (svex-kind (caar x)) :var)) (hons-acons (caar x) (4vmask-fix (cdar x)) (svex-mask-alist-extract-vars (cdr x))) (svex-mask-alist-extract-vars (cdr x)))) /// (defret lookup-in-svex-mask-alist-extract-vars (equal (hons-assoc-equal s new-x) (and (svex-p s) (equal (svex-kind s) :var) (hons-assoc-equal s (svex-mask-alist-fix x))))) (local (defthm assoc-in-svex-mask-alist-p (implies (svex-mask-alist-p x) (equal (assoc k x) (hons-assoc-equal k x))) :hints(("Goal" :in-theory (enable svex-mask-alist-p))))) (defret svex-mask-lookup-in-svex-mask-alist-extract-vars (equal (svex-mask-lookup s new-x) (if (equal (svex-kind s) :var) (svex-mask-lookup s x) 0)) :hints(("Goal" :in-theory (enable svex-mask-lookup)))) (defret svex-maskbits-ok-of-svex-mask-alist-extract-vars (iff (svex-maskbits-ok vars new-x) (svex-maskbits-ok vars x)) :hints(("Goal" :in-theory (enable svex-maskbits-ok) :induct (svex-maskbits-ok vars x) :do-not-induct t))) (defret svex-maskbits-for-vars-of-svex-mask-alist-extract-vars (equal (svex-maskbits-for-vars vars new-x boolmasks) (svex-maskbits-for-vars vars x boolmasks)) :hints(("Goal" :in-theory (e/d (svex-maskbits-for-vars) (svex-mask-alist-extract-vars))))) (deffixequiv svex-mask-alist-extract-vars :hints(("Goal" :in-theory (enable svex-mask-alist-fix))))) (define svex-varmasks/env->aig-env-rec ((vars svarlist-p) (masks svex-mask-alist-p) (boolmasks svar-boolmasks-p) (env svex-env-p "look up variables in env to get 4vecs to assign -- symbolic") (nextvar natp) (acc "aig environment accumulator")) :prepwork ((local (in-theory (enable svarlist-p svarlist-fix)))) :returns (mv (err "some mask was negative" (implies (svex-mask-alist-p masks) (iff err (not (svex-maskbits-ok vars masks)))) :hints(("Goal" :in-theory (enable svex-maskbits-ok)))) (env) ;; binds AIG vars to Boolean values (nextvar1 (implies (and (svex-mask-alist-p masks) (svar-boolmasks-p boolmasks)) (equal nextvar1 (+ (nfix nextvar) (svex-maskbits-for-vars vars masks boolmasks)))) :hints(("Goal" :in-theory (enable svex-maskbits-for-vars))))) ;; :hooks ((:fix :args (vars nextvar))) (b* (((when (atom vars)) (mv nil acc (lnfix nextvar))) (mask (svex-mask-lookup (svex-var (car vars)) masks)) ((when (sparseint-< mask 0)) (mv (msg "Negative mask: ~x0~%" (svar-fix (car vars))) acc (lnfix nextvar))) (boolmask (svar-boolmasks-lookup (car vars) boolmasks)) (4vec (4vec-fix (svex-env-lookup (svar-fix (car vars)) env))) (env-part (4vmask-to-a4vec-env mask boolmask 4vec nextvar)) (nextvar (+ (lnfix nextvar) (4vmask-to-a4vec-varcount mask boolmask)))) (svex-varmasks/env->aig-env-rec (cdr vars) masks boolmasks env nextvar (append env-part acc))) /// (defthm key-exists-in-svex-varmasks/env->aig-env-rec (implies (and (svex-mask-alist-p masks) (svar-boolmasks-p boolmasks)) (iff (hons-assoc-equal v (mv-nth 1 (svex-varmasks/env->aig-env-rec vars masks boolmasks env nextvar acc))) (or (hons-assoc-equal v acc) (and (natp v) (<= (nfix nextvar) v) (< v (+ (nfix nextvar) (svex-maskbits-for-vars vars masks boolmasks))))))) :hints(("Goal" :in-theory (enable svex-maskbits-for-vars)))) (local (defun-sk svex-varmasks/env->aig-env-accumulator-elim-correct (vars masks boolmasks env nextvar) (forall acc (implies (syntaxp (not (equal acc ''nil))) (equal (mv-nth 1 (svex-varmasks/env->aig-env-rec vars masks boolmasks env nextvar acc)) (append (mv-nth 1 (svex-varmasks/env->aig-env-rec vars masks boolmasks env nextvar nil)) acc)))) :rewrite :direct)) (local (in-theory (disable svex-varmasks/env->aig-env-accumulator-elim-correct))) (local (defthmd svex-varmasks/env->aig-env-accumulator-elim-lemma (svex-varmasks/env->aig-env-accumulator-elim-correct vars masks boolmasks env nextvar) :hints (("goal" :induct (svex-varmasks/env->aig-env-rec vars masks boolmasks env nextvar acc)) (and stable-under-simplificationp `(:expand (,(car (last clause)) (:free (acc) (svex-varmasks/env->aig-env-rec vars masks boolmasks env nextvar acc)))))))) (defthm svex-varmasks/env->aig-env-accumulator-elim (implies (syntaxp (not (equal acc ''nil))) (equal (mv-nth 1 (svex-varmasks/env->aig-env-rec vars masks boolmasks env nextvar acc)) (append (mv-nth 1 (svex-varmasks/env->aig-env-rec vars masks boolmasks env nextvar nil)) acc))) :hints (("goal" :use svex-varmasks/env->aig-env-accumulator-elim-lemma))) (defthm 4vmask-to-a4vec-vars-subset-of-keys (SUBSETP-EQUAL (NAT-BOOL-A4VEC-VARS (4vmask-to-a4vec mask boolmask nextvar)) (ALIST-KEYS (4vmask-to-a4vec-env mask boolmask val nextvar))) :hints ((acl2::set-reasoning))) (defthm member-nat-bool-a4vec-vars-of-lookup-when-upper-bounded (implies (and (nat-bool-a4env-p a4acc) (nat-bool-a4env-upper-boundp nextvar a4acc) (<= (nfix nextvar) k)) (not (member k (nat-bool-a4vec-vars (cdr (hons-assoc-equal v a4acc)))))) :hints(("Goal" :in-theory (enable nat-bool-a4env-p nat-bool-a4env-upper-boundp)))) (defthm 4vmask-to-a4vec-env-vars-not-intersect-when-upper-bounded (implies (and (nat-bool-a4env-p a4acc) (double-rewrite (nat-bool-a4env-upper-boundp nextvar a4acc))) (not (intersectp (nat-bool-a4vec-vars (cdr (hons-assoc-equal v a4acc))) (alist-keys (4vmask-to-a4vec-env mask boolmask val nextvar))))) :hints ((acl2::set-reasoning))) (local (defthm 4vmask-to-a4vec-vars-not-intersect-svex-varmsks/env->aig-env-rec-keys (implies (and (svex-mask-alist-p masks) (svar-boolmasks-p boolmasks)) (NOT (INTERSECTP-EQUAL (NAT-BOOL-A4VEC-VARS (4VMASK-TO-A4VEC mask boolmask NEXTVAR)) (ALIST-KEYS (MV-NTH 1 (SVEX-VARMASKS/ENV->AIG-ENV-REC vars masks BOOLMASKS GOALENV (+ (NFIX NEXTVAR) (4VMASK-TO-A4VEC-VARCOUNT mask boolmask)) NIL)))))) :hints ((set-reasoning)))) (local (defthm not-member-a4vec-vars-lookup-when-not-member-a4env-vars (implies (not (member v (nat-bool-a4env-vars a4env))) (not (member v (nat-bool-a4vec-vars (cdr (hons-assoc-equal v0 a4env)))))) :hints(("Goal" :in-theory (enable nat-bool-a4env-vars))))) (local (defthm 4vmask-to-a4vec-vars-subset-svex-varmsks/env->aig-env-rec-keys-2 (implies (and (svex-mask-alist-p masks) (svar-boolmasks-p boolmasks)) (SUBSETP-EQUAL (NAT-BOOL-A4VEC-VARS (CDR (HONS-ASSOC-EQUAL v0 (MV-NTH 1 (SVEX-VARMASKS->A4ENV-REC vars MASKS BOOLMASKS nextvar NIL))))) (ALIST-KEYS (MV-NTH 1 (SVEX-VARMASKS/ENV->AIG-ENV-REC vars (SVEX-MASK-ALIST-EXTRACT-VARS MASKS) BOOLMASKS GOALENV nextvar NIL))))) :hints ((set-reasoning)))) (acl2::defquant svex-env-boolmasks-ok (env boolmasks) (forall v (4vec-boolmaskp (svex-env-lookup v env) (svar-boolmasks-lookup v boolmasks))) :rewrite :direct) (local (defthm svex-env-lookup-of-cons (equal (svex-env-lookup k (cons (cons k0 v0) rest)) (if (and (svar-p k0) (equal (svar-fix k) k0)) (4vec-fix v0) (svex-env-lookup k rest))) :hints(("Goal" :in-theory (enable svex-env-lookup svex-env-fix))))) (local (in-theory (enable svex-env-boolmasks-ok-necc svex-varmasks->a4env-rec-accumulator-elim))) (defthm eval-svex-varmasks->a4env-rec-with-env (b* (((mv err a4env ?nextvar1) ;; Assigns AIG variable numbers to each SVEX var. Ignores goalenv (does ;; not need to know anything about the values of the svex vars to do ;; this, just their caremasks/boolmasks). (svex-varmasks->a4env-rec vars masks boolmasks nextvar nil)) ((mv ?err1 env ?nextvar1) ;; Binds AIG variable numbers to (symbolic) bits extracted from the goalenv. (svex-varmasks/env->aig-env-rec vars (svex-mask-alist-extract-vars masks) boolmasks goalenv nextvar nil))) (implies (and (not err) ;; (nat-bool-a4env-p a4acc) ;; (nat-bool-a4env-upper-boundp nextvar a4acc) (svex-mask-alist-p masks) (svar-boolmasks-p boolmasks) (svex-env-boolmasks-ok goalenv boolmasks) ;; (svex-env-p goalenv) ;; (svex-envs-masks-partly-equiv ;; vars masks ;; (svex-a4vec-env-eval a4acc envacc) ;; goalenv) ;; (subsetp (alist-keys (svex-env-fix goalenv)) ;; (append (svarlist-fix vars) ;; (alist-keys (svex-a4vec-env-fix a4acc)))) ) (svex-envs-mask-equiv-on-vars vars masks (svex-a4vec-env-eval a4env env) goalenv))) :hints(("Goal" :in-theory (enable svex-varmasks->a4env-rec svarlist-fix svex-maskbits-ok nat-bool-a4env-p nat-bool-a4env-upper-boundp svex-a4vec-env-fix svex-a4vec-env-eval alist-keys svex-alist-keys) :induct (svex-varmasks->a4env-rec vars masks boolmasks nextvar nil) ;; (svex-varmasks->a4env-rec-induct ;; vars masks boolmasks nextvar a4acc goalenv envacc) :expand ((:free (a4acc) (svex-varmasks->a4env-rec vars masks boolmasks nextvar a4acc)) (:free (envacc masks) (svex-varmasks/env->aig-env-rec vars masks boolmasks goalenv nextvar envacc)))) (and stable-under-simplificationp (cond ((assoc 'subsetp-equal clause) ;; has a (not (subsetp-equal... lit (acl2::set-reasoning)) ;; ((assoc 'svex-envs-masks-partly-equiv clause) ;; '(:computed-hint-replacement ;; ((acl2::witness :ruleset (svex-envs-masks-partly-equiv-witnessing)) ;; (acl2::witness :ruleset (svex-envs-masks-partly-equiv-example))) ;; :in-theory (enable ;; svex-env-lookup ;; svex-env-fix))) ;; (t '(:computed-hint-replacement ;; ((acl2::witness :ruleset (svex-envs-mask-equiv-witnessing)) ;; (acl2::witness :ruleset (svex-envs-masks-partly-equiv-example))) ;; :no-op t)) (t '(:computed-hint-replacement ((acl2::witness :ruleset (svex-envs-mask-equiv-on-vars-witnessing)) (acl2::witness :ruleset (svex-envs-mask-equiv-on-vars-example))) :no-op t)) ))))) (define svex-varmasks->a4env ((vars svarlist-p) (masks svex-mask-alist-p) (boolmasks svar-boolmasks-p)) :returns (mv (err "some mask was negative" (iff err (not (svex-maskbits-ok vars masks)))) (a4env nat-bool-a4env-p!)) (b* (((mv err res &) (svex-varmasks->a4env-rec vars masks boolmasks 0 nil))) (mv err res)) /// (defret alist-keys-of-svex-varmasks->a4env (implies (not err) (equal (alist-keys a4env) (rev (svarlist-fix vars)))))) (define svex-varmasks/env->aig-env ((vars svarlist-p) (masks svex-mask-alist-p) (boolmasks svar-boolmasks-p) (env svex-env-p "look up variables in env to get 4vecs to assign")) :returns (mv (err "some mask was negative" (implies (svex-mask-alist-p masks) (iff err (not (svex-maskbits-ok vars masks)))) :hints(("Goal" :in-theory (enable svex-maskbits-ok)))) (env "binds AIG vars to Boolean values")) :hooks ((:fix :args (vars))) (b* (((mv err res &) (svex-varmasks/env->aig-env-rec vars masks boolmasks env 0 nil))) (mv err res)) /// (defthm eval-svex-varmasks->a4env-with-env (b* (((mv err a4env) (svex-varmasks->a4env vars masks boolmasks1)) ((mv ?err1 env) (svex-varmasks/env->aig-env vars (svex-mask-alist-extract-vars masks) boolmasks goalenv))) (implies (and (not err) (svex-mask-alist-p masks) (equal boolmasks (svar-boolmasks-fix boolmasks1)) ;; (svex-env-p goalenv) (svex-env-boolmasks-ok goalenv boolmasks)) (svex-envs-mask-equiv-on-vars vars masks (svex-a4vec-env-eval a4env env) goalenv))) :hints (("goal" :use ((:instance eval-svex-varmasks->a4env-rec-with-env (nextvar 0))) :in-theory (e/d (svex-varmasks->a4env svex-env-lookup svex-lookup) (eval-svex-varmasks->a4env-rec-with-env))) ;; (acl2::witness :ruleset (svex-envs-mask-equiv-on-vars)) ;; (acl2::set-reasoning) ))) (define svexlist-full-masks-p ((x svexlist-p) (masks svex-mask-alist-p)) (if (atom x) t (and (equal -1 (sparseint-val (svex-mask-lookup (car x) masks))) (svexlist-full-masks-p (cdr x) masks))) /// (defthm svexlist-full-masks-p-of-take (implies (and (svexlist-full-masks-p x masks) (<= (nfix n) (len x))) (svexlist-full-masks-p (take n x) masks))) (defthm svexlist-full-masks-p-of-nthcdr (implies (svexlist-full-masks-p x masks) (svexlist-full-masks-p (nthcdr n x) masks))) (defthmd svexlist-full-masks-p-of-svexlist-mask-alist-lemma (implies (subsetp (svexlist-fix y) (svexlist-fix x)) (svexlist-full-masks-p y (svexlist-mask-alist x))) :hints(("Goal" :in-theory (enable subsetp svexlist-fix)))) (defthm svexlist-full-masks-p-of-svexlist-mask-alist (svexlist-full-masks-p x (svexlist-mask-alist x)) :hints(("Goal" :in-theory (enable svexlist-full-masks-p-of-svexlist-mask-alist-lemma)))) (local (defun cdr2 (x y) (if (atom x) y (cdr2 (Cdr x) (cdr y))))) (defthm 4veclist-mask-when-full-masksp (implies (and (svexlist-full-masks-p x masks) (equal (len 4vecs) (len x))) (equal (4veclist-mask (svex-argmasks-lookup x masks) 4vecs) (4veclist-fix 4vecs))) :hints(("Goal" :in-theory (enable 4veclist-mask svex-argmasks-lookup 4veclist-fix 4vec-mask) :induct (cdr2 x 4vecs))))) (defsection general-correctness-theorems (local (defthm subsetp-intersection (subsetp (intersection$ x y) y) :hints ((set-reasoning)))) (defthm svexlist->a4vec-correct-for-varmasks-aig-env (b* (((mv err a4env) (svex-varmasks->a4env vars masks boolmasks1)) ((mv ?err1 env) (svex-varmasks/env->aig-env vars (svex-mask-alist-extract-vars masks) boolmasks goalenv)) (a4vecs (svexlist->a4vec x a4env masks))) (implies (and (not err) (svex-mask-alist-p masks) (svex-mask-alist-complete masks) (equal boolmasks (svar-boolmasks-fix boolmasks1)) (svex-env-boolmasks-ok goalenv boolmasks) (subsetp (intersection-equal (svexlist-vars x) (alist-keys (svex-env-fix goalenv))) (svarlist-fix vars))) (equal (4veclist-mask (svex-argmasks-lookup x masks) (a4veclist-eval a4vecs env)) (4veclist-mask (svex-argmasks-lookup x masks) (svexlist-eval x goalenv))))) :hints (("goal" :use ((:instance svexlist-eval-of-mask-equiv-on-vars-envs (env2 goalenv) (env1 (svex-a4vec-env-eval (mv-nth 1 (svex-varmasks->a4env vars masks boolmasks)) (mv-nth 1 (svex-varmasks/env->aig-env vars (svex-mask-alist-extract-vars masks) boolmasks goalenv)))))) :in-theory (disable svexlist-eval-of-mask-equiv-on-vars-envs)))) (defthm svexlist->a4vec-correct-for-varmasks-aig-env-top (b* (((mv err a4env) (svex-varmasks->a4env vars masks boolmasks1)) ((mv ?err1 env) (svex-varmasks/env->aig-env vars (svex-mask-alist-extract-vars masks) boolmasks goalenv)) (a4vecs (svexlist->a4vec x a4env masks))) (implies (and (not err) (svexlist-full-masks-p x masks) (svex-mask-alist-p masks) (svex-mask-alist-complete masks) (equal boolmasks (svar-boolmasks-fix boolmasks1)) (svex-env-boolmasks-ok goalenv boolmasks) (subsetp (intersection-equal (svexlist-vars x) (alist-keys (svex-env-fix goalenv))) (svarlist-fix vars))) (equal (a4veclist-eval a4vecs env) (svexlist-eval x goalenv)))) :hints (("goal" :use svexlist->a4vec-correct-for-varmasks-aig-env :in-theory (disable svexlist->a4vec-correct-for-varmasks-aig-env))))) (define svex-env-check-boolmasks ((boolmasks svar-boolmasks-p) (env svex-env-p)) :prepwork ((local (in-theory (enable svar-boolmasks-p svar-boolmasks-fix)))) ;; :hooks nil (b* (((when (atom boolmasks)) t) ((unless (mbt (svar-p (caar boolmasks)))) (svex-env-check-boolmasks (cdr boolmasks) env)) ((cons var mask) (car boolmasks)) (val (svex-env-lookup var env)) (ok (4vec-boolmaskp val mask)) (?ign (and (not ok) (cw "not 4vec-boolmaskp: ~x0~%" var)))) (and (svex-env-check-boolmasks (cdr boolmasks) env) ok)) /// (acl2::defexample svex-env-boolmasks-ok-example :pattern (svex-env-lookup v env) :templates (v) :instance-rulename svex-env-boolmasks-ok-instancing) (defthm svex-env-check-boolmasks-correct (implies (and (svex-env-check-boolmasks boolmasks env) ;; (svex-env-p env) (svar-boolmasks-p boolmasks)) (svex-env-boolmasks-ok env boolmasks)) :hints (("goal" :induct (svex-env-check-boolmasks boolmasks env)) (acl2::witness :ruleset (svex-env-boolmasks-ok-witnessing svex-env-boolmasks-ok-example)) (and stable-under-simplificationp '(:in-theory (enable svar-boolmasks-lookup) :expand ((:free (x) (4vec-boolmaskp x 0)))))))) (define svexlist-mask-alist-memo ((x svexlist-p)) :enabled t (svexlist-mask-alist x) /// (memoize 'svexlist-mask-alist-memo)) (define svexlist-vars-memo ((x svexlist-p)) :enabled t (svexlist-collect-vars x) /// (memoize 'svexlist-vars-memo)) (define svexlist->a4vecs-for-varlist ((x svexlist-p) (vars svarlist-p) (boolmasks svar-boolmasks-p)) :returns (mv (err (iff err (not (svex-maskbits-ok vars (svexlist-mask-alist x))))) (a4vecs a4veclist-p)) :short "Creates a symbolic bit-level representation for x, assuming that vars are the only vars relevant to x and that the bits of vars given in boolmasks are Boolean-valued." :long "<p>Steps: First creates a symbolic environment mapping the variables to a4vec structures, each bit of which is a free variable. (For bits constrained to be Boolean by boolmasks, the same variable is shared for upper/lower.) Then uses @('svexlist->a4vec-top') to generate a4vecs corresponding to the svexes.</p>" (b* (;; (- (sneaky-push 'svexlist x)) (masks (svexlist-mask-alist-memo x)) ((mv err a4env) (svex-varmasks->a4env vars masks boolmasks)) ((when err) (mv err nil)) (a4env (make-fast-alist a4env)) (res (svexlist->a4vec-top x a4env masks)) (?ign (fast-alist-free a4env))) (mv nil res)) /// (memoize 'svexlist->a4vecs-for-varlist)) (define svexlist-variable-mask-alist ((x svexlist-p)) ;; We've seen problems in GL where we get a stack overflow in ;; gobject-hierarchy-lite traversing the full masks inside ;; svexlist->a4vec-aig-env-for-varlist. But we don't need the full set of ;; masks there, only those for the variables. So to work around this ;; problem, this function extracts only the variables from the mask alist, ;; producing a much smaller alist. :returns (varmasks svex-mask-alist-p) :enabled t (b* ((masks-full (svexlist-mask-alist-memo x))) (svex-mask-alist-extract-vars masks-full)) /// (memoize 'svexlist-variable-mask-alist)) (define svexlist->a4vec-aig-env-for-varlist ((x svexlist-p) (vars svarlist-p) (boolmasks svar-boolmasks-p) (env svex-env-p)) :returns (mv (err (iff err (not (svex-maskbits-ok vars (svexlist-mask-alist x))))) (aig-env)) :hooks ((:fix :args (x vars))) ;; We use svexlist-variable-mask-alist here rather than ;; svexlist-mask-alist-memo so that GL won't have to traverse the full mask ;; alist with gobject-hierarchy-lite, which we've seen cause stack overflows. (b* ((masks (svexlist-variable-mask-alist x))) (svex-varmasks/env->aig-env vars masks boolmasks env)) /// ;; (local (defthm svex-envs-mask-equiv-lemma ;; (iff (svex-envs-mask-equiv ;; (svexlist-mask-alist x) y z) ;; (svex-envs-mask-equiv ;; (svexlist-variable-mask-alist x) y z)) ;; :hints ((witness)))) ;; This is directly proved by svexlist->a4vec-top-correct-for-varmasks-aig-env-top (defthm svexlist->a4vec-for-varlist-correct (b* (((mv err a4vecs) (svexlist->a4vecs-for-varlist x vars boolmasks)) ((mv ?err1 aig-env) (svexlist->a4vec-aig-env-for-varlist x vars boolmasks env))) (implies (and (not err) ;; (svex-env-p env) (svar-boolmasks-p boolmasks) (svex-env-boolmasks-ok env boolmasks) (subsetp (intersection-equal (svexlist-vars x) (alist-keys (svex-env-fix env))) (svarlist-fix vars))) (equal (a4veclist-eval a4vecs aig-env) (svexlist-eval x env)))) :hints(("Goal" :in-theory (e/d (svexlist->a4vecs-for-varlist) (svexlist-eval-of-mask-equiv-on-vars-envs)))) :otf-flg t)) (local (defthm subset-of-mergesorts-is-subsetp (iff (subset (mergesort a) (mergesort b)) (subsetp a b)) :hints(("Goal" :in-theory (enable* set::definitions))))) (define svexlist-rewrite-fixpoint-memo ((x svexlist-p)) :enabled t (time$ (svexlist-rewrite-fixpoint x :verbosep t :count 2) :msg "; svex rewriting: ~st sec, ~sa bytes.~%") /// (memoize 'svexlist-rewrite-fixpoint-memo)) (define maybe-svexlist-rewrite-fixpoint ((x svexlist-p) (do-it)) :returns (new-x svexlist-p) (if do-it (svexlist-rewrite-fixpoint-memo x) (hons-copy (svexlist-fix x))) /// (defret maybe-svexlist-rewrite-fixpoint-correct (equal (svexlist-eval new-x env) (svexlist-eval x env))) (defret maybe-svexlist-rewrite-fixpoint-len (equal (len new-x) (len x))) (defret vars-of-maybe-svexlist-rewrite-fixpoint (implies (not (member v (svexlist-vars x))) (not (member v (svexlist-vars new-x)))))) (local (defthm svarlist-p-of-alist-keys-when-svex-env-p (implies (svex-env-p env) (svarlist-p (alist-keys env))) :hints(("Goal" :in-theory (enable svex-env-p svarlist-p alist-keys))))) (define svexlist-vars-for-symbolic-eval ((x svexlist-p) (env svex-env-p) (symbolic-params alistp)) :returns (vars svarlist-p) :guard-hints (("goal" :in-theory (e/d (SET::UNION-WITH-SUBSET-LEFT double-containment set::subset-to-subsetp) (SUBSET-OF-MERGESORTS-IS-SUBSETP)))) (b* ((allvars (assoc :allvars symbolic-params)) (vars (if allvars (svexlist-vars-memo x) (ec-call (svarlist-fix (cdr (assoc :vars symbolic-params)))))) (svars (mbe :logic (set::mergesort vars) :exec (if (set::setp vars) vars (set::mergesort vars)))) ((when allvars) (hons-copy svars)) (keys (svarlist-filter (alist-keys env))) (keys (mbe :logic (set::mergesort keys) :exec (if (set::setp keys) keys (set::mergesort keys))))) (hons-copy (mbe :logic (union keys svars) :exec (if (set::subset keys svars) svars (if (eq svars nil) keys (union keys svars)))))) /// (local (defthm alist-keys-of-svex-env-fix (equal (alist-keys (svex-env-fix env)) (svarlist-filter (alist-keys env))) :hints(("Goal" :in-theory (enable svex-env-fix svarlist-filter))))) (defret svexlist-vars-for-symbolic-eval-sufficient (subsetp (intersection-equal (svexlist-vars x) (alist-keys (svex-env-fix env))) vars) :hints ((set-reasoning))) (defret member-of-svexlist-vars-for-symbolic-eval (implies (and (member v (svexlist-vars x)) (hons-assoc-equal v (svex-env-fix env))) (member v vars)) :hints (("goal" :use svexlist-vars-for-symbolic-eval-sufficient :in-theory (disable svexlist-vars-for-symbolic-eval-sufficient svexlist-vars-for-symbolic-eval alist-keys-of-svex-env-fix)) (set-reasoning)))) (defines svex-fastsubst :verify-guards nil (define svex-fastsubst :parents (svex-subst) :short "Substitution for @(see svex)es, identical to @(see svex-subst), except that we memoize the results and we use fast alist lookups." ((pat svex-p) (al svex-alist-p)) :returns (x (equal x (svex-subst pat al)) :hints ((and stable-under-simplificationp '(:expand ((svex-subst pat al)))))) :measure (svex-count pat) (svex-case pat :var (or (svex-fastlookup pat.name al) (svex-quote (4vec-x))) :quote (svex-fix pat) :call (svex-call pat.fn (svexlist-fastsubst pat.args al)))) (define svexlist-fastsubst ((pat svexlist-p) (al svex-alist-p)) :returns (x (equal x (svexlist-subst pat al)) :hints ((and stable-under-simplificationp '(:expand ((svexlist-subst pat al)))))) :measure (svexlist-count pat) (if (atom pat) nil (cons (svex-fastsubst (car pat) al) (svexlist-fastsubst (cdr pat) al)))) /// (verify-guards svex-fastsubst) (memoize 'svex-fastsubst :condition '(eq (svex-kind pat) :call))) (define svexlist-x-out-unused-vars ((x svexlist-p) (svars svarlist-p) (do-it)) :returns (new-x svexlist-p) (if do-it (b* ((subst (make-fast-alist (pairlis$ (svarlist-fix svars) (svarlist-svex-vars svars)))) (ans (svexlist-fastsubst x subst))) (clear-memoize-table 'svex-fastsubst) (fast-alist-free subst) ans) (svexlist-fix x)) /// (defthm svex-alist-eval-of-svarlist-svex-vars (equal (svex-alist-eval (pairlis$ (svarlist-fix svars) (svarlist-svex-vars svars)) env) (svex-env-extract svars env)) :hints(("Goal" :in-theory (enable svex-env-extract svex-alist-eval svarlist-fix svarlist-svex-vars) :induct (len svars) :expand ((:free (x) (svex-eval (svex-var x) env)))))) (defthm-svex-eval-flag (defthm svex-eval-of-svex-env-extract-when-intersection-subset (implies (subsetp (intersection$ (svex-vars x) (alist-keys (svex-env-fix env))) (svarlist-fix svars)) (equal (svex-eval x (svex-env-extract svars env)) (svex-eval x env))) :hints ('(:expand ((:free (env) (svex-eval x env)) (svex-vars x))) (and stable-under-simplificationp '(:in-theory (enable svex-env-lookup) :expand ((:free (x y) (subsetp-equal (list x) y)) (:free (x y) (intersection-equal (list x) y)))))) :flag expr) (defthm svexlist-eval-of-svex-env-extract-when-intersection-subset (implies (subsetp (intersection$ (svexlist-vars x) (alist-keys (svex-env-fix env))) (svarlist-fix svars)) (equal (svexlist-eval x (svex-env-extract svars env)) (svexlist-eval x env))) :hints ('(:expand ((:free (env) (svexlist-eval x env)) (svexlist-vars x)))) :flag list)) (defret svex-eval-of-svexlist-x-out-unused-vars (implies (subsetp (intersection-equal (svexlist-vars x) (alist-keys (svex-env-fix env))) (svarlist-fix svars)) (equal (svexlist-eval new-x env) (svexlist-eval x env)))) (local (defthm hons-assoc-equal-of-pair-svex-vars (equal (hons-assoc-equal v (pairlis$ (svarlist-fix vars1) (svarlist-svex-vars vars1))) (and (member v (svarlist-fix vars1)) (cons v (svex-var (svar-fix v))))) :hints(("Goal" :in-theory (enable hons-assoc-equal pairlis$ svarlist-svex-vars svarlist-fix))))) (local (defthm svex-lookup-of-pair-svex-vars (implies (equal vars (svarlist-fix vars1)) (equal (svex-lookup v (pairlis$ vars (svarlist-svex-vars vars1))) (and (member (svar-fix v) vars) (svex-var (svar-fix v))))) :hints(("Goal" :in-theory (enable svex-lookup))))) (local (defthm-svex-eval-flag (defthm vars-of-svex-subst-lemma (implies (and (not (member v (svex-vars x))) (equal vars (svarlist-fix vars1))) (not (member v (svex-vars (svex-subst x (pairlis$ vars (svarlist-svex-vars vars1))))))) :flag expr :hints ('(:expand ((:free (al) (svex-subst x al)))))) (defthm vars-of-svexlist-subst-lemma (implies (and (not (member v (svexlist-vars x))) (equal vars (svarlist-fix vars1))) (not (member v (svexlist-vars (svexlist-subst x (pairlis$ vars (svarlist-svex-vars vars1))))))) :flag list :hints ('(:expand ((:free (al) (svexlist-subst x al)))))))) (defret svex-vars-of-svexlist-x-out-unused-vars (implies (not (member v (svexlist-vars x))) (not (member v (svexlist-vars new-x))))) (local (defthm len-of-svexlist-subst (equal (len (svexlist-subst x subst)) (len x)) :hints (("goal" :induct (len x) :in-theory (enable svexlist-subst))))) (defret len-of-<fn> (equal (len new-x) (len x)))) (define symbolic-params-x-out-cond ((symbolic-params alistp)) ;; Only makes sense to x out unused variables if ;; - we're simplifying, so they'll get constant propagated, and ;; - we're not using all vars, so there will be some substitutions. (and (cdr (assoc :simplify symbolic-params)) (not (cdr (assoc :all-vars symbolic-params))))) (define svexlist-eval-gl ((x svexlist-p "Svex expressions to evaluate.") (env svex-env-p "Bindings of variables to @(see 4vec) values.") (symbolic-params alistp "Alist giving symbolic execution parameters; see below.")) :short "Equivalent of svexlist-eval intended to work well under GL symbolic execution." :long " <p>This function is provably equivalent to @(see svexlist-eval), but is tailored to perform well under symbolic execution. For symbolic execution, we assume that the inputs to this function other than @('env') are fully concrete, and that @('env') is symbolic only in its values, not its keys or its shape.</p> <p>The @('symbolic-params') input is logically irrelevant, but allows important optimizations for symbolic execution performance, discussed further below. It is safe (but not necessarily optimal) to call this with symbolic-params equal @('NIL').</p> <h4>Behavior under Symbolic Execution</h4> <ol> <li>Applies rewriting to the supplied svex expressions, if @(':SIMPLIFY') is bound to a non-nil value in the @('symbolic-params') input -- see @(see svexlist-rewrite-fixpoint).</li> <li>If @(':boolmasks') is bound in the symbolic-params, compares the given @('env') with the bound value, which should be an alist. If there is a pair @('(name . mask)') in the boolmasks alist for which the binding for @('name') in env is not Boolean-valued on the bits set to 1 in @('mask'), then fail out of symbolic simulation. (In AIG mode, the masked bits must be <i>syntactically</i> Boolean-valued -- practically speaking, this means the upper/lower parts should result from the same computation.)</li> <li>If @(':VARS') is bound in symbolic-params, it should be bound to a list of input variables of the SVTV. Unions this list with the variables bound in @('env') to obtain the full list of variables to bind as inputs to the SVTV. Or if @(':ALLVARS') is bound in symbolic params, all the variables in the svex expressions are used instead.</li> <li>Compiles the svex list @('x') into @(see a4vec) objects, a symbolic analogue of @(see 4vec) but with each bit an AIG -- see @(see svexlist->a4vecs-for-varlist). This computation uses the assumptions, checked in the two steps above, that only the variables in @('vars') are non-X, and that the masked bits in @('boolmasks') are Boolean-valued. These assumptions can reduce the complexity of the generated AIGs. (Note everything used in this computation is concrete -- the @('env') isn't involved.)</li> <li>Creates an alist binding the AIG variables used in the above step to the appropriate symbolic bits from @('env').</li> <li>Symbolically evaluates each of the a4vec objects from step 4 under the bindings from step 5 using GL's symbolic simulator of @(see acl2::aig-eval). This results in GL-native symbolic 4vec objects, which is the result we want.</li> </ol> <h4>Optimization using the Extra Arguments</h4> <p>Performance of symbolic execution (and SAT solving, when in AIG mode) is related to the size of the AIGs produced by the svex to AIG transformation (step 4, above). Two ways to decrease that size are (1) to turn certain variables into constant Xes, if it is known that they're irrelevant, and (2) to assume certain bits of some variables are Boolean-valued, which means it can be represented by just one AIG variable rather than two.</p> <p>Another performance consideration is that the transformation to AIGs is itself sometimes significant. Especially for theorems proved by case-splitting, it is important not to need to repeat this transformation for each case. The function that does the transformation is memoized, but it is important in this case that it always be called with the same arguments.</p> <p>The @('vars') list pertains to optimization (1): if not present in the list, a variable in the svex expressions will just be replaced with an X. Therefore, in general it's best to use exactly the set of variables bound in the environment. However, it may not be worth it to redo the AIG conversion each time the environment's bound variables changes, so we take @('vars') separately.</p> <p>The @('boolmasks') allows optimization (2). It is best for symbolic execution performance to bind every variable in @('vars') to -1, but this may fail if the @('env') is not constructed in such a way that the values are obviously 2-vectors.</p>" :guard-hints (("goal" :in-theory (e/d (SET::UNION-WITH-SUBSET-LEFT) (SUBSET-OF-MERGESORTS-IS-SUBSETP)))) (b* ((env (make-fast-alist (svex-env-fix env))) (svars (svexlist-vars-for-symbolic-eval x env symbolic-params)) (x (svexlist-x-out-unused-vars x svars (symbolic-params-x-out-cond symbolic-params))) (x (maybe-svexlist-rewrite-fixpoint x (cdr (assoc :simplify symbolic-params)))) (boolmasks (make-fast-alist (hons-copy (ec-call (svar-boolmasks-fix (cdr (assoc :boolmasks symbolic-params))))))) ((unless (svex-env-check-boolmasks boolmasks env)) (b* ((?ign (cw "ERROR: some bits assumed to be Boolean were not~%")) (?ign (gl::gl-error 'boolcheck-failed))) (gl::gl-hide (svexlist-eval x env)))) ;; (?ign (cw "Boolmasks: ~x0~%" boolmasks)) ;; (?ign (bitops::sneaky-push 'boolmasks boolmasks)) ;; (?ign (bitops::sneaky-push 'vars vars)) ;; (?ign (bitops::sneaky-push 'x x)) ((mv err a4vecs) (time$ (svexlist->a4vecs-for-varlist x svars boolmasks) :msg "; svex->aigs: ~st sec, ~sa bytes.~%")) ((when err) (b* ((?ign (cw "ERROR gathering AIG bits for variables: ~@0~%" err)) (?ign (gl::gl-error 'a4env-failed))) (gl::gl-hide (svexlist-eval x env)))) ((mv ?err aig-env) ;; ignore the error; it can't exist if the above doesn't (time$ (svexlist->a4vec-aig-env-for-varlist x svars boolmasks env) :msg "; env -> aig env: ~st sec, ~sa bytes.~%")) (?ign (fast-alist-free env)) (aig-env (make-fast-alist aig-env)) (ans (a4veclist-eval a4vecs aig-env))) (fast-alist-free aig-env) ans) /// (defthm svexlist-eval-gl-is-svexlist-eval (equal (svexlist-eval-gl x env symbolic-params) (svexlist-eval x env)) :hints (("goal" :use ((:instance svexlist->a4vec-for-varlist-correct (boolmasks (svar-boolmasks-fix (cdr (assoc :boolmasks symbolic-params)))) (vars (svexlist-vars-for-symbolic-eval x env symbolic-params)) (x (maybe-svexlist-rewrite-fixpoint (svexlist-x-out-unused-vars x (svexlist-vars-for-symbolic-eval x env symbolic-params) (symbolic-params-x-out-cond symbolic-params)) (cdr (assoc :simplify symbolic-params)))) (env (svex-env-fix env)))) :in-theory (disable svexlist->a4vec-for-varlist-correct SVEXLIST->A4VECS-FOR-VARLIST-SVAR-BOOLMASKS-EQUIV-CONGRUENCE-ON-BOOLMASKS)) (set-reasoning) (and stable-under-simplificationp '(:cases ((member acl2::k0 (svexlist-vars x))))))) (gl::def-gl-rewrite svexlist-eval-for-symbolic-redef (equal (svexlist-eval-for-symbolic x env symbolic-params) (svexlist-eval-gl x env symbolic-params)))) ;;; Now rework a4veclist-eval to phrase it in terms of a single call to aig-eval-list (define a4vec->aiglist ((x a4vec-p)) :returns (lst true-listp :rule-classes :type-prescription) (b* (((a4vec x) x)) (append x.upper x.lower))) ;; (define v2i-alt ((v true-listp)) ;; :returns (v2i (equal v2i (gl::v2i v)) ;; :hints(("Goal" :in-theory (enable gl::scdr gl::s-endp)))) ;; :hooks nil ;; (if (atom (cdr v)) ;; (gl::bool->sign (car v)) ;; (logcons (acl2::bool->bit (car v)) ;; (v2i-alt (cdr v))))) (local (defthm v2i-of-aig-eval-list (equal (gl::v2i (aig-eval-list x env)) (aig-list->s x env)) :hints(("Goal" :in-theory (enable (:i aig-list->s) gl::v2i gl::scdr gl::s-endp) :induct (aig-list->s x env) :expand ((aig-list->s x env) (aig-eval-list x env) (:free (A b) (gl::v2i (cons a b)))))))) (define v2i-first-n ((n natp) (v true-listp)) :returns (v2i (equal v2i (gl::v2i (take n v))) :hints(("Goal" :in-theory (e/d (acl2::take) (acl2::take-of-too-many)) :induct t))) :prepwork ((local (defthm v2i-of-singleton (equal (gl::v2i (list x)) (gl::bool->sign x)) :hints(("Goal" :in-theory (enable gl::s-endp gl::v2i))))) (local (defthm v2i-of-cons (implies (consp y) (equal (gl::v2i (cons x y)) (logapp 1 (bool->bit x) (gl::v2i y)))) :hints(("Goal" :in-theory (enable gl::v2i logapp** gl::s-endp gl::scdr)))))) (cond ((zp n) (gl::bool->sign nil)) ((eql n 1) (gl::bool->sign (car v))) (t (logapp 1 (acl2::bool->bit (car v)) (v2i-first-n (1- n) (cdr v)))))) (define 4vec-from-bitlist ((upper-len natp) (lower-len natp) (bits true-listp)) :hooks ((:fix :omit (bits))) :returns (mv (vec 4vec-p) (rest true-listp :hyp (true-listp bits) :rule-classes :type-prescription)) ;; note: list-fixing bits is bad here because it's not even linear in the ;; number of bits we're operating on (b* ((upper (v2i-first-n upper-len bits)) (rest (nthcdr upper-len bits)) (lower (v2i-first-n lower-len rest)) (rest (nthcdr lower-len rest))) (mv (4vec upper lower) rest)) /// (defthm 4vec-from-bitlist-correct (b* (((a4vec x) x)) (equal (4vec-from-bitlist (len x.upper) (len x.lower) (append (aig-eval-list (a4vec->aiglist x) env) rest)) (mv (a4vec-eval x env) rest))) :hints(("Goal" :in-theory (enable a4vec->aiglist))))) (define a4veclist->aiglist ((x a4veclist-p)) :returns (aigs true-listp :rule-classes :type-prescription) (if (atom x) nil (append (a4vec->aiglist (car x)) (a4veclist->aiglist (cdr x))))) (define 4veclist-from-bitlist ((origs a4veclist-p) (bits true-listp)) :returns (4vecs 4veclist-p) :hooks ((:fix :omit (bits))) (b* (((when (atom origs)) nil) ((a4vec x) (car origs)) ((mv first restbits) (4vec-from-bitlist (len x.upper) (len x.lower) bits))) (cons first (4veclist-from-bitlist (cdr origs) restbits))) /// (defthm 4veclist-from-bitlist-correct (equal (4veclist-from-bitlist x (aig-eval-list (a4veclist->aiglist x) env)) (a4veclist-eval x env)) :hints(("Goal" :in-theory (enable a4veclist-eval a4veclist->aiglist))))) (define a4veclist-eval-gl ((x a4veclist-p) (env)) :returns (res 4veclist-p) (b* ((aiglist (time$ (a4veclist->aiglist x) :msg "; SV bit-blasting: a4veclist->aiglist: ~st sec, ~sa bytes.~%")) (bitlist (time$ (aig-eval-list aiglist env) :msg "; SV bit-blasting: aig-eval-list: ~st sec, ~sa bytes.~%"))) (time$ (4veclist-from-bitlist x bitlist) :msg "; bits->4vecs: ~st sec, ~sa bytes.~%")) /// (defthm a4veclist-eval-gl-correct (equal (a4veclist-eval-gl x env) (a4veclist-eval x env))) (gl::def-gl-rewrite a4veclist-eval-redef (equal (a4veclist-eval x env) (a4veclist-eval-gl x env)))) (gl::def-gl-rewrite svex-alist-eval-gl-rewrite (equal (svex-alist-eval x env) (pairlis$ (svex-alist-keys x) (svexlist-eval-for-symbolic (svex-alist-vals x) env nil))) :hints(("Goal" :in-theory (enable svex-alist-eval pairlis$ svex-alist-keys svex-alist-vals svexlist-eval)))) (gl::def-gl-rewrite svex-eval-gl-rewrite (equal (svex-eval x env) (car (svexlist-eval-for-symbolic (list x) env nil)))) (define svex-envlist-keyset ((x svex-envlist-p)) :returns (keys (and (svarlist-p keys) (set::setp keys))) (if (atom x) nil (set::union (set::mergesort (svarlist-filter (alist-keys (car x)))) (svex-envlist-keyset (cdr x)))) /// (local (defthm alist-keys-of-svex-env-fix (equal (alist-keys (svex-env-fix env)) (svarlist-filter (alist-keys env))) :hints(("Goal" :in-theory (enable svex-env-fix svarlist-filter))))) (defret svex-envlist-keyset-sufficient (implies (member env x) (subsetp (alist-keys (svex-env-fix env)) keys)))) (define svexlist/env-list-vars-for-symbolic-eval ((x svexlist-p) (envs svex-envlist-p) (symbolic-params alistp)) :returns (vars svarlist-p) :guard-hints (("goal" :in-theory (e/d (SET::UNION-WITH-SUBSET-LEFT double-containment set::subset-to-subsetp) (SUBSET-OF-MERGESORTS-IS-SUBSETP)))) (b* ((allvars (assoc :allvars symbolic-params)) (vars (if allvars (svexlist-vars-memo x) (ec-call (svarlist-fix (cdr (assoc :vars symbolic-params)))))) (svars (mbe :logic (set::mergesort vars) :exec (if (set::setp vars) vars (set::mergesort vars)))) ((when allvars) (hons-copy svars)) (keys (svex-envlist-keyset envs))) (hons-copy (mbe :logic (union keys svars) :exec (if (set::subset keys svars) svars (if (eq svars nil) keys (union keys svars)))))) /// (defret svexlist/env-list-vars-for-symbolic-eval-sufficient (subsetp (intersection-equal (svexlist-vars x) (svex-envlist-keyset envs)) vars) :hints ((set-reasoning)))) (define svex-envlist-check-boolmasks ((boolmasks svar-boolmasks-p) (envs svex-envlist-p)) (if (atom envs) t (and (svex-env-check-boolmasks boolmasks (make-fast-alist (car envs))) (svex-envlist-check-boolmasks boolmasks (cdr envs)))) /// (defthm svex-envlist-check-boolmasks-correct (implies (and (svex-envlist-check-boolmasks boolmasks envs) (member env envs) ;; (svex-env-p env) (svar-boolmasks-p boolmasks)) (svex-env-boolmasks-ok env boolmasks)))) (fty::deflist a4veclistlist :elt-type a4veclist :true-listp t) (define a4veclist/env-list-eval ((x a4veclistlist-p) (envs)) :guard (equal (len envs) (len x)) :returns (4vecs 4veclistlist-p) (if (atom x) nil (cons (a4veclist-eval (car x) (car envs)) (a4veclist/env-list-eval (cdr x) (cdr envs))))) (define svexlistlist->a4vec ((x svexlistlist-p) (env svex-a4vec-env-p) (masks svex-mask-alist-p)) :returns (a4vecs a4veclistlist-p) (if (atom x) nil (cons (svexlist->a4vec (car x) env masks) (svexlistlist->a4vec (cdr x) env masks)))) (define a4vec/svex-env-eval ((x a4veclist-p) (env svex-env-p) (svexes svexlist-p) (svars svarlist-p) (boolmasks svar-boolmasks-p)) :guard (svex-maskbits-ok svars (svexlist-mask-alist svexes)) :returns (4vecs 4veclist-p) :hooks ((:fix :args (x svexes svars))) (b* ((env (make-fast-alist env)) ((mv ?err aig-env) ;; ignore the error; it can't exist svex-maskbits-ok (svexlist->a4vec-aig-env-for-varlist svexes svars boolmasks env)) (?ign (fast-alist-free env)) (aig-env (make-fast-alist aig-env)) (ans (a4veclist-eval x aig-env))) (fast-alist-free aig-env) ans) /// (local (defthm not-svexlist-full-masks-p-by-member (implies (And (not (equal (sparseint-val (svex-mask-lookup x masks)) -1)) (member x svexes)) (not (svexlist-full-masks-p svexes masks))) :hints(("Goal" :in-theory (enable member svexlist-full-masks-p))))) (defthm svexlist-full-masks-p-when-subset (implies (and (subsetp-equal some-svexes svexes) (svexlist-full-masks-p svexes masks)) (svexlist-full-masks-p some-svexes masks)) :hints(("Goal" :in-theory (enable subsetp-equal svexlist-full-masks-p)))) (defret a4vec/svex-env-eval-correct :pre-bind ((masks (svexlist-mask-alist svexes)) ((mv ?err a4env) (svex-varmasks->a4env svars masks boolmasks1)) (x (svexlist->a4vec some-svexes a4env masks))) (implies (and (svex-maskbits-ok svars masks) (subsetp some-svexes svexes) (equal boolmasks (svar-boolmasks-fix boolmasks1)) (svex-env-boolmasks-ok env boolmasks) (subsetp (intersection-equal (svexlist-vars some-svexes) (alist-keys (svex-env-fix env))) (svarlist-fix svars))) (equal 4vecs (svexlist-eval some-svexes env))) :hints(("Goal" :in-theory (e/d (svexlist->a4vec-aig-env-for-varlist) (SVEXLIST->A4VEC-CORRECT)))))) (define a4veclist/svex-env-list-eval ((x a4veclistlist-p) (envs svex-envlist-p) (svexes svexlist-p) (svars svarlist-p) (boolmasks svar-boolmasks-p)) :guard (and (equal (len envs) (len x)) (svex-maskbits-ok svars (svexlist-mask-alist svexes))) :returns (4vecs 4veclistlist-p) :hooks ((:fix :args (x svexes svars))) (if (atom x) nil (cons (a4vec/svex-env-eval (car x) (car envs) svexes svars boolmasks) (a4veclist/svex-env-list-eval (cdr x) (cdr envs) svexes svars boolmasks))) /// (local (defthm alist-keys-of-svex-env-fix (equal (alist-keys (svex-env-fix env)) (svarlist-filter (alist-keys env))) :hints(("Goal" :in-theory (enable svex-env-fix svarlist-filter))))) (defret a4veclist/svex-env-list-eval-correct :pre-bind ((masks (svexlist-mask-alist svexes)) ((mv ?err a4env) (svex-varmasks->a4env svars masks boolmasks1)) (x (svexlistlist->a4vec some-svexes a4env masks))) (implies (and (svex-maskbits-ok svars masks) (equal (len envs) (len some-svexes)) (subsetp (append-lists some-svexes) svexes) (equal boolmasks (svar-boolmasks-fix boolmasks1)) (svex-envlist-check-boolmasks boolmasks envs) (subsetp (intersection-equal (svexlist-vars (append-lists some-svexes)) (svex-envlist-keyset envs)) (svarlist-fix svars))) (equal 4vecs (svexlist/env-list-eval some-svexes envs))) :hints (("goal" :induct (svexlist/env-list-eval some-svexes envs) :in-theory (e/d (svexlist/env-list-eval svex-envlist-check-boolmasks append-lists svex-envlist-keyset svexlistlist->a4vec)))))) (local (in-theory (enable svexlist->a4vecs-for-varlist))) (local (defthm a4veclistlist-p-of-extract-lists (implies (and (a4veclist-p list) (<= (sum-of-lengths x) (len list))) (a4veclistlist-p (extract-lists x list))) :hints (("goal" :use ((:functional-instance element-listlist-p-of-extract-lists (acl2::element-p a4vec-p) (acl2::element-list-p a4veclist-p) (acl2::element-list-final-cdr-p (lambda (x) (eq x nil))) (element-listlist-p a4veclistlist-p))))))) (defsection svexlist/env-list-eval-of-extract-of-rewrite (local (include-book "svex-equivs")) (local (define svex-eval-same-on-envs (x y envs) :verify-guards nil (if (atom envs) t (and (equal (svex-eval x (car envs)) (svex-eval y (car envs))) (svex-eval-same-on-envs x y (cdr envs)))) /// (defthm svex-eval-same-on-envs-implies-eval-same-with-member (implies (and (svex-eval-same-on-envs x y envs) (member env envs)) (equal (svex-eval x env) (svex-eval y env)))) (defthm svex-eval-same-on-envs-when-svex-eval-equiv (implies (svex-eval-equiv x y) (svex-eval-same-on-envs x y envs))))) (local (define svexlist-eval-same-on-envs (x y envs) :verify-guards nil (if (atom x) t (and (svex-eval-same-on-envs (car x) (car y) envs) (svexlist-eval-same-on-envs (cdr x) (cdr y) envs))) /// (defthm svexlist-eval-same-on-envs-implies-svexlist-eval-same-with-member (implies (and (svexlist-eval-same-on-envs x y envs) (member env envs) (equal (len x) (len y))) (equal (svexlist-eval x env) (svexlist-eval y env)))) (local (defun ind (n x y) (if (zp n) (list x y) (ind (1- n) (cdr x) (cdr y))))) (defthm svex-eval-same-on-envs-of-nth-when-svexlist-eval-same-on-envs (implies (and (svexlist-eval-same-on-envs x y envs) (< (nfix n) (len x))) (svex-eval-same-on-envs (nth n x) (nth n y) envs)) :hints(("Goal" :in-theory (enable nth svex-eval-same-on-envs) :induct (ind n x y)))) (local (defthm svexlist-eval-equiv-implies-svex-eval-equiv-car (implies (and (svexlist-eval-equiv x y) (consp x)) (equal (svex-eval-equiv (car x) (car y)) t)) :hints (("goal" :in-theory (enable svex-eval-equiv))))) (defthm svexlist-eval-same-on-envs-when-svexlist-eval-equiv (implies (svexlist-eval-equiv x y) (svexlist-eval-same-on-envs x y envs))) (defthm svexlist-eval-same-on-envs-of-atom (implies (atom envs) (svexlist-eval-same-on-envs x y envs)) :hints(("Goal" :in-theory (enable svex-eval-same-on-envs)))) (defthm svexlist-eval-same-on-envs-of-consp (implies (and (consp envs) (equal (len x) (len y)) (svexlist-eval-same-on-envs x y (cdr envs))) (iff (svexlist-eval-same-on-envs x y envs) (equal (svexlist-eval x (car envs)) (svexlist-eval y (car envs))))) :hints(("Goal" :in-theory (enable svex-eval-same-on-envs)))))) (local (define svexlistlist-eval-same-on-envs (x y envs) :verify-guards nil (if (atom x) t (and (svexlist-eval-same-on-envs (car x) (car y) envs) (svexlistlist-eval-same-on-envs (cdr x) (cdr y) envs))) /// (local (defun ind (x y envs1) (if (atom x) (list y envs1) (ind (cdr x) (cdr y) (cdr envs1))))) ;; (defthm svexlistlist-eval-same-on-envs-implies-svexlist-eval-same-with-member ;; (implies (and (svexlistlist-eval-same-on-envs x y envs) ;; (member env envs) ;; (equal (len x) (len y))) ;; (equal (svexlist-eval x env) ;; (svexlist-eval y env)))) (defthm svexlist/env-list-eval-when-svexlistlist-eval-same-on-envs (implies (and (svexlistlist-eval-same-on-envs x y envs) (subsetp envs1 envs) (equal (len x) (len y)) (lengths-equal x y) (equal (len x) (len envs1))) (equal (svexlist/env-list-eval x envs1) (svexlist/env-list-eval y envs1))) :hints(("Goal" :in-theory (enable svexlist/env-list-eval subsetp-equal lengths-equal) :induct (ind x y envs1)))))) (local (defthm svexlist-eval-equiv-of-maybe-svexlist-rewrite-fixpoint (svexlist-eval-equiv (maybe-svexlist-rewrite-fixpoint x do-it) x) :hints(("Goal" :in-theory (enable svexlist-eval-equiv))))) (local (defthm alist-keys-of-svex-env-fix (equal (alist-keys (svex-env-fix env)) (svarlist-filter (alist-keys env))) :hints(("Goal" :in-theory (enable svex-env-fix svarlist-filter))))) (local (defthm svexlist-eval-equiv-of-svexlist-x-out-unused-vars (implies (subsetp (intersection-equal (svexlist-vars x) (svex-envlist-keyset envs)) (svarlist-fix svars)) (svexlist-eval-same-on-envs x (maybe-svexlist-rewrite-fixpoint (svexlist-x-out-unused-vars x svars do-it) do-it1) envs)) :hints(("Goal" :in-theory (e/d (svex-envlist-keyset) ()) :induct (len envs))))) (local (defthm svex-eval-equiv-listlist-of-extract-lists-of-rewrite (implies (subsetp (intersection-equal (svexlist-vars (append-lists x)) (svex-envlist-keyset envs)) (svarlist-fix svars)) (svexlistlist-eval-same-on-envs x (extract-lists x (maybe-svexlist-rewrite-fixpoint (svexlist-x-out-unused-vars (append-lists x) svars do-it1) do-it)) envs)) :hints (("goal" :use ((:functional-instance extract-lists-of-pseudoproj (pseudoproj (lambda (x) (if (subsetp (intersection-equal (svexlist-vars x) (svex-envlist-keyset envs)) (svarlist-fix svars)) (maybe-svexlist-rewrite-fixpoint (svexlist-x-out-unused-vars x svars do-it1) do-it) x))) (pseudoproj-relation (lambda (x y) (svex-eval-same-on-envs x y envs))) (pseudoproj-relation-list (lambda (x y) (svexlist-eval-same-on-envs x y envs))) (pseudoproj-relation-listlist (lambda (x y) (svexlistlist-eval-same-on-envs x y envs)))))) (and stable-under-simplificationp '(:in-theory (enable svexlist-eval-same-on-envs svexlistlist-eval-same-on-envs)))))) (defthm svexlist/env-list-eval-of-extract-lists-of-rewrite (implies (and (subsetp (intersection-equal (svexlist-vars (append-lists x)) (svex-envlist-keyset envs)) (svarlist-fix svars)) (equal (len envs) (len x))) (equal (svexlist/env-list-eval (extract-lists x (maybe-svexlist-rewrite-fixpoint (svexlist-x-out-unused-vars (append-lists x) svars do-it1) do-it)) envs) (svexlist/env-list-eval x envs))) :hints (("goal" :use ((:instance svexlist/env-list-eval-when-svexlistlist-eval-same-on-envs (x x) (y (extract-lists x (maybe-svexlist-rewrite-fixpoint (svexlist-x-out-unused-vars (append-lists x) svars do-it1) do-it))) (envs envs) (envs1 envs))) :in-theory (disable svexlist/env-list-eval-when-svexlistlist-eval-same-on-envs) :do-not-induct t)))) (define svexlist/env-list-eval-gl ((x svexlistlist-p "Svex expressions to evaluate.") (envs svex-envlist-p "Bindings of variables to @(see 4vec) values.") (symbolic-params alistp "Alist giving symbolic execution parameters; see below.")) :short "Equivalent of svexlist/env-list-eval intended to work well under GL symbolic execution." :long " <p>This function is provably equivalent to @('svexlist/env-list-eval'), but is tailored to perform well under symbolic execution. For symbolic execution, we assume that the inputs to this function other than @('envs') are fully concrete, and that each @('envs') are symbolic only in its values, not its keys or its shape.</p> <p>It is analogous to @(see svexlist-eval-gl), but the individual lists of svexes within @('x') are each evaluated with the corresponding element of @('envs'). Symbolic execution is set up so that the svexes are all rendered into AIGs in a batch with memoization between all the lists.</p> <p>The @('symbolic-params') input behaves as it does in @(see svexlist-eval-gl). However, the @(':boolmasks') and @(':vars') entries must be applicable to all environments in the list. That is, for each entry in the boolmasks, the corresponding key must be bound in every entry in the envs to a symbolic 4vec value that is (syntactically) Boolean-valued in the masked bits. Similarly, the @(':vars') entry, if given, is unioned with the variables bound in all environments.</p>" :guard-hints (("goal" :in-theory (e/d (SET::UNION-WITH-SUBSET-LEFT) (SUBSET-OF-MERGESORTS-IS-SUBSETP)))) :guard-debug t (b* ((envs (take (len x) envs)) (x (svexlistlist-fix x)) (svexes (append-lists x)) (svars (svexlist/env-list-vars-for-symbolic-eval svexes envs symbolic-params)) (svexes (svexlist-x-out-unused-vars svexes svars (symbolic-params-x-out-cond symbolic-params))) (svexes (maybe-svexlist-rewrite-fixpoint svexes (cdr (assoc :simplify symbolic-params)))) (boolmasks (make-fast-alist (hons-copy (ec-call (svar-boolmasks-fix (cdr (assoc :boolmasks symbolic-params))))))) ((unless (svex-envlist-check-boolmasks boolmasks envs)) (b* ((?ign (cw "ERROR: some bits assumed to be Boolean were not~%")) (?ign (gl::gl-error 'boolcheck-failed))) (gl::gl-hide (svexlist/env-list-eval x envs)))) ((mv err a4vecs) (time$ (svexlist->a4vecs-for-varlist svexes svars boolmasks) :msg "; svex->aigs: ~st sec, ~sa bytes.~%")) ((when err) (b* ((?ign (cw "ERROR gathering AIG bits for variables: ~@0~%" err)) (?ign (gl::gl-error 'a4env-failed))) (gl::gl-hide (svexlist/env-list-eval x envs)))) (a4veclist-list (extract-lists x a4vecs))) (a4veclist/svex-env-list-eval a4veclist-list envs svexes svars boolmasks)) /// (local (defthm svexlist/env-list-eval-of-take (equal (svexlist/env-list-eval x (take (len x) envs)) (svexlist/env-list-eval x envs)) :hints(("Goal" :in-theory (enable svexlist/env-list-eval))))) (local (defthm extract-lists-of-svexlist->a4vec (implies (<= (sum-of-lengths x) (len y)) (equal (extract-lists x (svexlist->a4vec y env masks)) (svexlistlist->a4vec (extract-lists x y) env masks))) :hints (("goal" :use ((:functional-instance extract-lists-of-projection (acl2::element-p (lambda (x) t)) (acl2::outelement-p (lambda (x) t)) (acl2::outelement-example (lambda () t)) (acl2::element-xformer (lambda (x) (svex->a4vec x env masks))) (acl2::elementlist-projection (lambda (x) (svexlist->a4vec x env masks))) (elementlistlist-projection (lambda (x) (svexlistlist->a4vec x env masks))))) :in-theory (enable svexlistlist->a4vec svexlist->a4vec))))) (local (defthm vars-subset-lemma (b* ((vars (SVEXLIST/ENV-LIST-VARS-FOR-SYMBOLIC-EVAL svexes envs params))) (SUBSETP-EQUAL (INTERSECTION-EQUAL (SVEXLIST-VARS (MAYBE-SVEXLIST-REWRITE-FIXPOINT (SVEXLIST-X-OUT-UNUSED-VARS svexes vars x-out) simp)) (SVEX-ENVLIST-KEYSET envs)) vars)) :hints (("goal" :use ((:instance svexlist/env-list-vars-for-symbolic-eval-sufficient (x svexes) (symbolic-params params))) :in-theory (disable svexlist/env-list-vars-for-symbolic-eval-sufficient)) (set-reasoning)))) (defthm svexlist/env-list-eval-gl-correct (equal (svexlist/env-list-eval-gl x envs symbolic-params) (svexlist/env-list-eval x envs)) :hints (("goal" :do-not-induct t))) (gl::def-gl-rewrite svexlist/env-list-eval-for-symbolic-redef (equal (svexlist/env-list-eval x envs) (svexlist/env-list-eval-gl x envs nil))))
62113
; SV - Symbolic Vector Hardware Analysis Framework ; Copyright (C) 2014-2015 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 "SV") (include-book "eval") (include-book "a4vec-ops") (include-book "rewrite") (include-book "lists") (include-book "env-ops") (include-book "centaur/gl/gl-mbe" :dir :system) (include-book "centaur/gl/def-gl-rewrite" :dir :system) (local (include-book "arithmetic/top-with-meta" :dir :system)) (local (include-book "centaur/bitops/ihsext-basics" :dir :system)) (local (include-book "std/alists/alist-keys" :dir :System)) (local (include-book "centaur/bitops/equal-by-logbitp" :dir :system)) (local (include-book "clause-processors/just-expand" :dir :system)) (local (std::add-default-post-define-hook :fix)) (local (std::deflist svarlist-p (x) (svar-p x) :true-listp t :elementp-of-nil nil)) (local (defthm true-listp-nthcdr (implies (true-listp x) (true-listp (nthcdr n x))) :hints(("Goal" :in-theory (e/d (nthcdr) (acl2::cdr-nthcdr)) :induct (nthcdr n x))) :rule-classes :type-prescription)) (local (defthm nthcdr-of-append-equal-len (implies (equal (nfix n) (len x)) (equal (nthcdr n (append x y)) y)) :hints(("Goal" :in-theory (e/d (nthcdr) (acl2::cdr-nthcdr)) :induct (nthcdr n x))))) (local (defthm take-of-append-equal-len (implies (equal (nfix n) (len x)) (equal (take n (append x y)) (list-fix x))) :hints(("Goal" :in-theory (e/d (acl2::take)) :induct (nthcdr n x))))) (local (in-theory (disable double-containment))) (local (defthm 3vec-p-of-4vec-mask (implies (3vec-p x) (3vec-p (4vec-mask mask x))) :hints(("Goal" :in-theory (enable 4vec-mask 3vec-p)) (acl2::logbitp-reasoning)))) (local (defthm true-listp-of-scdr (implies (true-listp x) (true-listp (gl::scdr x))) :hints(("Goal" :in-theory (enable gl::scdr))) :rule-classes :type-prescription)) (local (in-theory (disable gl::s-endp-of-bfr-scons aig-list->s))) (local (defthm aig-list->s-open-quote (implies (syntaxp (quotep x)) (equal (aig-list->s x env) (B* (((MV FIRST REST GL::END) (GL::FIRST/REST/END X))) (IF GL::END (GL::BOOL->SIGN (AIG-EVAL FIRST ENV)) (BITOPS::LOGCONS (BOOL->BIT (AIG-EVAL FIRST ENV)) (AIG-LIST->S REST ENV)))))) :hints(("Goal" :in-theory (enable aig-list->s))))) (local (defthm aig-list->s-of-bfr-snorm (equal (aig-list->s (gl::bfr-snorm x) env) (aig-list->s x env)) :hints(("Goal" :in-theory (enable aig-list->s gl::bfr-snorm))))) (local (defthm aig-list->s-of-bfr-scons (equal (aig-list->s (gl::bfr-scons a b) env) (bitops::logcons (bool->bit (aig-eval a env)) (aig-list->s b env))) :hints(("Goal" :expand ((aig-list->s (gl::bfr-scons a b) env) (aig-list->s b env)) :in-theory (enable gl::s-endp-of-bfr-scons) :do-not-induct t)))) (defxdoc bit-blasting :parents (expressions) :short "We implement an efficient translation from @(see svex) expressions into @(see acl2::aig)s, to support symbolic simulation with @(see acl2::gl).") (local (xdoc::set-default-parents bit-blasting)) (defalist svex-a4vec-env :key-type svar :val-type a4vec) (define svex-a4vec-env-eval ((x svex-a4vec-env-p) env) :returns (xx svex-env-p) :measure (len (svex-a4vec-env-fix x)) (b* ((x (svex-a4vec-env-fix x))) (if (atom x) nil (cons (cons (svar-fix (caar x)) (a4vec-eval (cdar x) env)) (svex-a4vec-env-eval (cdr x) env)))) /// (defret alist-keys-of-svex-a4vec-env-eval (equal (alist-keys xx) (alist-keys (svex-a4vec-env-fix x))) :hints(("Goal" :in-theory (enable svex-a4vec-env-fix alist-keys))))) (define a4veclist-nth ((n natp) (x a4veclist-p)) :returns (elt a4vec-p) :guard-hints (("goal" :in-theory (enable nth a4veclist-p))) (mbe :logic (if (< (nfix n) (len x)) (a4vec-fix (nth n x)) (a4vec-x)) :exec (or (nth n x) (a4vec-x))) /// (defthm a4veclist-nth-out-of-bounds (implies (<= (len x) (nfix n)) (equal (a4veclist-nth n x) (a4vec-x)))) (defthm a4veclist-nth-in-of-bounds (implies (< (nfix n) (len x)) (equal (a4veclist-nth n x) (a4vec-fix (nth n x)))))) (define svexlist-nth ((n natp) (x svexlist-p)) :returns (elt svex-p) :guard-hints (("goal" :in-theory (enable nth svexlist-p))) (mbe :logic (if (< (nfix n) (len x)) (svex-fix (nth n x)) (svex-x)) :exec (or (nth n x) (svex-x))) /// (defthm svexlist-nth-out-of-bounds (implies (<= (len x) (nfix n)) (equal (svexlist-nth n x) (svex-x)))) (defthm svexlist-nth-in-of-bounds (implies (< (nfix n) (len x)) (equal (svexlist-nth n x) (svex-fix (nth n x)))))) (local (defthm nth-of-svexlist-eval (equal (nth n (svexlist-eval x env)) (and (< (nfix n) (len x)) (svex-eval (nth n x) env))) :hints(("Goal" :in-theory (enable nth svexlist-eval) :induct (nth n x))))) (local (defthm nth-of-a4veclist-eval (equal (nth n (a4veclist-eval x env)) (and (< (nfix n) (len x)) (a4vec-eval (nth n x) env))) :hints(("Goal" :in-theory (enable nth a4veclist-eval) :induct (nth n x))))) (define maybe-a3vec-fix ((v (a4vec-p v)) (x svex-p)) :returns (vv a4vec-p) (if (3valued-syntaxp (svex-fix x)) (a4vec-fix v) (a3vec-fix v)) /// (local (defthm nth-under-iff-when-a4veclist-p (implies (a4veclist-p x) (iff (nth n x) (< (nfix n) (len x)))) :hints(("Goal" :in-theory (enable a4veclist-p nth))))) (local (defthm nth-out-of-bounds (implies (<= (len x) (nfix n)) (not (nth n x))) :hints(("Goal" :in-theory (enable nth))))) (defthm maybe-a3vec-fix-when-implies (implies (case-split (implies (3valued-syntaxp x) (3vec-p (a4vec-eval v env)))) (equal (a4vec-eval (maybe-a3vec-fix v x) env) (3vec-fix (a4vec-eval v env))))) (defthm maybe-a3vec-fix-of-nths (implies (equal (a4veclist-eval vals env) (svexlist-eval x (svex-a4vec-env-eval a4env env))) (equal (a4vec-eval (maybe-a3vec-fix (nth n vals) (nth n x)) env) (3vec-fix (a4vec-eval (nth n vals) env)))) :hints(("Goal" :in-theory (e/d (a4veclist-nth) (nth-of-svexlist-eval) (nth-of-a4veclist-eval)) :use ((:instance nth-of-svexlist-eval (env (svex-a4vec-env-eval a4env env))) (:instance nth-of-a4veclist-eval))))) (defthm maybe-a3vec-fix-of-a3vec (implies (a4vec-syntactic-3vec-p v) (equal (maybe-a3vec-fix v x) (a4vec-fix v))) :hints(("Goal" :in-theory (enable a3vec-fix))))) ;; (define 4vmask-nth ((n natp) (x 4vmasklist-p)) ;; :returns (mask 4vmask-p :rule-classes (:rewrite :type-prescription)) ;; (b* ((x (4vmasklist-fix x))) ;; (if (< (lnfix n) (len x)) ;; (4vmask-fix (nth n x)) ;; -1))) ;; (define maybe-a4vec-fix ((v (or (a4vec-p v) (not v)))) ;; :returns (vv a4vec-p) ;; (if v (a4vec-fix v) (a4vec-x))) (defconst *svex-aig-op-table* ;; fn name, non-3vec-fixing function, args (with notation for 3vec-fixed ones and masks) '((id a4vec-fix (x) "identity function") (bitsel a4vec-bit-extract (index x) "bit select") (unfloat a4vec-fix ((3v x)) "change Z bits to Xes") (bitnot a3vec-bitnot ((3v x)) "bitwise negation") (onp a4vec-onset (x) "bitwise onset") (offp a4vec-offset (x) "bitwise offset") (bitand a3vec-bitand ((3v x) (3v y)) "bitwise AND") (bitor a3vec-bitor ((3v x) (3v y)) "bitwise OR") (bitxor a3vec-bitxor ((3v x) (3v y)) "bitwise XOR") (res a4vec-res (x y) "resolve (short together)") (resand a4vec-resand (x y) "resolve wired AND") (resor a4vec-resor (x y) "resolve wired OR") (override a4vec-override (x y) "resolve different strengths") (uand a3vec-reduction-and ((3v x)) "unary (reduction) AND") (uor a3vec-reduction-or ((3v x)) "unary (reduction) OR") (uxor a4vec-parity (x) "reduction XOR, i.e. parity") (zerox a4vec-zero-ext (width x (mask m)) "zero extend") (signx a4vec-sign-ext (width x (mask m)) "sign extend") (concat a4vec-concat (width x y (mask m)) "concatenate at a given bit width") (partsel a4vec-part-select (lsb width in (mask m)) "part select") (partinst a4vec-part-install (lsb width in val (mask m)) "part install") (blkrev a4vec-rev-blocks (width blksz x) "reverse block order") (rsh a4vec-rsh (shift x (mask m)) "right shift") (lsh a4vec-lsh (shift x (mask m)) "left shift") (+ a4vec-plus (x y) "addition") (b- a4vec-minus (x y) "subtraction") (u- a4vec-uminus (x) "unary minus") (xdet a4vec-xdet (x) "x detect") (countones a4vec-countones (x) "count of set bits") (onehot a4vec-onehot (x) "one-hot check") (onehot0 a4vec-onehot0 (x) "one-hot check (zero-hot allowed)") (* a4vec-times (x y) "multiplication") (/ a4vec-quotient (x y) "division") (% a4vec-remainder (x y) "modulus") (< a4vec-< (x y) "less than") (clog2 a4vec-clog2 (x) "ceiling of log2") (pow a4vec-pow (x y) "exponentiation") (== a3vec-== ((3v x) (3v y)) "equality") (=== a4vec-=== (x y) "case equality") (===* a4vec-===* (x y) "modified case equality") (==? a4vec-wildeq (x y) "wildcard equality") (safer-==? a4vec-wildeq-safe (x y) "wildcard equality (monotonic version)") (==?? a4vec-symwildeq (x y) "symmetric wildcard equality") (? a3vec-? ((3v test) (3vp then) (3vp else)) "if-then-else") (?* a3vec-?* ((3v test) (3vp then) (3vp else)) "if-then-else") (bit? a3vec-bit? ((3v test) (3vp then) (3vp else)) "bitwise if-then-else") (?! a4vec-?! (test them else) "procedural if-then-else") (bit?! a4vec-bit?! ((3v test) (3vp then) (3vp else)) "bitwise if-then-else"))) #|| (loop for lst in sv::*svex-aig-op-table* do (let ((fn (cadr lst))) (unless (eq fn 'sv::a4vec-fix) (profile-fn fn)))) ||# (defun svex-apply-aig-collect-args (n restargs argsvar svvar maskvar ;; argmasks-var ) (let* ((n (nfix n))) (if (atom restargs) nil (append (if (consp (car restargs)) (case (caar restargs) (3v `((maybe-a3vec-fix ;; (a4vec-mask (4vmask-nth ,n ,argmasks-var) (a4veclist-nth ,n ,argsvar) (svexlist-nth ,n ,svvar)))) (3vp `(;; (a4vec-mask (4vmask-nth ,n ,argmasks-var) (a4veclist-nth ,n ,argsvar) (3valued-syntaxp (svexlist-nth ,n ,svvar)))) (mask `(,maskvar)) (t (prog2$ (er hard? 'svex-apply-aig-collect-args "bad formal expr") `((a4veclist-nth ,n ,argsvar))))) `((a4veclist-nth ,n ,argsvar))) (svex-apply-aig-collect-args (+ 1 n) (cdr restargs) argsvar svvar maskvar ;; argmasks-var ))))) ;; (defun svex-apply-aig-uses-argmasks (args) ;; (if (atom args) ;; nil ;; (or (and (consp (car args)) ;; (or (eq (caar args) '3v) ;; (eq (caar args) '3vp))) ;; (svex-apply-aig-uses-argmasks (cdr args))))) (defun svex-apply-aig-cases-fn (argsvar svvar maskvar optable) (b* (((when (atom optable)) '((otherwise (a4vec-x)))) ((list sym fn args) (car optable)) (acc-args (svex-apply-aig-collect-args 0 args argsvar svvar maskvar ;; 'tmp-argmasks )) (call `(,fn . ,acc-args)) (full ;; (if (svex-apply-aig-uses-argmasks args) ;; `(let ((tmp-argmasks (svex-argmasks ,maskvar ',sym ,svvar))) ;; ,call) call)) (cons `(,sym ,full) (svex-apply-aig-cases-fn argsvar svvar maskvar (cdr optable))))) (defmacro svex-apply-aig-cases (fn args svex mask) `(case ,fn . ,(svex-apply-aig-cases-fn args svex mask *svex-aig-op-table*))) (defthm svex-p-when-nth (implies (and (svexlist-p x) (nth n x)) (svex-p (nth n x))) :hints(("Goal" :in-theory (enable nth svexlist-p)))) (defthm a4vec-p-when-nth (implies (and (a4veclist-p x) (nth n x)) (a4vec-p (nth n x))) :hints(("Goal" :in-theory (enable nth svexlist-p)))) ;; (defthm a4vec-eval-of-maybe-a4vec-fix-nth-out-of-bounds ;; (implies (<= (len x) (nfix n)) ;; (equal (a4vec-eval (maybe-a4vec-fix (nth n x)) env) ;; (4vec-x))) ;; :hints(("Goal" :in-theory (enable maybe-a4vec-fix nth)))) (local (in-theory (disable nth))) (local (defthm 4vec-bit?!-of-3vec-fix (equal (4vec-bit?! (3vec-fix test) then else) (4vec-bit?! test then else)) :hints(("Goal" :in-theory (enable 4vec-bit?! 3vec-fix))))) (define svex-apply-aig ((fn fnsym-p) (args a4veclist-p) (terms svexlist-p) (mask 4vmask-p)) :prepwork ((local (Defthm 4veclist-nth-safe-of-a4veclist-eval (equal (a4vec-eval (a4veclist-nth n x) aigenv) (4veclist-nth-safe n (a4veclist-eval x aigenv))) :hints(("Goal" :in-theory (enable a4veclist-eval a4veclist-nth 4veclist-nth-safe))))) (local (defun ind (n vals x) (if (zp n) (list vals x) (ind (1- n) (cdr vals) (cdr x))))) (local (defthm 3vec-p-when-3valued-syntaxp-nth (implies (and (EQUAL (A4VECLIST-EVAL VALS AIGENV) (SVEXLIST-EVAL X (SVEX-A4VEC-ENV-EVAL A4ENV AIGENV))) (3valued-syntaxp (svexlist-nth n x))) (3vec-p (a4vec-eval (nth n vals) aigenv))) :hints(("Goal" :in-theory (enable a4veclist-eval svexlist-eval svexlist-nth nth) :induct (ind n vals x) :expand ((a4veclist-eval vals aigenv) (:free (env) (svexlist-eval x env)))) (and stable-under-simplificationp '(:use ((:instance 3vec-p-of-eval-when-3valued-syntaxp (x (car x)) (env (svex-a4vec-env-eval a4env aigenv))))))))) (local (encapsulate nil (local (defun ind2 (n masks vals x) (if (zp n) (list masks vals x) (ind2 (1- n) (cdr masks) (cdr vals) (cdr x))))) ;; BOZO do we need this? ;; (defthm 4vmask-of-nths ;; (implies (equal (len masks) (len vecs)) ;; (equal (4vec-mask (4vmask-nth n masks) ;; (4veclist-nth-safe n vecs)) ;; (4veclist-nth-safe n (4veclist-mask masks vecs)))) ;; :hints(("Goal" :in-theory (enable 4vmask-nth 4veclist-nth-safe 4veclist-mask nth ;; 4vmasklist-fix) ;; :induct (ind2 n masks vecs nil)))) (defthm svex-eval-of-nth-rev (equal (svex-eval (nth n x) env) (4veclist-nth-safe n (svexlist-eval x env)))) (in-theory (disable svex-eval-of-nth 4veclist-nth-safe-of-svexlist-eval)) (local (defthm 3vec-p-of-eval-by-equal (implies (and (equal x (svex-eval y env)) (3valued-syntaxp y)) (3vec-p x)))) (local (defthm 3vec-p-of-eval-by-equal-with-mask (implies (and (equal x (4vec-mask mask (svex-eval y env))) (3valued-syntaxp y)) (3vec-p x)))) (defthm 4veclist-masked-idempotent (implies (equal x (4veclist-mask masks y)) (equal (4veclist-mask masks x) x))) (defthm dumb (implies (and (EQUAL (A4VECLIST-EVAL VALS AIGENV) (4VECLIST-MASK masks (SVEXLIST-EVAL X (SVEX-A4VEC-ENV-EVAL A4ENV AIGENV)))) (3valued-syntaxp (svexlist-nth n x))) (3vec-p (4veclist-nth-safe n (a4veclist-eval vals aigenv))) ;; (3vec-p (4vec-mask (4vmask-nth n masks) ;; (a4vec-eval (a4veclist-nth n vals) aigenv))) ) :hints (("goal" :in-theory (e/d (nth len 4veclist-nth-safe a4veclist-eval 4veclist-mask svexlist-eval a4veclist-eval svexlist-nth) (4veclist-nth-safe-of-a4veclist-eval)) :expand ((:free (env) (svexlist-eval x env)) (a4veclist-eval vals aigenv) (:free (a b) (4veclist-mask masks (cons a b)))) :induct (ind2 n masks vals x)))) ))) :verbosep t :guard-debug t :returns (res a4vec-p) (b* ((fn (fnsym-fix fn)) (args (a4veclist-fix args)) (res (svex-apply-aig-cases fn args terms mask))) ;; ;; This cleverly masks out any bits of the result that we don't care about, ;; ;; replacing them with Xes. This might be a great way to get a lot more ;; ;; constant propagation... (a4vec-mask mask res)) /// (defthm svex-apply-aig-correct (implies (and (fnsym-p fn) (bind-free '((a4env . env)) (a4env)) (equal (a4veclist-eval vals aigenv) (4veclist-mask argmasks (svexlist-eval x (svex-a4vec-env-eval a4env aigenv)))) (svex-argmasks-okp (svex-call fn x) mask argmasks)) (equal (a4vec-eval (svex-apply-aig fn vals x mask) aigenv) (4vec-mask mask (svex-apply fn (svexlist-eval x (svex-a4vec-env-eval a4env aigenv)))))) :hints(("Goal" :in-theory (disable len-of-4veclist-mask svex-apply-aig) ;; Establish that (len vals) = (len x). :use ((:instance len-of-4veclist-mask (masks (svex-argmasks mask fn x)) (values (a4veclist-eval vals aigenv))) (:instance len-of-4veclist-mask (masks (svex-argmasks mask fn x)) (values (svexlist-eval x (svex-a4vec-env-eval a4env aigenv)))))) (and stable-under-simplificationp '( :in-theory (e/d (svex-apply svexlist-eval ;; 4veclist-nth-safe ;; 4veclist-mask 4veclist-mask? 4vec-bitnot 4vec-bitand 4vec-bitor 4vec-bitxor-redef 4vec-reduction-and 4vec-reduction-or 4vec-? 4vec-?* 4vec-bit? 4vec-==) (;; len-of-svexlist-eval ;; len-of-a4veclist-eval ;; len-of-4veclist-mask svex-argmasks-correct svex-argmasks-remove-mask)) :use ;; ((:instance len-of-svexlist-eval ;; (env (svex-a4vec-env-eval a4env aigenv))) ;; (:instance len-of-a4veclist-eval ;; (x vals) (env aigenv))) ((:instance svex-argmasks-okp-necc (x (svex-call fn x)) (vals (a4veclist-eval vals aigenv)) (env (svex-a4vec-env-eval a4env aigenv))) ;; (:instance svex-argmasks-remove-mask ;; (fn fn) ;; (args x) ;; (env (svex-a4vec-env-eval a4env aigenv))) ) :do-not-induct t :do-not '(fertilize generalize eliminate-destructors) ))) :otf-flg t)) (defalist svex-aig-memotable :key-type svex :val-type a4vec) (defthm a4vec-p-of-svex-a4vec-env-lookup (implies (and (svex-a4vec-env-p x) (hons-assoc-equal k x)) (a4vec-p (cdr (hons-assoc-equal k x))))) (defthm a4vec-p-of-svex-aig-memotable-lookup (implies (and (svex-aig-memotable-p x) (hons-assoc-equal k x)) (a4vec-p (cdr (hons-assoc-equal k x))))) ;; (SVEX->A4VEC ;; '(RSH (? (< 0 (* 32 (B- (CONCAT 16 CNST 0) 0))) (* 32 (B- (CONCAT 16 CNST 0) 0)) 0) '(-71265535176078871931497435759850128999 . 269016831744859591531877171671918082457)) ;; (make-fast-alist `((cnst ,(acl2::numlist 0 2 16) . ,(acl2::numlist 1 2 16)))) ;; nil) (define svex-is-const-concat ((x svex-p)) :returns (is-concat) :guard-hints (("goal" :in-theory (enable nth))) (svex-case x :call (and (eq x.fn 'concat) (eql (len x.args) 3) (let ((arg1 (mbe :logic (nth 0 x.args) :exec (car x.args)))) (svex-case arg1 :quote))) :otherwise nil)) (define svex-const-concat-args ((x svex-p)) :guard (svex-is-const-concat x) :guard-hints (("goal" :expand ((:free (n) (nth n (svex-call->args x))) (:free (n) (nth n (cdr (svex-call->args x)))) (:free (n) (nth n (cddr (svex-call->args x))))))) :prepwork ((local (in-theory (enable svex-is-const-concat)))) :returns (mv (width 4vec-p) (lsbs svex-p) (msbs svex-p)) (b* (((svex-call x))) (mv (svex-quote->val (mbe :logic (svex-fix (nth 0 x.args)) :exec (first x.args))) (mbe :logic (svex-fix (nth 1 x.args)) :exec (second x.args)) (mbe :logic (svex-fix (nth 2 x.args)) :exec (third x.args)))) /// (local (defthm nth-when-n-too-big (implies (<= (len x) (nfix n)) (equal (nth n x) nil)) :hints(("Goal" :in-theory (enable nth))))) (local (defthm 4vec-zero-ext-is-concat (equal (4vec-zero-ext n x) (4vec-concat n x 0)) :hints(("Goal" :in-theory (enable 4vec-zero-ext 4vec-concat))))) (defretd svex-const-concat-args-correct-rw (implies (svex-is-const-concat x) (equal (svex-eval x env) (4vec-concat width (svex-eval lsbs env) (svex-eval msbs env)))) :hints(("Goal" :in-theory (enable svex-apply svexlist-eval)))) (local (defthm svex-count-of-nth (<= (svex-count (nth n x)) (svexlist-count x)) :hints(("Goal" :in-theory (enable nth svexlist-count))) :rule-classes :linear)) (local (defthm svex-count-of-svexlist-nth (<= (svex-count (svexlist-nth n x)) (svexlist-count x)) :hints(("Goal" :in-theory (enable svexlist-nth))) :rule-classes :linear)) (defret svex-count-of-svex-const-concat-args-lsbs (implies (svex-is-const-concat x) (< (svex-count lsbs) (svex-count x))) :rule-classes :linear) (defret svex-count-of-svex-const-concat-args-msbs (implies (svex-is-const-concat x) (< (svex-count msbs) (svex-count x))) :hints ((and stable-under-simplificationp '(:expand ((svex-count x))))) :rule-classes :linear)) (progn (local (defthm 4vec-zero-ext-of-4vec-mask? (equal (4vec-zero-ext w (4vec-mask? mask x y)) (4vec-mask? (if (and (2vec-p w) (<= 0 (2vec->val w))) (sparseint-concatenate (2vec->val w) (4vmask-fix mask) 0) mask) (4vec-zero-ext w x) (4vec-zero-ext w y))) :hints(("Goal" :in-theory (enable 4vec-mask? 4vec-bit? 3vec-bit? 4vec-zero-ext)) (logbitp-reasoning)))) (local (defthm 4vec-zero-ext-of-equal-4vec-mask? (implies (equal z (4vec-mask? mask x y)) (equal (4vec-zero-ext w z) (4vec-mask? (if (and (2vec-p w) (<= 0 (2vec->val w))) (sparseint-concatenate (2vec->val w) (4vmask-fix mask) 0) mask) (4vec-zero-ext w x) (4vec-zero-ext w y)))))) (local (defthm 4vec-zero-ext-of-zero-ext (equal (4vec-zero-ext w (4vec-zero-ext w x)) (4vec-zero-ext w x)) :hints(("Goal" :in-theory (enable 4vec-zero-ext)))))) (defines svex->a4vec ;; Self-memoized version of svex-eval, for GL :verify-guards nil :ruler-extenders :all (define svex->a4vec ((x svex-p) (env svex-a4vec-env-p) (masks svex-mask-alist-p)) :returns (res a4vec-p) :measure (two-nats-measure (svex-count x) 1) (b* ((env (svex-a4vec-env-fix env))) (svex-case x :quote (b* ((mask (svex-mask-lookup x masks))) (4vec->a4vec (4vec-mask mask x.val))) :var (let ((look (hons-get x.name env)) (mask (svex-mask-lookup x masks))) (a4vec-mask mask (if look (cdr look) (a4vec-x)))) :call (b* ((x (svex-fix x)) ((when (svex-is-const-concat x)) (b* (((mv upper lower) (svex-concat->a4vec x env masks)) (mask (svex-mask-lookup x masks))) (a4vec-mask mask (a4vec upper lower)))) (args (svexlist->a4vec x.args env masks)) (mask (svex-mask-lookup x masks))) (svex-apply-aig x.fn args x.args mask))))) (define svexlist->a4vec ((x svexlist-p) (env svex-a4vec-env-p) (masks svex-mask-alist-p)) :returns (res a4veclist-p) :measure (two-nats-measure (svexlist-count x) 0) (if (atom x) nil (cons (svex->a4vec (car x) env masks) (svexlist->a4vec (cdr x) env masks)))) (define svex-concat->a4vec ((x svex-p) (env svex-a4vec-env-p) (masks svex-mask-alist-p)) :returns (mv (upper true-listp) (lower true-listp)) :measure (two-nats-measure (svex-count x) (if (svex-is-const-concat x) 0 2)) (b* (((unless (svex-is-const-concat x)) (b* ((res (svex->a4vec x env masks))) (mv (a4vec->upper res) (a4vec->lower res)))) ((mv width lsbs msbs) (svex-const-concat-args x)) ((unless (and (2vec-p width) (natp (2vec->val width)))) (mv (a4vec->upper (a4vec-x)) (a4vec->lower (a4vec-x)))) (width (2vec->val width)) (mask (svex-mask-lookup x masks)) ((unless (sparseint-test-bitand (sparseint-concatenate width 0 -1) mask)) (svex-concat->a4vec lsbs env masks)) ((mv upper2 lower2) (svex-concat->a4vec msbs env masks))) (svex-concat->a4vec-lower lsbs width upper2 lower2 env masks))) (define svex-concat->a4vec-lower ((x svex-p) (width natp) (upper-acc true-listp) (lower-acc true-listp) (env svex-a4vec-env-p) (masks svex-mask-alist-p)) :returns (mv (upper true-listp) (lower true-listp)) :measure (two-nats-measure (svex-count x) (if (svex-is-const-concat x) 0 2)) (b* ((upper-acc (llist-fix upper-acc)) (lower-acc (llist-fix lower-acc)) ((When (zp width)) (mv upper-acc lower-acc)) ((unless (svex-is-const-concat x)) (b* ((res (svex->a4vec x env masks))) (mv (aig-logapp-nss width (a4vec->upper res) upper-acc) (aig-logapp-nss width (a4vec->lower res) lower-acc)))) ((mv sub-width lsbs msbs) (svex-const-concat-args x)) ((unless (and (2vec-p sub-width) (natp (2vec->val sub-width)))) (mv (aig-logapp-nss width (a4vec->upper (a4vec-x)) upper-acc) (aig-logapp-nss width (a4vec->lower (a4vec-x)) lower-acc))) (sub-width (2vec->val sub-width)) (lsbs-width (min width sub-width)) (msbs-width (- width lsbs-width)) ((mv upper-acc lower-acc) (svex-concat->a4vec-lower msbs msbs-width upper-acc lower-acc env masks))) (svex-concat->a4vec-lower lsbs lsbs-width upper-acc lower-acc env masks))) /// (verify-guards svex->a4vec :guard-debug t) (local (in-theory (disable svex->a4vec svexlist->a4vec))) (encapsulate nil (local (defthm lookup-in-svex-a4vec-env-eval-lemma (implies (svex-a4vec-env-p env) (equal (hons-assoc-equal k (svex-a4vec-env-eval env aigenv)) (and (hons-assoc-equal k env) (cons k (a4vec-eval (cdr (hons-assoc-equal k env)) aigenv))))) :hints(("Goal" :in-theory (enable svex-a4vec-env-eval svex-a4vec-env-p) :induct (svex-a4vec-env-eval env aigenv) :do-not-induct t)) :rule-classes nil)) (defthm lookup-in-svex-a4vec-env-eval (equal (hons-assoc-equal k (svex-a4vec-env-eval env aigenv)) (and (hons-assoc-equal k (svex-a4vec-env-fix env)) (cons k (a4vec-eval (cdr (hons-assoc-equal k (svex-a4vec-env-fix env))) aigenv)))) :hints(("Goal" :use ((:instance lookup-in-svex-a4vec-env-eval-lemma (env (svex-a4vec-env-fix env)))))))) (defthm svex-env-lookup-in-svex-a4vec-env-eval (equal (svex-env-lookup k (svex-a4vec-env-eval env aigenv)) (if (hons-assoc-equal (svar-fix k) (svex-a4vec-env-fix env)) (a4vec-eval (cdr (hons-assoc-equal (svar-fix k) (svex-a4vec-env-fix env))) aigenv) (4vec-x))) :hints(("Goal" :in-theory (enable svex-env-lookup)))) ;; (local (defthm svex-apply-aig-correct-rw ;; (implies (and (fnsym-p fn) ;; (bind-free '((a4env . env)) (a4env)) ;; (equal (a4veclist-eval vals aigenv) ;; (4veclist-mask argmasks (svexlist-eval x (svex-a4vec-env-eval a4env aigenv)))) ;; (svex-argmasks-okp (svex-call fn x) mask argmasks)) ;; (equal (a4vec-eval (svex-apply-aig fn vals x mask) aigenv) ;; (4vec-mask mask (svex-apply fn (svexlist-eval x (svex-a4vec-env-eval a4env aigenv)))))) (local (in-theory (enable svex-mask-alist-complete-necc))) (local (defthm 4vec-concat-when-not-2vec (implies (not (equal (4vec->upper width) (4vec->lower width))) (equal (4vec-concat width x y) (4vec-x))) :hints(("Goal" :in-theory (enable 4vec-concat))))) (local (defthm 4vec-concat-when-not-natp (implies (< (4vec->lower width) 0) (equal (4vec-concat width x y) (4vec-x))) :hints(("Goal" :in-theory (enable 4vec-concat))))) (local (defthm 4vec-mask-idempotence-rw (implies (equal y (4vec-mask mask x)) (equal (4vec-mask mask y) y)))) (local (defthm 4vec-concat-when-width-0 (implies (and (equal 0 (4vec->upper width)) (equal 0 (4vec->lower width))) (equal (4vec-concat width x y) (4vec-fix y))) :hints(("Goal" :in-theory (enable 4vec-concat))))) (local (define 4vec-change-all-bits ((x 4vec-p)) :returns (new-x 4vec-p) (4vec (lognot (4vec->upper x)) (lognot (4vec->lower x))))) (local (encapsulate nil (local (in-theory (disable* (:rules-of-class :linear :here) bitops::logand-natp-type-2 bitops::logand-natp-type-1 bitops::logior-natp-type bitops::lognot-negp bitops::lognot-natp member-svex-mask-alist-keys acl2::loghead-identity))) (defthm mask-of-bit?-logand-lognot (implies (4vmask-p mask) (equal (4vec-mask mask (4vec-bit? (2vec (logand a (lognot (sparseint-val mask)))) x y)) (4vec-mask mask y))) :hints(("Goal" :in-theory (e/d* (4vec-mask 4vec-bit? 3vec-bit?))) (logbitp-reasoning))) (defthm mask-of-bit?-logand-lognot2 (implies (4vmask-p mask) (equal (4vec-mask mask (4vec-bit? (2vec (logand (lognot (sparseint-val mask)) a)) x y)) (4vec-mask mask y))) :hints(("Goal" :in-theory (e/d* (4vec-mask 4vec-bit? 3vec-bit?))) (logbitp-reasoning))) (defthm argmasks-okp-for-const-concat-implies-lsb-mask-subsumes-outer (b* (((mv width lsbs msbs) (svex-const-concat-args x))) (implies (and (svex-is-const-concat x) (svex-mask-alist-complete masks) (2vec-p width) (<= (nfix w) (2vec->val width))) (4vmask-subsumes (sparseint-concatenate w (svex-mask-lookup lsbs masks) 0) (sparseint-concatenate w (svex-mask-lookup x masks) 0)))) :hints (("goal" :use ((:instance svex-mask-alist-complete-necc (y x) (mask-al masks)) (:instance svex-argmasks-okp-necc (vals (b* (((mv width lsbs msbs) (svex-const-concat-args x))) (list width (4vec-bit? (2vec (logandc1 (sparseint-val (svex-mask-lookup lsbs masks)) (sparseint-val (svex-mask-lookup x masks)))) (4vec-change-all-bits (svex-eval lsbs env)) (svex-eval lsbs env)) (svex-eval msbs env)))) (mask (svex-mask-lookup x masks)) (argmasks (svex-argmasks-lookup (svex-call->args x) masks)))) :in-theory (enable svex-argmasks-lookup svex-apply 4vmask-subsumes svexlist-eval 4veclist-mask len nth) :expand ((svex-is-const-concat x) (svex-const-concat-args x) (len (svex-call->args x)) (len (cdr (svex-call->args x))) (len (cddr (svex-call->args x))) (len (cdddr (svex-call->args x))) (:free (n) (nth n (svex-call->args x))) (:free (n) (nth n (cdr (svex-call->args x)))) (:free (n) (nth n (cddr (svex-call->args x)))) (:free (n) (nth n (cdddr (svex-call->args x)))))) (and stable-under-simplificationp '(:in-theory (enable 4vec-mask 4vec-bit? 3vec-bit? 4vec-change-all-bits 4vec-concat))) (logbitp-reasoning :add-hints (:in-theory (enable* logbitp-case-splits)) :simp-hint (:in-theory (enable* logbitp-case-splits))) ) :otf-flg t) (local (in-theory (disable iff not))) (defthm argmasks-okp-for-const-concat-implies-msb-mask-subsumes-outer (b* (((mv width lsbs msbs) (svex-const-concat-args x))) (implies (and (svex-is-const-concat x) (svex-mask-alist-complete masks) (2vec-p width) (<= 0 (2vec->val width))) (4vmask-subsumes (svex-mask-lookup msbs masks) (sparseint-rightshift (4vec->lower width) (svex-mask-lookup x masks))))) :hints (("goal" :use ((:instance svex-mask-alist-complete-necc (y x) (mask-al masks)) (:instance svex-argmasks-okp-necc (vals (b* (((mv width lsbs msbs) (svex-const-concat-args x))) (list width (svex-eval lsbs env) (4vec-bit? (2vec (logandc1 (sparseint-val (svex-mask-lookup msbs masks)) (logtail (2vec->val width) (sparseint-val (svex-mask-lookup x masks))))) (4vec-change-all-bits (svex-eval msbs env)) (svex-eval msbs env))))) (mask (svex-mask-lookup x masks)) (argmasks (svex-argmasks-lookup (svex-call->args x) masks)))) :in-theory (enable svex-argmasks-lookup svex-apply 4vmask-subsumes svexlist-eval 4veclist-mask len nth) :expand ((svex-is-const-concat x) (svex-const-concat-args x) (len (svex-call->args x)) (len (cdr (svex-call->args x))) (len (cddr (svex-call->args x))) (len (cdddr (svex-call->args x))) (:free (n) (nth n (svex-call->args x))) (:free (n) (nth n (cdr (svex-call->args x)))) (:free (n) (nth n (cddr (svex-call->args x)))) (:free (n) (nth n (cdddr (svex-call->args x)))))) (and stable-under-simplificationp '(:in-theory (enable 4vec-mask 4vec-bit? 3vec-bit? 4vec-change-all-bits 4vec-concat))) (logbitp-reasoning :add-hints (:in-theory (enable* logbitp-case-splits)) :simp-hint (:in-theory (enable* logbitp-case-splits))) ) :otf-flg t) (defthm argmasks-okp-for-const-concat-implies-lsb-mask-subsumes-outer-when-tail-0 (b* (((mv width lsbs msbs) (svex-const-concat-args x))) (implies (and (svex-is-const-concat x) (svex-mask-alist-complete masks) (2vec-p width) (<= 0 (2vec->val width)) (equal 0 (logtail (2vec->val width) (sparseint-val (svex-mask-lookup x masks))))) (4vmask-subsumes (svex-mask-lookup lsbs masks) (svex-mask-lookup x masks)))) :hints (("goal" :use ((:instance argmasks-okp-for-const-concat-implies-lsb-mask-subsumes-outer (w (2vec->val (mv-nth 0 (svex-const-concat-args x)))))) :in-theory (e/d (4vmask-subsumes) (argmasks-okp-for-const-concat-implies-lsb-mask-subsumes-outer))) (logbitp-reasoning :prune-examples nil) ) :otf-flg t))) (local (defthmd 4vec-mask-over-4vec-zero-ext (implies (and (2vec-p width) (<= 0 (2vec->val width))) (equal (4vec-mask mask (4vec-zero-ext width x)) (4vec-concat width (4vec-mask mask x) (4vec-mask (sparseint-rightshift (2vec->val width) (4vmask-fix mask)) 0)))) :hints(("Goal" :in-theory (enable 4vec-mask 4vec-zero-ext 4vec-concat)) (logbitp-reasoning :prune-examples nil)))) (local (defthmd 4vec-mask-over-4vec-concat (implies (and (2vec-p width) (<= 0 (2vec->val width))) (equal (4vec-mask mask (4vec-concat width x y)) (4vec-concat width (4vec-mask mask x) (4vec-mask (sparseint-rightshift (2vec->val width) (4vmask-fix mask)) y)))) :hints(("Goal" :in-theory (enable 4vec-mask 4vec-concat)) (logbitp-reasoning :prune-examples nil)))) (local (defthmd 4vec-concat-of-4vec-mask-identity (implies (and (equal mask1 (4vmask-fix mask)) (2vec-p w) (<= 0 (2vec->val w)) (equal w1 (2vec->val w))) (equal (4vec-concat w (4vec-mask mask x) (4vec-mask (sparseint-rightshift w1 mask1) (4vec-rsh w x))) (4vec-mask mask x))) :hints(("Goal" :in-theory (enable 4vec-mask 4vec-concat 4vec-rsh 4vec-shift-core)) (logbitp-reasoning :prune-examples nil)))) (local (defthmd 4vec-concat-of-equal-4vec-conct (implies (and (equal x (4vec-concat w a b)) (2vec-p w) (<= 0 (2vec->val w))) (equal (4vec-concat w x y) (4vec-concat w a y))))) (local (defthm min-gte-zero (implies (and (<= 0 x) (<= 0 y)) (<= 0 (min x y))))) (local (defthm 2vec-of-4vec-acc (implies (2vec-p x) (and (equal (2vec (4vec->lower x)) (4vec-fix x)) (equal (2vec (4vec->upper x)) (4vec-fix x)))) :hints(("Goal" :in-theory (enable 2vec))))) (local (defthmd 4vec-concat-identity (implies (and (2vec-p w) (<= 0 (2vec->val w))) (equal (4vec-concat w x (4vec-rsh w x)) (4vec-fix x))) :hints(("Goal" :in-theory (enable 4vec-concat 4vec-rsh 4vec-shift-core)) (logbitp-reasoning :prune-examples nil)))) (local (defthmd equal-of-4vec-concat2 (implies (and (2vec-p w) (<= 0 (2vec->val w))) (equal (equal (4vec-concat w x y) z) (and (4vec-p z) (equal (4vec-zero-ext w x) (4vec-zero-ext w z)) (equal (4vec-fix y) (4vec-rsh w z))))) :hints(("Goal" :in-theory (enable 4vec-concat 4vec-zero-ext 4vec-rsh 4vec-shift-core)) (logbitp-reasoning)) :otf-flg t)) (local (defthm 4vec-zero-ext-of-concat (implies (and (2vec-p w1) (2vec-p w2) (<= 0 (2vec->val w1)) (<= (2vec->val w1) (2vec->val w2))) (equal (4vec-zero-ext w1 (4vec-concat w2 x y)) (4vec-zero-ext w1 x))) :hints(("Goal" :in-theory (enable 4vec-zero-ext 4vec-concat))))) (local (defthm 4vec-rsh-of-4vec-mask (implies (and (2vec-p shift) (<= 0 (2vec->val shift))) (equal (4vec-rsh shift (4vec-mask mask x)) (4vec-mask (sparseint-rightshift (2vec->val shift) (4vmask-fix mask)) (4vec-rsh shift x)))) :hints(("Goal" :in-theory (enable 4vec-mask 4vec-rsh 4vec-shift-core))))) (local (defthm equal-zero-ext-of-mask (implies (and (2vec-p w) (<= 0 (2vec->val w))) (equal (equal (4vec-zero-ext w (4vec-mask m x)) (4vec-zero-ext w (4vec-mask m y))) (equal (4vec-mask (sparseint-concatenate (2vec->val w) (4vmask-fix m) 0) x) (4vec-mask (sparseint-concatenate (2vec->val w) (4vmask-fix m) 0) y)))) :hints(("Goal" :in-theory (enable 4vec-zero-ext 4vec-mask)) (logbitp-reasoning)))) (local (defthmd 4vec-mask-of-4vec-concat-under-mask (implies (and (equal (logtail (2vec->val width) (sparseint-val (4vmask-fix mask))) 0) (2vec-p width) (<= 0 (2vec->val width))) (equal (4vec-mask mask (4vec-concat width x y)) (4vec-mask mask x))) :hints(("Goal" :in-theory (enable 4vec-mask 4vec-concat)) (logbitp-reasoning :prune-examples nil)))) (local (defthmd 4vec-concat-of-4vec (equal (4vec (logapp w a b) (logapp w c d)) (4vec-concat (2vec (nfix w)) (4vec a c) (4vec b d))) :hints(("Goal" :in-theory (enable 4vec-concat))))) (local (defthmd 4vec-zero-ext-of-4vec (equal (4vec (loghead w a) (loghead w c)) (4vec-zero-ext (2vec (nfix w)) (4vec a c))) :hints(("Goal" :in-theory (enable 4vec-zero-ext))))) (local (defthmd 4vec-zero-ext-of-4vec/0 (equal (4vec (loghead w a) 0) (4vec-zero-ext (2vec (nfix w)) (4vec a 0))) :hints(("Goal" :in-theory (enable 4vec-zero-ext))))) (local (defthmd 4vec-of-aig-list->s-of-upper/lower (equal (4vec (aig-list->s (a4vec->upper x) env) (aig-list->s (a4vec->lower x) env)) (a4vec-eval x env)) :hints(("Goal" :in-theory (enable a4vec-eval))))) (local (defthm aig-list->s-of-list-fix (equal (aig-list->s (list-fix x) env) (aig-list->s x env)) :hints(("Goal" :in-theory (enable aig-list->s))))) (local (defthm 4vec-mask-of-loghead-4vec-mask (implies (equal mask1 (4vmask-fix mask)) (Equal (4vec-mask (sparseint-concatenate n mask1 0) (4vec-mask mask x)) (4vec-mask (sparseint-concatenate n mask1 0) x))) :hints(("Goal" :in-theory (enable 4vec-mask)) (logbitp-reasoning)))) (local (defun aig-logapp-nss-ind (w1 w2 x y) (declare (xargs :measure (nfix w1))) (if (or (zp w1) (zp w2)) (list x y) (aig-logapp-nss-ind (1- w1) (1- w2) (gl::scdr x) y)))) (local (defthm aig-logapp-nss-of-nfix (Equal (aig-logapp-nss (nfix w) x y) (aig-logapp-nss w x y)) :hints(("Goal" :in-theory (enable aig-logapp-nss))))) (local (defthm aig-logapp-nss-of-list-fix (Equal (aig-logapp-nss w (list-fix x) y) (aig-logapp-nss w x y)) :hints(("Goal" :in-theory (enable aig-logapp-nss))))) (local (defthm aig-logapp-nss-of-snorm (Equal (aig-logapp-nss w (gl::bfr-snorm x) y) (aig-logapp-nss w x y)) :hints(("Goal" :in-theory (enable aig-logapp-nss))))) (local (defthm aig-logapp-nss-of-aig-logapp-nss (equal (aig-logapp-nss w1 (aig-logapp-nss w2 x y) z) (let* ((wa (min (nfix w1) (nfix w2))) (wb (- (nfix w1) wa))) (aig-logapp-nss wa x (aig-logapp-nss wb y z)))) :hints(("Goal" :in-theory (enable aig-logapp-nss) :induct (aig-logapp-nss-ind w1 w2 x y) :expand ((:free (x y) (aig-logapp-nss w1 x y)) (:free (x y) (aig-logapp-nss w2 x y))))))) (local (defthm aig-logapp-nss-when-zp (implies (zp w) (equal (aig-logapp-nss w x y) (list-fix y))) :hints(("Goal" :in-theory (enable aig-logapp-nss))))) (local (defun-sk svex-concat->a4vec-lower-acc-elim-correct (x width env masks) (forall (upper-acc lower-acc) (implies (syntaxp (not (and (equal upper-acc ''nil) (equal lower-acc ''nil)))) (b* (((mv upper-impl lower-impl) (svex-concat->a4vec-lower x width upper-acc lower-acc env masks)) ((mv upper-spec lower-spec) (svex-concat->a4vec-lower x width nil nil env masks))) (and (equal upper-impl (aig-logapp-nss width upper-spec (list-fix upper-acc))) (equal lower-impl (aig-logapp-nss width lower-spec (list-fix lower-acc))))))) :rewrite :direct)) (local (in-theory (disable svex-concat->a4vec-lower-acc-elim-correct))) (local (std::defret-mutual svex-concat->a4vec-lower-acc-elim-lemma (defret svex-concat->a4vec-lower-acc-elim-lemma (svex-concat->a4vec-lower-acc-elim-correct x width env masks) :hints ((and stable-under-simplificationp `(:expand (,(car (last clause)) (:free (upper-acc lower-acc) <call>))))) :fn svex-concat->a4vec-lower :rule-classes nil) :skip-others t)) (defthm svex-concat->a4vec-lower-acc-elim (implies (syntaxp (not (and (equal upper-acc ''nil) (equal lower-acc ''nil)))) (b* (((mv upper-impl lower-impl) (svex-concat->a4vec-lower x width upper-acc lower-acc env masks)) ((mv upper-spec lower-spec) (svex-concat->a4vec-lower x width nil nil env masks))) (and (equal upper-impl (aig-logapp-nss width upper-spec (list-fix upper-acc))) (equal lower-impl (aig-logapp-nss width lower-spec (list-fix lower-acc)))))) :hints (("goal" :use svex-concat->a4vec-lower-acc-elim-lemma))) ;; (define svex-concat->a4vec-lower-zero ((x svex-p) ;; (width natp) ;; (env svex-a4vec-env-p) ;; (masks svex-mask-alist-p) ;; (memo svex-aig-memotable-p)) ;; :returns (mv (upper true-listp) ;; (lower true-listp) ;; (memo1 svex-aig-memotable-p)) ;; :measure (svex-count x) ;; :hooks nil ;; :verify-guards nil ;; (b* ((memo (svex-aig-memotable-fix memo)) ;; ((When (zp width)) ;; (mv nil nil memo)) ;; ((unless (svex-is-const-concat x)) ;; (b* (((mv res memo) (svex->a4vec x env masks memo))) ;; (mv (aig-logapp-nss width (a4vec->upper res) nil) ;; (aig-logapp-nss width (a4vec->lower res) nil) ;; memo))) ;; ((mv sub-width lsbs msbs) ;; (svex-const-concat-args x)) ;; ((unless (and (2vec-p sub-width) (natp (2vec->val sub-width)))) ;; (mv (aig-logapp-nss width (a4vec->upper (a4vec-x)) nil) ;; (aig-logapp-nss width (a4vec->lower (a4vec-x)) nil) ;; (svex-aig-memotable-fix memo))) ;; (sub-width (2vec->val sub-width)) ;; (lsbs-width (min width sub-width)) ;; (msbs-width (- width lsbs-width)) ;; ((mv upper2 lower2 memo) ;; (svex-concat->a4vec-lower-zero msbs msbs-width env masks memo)) ;; ((mv upper1 lower1 memo) ;; (svex-concat->a4vec-lower-zero lsbs lsbs-width env masks memo))) ;; (mv (aig-logapp-nss lsbs-width upper1 upper2) ;; (aig-logapp-nss lsbs-width lower1 lower2) ;; memo)) ;; /// ;; (defthm-svex->a4vec-flag ;; (defthm svex-concat->a4vec-lower-in-terms-of-zero ;; (b* (((mv upper-impl lower-impl memo-impl) ;; (svex-concat->a4vec-lower x width upper-acc lower-acc env masks memo)) ;; ((mv upper-spec lower-spec memo-spec) ;; (svex-concat->a4vec-lower-zero x width env masks memo))) ;; (and (equal memo-impl memo-spec) ;; (equal upper-impl (aig-logapp-nss width upper-spec (list-fix upper-acc))) ;; (equal lower-impl (aig-logapp-nss width lower-spec (list-fix lower-acc))))) ;; :flag svex-concat->a4vec-lower ;; :hints ('(:expand ((svex-concat->a4vec-lower x width upper-acc lower-acc env masks memo) ;; (svex-concat->a4vec-lower-zero x width env masks memo))))) ;; :skip-others t)) (local (defthm 4vec-mask-of-loghead-zero-ext (implies (natp width) (equal (4vec-mask (sparseint-concatenate width mask 0) (4vec-zero-ext (2vec width) x)) (4vec-mask (sparseint-concatenate width mask 0) x))) :hints(("Goal" :in-theory (enable 4vec-mask 4vec-zero-ext)) (logbitp-reasoning)))) (local (defthm 4vec-mask-zero-ext-mask (equal (4vec-mask mask (4vec-zero-ext w (4vec-mask mask x))) (4vec-mask mask (4vec-zero-ext w x))) :hints(("Goal" :in-theory (enable 4vec-mask 4vec-zero-ext)) (logbitp-reasoning)))) (local (defthm 4vec-zero-ext-0 (equal (4vec-zero-ext 0 x) 0) :hints(("Goal" :in-theory (enable 4vec-zero-ext))))) ;; (local (Defthm 4vec-zero-ext-of-zp ;; (equal (4vec-zero-ext (2vec width) x) 0)) ;; :hints(("Goal" :in-theory (enable* 4vec-zero-ext ;; ihsext-recursive-redefs)))) (local (defthm 4vec-concat-0 (equal (4vec-concat width x 0) (4vec-zero-ext width x)) :hints(("Goal" :in-theory (enable 4vec-concat 4vec-zero-ext))))) (local (defthm 4vec-of-equal-upper-lower (implies (and (equal a (4vec->upper x)) (equal b (4vec->lower x))) (equal (4vec a b) (4vec-fix x))))) (local (defthm 4vec-mask?-of-4vec-mask?-when-subsumes (implies (4vmask-subsumes m1 m2) (equal (4vec-mask? m2 a (4vec-mask? m1 a b)) (4vec-mask? m1 a b))) :hints(("Goal" :in-theory (enable 4vec-mask? 4vec-bit? 3vec-bit? 4vmask-subsumes)) (logbitp-reasoning)))) (local (defthm zero-ext-of-zero-ext (implies (and (2vec-p a) (2vec-p b) (<= 0 (2vec->val a)) (<= (2vec->val a) (2vec->val b))) (and (equal (4vec-zero-ext a (4vec-zero-ext b x)) (4vec-zero-ext a x)) (equal (4vec-zero-ext b (4vec-zero-ext a x)) (4vec-zero-ext a x)))) :hints(("Goal" :in-theory (enable 4vec-zero-ext))))) (local (Defthm 4vec-rsh-of-4vec-mask? (implies (and (2vec-p sh) (<= 0 (2vec->val sh))) (equal (4vec-rsh sh (4vec-mask? mask a b)) (4vec-mask? (sparseint-rightshift (2vec->val sh) (4vmask-fix mask)) (4vec-rsh sh a) (4vec-rsh sh b)))) :hints(("Goal" :in-theory (enable 4vec-rsh 4vec-shift-core 4vec-mask? 4vec-bit? 3vec-bit?))))) (local (defthm 4vec-rsh-of-4vec-zero-ext (implies (and (2vec-p a) (2vec-p b) (<= 0 (2vec->val a)) (<= (2vec->val a) (2vec->val b))) (and (equal (4vec-rsh a (4vec-zero-ext b x)) (4vec-zero-ext (2vec (- (2vec->val b) (2vec->val a))) (4vec-rsh a x))) (equal (4vec-rsh b (4vec-zero-ext a x)) 0))) :hints(("Goal" :in-theory (enable 4vec-rsh 4vec-shift-core 4vec-zero-ext)) (and stable-under-simplificationp '(:in-theory (enable* ihsext-recursive-redefs)))))) (local (defthm 4vmask-subsumes-of-loghead (implies (and (4vmask-subsumes a b) (4vmask-p a) (4vmask-p b)) (4vmask-subsumes (sparseint-concatenate w a 0) (sparseint-concatenate w b 0))) :hints(("Goal" :in-theory (enable 4vmask-subsumes)) (logbitp-reasoning)))) (local (defthm 4vec-mask?-of-concat-same (implies (and (2vec-p w) (<= 0 (2vec->val w))) (equal (4vec-mask? mask (4vec-concat w a b) (4vec-concat w c d)) (4vec-concat w (4vec-mask? (sparseint-concatenate (2vec->val w) (4vmask-fix mask) 0) (4vec-zero-ext w a) (4vec-zero-ext w c)) (4vec-mask? (sparseint-rightshift (2vec->val w) (4vmask-fix mask)) b d)))) :hints(("Goal" :in-theory (enable 4vec-mask? 4vec-bit? 3vec-bit? 4vec-concat 4vec-zero-ext)) (logbitp-reasoning)))) (local (defthm 4vec-mask?-of-concat-when-logtail-0 (implies (and (equal 0 (logtail (2vec->val w) (sparseint-val (4vmask-fix mask)))) (2vec-p w) (<= 0 (2vec->val w))) (equal (4vec-mask? mask (4vec-concat w a b) c) (4vec-mask? mask a c))) :hints(("Goal" :in-theory (enable 4vec-mask? 4vec-bit? 3vec-bit? 4vec-concat)) (logbitp-reasoning :prune-examples nil)))) ;; (local (defthm 4vec-mask?-of-zero-ext-when-logtail-0 ;; (implies (and (equal 0 (logtail (2vec->val w) (sparseint-val (4vmask-fix mask)))) ;; (2vec-p w) (<= 0 (2vec->val w))) ;; (equal (4vec-mask? mask (4vec-zero-ext w a) c) ;; (4vec-mask? mask a c))) ;; :hints(("Goal" :in-theory (enable 4vec-mask? 4vec-bit? 3vec-bit? 4vec-zero-ext)) ;; (logbitp-reasoning :prune-examples nil)))) ;; (local (defthm 4vec-mask?-of-zero-ext-when-logtail-0-2 ;; (implies (and (equal 0 (logtail (2vec->val w) (sparseint-val (4vmask-fix mask)))) ;; (2vec-p w) (<= 0 (2vec->val w))) ;; (equal (4vec-mask? mask a (4vec-zero-ext w c)) ;; (4vec-mask? mask a c))) ;; :hints(("Goal" :in-theory (enable 4vec-mask? 4vec-bit? 3vec-bit? 4vec-zero-ext)) ;; (logbitp-reasoning :prune-examples nil)))) (local (defthm 4veclist-mask?-of-conses (equal (4veclist-mask? (cons c1 c2) (cons t1 t2) (cons f1 f2)) (cons (4vec-mask? c1 t1 f1) (4veclist-mask? c2 t2 f2))) :hints(("Goal" :in-theory (enable 4veclist-mask?))))) (local (progn (defcong 4vmask-equal equal (4vec-mask? mask a b) 1 :hints(("Goal" :in-theory (enable 4vec-mask?)))) (defthm sparseint-concatenate-self-under-4vmask-equal (4vmask-equal (sparseint-concatenate width (sparseint-concatenate width a b) c) (sparseint-concatenate width a c)) :hints(("Goal" :in-theory (enable bitops::logapp-right-assoc)))) (defcong sparseint-equal 4vmask-equal (sparseint-concatenate width a b) 2) (defcong sparseint-equal 4vmask-equal (sparseint-concatenate width a b) 3) (defthm sparseint-equal-rightshift-0 (sparseint-equal (sparseint-rightshift 0 x) x)))) (local (defthm logand-ash-neg1-equal-0 (implies (natp n) (equal (equal 0 (logand (ash -1 n) x)) (equal 0 (logtail n x)))) :hints ((logbitp-reasoning :prune-examples nil)))) (local (defthm loghead-when-width-zp (implies (zp width) (equal (loghead width x) 0)))) (local (defthm 4vec-mask-of-4vec-mask?-when-subsumes (implies (4vmask-subsumes m1 m2) (equal (4vec-mask m2 (4vec-mask? m1 b c)) (4vec-mask m2 b))) :hints(("Goal" :in-theory (enable 4vec-mask? 4vec-mask 4vec-bit? 3vec-bit? 4vmask-subsumes)) (logbitp-reasoning)))) ;; (local (defthm 4vec-zero-ext-to-concat ;; (equal (4vec-zero-ext w x) ;; (4vec-concat w x 0)))) ;; (local (in-theory (disable 4vec-concat-0))) (std::defret-mutual svex->a4vec-correct (defret svex->a4vec-correct (implies (svex-mask-alist-complete masks) (equal (a4vec-eval res aigenv) (4vec-mask (svex-mask-lookup x masks) (svex-eval x (svex-a4vec-env-eval env aigenv))))) :hints ('(:expand (<call> (:free (env) (svex-eval x env))))) :fn svex->a4vec) (defret svexlist->a4vec-correct (implies (svex-mask-alist-complete masks) (equal (a4veclist-eval res aigenv) (4veclist-mask (svex-argmasks-lookup x masks) (svexlist-eval x (svex-a4vec-env-eval env aigenv))))) :hints ('(:expand (<call> (:free (env) (svexlist-eval x env)) (a4veclist-eval nil aigenv) (svex-argmasks-lookup x masks) (:free (a b) (a4veclist-eval (cons a b) aigenv))) :in-theory (enable 4veclist-mask))) :fn svexlist->a4vec) (defret svex-concat->a4vec-correct (implies (svex-mask-alist-complete masks) (4vec-mask-equiv (a4vec-eval (a4vec upper lower) aigenv) (svex-eval x (svex-a4vec-env-eval env aigenv)) (svex-mask-lookup x masks))) :hints ((acl2::just-expand ((:free (x) (hide x))) :last-only t :lambdasp t) '(:expand (<call>) :in-theory (e/d (svex-const-concat-args-correct-rw 4vec-concat-of-4vec)))) :fn svex-concat->a4vec) (defret svex-concat->a4vec-lower-correct :pre-bind ((lower-acc nil) (upper-acc nil)) (implies (svex-mask-alist-complete masks) (let ((ans (a4vec-eval (a4vec upper lower) aigenv))) (equal ans (4vec-zero-ext (2vec (nfix width)) (4vec-mask? (svex-mask-lookup x masks) (svex-eval x (svex-a4vec-env-eval env aigenv)) (hide ans)))))) :hints ((acl2::just-expand ((:free (x) (hide x))) :last-only t :lambdasp t) '(:expand ((svex-concat->a4vec-lower x width nil nil env masks)) :in-theory (e/d (svex-const-concat-args-correct-rw 4vec-concat-of-4vec 4vec-zero-ext-of-4vec 4vec-zero-ext-of-4vec/0 4vec-of-aig-list->s-of-upper/lower ;; 4vec-mask-over-4vec-concat ;; 4vec-mask-over-4vec-zero-ext ) (BITOPS::LOGAPP-OF-I-0 a4vec-eval-of-var))) (and stable-under-simplificationp '(:in-theory (e/d (equal-of-4vec-concat2 4vec-mask-of-4vec-concat-under-mask svex-const-concat-args-correct-rw 4vec-concat-of-4vec 4vec-zero-ext-of-4vec 4vec-zero-ext-of-4vec/0 4vec-of-aig-list->s-of-upper/lower) (a4vec-eval-of-var)) :do-not-induct t))) :fn svex-concat->a4vec-lower) ) (std::defret-mutual svexlist->a4vec-true-listp (defret svexlist->a4vec-true-listp (true-listp res) :hints ('(:expand (<call>))) :fn svexlist->a4vec) :skip-others t) (std::defret-mutual len-of-svexlist->a4vec (defret len-of-svexlist->a4vec (equal (len res) (len x)) :hints ('(:expand (<call>))) :fn svexlist->a4vec) :skip-others t) (deffixequiv-mutual svex->a4vec)) (define svex->a4vec-memotable-correctp ((memo svex-aig-memotable-p) (env svex-a4vec-env-p) (masks svex-mask-alist-p)) (if (atom memo) t (and (or (not (mbt (consp (car memo)))) (equal (svex->a4vec (caar memo) env masks) (a4vec-fix (cdar memo)))) (svex->a4vec-memotable-correctp (cdr memo) env masks))) /// (defthm svex->a4vec-memotable-correctp-implies-lookup (implies (and (svex->a4vec-memotable-correctp memo env masks) (hons-assoc-equal x memo)) (a4vec-equiv (cdr (hons-assoc-equal x memo)) (svex->a4vec x env masks)))) (defthm svex->a4vec-memotable-correctp-implies-lookup-fix (implies (and (svex->a4vec-memotable-correctp memo env masks) (hons-assoc-equal x (svex-aig-memotable-fix memo))) (equal (cdr (hons-assoc-equal x (svex-aig-memotable-fix memo))) (svex->a4vec x env masks))) :hints(("Goal" :in-theory (enable svex-aig-memotable-fix)))) (defthm svex->a4vec-memotable-correctp-of-cons (implies (and (svex->a4vec-memotable-correctp memo env masks) (a4vec-equiv val (svex->a4vec x env masks))) (svex->a4vec-memotable-correctp (cons (cons x val) memo) env masks))) (defthm svex->a4vec-memotable-correctp-of-nil (svex->a4vec-memotable-correctp nil env masks)) (local (in-theory (enable svex-aig-memotable-fix)))) (defines svex->a4vec-memo ;; Self-memoized version of svex-eval, for GL :verify-guards nil :ruler-extenders :all (define svex->a4vec-memo ((x svex-p) (env svex-a4vec-env-p) (masks svex-mask-alist-p) (memo svex-aig-memotable-p)) :returns (mv (res a4vec-p) (memo1 svex-aig-memotable-p)) :measure (two-nats-measure (svex-count x) 1) (b* ((memo (svex-aig-memotable-fix memo)) (env (svex-a4vec-env-fix env))) (svex-case x :quote (b* ((mask (svex-mask-lookup x masks))) (mv (4vec->a4vec (4vec-mask mask x.val)) memo)) :var (mv (let ((look (hons-get x.name env)) (mask (svex-mask-lookup x masks))) (a4vec-mask mask (if look (cdr look) (a4vec-x)))) memo) :call (b* ((x (svex-fix x)) (look (hons-get x memo)) ((when look) (mv (cdr look) memo)) ((mv res memo) (b* (((when (svex-is-const-concat x)) (b* (((mv upper lower memo) (svex-concat->a4vec-memo x env masks memo)) (mask (svex-mask-lookup x masks))) (mv (a4vec-mask mask (a4vec upper lower)) memo))) ((mv args memo) (svexlist->a4vec-memo x.args env masks memo)) (mask (svex-mask-lookup x masks)) (res (svex-apply-aig x.fn args x.args mask))) (mv res memo))) (memo (hons-acons x res memo))) (mv res memo))))) (define svexlist->a4vec-memo ((x svexlist-p) (env svex-a4vec-env-p) (masks svex-mask-alist-p) (memo svex-aig-memotable-p)) :returns (mv (res a4veclist-p) (memo1 svex-aig-memotable-p)) :measure (two-nats-measure (svexlist-count x) 0) (b* (((when (atom x)) (mv nil (svex-aig-memotable-fix memo))) ((mv first memo) (svex->a4vec-memo (car x) env masks memo)) ((mv rest memo) (svexlist->a4vec-memo (cdr x) env masks memo))) (mv (cons first rest) memo))) (define svex-concat->a4vec-memo ((x svex-p) (env svex-a4vec-env-p) (masks svex-mask-alist-p) (memo svex-aig-memotable-p)) :returns (mv (upper true-listp) (lower true-listp) (memo1 svex-aig-memotable-p)) :measure (two-nats-measure (svex-count x) (if (svex-is-const-concat x) 0 2)) (b* (((unless (svex-is-const-concat x)) (b* (((mv res memo) (svex->a4vec-memo x env masks memo))) (mv (a4vec->upper res) (a4vec->lower res) memo))) ((mv width lsbs msbs) (svex-const-concat-args x)) ((unless (and (2vec-p width) (natp (2vec->val width)))) (mv (a4vec->upper (a4vec-x)) (a4vec->lower (a4vec-x)) (svex-aig-memotable-fix memo))) (width (2vec->val width)) (mask (svex-mask-lookup x masks)) ((unless (sparseint-test-bitand (sparseint-concatenate width 0 -1) mask)) (svex-concat->a4vec-memo lsbs env masks memo)) ((mv upper2 lower2 memo) (svex-concat->a4vec-memo msbs env masks memo))) (svex-concat->a4vec-memo-lower lsbs width upper2 lower2 env masks memo))) (define svex-concat->a4vec-memo-lower ((x svex-p) (width natp) (upper-acc true-listp) (lower-acc true-listp) (env svex-a4vec-env-p) (masks svex-mask-alist-p) (memo svex-aig-memotable-p)) :returns (mv (upper true-listp) (lower true-listp) (memo1 svex-aig-memotable-p)) :measure (two-nats-measure (svex-count x) (if (svex-is-const-concat x) 0 2)) (b* ((upper-acc (llist-fix upper-acc)) (lower-acc (llist-fix lower-acc)) (memo (svex-aig-memotable-fix memo)) ((When (zp width)) (mv upper-acc lower-acc memo)) ((unless (svex-is-const-concat x)) (b* (((mv res memo) (svex->a4vec-memo x env masks memo))) (mv (aig-logapp-nss width (a4vec->upper res) upper-acc) (aig-logapp-nss width (a4vec->lower res) lower-acc) memo))) ((mv sub-width lsbs msbs) (svex-const-concat-args x)) ((unless (and (2vec-p sub-width) (natp (2vec->val sub-width)))) (mv (aig-logapp-nss width (a4vec->upper (a4vec-x)) upper-acc) (aig-logapp-nss width (a4vec->lower (a4vec-x)) lower-acc) (svex-aig-memotable-fix memo))) (sub-width (2vec->val sub-width)) (lsbs-width (min width sub-width)) (msbs-width (- width lsbs-width)) ((mv upper-acc lower-acc memo) (svex-concat->a4vec-memo-lower msbs msbs-width upper-acc lower-acc env masks memo))) (svex-concat->a4vec-memo-lower lsbs lsbs-width upper-acc lower-acc env masks memo))) /// (verify-guards svex->a4vec-memo :guard-debug t) (local (in-theory (disable svex-concat->a4vec-lower-acc-elim))) (std::defret-mutual svex->a4vec-memo-correct (defret svex->a4vec-memo-correct (implies (svex->a4vec-memotable-correctp memo env masks) (and (equal res (svex->a4vec x env masks)) (svex->a4vec-memotable-correctp memo1 env masks))) :hints ('(:expand (<call> (svex->a4vec x env masks)))) :fn svex->a4vec-memo) (defret svexlist->a4vec-memo-correct (implies (svex->a4vec-memotable-correctp memo env masks) (and (equal res (svexlist->a4vec x env masks)) (svex->a4vec-memotable-correctp memo1 env masks))) :hints ('(:expand (<call> (svexlist->a4vec x env masks)))) :fn svexlist->a4vec-memo) (defret svex-concat->a4vec-memo-correct (implies (svex->a4vec-memotable-correctp memo env masks) (b* (((mv upper-spec lower-spec) (svex-concat->a4vec x env masks))) (and (equal upper upper-spec) (equal lower lower-spec) (svex->a4vec-memotable-correctp memo1 env masks)))) :hints ('(:expand (<call> (svex-concat->a4vec x env masks)))) :fn svex-concat->a4vec-memo) (defret svex-concat->a4vec-memo-lower-correct (implies (svex->a4vec-memotable-correctp memo env masks) (b* (((mv upper-spec lower-spec) (svex-concat->a4vec-lower x width upper-acc lower-acc env masks))) (and (equal upper upper-spec) (equal lower lower-spec) (svex->a4vec-memotable-correctp memo1 env masks)))) :hints ('(:expand ((:free (width) <call>) (:free (width) (svex-concat->a4vec-lower x width upper-acc lower-acc env masks))))) :fn svex-concat->a4vec-memo-lower)) (deffixequiv-mutual svex->a4vec-memo)) (define svexlist->a4vec-nrev ((x svexlist-p) (env svex-a4vec-env-p) (masks svex-mask-alist-p) (memo svex-aig-memotable-p) (acl2::nrev)) :returns (mv (new-nrev) (memo1 svex-aig-memotable-p)) (if (atom x) (b* ((acl2::nrev (acl2::nrev-fix acl2::nrev))) (mv acl2::nrev (svex-aig-memotable-fix memo))) (b* (((mv first memo) (svex->a4vec-memo (car x) env masks memo)) (acl2::nrev (acl2::nrev-push first acl2::nrev))) (svexlist->a4vec-nrev (cdr x) env masks memo acl2::nrev))) /// (defret svexlist->a4vec-nrev-removal (b* (((mv out-spec memo1-spec) (svexlist->a4vec-memo x env masks memo))) (and (equal new-nrev (append acl2::nrev out-spec)) (equal memo1 memo1-spec))) :hints(("Goal" :induct t :expand ((svexlist->a4vec-memo x env masks memo)))))) (define svexlist->a4vec-top ((x svexlist-p) (env svex-a4vec-env-p) (masks svex-mask-alist-p)) ;; note: env must be fast ;; :prepwork ((local (defthm svexlist->a4vec-decomp ;; (equal (list (mv-nth 0 (svexlist->a4vec x env masks memo)) ;; (mv-nth 1 (svexlist->a4vec x env masks memo))) ;; (svexlist->a4vec x env masks memo)) ;; :hints (("goal" :expand ((svexlist->a4vec x env masks memo))))))) :enabled t (mbe :logic (svexlist->a4vec x env masks) :exec (b* (((mv res memo) (with-local-stobj acl2::nrev (mv-let (res memo acl2::nrev) (b* (((mv acl2::nrev memo) (svexlist->a4vec-nrev x env masks nil acl2::nrev)) ((mv res acl2::nrev) (acl2::nrev-finish acl2::nrev))) (mv res memo acl2::nrev)) (mv res memo))))) (fast-alist-free memo) res))) ;; There are a few possible approaches to generating the a4vec-env to use in ;; building AIGs. Basically, we're going to generate a pair of Boolean ;; variables for each bit that matters (mask-wise) in x; the masks for the ;; variables of x must be finite so that we can determine which bits matter. ;; (The don't-care bits will be assigned X.) ;; But there are still a few options: ;; 1. Always assign AIG variables to every care bit of every variable. This ;; has the advantage that the input and output to svexlist->a4vec is always ;; identical for a given svexlist, so we can memoize, which may improve ;; performance if we run several simulations with the same svex but different ;; environments. But the complete set of variables might be overkill, ;; e.g. svtvs have lots of variables for don't-care inputs and initial ;; states. ;; 2. Assign AIG variables to the care bits of all the variables bound in the ;; environment. This could still allow good memoization as long as the same ;; variables are going to be assigned basically all the time. We can extract ;; and sort the variables so that the order of the bindings doesn't matter. ;; 3. In between 1 and 2: Take a list of variables as an extra argument, ;; ignored in the logic, which should be a superset of the variables in the ;; environment; only generate AIG vars for these variables. This care list ;; could be provided e.g. by the SVTV. This has the advantage over 2 that ;; memoization still works if different subsets of the care variables are ;; used in different runs. ;; The implementations of 1,2,3 would be quite similar and could basically ;; all be based on 3. ;; 4. More extreme than 2, more difficult to implement, and little chance of ;; memoization working: in the symbolic environment provided, we only really ;; need AIG variables for non-constant bits. So ignore masks and just ;; produce an a4vec environment that replicates the constants assigned in env ;; and generates AIG variables for the non-constant bits. This would mean ;; we'd need to get a hold of the symbolic environment, which probably would ;; mean we'd need a symbolic counterpart function, not just an alternate ;; definition. ;; The following implements option 3 above. We provide the svexlist and the ;; list of care vars. The function returns the a4veclist and the a4vec-env. (define nat-bool-listp (x) (if (atom x) (eq x nil) (and (or (natp (car x)) (booleanp (car x))) (nat-bool-listp (cdr x)))) /// (defthm nat-bool-listp-of-aig-sterm (implies (or (booleanp x) (natp x)) (nat-bool-listp (aig-sterm x))) :hints(("Goal" :in-theory (enable gl::bfr-sterm)))) (defthm nat-bool-listp-of-aig-scons (implies (and (or (booleanp x) (natp x)) (nat-bool-listp y)) (nat-bool-listp (aig-scons x y))) :hints(("Goal" :in-theory (enable gl::bfr-scons)))) (defthm nat-bool-listp-of-list-fix (implies (nat-bool-listp x) (nat-bool-listp (list-fix x))))) (define nat-bool-list-nats ((x nat-bool-listp)) :prepwork ((local (in-theory (enable nat-bool-listp)))) (if (atom x) nil (if (booleanp (car x)) (nat-bool-list-nats (cdr x)) (cons (lnfix (car x)) (nat-bool-list-nats (cdr x))))) /// (defthm nat-bool-list-nats-of-list-fix (equal (nat-bool-list-nats (list-fix x)) (nat-bool-list-nats x))) (defthm nat-bool-list-nats-of-aig-sterm (equal (nat-bool-list-nats (aig-sterm x)) (if (booleanp x) nil (list (nfix x)))) :hints(("Goal" :in-theory (enable gl::bfr-sterm)))) (defthm nat-bool-list-nats-of-aig-scons-bool (implies (booleanp x) (equal (nat-bool-list-nats (aig-scons x y)) (nat-bool-list-nats y))) :hints(("Goal" :in-theory (enable gl::bfr-scons)))) (defthm nat-bool-list-nats-of-aig-scons-nat (implies (and (natp x) (not (member x (nat-bool-list-nats y)))) (equal (nat-bool-list-nats (aig-scons x y)) (cons x (nat-bool-list-nats y)))) :hints(("Goal" :in-theory (enable gl::bfr-scons))))) (define nat-bool-list-lower-boundp ((bound natp) (x nat-bool-listp)) :prepwork ((local (in-theory (enable nat-bool-listp)))) (if (atom x) t (and (or (booleanp (car x)) (<= (lnfix bound) (lnfix (car x)))) (nat-bool-list-lower-boundp bound (cdr x)))) /// (defthm nat-bool-list-lower-boundp-of-list-fix (equal (nat-bool-list-lower-boundp bound (list-fix x)) (nat-bool-list-lower-boundp bound x))) (defthm nat-bool-list-nonmember-by-lower-bound (implies (and (nat-bool-list-lower-boundp bound x) (< v (nfix bound)) (nat-bool-listp x)) (not (member v (nat-bool-list-nats x)))) :hints(("Goal" :in-theory (enable nat-bool-list-nats)))) (Defthm nat-bool-list-lower-boundp-lower (implies (and (nat-bool-list-lower-boundp bound x) (<= (nfix n) (nfix bound))) (nat-bool-list-lower-boundp n x)))) (define nat-bool-list-upper-boundp ((bound natp) (x nat-bool-listp)) :prepwork ((local (in-theory (enable nat-bool-listp)))) (if (atom x) t (and (or (booleanp (car x)) (< (lnfix (car x)) (lnfix bound))) (nat-bool-list-upper-boundp bound (cdr x)))) /// (defthm nat-bool-list-upper-boundp-of-list-fix (equal (nat-bool-list-upper-boundp bound (list-fix x)) (nat-bool-list-upper-boundp bound x))) (defthm nat-bool-list-nonmember-by-upper-bound (implies (and (nat-bool-list-upper-boundp bound x) (<= (nfix bound) v) (nat-bool-listp x)) (not (member v (nat-bool-list-nats x)))) :hints(("Goal" :in-theory (enable nat-bool-list-nats)))) (defthm nat-bool-list-no-intersection-by-bounds (implies (and (nat-bool-list-upper-boundp bound0 x0) (nat-bool-list-lower-boundp bound1 x1) (<= (nfix bound0) (nfix bound1)) (nat-bool-listp x0) (nat-bool-listp x1)) (not (intersectp (nat-bool-list-nats x0) (nat-bool-list-nats x1)))) :hints(("Goal" :in-theory (e/d (intersectp-equal nat-bool-listp nat-bool-list-nats) (acl2::intersectp-equal-commute))))) (Defthm nat-bool-list-upper-boundp-higher (implies (and (nat-bool-list-upper-boundp bound x) (<= (nfix bound) (nfix n))) (nat-bool-list-upper-boundp n x)))) (define nat-bool-a4vec-p ((x a4vec-p)) (b* (((a4vec x) x)) (and (nat-bool-listp x.upper) (nat-bool-listp x.lower))) /// (deffixtype nba4vec :pred nat-bool-a4vec-p! :fix a4vec-fix :equiv a4vec-equiv)) (defmacro nat-bool-a4vec-p! (x) `(and (a4vec-p ,x) (nat-bool-a4vec-p ,x))) (define nat-bool-a4vec-vars ((x nat-bool-a4vec-p!)) :prepwork ((local (in-theory (enable nat-bool-a4vec-p)))) (b* (((a4vec x) x)) (append (nat-bool-list-nats x.upper) (nat-bool-list-nats x.lower)))) (define nat-bool-a4vec-lower-boundp ((bound natp) (x nat-bool-a4vec-p!)) :prepwork ((local (in-theory (enable nat-bool-a4vec-p)))) (b* (((a4vec x) x)) (and (nat-bool-list-lower-boundp bound x.upper) (nat-bool-list-lower-boundp bound x.lower))) /// (defthm nat-bool-a4vec-vars-nonmember-by-lower-bound (implies (and (nat-bool-a4vec-lower-boundp bound x) (< v (nfix bound)) (nat-bool-a4vec-p x)) (not (member v (nat-bool-a4vec-vars x)))) :hints(("Goal" :in-theory (enable nat-bool-a4vec-vars nat-bool-a4vec-p nat-bool-list-nonmember-by-lower-bound)))) (Defthm nat-bool-a4vec-lower-boundp-lower (implies (and (nat-bool-a4vec-lower-boundp bound x) (<= (nfix n) (nfix bound))) (nat-bool-a4vec-lower-boundp n x)))) (define nat-bool-a4vec-upper-boundp ((bound natp) (x nat-bool-a4vec-p!)) :prepwork ((local (in-theory (enable nat-bool-a4vec-p)))) (b* (((a4vec x) x)) (and (nat-bool-list-upper-boundp bound x.upper) (nat-bool-list-upper-boundp bound x.lower))) /// (defthm nat-bool-a4vec-vars-nonmember-by-upper-bound (implies (and (nat-bool-a4vec-upper-boundp bound x) (<= (nfix bound) v) (nat-bool-a4vec-p x)) (not (member v (nat-bool-a4vec-vars x)))) :hints(("Goal" :in-theory (enable nat-bool-a4vec-vars nat-bool-a4vec-p nat-bool-list-nonmember-by-upper-bound)))) (defthm nat-bool-a4vec-no-intersection-by-bounds (implies (and (nat-bool-a4vec-upper-boundp bound0 x0) (nat-bool-a4vec-lower-boundp bound1 x1) (<= (nfix bound0) (nfix bound1)) (nat-bool-a4vec-p x0) (nat-bool-a4vec-p x1)) (not (intersectp (nat-bool-a4vec-vars x0) (nat-bool-a4vec-vars x1)))) :hints(("Goal" :in-theory (e/d (intersectp-equal nat-bool-a4vec-p nat-bool-a4vec-vars nat-bool-a4vec-upper-boundp nat-bool-a4vec-lower-boundp) (acl2::intersectp-equal-commute))))) (Defthm nat-bool-a4vec-upper-boundp-higher (implies (and (nat-bool-a4vec-upper-boundp bound x) (<= (nfix bound) (nfix n))) (nat-bool-a4vec-upper-boundp n x)))) (define nat-bool-a4env-p ((x svex-a4vec-env-p)) :prepwork ((local (in-theory (enable svex-a4vec-env-fix)))) (if (atom x) t (and (if (mbt (consp (car x))) (nat-bool-a4vec-p (cdar x)) t) (nat-bool-a4env-p (cdr x)))) /// (deffixtype nba4env :pred nat-bool-a4env-p! :fix svex-a4vec-env-fix :equiv svex-a4vec-env-equiv)) (defmacro nat-bool-a4env-p! (x) `(and (svex-a4vec-env-p ,x) (nat-bool-a4env-p ,x))) (define nat-bool-a4env-vars ((x nat-bool-a4env-p!)) :prepwork ((local (in-theory (enable nat-bool-a4env-p svex-a4vec-env-fix)))) (if (atom x) nil (append (and (mbt (consp (car x))) (nat-bool-a4vec-vars (cdar x))) (nat-bool-a4env-vars (cdr x))))) (define nat-bool-a4env-lower-boundp ((bound natp) (x nat-bool-a4env-p!)) :prepwork ((local (in-theory (enable nat-bool-a4env-p svex-a4vec-env-fix)))) (if (atom x) t (and (if (mbt (consp (car x))) (nat-bool-a4vec-lower-boundp bound (cdar x)) t) (nat-bool-a4env-lower-boundp bound (cdr x)))) /// (defthm nat-bool-a4env-vars-nonmember-by-lower-bound (implies (and (nat-bool-a4env-lower-boundp bound x) (< v (nfix bound)) (nat-bool-a4env-p x)) (not (member v (nat-bool-a4env-vars x)))) :hints(("Goal" :in-theory (enable nat-bool-a4env-vars nat-bool-a4env-p nat-bool-list-nonmember-by-lower-bound)))) (Defthm nat-bool-a4env-lower-boundp-lower (implies (and (nat-bool-a4env-lower-boundp bound x) (<= (nfix n) (nfix bound))) (nat-bool-a4env-lower-boundp n x)))) (define nat-bool-a4env-upper-boundp ((bound natp) (x nat-bool-a4env-p!)) :prepwork ((local (in-theory (enable nat-bool-a4env-p svex-a4vec-env-fix)))) (if (atom x) t (and (if (mbt (consp (car x))) (nat-bool-a4vec-upper-boundp bound (cdar x)) t) (nat-bool-a4env-upper-boundp bound (cdr x)))) /// (defthm nat-bool-a4env-vars-nonmember-by-upper-bound (implies (and (nat-bool-a4env-upper-boundp bound x) (<= (nfix bound) v) (nat-bool-a4env-p x)) (not (member v (nat-bool-a4env-vars x)))) :hints(("Goal" :in-theory (enable nat-bool-a4env-vars nat-bool-a4env-p nat-bool-list-nonmember-by-upper-bound)))) (defthm nat-bool-a4vec/env-no-intersection-by-bounds (implies (and (nat-bool-a4vec-upper-boundp bound0 x0) (nat-bool-a4env-lower-boundp bound1 x1) (<= (nfix bound0) (nfix bound1)) (nat-bool-a4vec-p x0) (nat-bool-a4env-p x1)) (not (intersectp (nat-bool-a4vec-vars x0) (nat-bool-a4env-vars x1)))) :hints(("Goal" :in-theory (e/d (intersectp-equal nat-bool-a4env-p nat-bool-a4env-lower-boundp) (acl2::intersectp-equal-commute)) :expand ((nat-bool-a4env-vars x1)) :induct (nat-bool-a4env-lower-boundp bound1 x1)))) (defthm nat-bool-a4env-no-intersection-by-bounds (implies (and (nat-bool-a4env-upper-boundp bound0 x0) (nat-bool-a4env-lower-boundp bound1 x1) (<= (nfix bound0) (nfix bound1)) (nat-bool-a4env-p x0) (nat-bool-a4env-p x1)) (not (intersectp (nat-bool-a4env-vars x0) (nat-bool-a4env-vars x1)))) :hints(("Goal" :in-theory (e/d (intersectp-equal nat-bool-a4env-p nat-bool-a4env-vars nat-bool-a4env-upper-boundp nat-bool-a4env-lower-boundp) (acl2::intersectp-equal-commute))))) (defthm nat-bool-a4env-a4vec-no-intersection-by-bounds (implies (and (nat-bool-a4env-upper-boundp bound0 x0) (nat-bool-a4vec-lower-boundp bound1 x1) (<= (nfix bound0) (nfix bound1)) (nat-bool-a4env-p x0) (nat-bool-a4vec-p x1)) (not (intersectp (nat-bool-a4env-vars x0) (nat-bool-a4vec-vars x1)))) :hints(("Goal" :in-theory (e/d (intersectp-equal nat-bool-a4env-p nat-bool-a4env-vars nat-bool-a4env-upper-boundp nat-bool-a4env-lower-boundp) (acl2::intersectp-equal-commute))))) (Defthm nat-bool-a4env-upper-boundp-higher (implies (and (nat-bool-a4env-upper-boundp bound x) (<= (nfix bound) (nfix n))) (nat-bool-a4env-upper-boundp n x)))) (local (defthm logcount-of-logand (implies (natp y) (<= (logcount (logand x y)) (logcount y))) :hints(("Goal" :in-theory (e/d* (bitops::logcount** bitops::logand** bitops::ihsext-inductions)))) :rule-classes :linear)) (define sparseint-nfix ((x sparseint-p)) :guard (not (sparseint-< x 0)) :returns (new-x sparseint-p) :inline t (mbe :logic (if (sparseint-< x 0) 0 (sparseint-fix x)) :exec x) /// (defret <fn>-correct (equal (sparseint-val new-x) (nfix (sparseint-val x))))) (define 4vmask-to-a4vec-varcount ((mask 4vmask-p) (boolmask integerp)) :guard (not (sparseint-< mask 0)) :returns (count natp :rule-classes :type-prescription) (b* ((mask (sparseint-nfix (4vmask-fix mask)))) (- (* 2 (sparseint-bitcount mask)) (sparseint-bitcount (sparseint-bitand mask (int-to-sparseint boolmask)))))) (local (defcong sparseint-equal sparseint-equal (sparseint-nfix x) 1)) (local (defthm integer-length-posp (implies (posp x) (posp (integer-length x))) :hints(("Goal" :in-theory (enable* ihsext-recursive-redefs ihsext-inductions))) :rule-classes :type-prescription)) (define 4vmask-to-a4vec-rec ((mask 4vmask-p) (boolmask integerp) (nextvar natp)) :guard (not (sparseint-< mask 0)) :returns (mv (upper nat-bool-listp) (lower nat-bool-listp)) :verify-guards nil :measure (sparseint-length (sparseint-nfix mask)) :hints(("Goal" :in-theory (enable bitops::integer-length** 4vmask-fix))) (b* ((mask (sparseint-nfix (4vmask-fix mask))) (nextvar (lnfix nextvar)) ((when (sparseint-equal mask 0)) (mv (aig-sterm t) (aig-sterm nil))) ((mv ubit0 ubit1 nextvar) (if (eql 1 (sparseint-bit 0 mask)) (if (logbitp 0 boolmask) (mv nextvar nextvar (+ 1 nextvar)) (mv nextvar (1+ nextvar) (+ 2 nextvar))) (mv t nil nextvar))) ((mv rest-upper rest-lower) (4vmask-to-a4vec-rec (sparseint-rightshift 1 mask) (logcdr boolmask) nextvar))) (mv (aig-scons ubit0 rest-upper) (aig-scons ubit1 rest-lower))) /// ;; (defthm 4vmask-to-a4vec-rec-nextvar ;; (equal (mv-nth 2 (4vmask-to-a4vec-rec mask nextvar)) ;; (+ (* 2 (logcount (nfix mask))) (nfix nextvar))) ;; :hints(("Goal" :in-theory (enable bitops::logcount**)))) (defret true-listp-of-<fn>-upper (true-listp upper) :rule-classes :type-prescription) (defret true-listp-of-<fn>-lower (true-listp lower) :rule-classes :type-prescription) (verify-guards 4vmask-to-a4vec-rec) (defthm 4vmask-to-a4vec-rec-lower-bounds (and (nat-bool-list-lower-boundp nextvar (mv-nth 0 (4vmask-to-a4vec-rec mask boolmask nextvar))) (nat-bool-list-lower-boundp nextvar (mv-nth 1 (4vmask-to-a4vec-rec mask boolmask nextvar)))) :hints(("Goal" :in-theory (enable nat-bool-list-lower-boundp gl::bfr-scons))) :rule-classes ((:forward-chaining :trigger-terms ((4vmask-to-a4vec-rec mask boolmask nextvar))))) (defthm 4vmask-to-a4vec-rec-upper-bounds (and (nat-bool-list-upper-boundp (+ (nfix nextvar) (4vmask-to-a4vec-varcount mask boolmask)) (mv-nth 0 (4vmask-to-a4vec-rec mask boolmask nextvar))) (nat-bool-list-upper-boundp (+ (nfix nextvar) (4vmask-to-a4vec-varcount mask boolmask)) (mv-nth 1 (4vmask-to-a4vec-rec mask boolmask nextvar)))) :hints(("Goal" :in-theory (enable gl::bfr-scons 4vmask-to-a4vec-varcount bitops::logand** bitops::logbitp** bitops::logcount**) :induct (4vmask-to-a4vec-rec mask boolmask nextvar) :expand ((:free (bound a b) (nat-bool-list-upper-boundp bound (cons a b))) (:free (bound) (nat-bool-list-upper-boundp bound nil)) (:free (x) (logtail 1 x))) :do-not-induct t)) :rule-classes ((:forward-chaining :trigger-terms ((4vmask-to-a4vec-rec mask boolmask nextvar))))) ;; (defthm 4vmask-to-a4vec-rec-no-duplicate-vars ;; (b* (((mv upper lower) ;; (4vmask-to-a4vec-rec mask boolmask nextvar))) ;; (and (no-duplicatesp (nat-bool-list-nats upper)) ;; (no-duplicatesp (nat-bool-list-nats lower)) ;; (not (intersectp (nat-bool-list-nats upper) ;; (nat-bool-list-nats lower))))) ;; :hints(("Goal" :in-theory (enable nat-bool-list-nats ;; intersectp-equal)))) (defthm member-4vmask-to-a4vec-rec-vars ;; not a good rewrite rule but useful for the next phase (iff (member v (append (nat-bool-list-nats (mv-nth 0 (4vmask-to-a4vec-rec mask boolmask nextvar))) (nat-bool-list-nats (mv-nth 1 (4vmask-to-a4vec-rec mask boolmask nextvar))))) (and (natp v) (<= (nfix nextvar) v) (< v (+ (nfix nextvar) (4vmask-to-a4vec-varcount mask boolmask))))) :hints(("Goal" :in-theory (enable nat-bool-list-nats 4vmask-to-a4vec-varcount bitops::logand** bitops::logcount** bitops::logbitp**) :induct (4vmask-to-a4vec-rec mask boolmask nextvar)) (and stable-under-simplificationp '(:expand ((logcount (sparseint-val (4vmask-fix mask))) (:free (x) (logtail 1 x)))))) :rule-classes nil)) ;; (defthm eval-4vmask-to-a4vec-rec-cons-greater ;; (b* (((mv ?err upper lower nextvar1) ;; (4vmask-to-a4vec-rec mask nextvar))) ;; (implies (<= nextvar1 var) ;; (and (equal (aig-list->s upper (cons (cons var val) env)) ;; (aig-list->s upper env)) ;; (equal (aig-list->s lower (cons (cons var val) env)) ;; (aig-list->s lower env)))))) ;; (defthm eval-4vmask-to-a4vec-rec-cons-lesser ;; (b* (((mv ?err upper lower ?nextvar1) ;; (4vmask-to-a4vec-rec mask nextvar))) ;; (implies (< var (nfix nextvar)) ;; (and (equal (aig-list->s upper (cons (cons var val) env)) ;; (aig-list->s upper env)) ;; (equal (aig-list->s lower (cons (cons var val) env)) ;; (aig-list->s lower env))))))) (define 4vmask-to-a4vec-rec-env ((mask 4vmask-p) (boolmask integerp) (upper integerp) (lower integerp) (nextvar natp)) :guard (not (sparseint-< mask 0)) :returns (env "environment for the resulting 4vmask") :measure (sparseint-length (sparseint-nfix (4vmask-fix mask))) :hints(("Goal" :in-theory (enable bitops::integer-length** 4vmask-fix))) (b* ((mask (sparseint-nfix (4vmask-fix mask))) (nextvar (lnfix nextvar)) ((when (sparseint-equal mask 0)) nil) (rest-env (4vmask-to-a4vec-rec-env (sparseint-rightshift 1 mask) (logcdr boolmask) (logcdr upper) (logcdr lower) (if (eql 1 (sparseint-bit 0 mask)) (if (logbitp 0 boolmask) (+ 1 nextvar) (+ 2 nextvar)) nextvar)))) (if (eql 1 (sparseint-bit 0 mask)) (cons (cons nextvar (logbitp 0 upper)) (if (logbitp 0 boolmask) rest-env (cons (cons (1+ nextvar) (logbitp 0 lower)) rest-env))) rest-env)) /// (defthm key-exists-in-4vmask-to-a4vec-rec-env (iff (hons-assoc-equal v (4vmask-to-a4vec-rec-env mask boolmask upper lower nextvar)) (and (natp v) (<= (nfix nextvar) v) (< v (+ (nfix nextvar) (4vmask-to-a4vec-varcount mask boolmask))))) :hints(("Goal" :in-theory (enable bitops::logcount** bitops::logbitp** 4vmask-to-a4vec-varcount bitops::logand**) :do-not-induct t :induct (4vmask-to-a4vec-rec-env mask boolmask upper lower nextvar)) (and stable-under-simplificationp '(:expand ((:free (x) (logtail 1 x)) (logcount (sparseint-val (4vmask-fix mask)))))))) (defthm nat-bool-aig-list->s-of-cons-nonmember (implies (and (nat-bool-listp x) (not (member n (nat-bool-list-nats x)))) (equal (aig-list->s x (cons (cons n v) env)) (aig-list->s x env))) :hints(("Goal" :in-theory (enable aig-list->s nat-bool-listp nat-bool-list-nats gl::scdr gl::s-endp) :induct (aig-list->s x env) :expand ((:Free (env) (aig-list->s x env)))))) (local (defthm equal-nfix-plus-1 (not (equal x (+ 1 (nfix x)))) :hints(("Goal" :in-theory (enable nfix))))) (defthm eval-4vmask-to-a4vec-rec-with-env (b* (((mv uppera lowera) (4vmask-to-a4vec-rec mask boolmask nextvar)) (env (4vmask-to-a4vec-rec-env mask boolmask upper lower nextvar))) (and (equal (logand (nfix (sparseint-val (4vmask-fix mask))) (aig-list->s uppera env)) (logand (nfix (sparseint-val (4vmask-fix mask))) upper)) (implies (eql 0 (logand boolmask (logxor upper lower))) (equal (logand (nfix (sparseint-val (4vmask-fix mask))) (aig-list->s lowera env)) (logand (nfix (sparseint-val (4vmask-fix mask))) lower))))) :hints(("Goal" :in-theory (enable 4vmask-to-a4vec-rec bitops::logand** bitops::logxor** bitops::logbitp** 4vmask-fix) :induct (4vmask-to-a4vec-rec-env mask boolmask upper lower nextvar) :expand ((:free (x) (logtail 1 x)))) (and stable-under-simplificationp '(:in-theory (enable bitops::b-xor))) (and stable-under-simplificationp '(:in-theory (enable nfix)))))) (define 4vec-boolmaskp ((x 4vec-p) (mask integerp)) (b* (((4vec x) x)) (eql 0 (logand mask (logxor x.upper x.lower))))) (define 4vmask-to-a4vec ((mask 4vmask-p) (boolmask integerp) (nextvar natp)) :guard (not (sparseint-< mask 0)) :returns (res nat-bool-a4vec-p! :hints(("Goal" :in-theory (enable nat-bool-a4vec-p)))) :prepwork ((local (defthm true-listp-when-nat-bool-listp (implies (nat-bool-listp x) (true-listp x)) :hints(("Goal" :in-theory (enable nat-bool-listp)))))) (b* (((mv upper lower) (4vmask-to-a4vec-rec mask boolmask nextvar))) (a4vec upper lower)) /// ;; (defthm 4vmask-to-a4vec-nextvar ;; (equal (mv-nth 1 (4vmask-to-a4vec mask nextvar)) ;; (+ (* 2 (logcount (nfix mask))) (nfix nextvar)))) (defthm member-vars-of-4vmask-to-a4vec (iff (member v (nat-bool-a4vec-vars (4vmask-to-a4vec mask boolmask nextvar))) (and (natp v) (<= (nfix nextvar) v) (< v (+ (nfix nextvar) (4vmask-to-a4vec-varcount mask boolmask))))) :hints (("goal" :use member-4vmask-to-a4vec-rec-vars :in-theory (enable nat-bool-a4vec-vars)))) (defthm 4vmask-to-a4vec-lower-bounds (nat-bool-a4vec-lower-boundp nextvar (4vmask-to-a4vec mask boolmask nextvar)) :hints(("Goal" :in-theory (enable nat-bool-a4vec-lower-boundp))) :rule-classes ((:forward-chaining :trigger-terms ((4vmask-to-a4vec mask boolmask nextvar))))) (defthm 4vmask-to-a4vec-upper-bounds (nat-bool-a4vec-upper-boundp (+ (nfix nextvar) (4vmask-to-a4vec-varcount mask boolmask)) (4vmask-to-a4vec mask boolmask nextvar)) :hints(("Goal" :in-theory (enable nat-bool-a4vec-upper-boundp))) :rule-classes ((:forward-chaining :trigger-terms ((4vmask-to-a4vec mask boolmask nextvar)))))) (define 4vmask-to-a4vec-env ((mask 4vmask-p) (boolmask integerp) (val 4vec-p) (nextvar natp)) :guard (not (sparseint-< mask 0)) :returns env :prepwork ((local (defthm true-listp-when-nat-bool-listp (implies (nat-bool-listp x) (true-listp x)) :hints(("Goal" :in-theory (enable nat-bool-listp)))))) (4vmask-to-a4vec-rec-env mask boolmask (4vec->upper val) (4vec->lower val) nextvar) /// (defthm key-exists-in-4vmask-to-a4vec-env (iff (hons-assoc-equal v (4vmask-to-a4vec-env mask boolmask val nextvar)) (and (natp v) (<= (nfix nextvar) v) (< v (+ (nfix nextvar) (4vmask-to-a4vec-varcount mask boolmask)))))) (local (defthm mask-lemma (IMPLIES (AND (EQUAL (LOGAND mask a) (LOGAND b mask))) (EQUAL (LOGIOR b (lognot mask)) (LOGIOR (LOGNOT mask) a))) :hints ((bitops::logbitp-reasoning)))) (defthm eval-4vmask-to-a4vec-with-env (b* ((vala (4vmask-to-a4vec mask boolmask nextvar)) (env (4vmask-to-a4vec-env mask boolmask val nextvar))) (implies (and (4vec-boolmaskp val boolmask) (4vmask-p mask) (natp (sparseint-val mask))) (equal (4vec-mask mask (a4vec-eval vala env)) (4vec-mask mask val)))) :hints(("Goal" :in-theory (e/d (4vmask-to-a4vec 4vec-boolmaskp 4vmask-fix 4vec-mask a4vec-eval) (eval-4vmask-to-a4vec-rec-with-env)) :use ((:instance eval-4vmask-to-a4vec-rec-with-env (upper (4vec->upper val)) (lower (4vec->lower val))))) ;; (bitops::logbitp-reasoning) ;; (and stable-under-simplificationp ;; '(:bdd (:vars nil))) )) ;; (defthm eval-4vmask-to-a4vec-with-env-mask-natp ;; (b* ((vala (4vmask-to-a4vec mask boolmask nextvar)) ;; (env (4vmask-to-a4vec-env mask boolmask val nextvar))) ;; (implies (and (4vec-boolmaskp val boolmask)) ;; (equal (4vec-mask mask (a4vec-eval vala env)) ;; (4vec-mask mask val)))) ;; :hints (("Goal" :use eval-4vmask-to-a4vec-with-env ;; :in-theory (disable eval-4vmask-to-a4vec-with-env)))) ) (local (in-theory (disable PICK-A-POINT-SUBSET-STRATEGY))) (define svex-maskbits-for-vars ((vars svarlist-p) (masks svex-mask-alist-p) (boolmasks svar-boolmasks-p)) :prepwork ((local (in-theory (enable svarlist-p svarlist-fix)))) :returns (incr natp :rule-classes :type-prescription) (b* (((when (atom vars)) 0) (mask (svex-mask-lookup (svex-var (car vars)) masks)) (boolmask (svar-boolmasks-lookup (car vars) boolmasks)) ((when (sparseint-< mask 0)) 0)) (+ (4vmask-to-a4vec-varcount mask boolmask) (svex-maskbits-for-vars (cdr vars) masks boolmasks)))) (define svex-maskbits-ok ((vars svarlist-p) (masks svex-mask-alist-p)) :prepwork ((local (in-theory (enable svarlist-p svarlist-fix)))) (b* (((when (atom vars)) t) (mask (svex-mask-lookup (svex-var (car vars)) masks)) ((when (sparseint-< mask 0)) nil)) (svex-maskbits-ok (cdr vars) masks))) (define svex-varmasks->a4env-rec ((vars svarlist-p) (masks svex-mask-alist-p) (boolmasks svar-boolmasks-p) (nextvar natp) (acc nat-bool-a4env-p!)) :prepwork ((local (in-theory (enable svarlist-p svarlist-fix nat-bool-a4env-p svex-mask-alist-fix svex-a4vec-env-fix)))) :returns (mv (err "some mask was negative" (iff err (not (svex-maskbits-ok vars masks))) :hints(("Goal" :in-theory (enable svex-maskbits-ok)))) (a4env nat-bool-a4env-p! :hyp (nat-bool-a4env-p! acc)) (nextvar1 (equal nextvar1 (+ (nfix nextvar) (svex-maskbits-for-vars vars masks boolmasks))) :hints(("Goal" :in-theory (enable svex-maskbits-for-vars))))) (b* ((acc (svex-a4vec-env-fix acc)) ((when (atom vars)) (mv nil acc (lnfix nextvar))) (mask (svex-mask-lookup (svex-var (car vars)) masks)) ((when (sparseint-< mask 0)) (mv (msg "Negative mask: ~x0~%" (svar-fix (car vars))) acc (lnfix nextvar))) (boolmask (svar-boolmasks-lookup (car vars) boolmasks)) (a4vec (4vmask-to-a4vec mask boolmask nextvar)) (nextvar (+ (lnfix nextvar) (4vmask-to-a4vec-varcount mask boolmask)))) (svex-varmasks->a4env-rec (cdr vars) masks boolmasks nextvar (cons (cons (svar-fix (car vars)) a4vec) acc))) /// (local (defun-sk svex-varmasks->a4env-rec-accumulator-elim-correct (vars masks boolmasks nextvar) (forall acc (implies (syntaxp (not (equal acc ''nil))) (b* (((mv err1 a4env1 nextvar1) (svex-varmasks->a4env-rec vars masks boolmasks nextvar acc)) ((mv err2 a4env2 nextvar2) (svex-varmasks->a4env-rec vars masks boolmasks nextvar nil))) (and (equal err1 err2) (equal a4env1 (append a4env2 (svex-a4vec-env-fix acc))) (equal nextvar1 nextvar2))))) :rewrite :direct)) (local (in-theory (disable svex-varmasks->a4env-rec-accumulator-elim-correct))) (local (defthmd svex-varmasks->a4env-rec-accumulator-elim-lemma (svex-varmasks->a4env-rec-accumulator-elim-correct vars masks boolmasks nextvar) :hints (("goal" :induct (svex-varmasks->a4env-rec vars masks boolmasks nextvar acc)) (and stable-under-simplificationp `(:expand (,(car (last clause)) (:free (acc) (svex-varmasks->a4env-rec vars masks boolmasks nextvar acc)))))))) (defthmd svex-varmasks->a4env-rec-accumulator-elim (implies (syntaxp (not (equal acc ''nil))) (b* (((mv err1 a4env1 nextvar1) (svex-varmasks->a4env-rec vars masks boolmasks nextvar acc)) ((mv err2 a4env2 nextvar2) (svex-varmasks->a4env-rec vars masks boolmasks nextvar nil))) (and (equal err1 err2) (equal a4env1 (append a4env2 (svex-a4vec-env-fix acc))) (equal nextvar1 nextvar2)))) :hints (("goal" :use svex-varmasks->a4env-rec-accumulator-elim-lemma))) (defthm member-vars-of-svex-varmasks->a4env-rec (iff (member v (nat-bool-a4env-vars (mv-nth 1 (svex-varmasks->a4env-rec vars masks boolmasks nextvar acc)))) (or (member v (nat-bool-a4env-vars acc)) (and (natp v) (<= (nfix nextvar) v) (< v (+ (nfix nextvar) (svex-maskbits-for-vars vars masks boolmasks)))))) :hints(("Goal" :in-theory (enable svex-maskbits-for-vars nat-bool-a4env-vars)))) (defthm svex-varmasks->a4env-rec-lower-bounds (implies (and (nat-bool-a4env-lower-boundp bound acc) (<= (nfix bound) (nfix nextvar))) (nat-bool-a4env-lower-boundp bound (mv-nth 1 (svex-varmasks->a4env-rec vars masks boolmasks nextvar acc)))) :hints(("Goal" :in-theory (enable nat-bool-a4env-lower-boundp)))) (defthm svex-varmasks->a4env-rec-upper-bounds (implies (and (nat-bool-a4env-upper-boundp bound acc) (<= (+ (nfix nextvar) (svex-maskbits-for-vars vars masks boolmasks)) (nfix bound))) (nat-bool-a4env-upper-boundp bound (mv-nth 1 (svex-varmasks->a4env-rec vars masks boolmasks nextvar acc)))) :hints(("Goal" :in-theory (enable nat-bool-a4env-upper-boundp svex-maskbits-for-vars)))) (defret key-exists-in-svex-varmasks->a4env-rec (implies (not err) (iff (hons-assoc-equal v a4env) (or (member v (svarlist-fix vars)) (hons-assoc-equal v (svex-a4vec-env-fix acc)))))) (defret alist-keys-of-svex-varmasks->a4env-rec (implies (not err) (equal (alist-keys a4env) (append (rev (svarlist-fix vars)) (alist-keys (svex-a4vec-env-fix acc))))) :hints(("Goal" :in-theory (enable svex-maskbits-ok))))) ;; (defsection svex-envs-masks-partly-equiv ;; (defquant svex-envs-masks-partly-equiv (vars masks env1 env2) ;; (forall v ;; (implies (not (member (svar-fix v) (svarlist-fix vars))) ;; (equal (4vec-mask (svex-mask-lookup (svex-var v) masks) ;; (svex-env-lookup v env1)) ;; (4vec-mask (svex-mask-lookup (svex-var v) masks) ;; (svex-env-lookup v env2))))) ;; :rewrite :direct) ;; (defexample svex-envs-masks-partly-equiv-example ;; :pattern (equal (4vec-mask (svex-mask-lookup (svex-var v) masks) ;; val1) ;; (4vec-mask mask2 val2)) ;; :templates (v) ;; :instance-rulename svex-envs-masks-partly-equiv-instancing)) (defsection svex-envs-mask-equiv-on-vars (defquant svex-envs-mask-equiv-on-vars (vars masks env1 env2) (forall v (implies (member (svar-fix v) (svarlist-fix vars)) (equal (4vec-mask (svex-mask-lookup (svex-var v) masks) (svex-env-lookup v env1)) (4vec-mask (svex-mask-lookup (svex-var v) masks) (svex-env-lookup v env2))))) :rewrite :direct) (defexample svex-envs-mask-equiv-on-vars-example :pattern (equal (4vec-mask (svex-mask-lookup (svex-var v) masks) val1) (4vec-mask mask2 val2)) :templates (v) :instance-rulename svex-envs-mask-equiv-on-vars-instancing) (local (defexample svex-envs-mask-equiv-on-vars-mask-look-example :pattern (svex-mask-lookup (svex-var var) masks) :templates (var) :instance-rulename svex-envs-mask-equiv-on-vars-instancing)) (local (defexample svex-envs-mask-equiv-on-vars-env-look-example :pattern (svex-env-lookup var env) :templates (var) :instance-rulename svex-envs-mask-equiv-on-vars-instancing)) (local (defexample svex-argmasks-okp-example :pattern (equal (4vec-mask mask (svex-apply fn (svexlist-eval args env1))) (4vec-mask mask (svex-apply fn (svexlist-eval args env2)))) :templates (env1 (svexlist-eval args env2)) :instance-rulename svex-argmasks-okp-instancing)) (local (acl2::def-witness-ruleset svex-mask-alist-reasoning '(svex-mask-alist-complete-witnessing svex-mask-alist-complete-instancing svex-mask-alist-complete-example svex-mask-alist-partly-complete-witnessing svex-mask-alist-partly-complete-instancing svex-mask-alist-partly-complete-example))) (local (acl2::def-witness-ruleset svex-env-reasoning '(svex-envs-mask-equiv-on-vars-instancing svex-envs-mask-equiv-on-vars-witnessing svex-envs-mask-equiv-on-vars-mask-look-example svex-envs-mask-equiv-on-vars-env-look-example svex-mask-alist-reasoning SVEX-ARGMASKS-OKP-WITNESSING SVEX-ARGMASKS-OKP-INSTANCING SVEX-ARGMASKS-OKP-EXAMPLE ))) (defthm-svex-eval-flag (defthm svex-eval-of-mask-equiv-on-vars-envs (implies (and (svex-mask-alist-complete masks) (svex-envs-mask-equiv-on-vars vars masks env1 env2) (subsetp-equal (intersection-equal (svex-vars x) (union-equal (alist-keys (svex-env-fix env1)) (alist-keys (svex-env-fix env2)))) (svarlist-fix vars))) (equal (equal (4vec-mask (svex-mask-lookup x masks) (svex-eval x env1)) (4vec-mask (svex-mask-lookup x masks) (svex-eval x env2))) t)) :hints ('(:expand ((:free (env) (svex-eval x env)) (svex-vars x)) :do-not-induct t) (witness :ruleset svex-env-reasoning) (witness :ruleset svex-env-reasoning) (set-reasoning) (and stable-under-simplificationp '(:in-theory (enable svex-env-lookup))) ;; (and stable-under-simplificationp ;; '(:use ((:instance svex-argmasks-okp-necc ;; (mask (svex-mask-lookup x masks)) ;; (argmasks (svex-argmasks-lookup ;; (svex-call->args x) masks)) ;; (env env1) ;; (vals (svexlist-eval (svex-call->args x) env2)))))) ) :flag expr) (defthm svexlist-eval-of-mask-equiv-on-vars-envs (implies (and (svex-mask-alist-complete masks) (svex-envs-mask-equiv-on-vars vars masks env1 env2) (subsetp-equal (intersection-equal (svexlist-vars x) (union-equal (alist-keys (svex-env-fix env1)) (alist-keys (svex-env-fix env2)))) (svarlist-fix vars))) (equal (equal (4veclist-mask (svex-argmasks-lookup x masks) (svexlist-eval x env1)) (4veclist-mask (svex-argmasks-lookup x masks) (svexlist-eval x env2))) t)) :hints ('(:expand ((:free (env) (svexlist-eval x env)) (svexlist-vars x) (svex-argmasks-lookup x masks)))) :flag list)) ) (local (defthm hons-assoc-equal-of-append (equal (hons-assoc-equal k (append a b)) (or (hons-assoc-equal k a) (hons-assoc-equal k b))))) (defthm aig-list->s-of-append-when-first-superset (implies (and (nat-bool-listp x) (subsetp (nat-bool-list-nats x) (alist-keys env))) (equal (aig-list->s x (append env rest)) (aig-list->s x env))) :hints(("Goal" :in-theory (e/d* (aig-list->s nat-bool-listp nat-bool-list-nats gl::scdr gl::s-endp) ((:rules-of-class :type-prescription :here))) :induct (aig-list->s x env) :expand ((:free (env) (aig-list->s x env)))))) (defthm a4vec-eval-of-append-when-first-superset (implies (and (nat-bool-a4vec-p x) (subsetp (nat-bool-a4vec-vars x) (alist-keys env))) (equal (a4vec-eval x (append env rest)) (a4vec-eval x env))) :hints(("Goal" :in-theory (enable a4vec-eval nat-bool-a4vec-p nat-bool-a4vec-vars)))) (defthm aig-list->s-of-append-when-first-not-intersect (implies (and (nat-bool-listp x) (not (intersectp (nat-bool-list-nats x) (alist-keys prev)))) (equal (aig-list->s x (append prev env)) (aig-list->s x env))) :hints(("Goal" :in-theory (e/d* (aig-list->s nat-bool-listp nat-bool-list-nats gl::scdr gl::s-endp) ((:rules-of-class :type-prescription :here))) :induct (aig-list->s x env) :expand ((:free (env) (aig-list->s x env)))))) (defthm a4vec-eval-of-append-when-first-not-intersect (implies (and (nat-bool-a4vec-p x) (not (intersectp (nat-bool-a4vec-vars x) (alist-keys prev)))) (equal (a4vec-eval x (append prev env)) (a4vec-eval x env))) :hints(("Goal" :in-theory (enable a4vec-eval nat-bool-a4vec-p nat-bool-a4vec-vars)))) (defthm nat-bool-a4vec-p-of-nat-bool-a4env (implies (and (nat-bool-a4env-p x) (hons-assoc-equal k x)) (nat-bool-a4vec-p (cdr (hons-assoc-equal k x)))) :hints(("Goal" :in-theory (enable nat-bool-a4env-p)))) ;; (define svex-env-lookup-nofix (x env) ;; (or (cdr (hons-get x env)) (4vec-x)) ;; /// ;; (defthm svex-env-lookup-nofix-when-right-types ;; (implies (and (svar-p x) ;; (svex-env-p env)) ;; (equal (svex-env-lookup-nofix x env) ;; (svex-env-lookup x env))) ;; :hints(("Goal" :in-theory (enable svex-env-lookup ;; svex-env-p)))) ;; ;; (local (defthm lookup-in-svex-env-fix-when-svar-p ;; ;; (implies (and (svar-p x) ;; ;; (not (cdr (hons-assoc-equal x env)))) ;; ;; (4vec-equiv (cdr (hons-assoc-equal x (svex-env-fix env))) ;; ;; (4vec-x))) ;; ;; :hints(("Goal" :in-theory (enable svex-env-fix))))) ;; (defthm svex-env-lookup-nofix-when-right-types-weak ;; (implies (svar-p x) ;; (4vec-equiv (svex-env-lookup-nofix x env) ;; (svex-env-lookup x env))) ;; :hints(("Goal" :in-theory (enable svex-env-lookup svex-env-fix))))) (define svex-mask-alist-extract-vars ((x svex-mask-alist-p)) :returns (new-x svex-mask-alist-p) :hooks nil (if (atom x) nil (if (and (mbt (svex-p (caar x))) (eq (svex-kind (caar x)) :var)) (hons-acons (caar x) (4vmask-fix (cdar x)) (svex-mask-alist-extract-vars (cdr x))) (svex-mask-alist-extract-vars (cdr x)))) /// (defret lookup-in-svex-mask-alist-extract-vars (equal (hons-assoc-equal s new-x) (and (svex-p s) (equal (svex-kind s) :var) (hons-assoc-equal s (svex-mask-alist-fix x))))) (local (defthm assoc-in-svex-mask-alist-p (implies (svex-mask-alist-p x) (equal (assoc k x) (hons-assoc-equal k x))) :hints(("Goal" :in-theory (enable svex-mask-alist-p))))) (defret svex-mask-lookup-in-svex-mask-alist-extract-vars (equal (svex-mask-lookup s new-x) (if (equal (svex-kind s) :var) (svex-mask-lookup s x) 0)) :hints(("Goal" :in-theory (enable svex-mask-lookup)))) (defret svex-maskbits-ok-of-svex-mask-alist-extract-vars (iff (svex-maskbits-ok vars new-x) (svex-maskbits-ok vars x)) :hints(("Goal" :in-theory (enable svex-maskbits-ok) :induct (svex-maskbits-ok vars x) :do-not-induct t))) (defret svex-maskbits-for-vars-of-svex-mask-alist-extract-vars (equal (svex-maskbits-for-vars vars new-x boolmasks) (svex-maskbits-for-vars vars x boolmasks)) :hints(("Goal" :in-theory (e/d (svex-maskbits-for-vars) (svex-mask-alist-extract-vars))))) (deffixequiv svex-mask-alist-extract-vars :hints(("Goal" :in-theory (enable svex-mask-alist-fix))))) (define svex-varmasks/env->aig-env-rec ((vars svarlist-p) (masks svex-mask-alist-p) (boolmasks svar-boolmasks-p) (env svex-env-p "look up variables in env to get 4vecs to assign -- symbolic") (nextvar natp) (acc "aig environment accumulator")) :prepwork ((local (in-theory (enable svarlist-p svarlist-fix)))) :returns (mv (err "some mask was negative" (implies (svex-mask-alist-p masks) (iff err (not (svex-maskbits-ok vars masks)))) :hints(("Goal" :in-theory (enable svex-maskbits-ok)))) (env) ;; binds AIG vars to Boolean values (nextvar1 (implies (and (svex-mask-alist-p masks) (svar-boolmasks-p boolmasks)) (equal nextvar1 (+ (nfix nextvar) (svex-maskbits-for-vars vars masks boolmasks)))) :hints(("Goal" :in-theory (enable svex-maskbits-for-vars))))) ;; :hooks ((:fix :args (vars nextvar))) (b* (((when (atom vars)) (mv nil acc (lnfix nextvar))) (mask (svex-mask-lookup (svex-var (car vars)) masks)) ((when (sparseint-< mask 0)) (mv (msg "Negative mask: ~x0~%" (svar-fix (car vars))) acc (lnfix nextvar))) (boolmask (svar-boolmasks-lookup (car vars) boolmasks)) (4vec (4vec-fix (svex-env-lookup (svar-fix (car vars)) env))) (env-part (4vmask-to-a4vec-env mask boolmask 4vec nextvar)) (nextvar (+ (lnfix nextvar) (4vmask-to-a4vec-varcount mask boolmask)))) (svex-varmasks/env->aig-env-rec (cdr vars) masks boolmasks env nextvar (append env-part acc))) /// (defthm key-exists-in-svex-varmasks/env->aig-env-rec (implies (and (svex-mask-alist-p masks) (svar-boolmasks-p boolmasks)) (iff (hons-assoc-equal v (mv-nth 1 (svex-varmasks/env->aig-env-rec vars masks boolmasks env nextvar acc))) (or (hons-assoc-equal v acc) (and (natp v) (<= (nfix nextvar) v) (< v (+ (nfix nextvar) (svex-maskbits-for-vars vars masks boolmasks))))))) :hints(("Goal" :in-theory (enable svex-maskbits-for-vars)))) (local (defun-sk svex-varmasks/env->aig-env-accumulator-elim-correct (vars masks boolmasks env nextvar) (forall acc (implies (syntaxp (not (equal acc ''nil))) (equal (mv-nth 1 (svex-varmasks/env->aig-env-rec vars masks boolmasks env nextvar acc)) (append (mv-nth 1 (svex-varmasks/env->aig-env-rec vars masks boolmasks env nextvar nil)) acc)))) :rewrite :direct)) (local (in-theory (disable svex-varmasks/env->aig-env-accumulator-elim-correct))) (local (defthmd svex-varmasks/env->aig-env-accumulator-elim-lemma (svex-varmasks/env->aig-env-accumulator-elim-correct vars masks boolmasks env nextvar) :hints (("goal" :induct (svex-varmasks/env->aig-env-rec vars masks boolmasks env nextvar acc)) (and stable-under-simplificationp `(:expand (,(car (last clause)) (:free (acc) (svex-varmasks/env->aig-env-rec vars masks boolmasks env nextvar acc)))))))) (defthm svex-varmasks/env->aig-env-accumulator-elim (implies (syntaxp (not (equal acc ''nil))) (equal (mv-nth 1 (svex-varmasks/env->aig-env-rec vars masks boolmasks env nextvar acc)) (append (mv-nth 1 (svex-varmasks/env->aig-env-rec vars masks boolmasks env nextvar nil)) acc))) :hints (("goal" :use svex-varmasks/env->aig-env-accumulator-elim-lemma))) (defthm 4vmask-to-a4vec-vars-subset-of-keys (SUBSETP-EQUAL (NAT-BOOL-A4VEC-VARS (4vmask-to-a4vec mask boolmask nextvar)) (ALIST-KEYS (4vmask-to-a4vec-env mask boolmask val nextvar))) :hints ((acl2::set-reasoning))) (defthm member-nat-bool-a4vec-vars-of-lookup-when-upper-bounded (implies (and (nat-bool-a4env-p a4acc) (nat-bool-a4env-upper-boundp nextvar a4acc) (<= (nfix nextvar) k)) (not (member k (nat-bool-a4vec-vars (cdr (hons-assoc-equal v a4acc)))))) :hints(("Goal" :in-theory (enable nat-bool-a4env-p nat-bool-a4env-upper-boundp)))) (defthm 4vmask-to-a4vec-env-vars-not-intersect-when-upper-bounded (implies (and (nat-bool-a4env-p a4acc) (double-rewrite (nat-bool-a4env-upper-boundp nextvar a4acc))) (not (intersectp (nat-bool-a4vec-vars (cdr (hons-assoc-equal v a4acc))) (alist-keys (4vmask-to-a4vec-env mask boolmask val nextvar))))) :hints ((acl2::set-reasoning))) (local (defthm 4vmask-to-a4vec-vars-not-intersect-svex-varmsks/env->aig-env-rec-keys (implies (and (svex-mask-alist-p masks) (svar-boolmasks-p boolmasks)) (NOT (INTERSECTP-EQUAL (NAT-BOOL-A4VEC-VARS (4VMASK-TO-A4VEC mask boolmask NEXTVAR)) (ALIST-KEYS (MV-NTH 1 (SVEX-VARMASKS/ENV->AIG-ENV-REC vars masks BOOLMASKS GOALENV (+ (NFIX NEXTVAR) (4VMASK-TO-A4VEC-VARCOUNT mask boolmask)) NIL)))))) :hints ((set-reasoning)))) (local (defthm not-member-a4vec-vars-lookup-when-not-member-a4env-vars (implies (not (member v (nat-bool-a4env-vars a4env))) (not (member v (nat-bool-a4vec-vars (cdr (hons-assoc-equal v0 a4env)))))) :hints(("Goal" :in-theory (enable nat-bool-a4env-vars))))) (local (defthm 4vmask-to-a4vec-vars-subset-svex-varmsks/env->aig-env-rec-keys-2 (implies (and (svex-mask-alist-p masks) (svar-boolmasks-p boolmasks)) (SUBSETP-EQUAL (NAT-BOOL-A4VEC-VARS (CDR (HONS-ASSOC-EQUAL v0 (MV-NTH 1 (SVEX-VARMASKS->A4ENV-REC vars MASKS BOOLMASKS nextvar NIL))))) (ALIST-KEYS (MV-NTH 1 (SVEX-VARMASKS/ENV->AIG-ENV-REC vars (SVEX-MASK-ALIST-EXTRACT-VARS MASKS) BOOLMASKS GOALENV nextvar NIL))))) :hints ((set-reasoning)))) (acl2::defquant svex-env-boolmasks-ok (env boolmasks) (forall v (4vec-boolmaskp (svex-env-lookup v env) (svar-boolmasks-lookup v boolmasks))) :rewrite :direct) (local (defthm svex-env-lookup-of-cons (equal (svex-env-lookup k (cons (cons k0 v0) rest)) (if (and (svar-p k0) (equal (svar-fix k) k0)) (4vec-fix v0) (svex-env-lookup k rest))) :hints(("Goal" :in-theory (enable svex-env-lookup svex-env-fix))))) (local (in-theory (enable svex-env-boolmasks-ok-necc svex-varmasks->a4env-rec-accumulator-elim))) (defthm eval-svex-varmasks->a4env-rec-with-env (b* (((mv err a4env ?nextvar1) ;; Assigns AIG variable numbers to each SVEX var. Ignores goalenv (does ;; not need to know anything about the values of the svex vars to do ;; this, just their caremasks/boolmasks). (svex-varmasks->a4env-rec vars masks boolmasks nextvar nil)) ((mv ?err1 env ?nextvar1) ;; Binds AIG variable numbers to (symbolic) bits extracted from the goalenv. (svex-varmasks/env->aig-env-rec vars (svex-mask-alist-extract-vars masks) boolmasks goalenv nextvar nil))) (implies (and (not err) ;; (nat-bool-a4env-p a4acc) ;; (nat-bool-a4env-upper-boundp nextvar a4acc) (svex-mask-alist-p masks) (svar-boolmasks-p boolmasks) (svex-env-boolmasks-ok goalenv boolmasks) ;; (svex-env-p goalenv) ;; (svex-envs-masks-partly-equiv ;; vars masks ;; (svex-a4vec-env-eval a4acc envacc) ;; goalenv) ;; (subsetp (alist-keys (svex-env-fix goalenv)) ;; (append (svarlist-fix vars) ;; (alist-keys (svex-a4vec-env-fix a4acc)))) ) (svex-envs-mask-equiv-on-vars vars masks (svex-a4vec-env-eval a4env env) goalenv))) :hints(("Goal" :in-theory (enable svex-varmasks->a4env-rec svarlist-fix svex-maskbits-ok nat-bool-a4env-p nat-bool-a4env-upper-boundp svex-a4vec-env-fix svex-a4vec-env-eval alist-keys svex-alist-keys) :induct (svex-varmasks->a4env-rec vars masks boolmasks nextvar nil) ;; (svex-varmasks->a4env-rec-induct ;; vars masks boolmasks nextvar a4acc goalenv envacc) :expand ((:free (a4acc) (svex-varmasks->a4env-rec vars masks boolmasks nextvar a4acc)) (:free (envacc masks) (svex-varmasks/env->aig-env-rec vars masks boolmasks goalenv nextvar envacc)))) (and stable-under-simplificationp (cond ((assoc 'subsetp-equal clause) ;; has a (not (subsetp-equal... lit (acl2::set-reasoning)) ;; ((assoc 'svex-envs-masks-partly-equiv clause) ;; '(:computed-hint-replacement ;; ((acl2::witness :ruleset (svex-envs-masks-partly-equiv-witnessing)) ;; (acl2::witness :ruleset (svex-envs-masks-partly-equiv-example))) ;; :in-theory (enable ;; svex-env-lookup ;; svex-env-fix))) ;; (t '(:computed-hint-replacement ;; ((acl2::witness :ruleset (svex-envs-mask-equiv-witnessing)) ;; (acl2::witness :ruleset (svex-envs-masks-partly-equiv-example))) ;; :no-op t)) (t '(:computed-hint-replacement ((acl2::witness :ruleset (svex-envs-mask-equiv-on-vars-witnessing)) (acl2::witness :ruleset (svex-envs-mask-equiv-on-vars-example))) :no-op t)) ))))) (define svex-varmasks->a4env ((vars svarlist-p) (masks svex-mask-alist-p) (boolmasks svar-boolmasks-p)) :returns (mv (err "some mask was negative" (iff err (not (svex-maskbits-ok vars masks)))) (a4env nat-bool-a4env-p!)) (b* (((mv err res &) (svex-varmasks->a4env-rec vars masks boolmasks 0 nil))) (mv err res)) /// (defret alist-keys-of-svex-varmasks->a4env (implies (not err) (equal (alist-keys a4env) (rev (svarlist-fix vars)))))) (define svex-varmasks/env->aig-env ((vars svarlist-p) (masks svex-mask-alist-p) (boolmasks svar-boolmasks-p) (env svex-env-p "look up variables in env to get 4vecs to assign")) :returns (mv (err "some mask was negative" (implies (svex-mask-alist-p masks) (iff err (not (svex-maskbits-ok vars masks)))) :hints(("Goal" :in-theory (enable svex-maskbits-ok)))) (env "binds AIG vars to Boolean values")) :hooks ((:fix :args (vars))) (b* (((mv err res &) (svex-varmasks/env->aig-env-rec vars masks boolmasks env 0 nil))) (mv err res)) /// (defthm eval-svex-varmasks->a4env-with-env (b* (((mv err a4env) (svex-varmasks->a4env vars masks boolmasks1)) ((mv ?err1 env) (svex-varmasks/env->aig-env vars (svex-mask-alist-extract-vars masks) boolmasks goalenv))) (implies (and (not err) (svex-mask-alist-p masks) (equal boolmasks (svar-boolmasks-fix boolmasks1)) ;; (svex-env-p goalenv) (svex-env-boolmasks-ok goalenv boolmasks)) (svex-envs-mask-equiv-on-vars vars masks (svex-a4vec-env-eval a4env env) goalenv))) :hints (("goal" :use ((:instance eval-svex-varmasks->a4env-rec-with-env (nextvar 0))) :in-theory (e/d (svex-varmasks->a4env svex-env-lookup svex-lookup) (eval-svex-varmasks->a4env-rec-with-env))) ;; (acl2::witness :ruleset (svex-envs-mask-equiv-on-vars)) ;; (acl2::set-reasoning) ))) (define svexlist-full-masks-p ((x svexlist-p) (masks svex-mask-alist-p)) (if (atom x) t (and (equal -1 (sparseint-val (svex-mask-lookup (car x) masks))) (svexlist-full-masks-p (cdr x) masks))) /// (defthm svexlist-full-masks-p-of-take (implies (and (svexlist-full-masks-p x masks) (<= (nfix n) (len x))) (svexlist-full-masks-p (take n x) masks))) (defthm svexlist-full-masks-p-of-nthcdr (implies (svexlist-full-masks-p x masks) (svexlist-full-masks-p (nthcdr n x) masks))) (defthmd svexlist-full-masks-p-of-svexlist-mask-alist-lemma (implies (subsetp (svexlist-fix y) (svexlist-fix x)) (svexlist-full-masks-p y (svexlist-mask-alist x))) :hints(("Goal" :in-theory (enable subsetp svexlist-fix)))) (defthm svexlist-full-masks-p-of-svexlist-mask-alist (svexlist-full-masks-p x (svexlist-mask-alist x)) :hints(("Goal" :in-theory (enable svexlist-full-masks-p-of-svexlist-mask-alist-lemma)))) (local (defun cdr2 (x y) (if (atom x) y (cdr2 (Cdr x) (cdr y))))) (defthm 4veclist-mask-when-full-masksp (implies (and (svexlist-full-masks-p x masks) (equal (len 4vecs) (len x))) (equal (4veclist-mask (svex-argmasks-lookup x masks) 4vecs) (4veclist-fix 4vecs))) :hints(("Goal" :in-theory (enable 4veclist-mask svex-argmasks-lookup 4veclist-fix 4vec-mask) :induct (cdr2 x 4vecs))))) (defsection general-correctness-theorems (local (defthm subsetp-intersection (subsetp (intersection$ x y) y) :hints ((set-reasoning)))) (defthm svexlist->a4vec-correct-for-varmasks-aig-env (b* (((mv err a4env) (svex-varmasks->a4env vars masks boolmasks1)) ((mv ?err1 env) (svex-varmasks/env->aig-env vars (svex-mask-alist-extract-vars masks) boolmasks goalenv)) (a4vecs (svexlist->a4vec x a4env masks))) (implies (and (not err) (svex-mask-alist-p masks) (svex-mask-alist-complete masks) (equal boolmasks (svar-boolmasks-fix boolmasks1)) (svex-env-boolmasks-ok goalenv boolmasks) (subsetp (intersection-equal (svexlist-vars x) (alist-keys (svex-env-fix goalenv))) (svarlist-fix vars))) (equal (4veclist-mask (svex-argmasks-lookup x masks) (a4veclist-eval a4vecs env)) (4veclist-mask (svex-argmasks-lookup x masks) (svexlist-eval x goalenv))))) :hints (("goal" :use ((:instance svexlist-eval-of-mask-equiv-on-vars-envs (env2 goalenv) (env1 (svex-a4vec-env-eval (mv-nth 1 (svex-varmasks->a4env vars masks boolmasks)) (mv-nth 1 (svex-varmasks/env->aig-env vars (svex-mask-alist-extract-vars masks) boolmasks goalenv)))))) :in-theory (disable svexlist-eval-of-mask-equiv-on-vars-envs)))) (defthm svexlist->a4vec-correct-for-varmasks-aig-env-top (b* (((mv err a4env) (svex-varmasks->a4env vars masks boolmasks1)) ((mv ?err1 env) (svex-varmasks/env->aig-env vars (svex-mask-alist-extract-vars masks) boolmasks goalenv)) (a4vecs (svexlist->a4vec x a4env masks))) (implies (and (not err) (svexlist-full-masks-p x masks) (svex-mask-alist-p masks) (svex-mask-alist-complete masks) (equal boolmasks (svar-boolmasks-fix boolmasks1)) (svex-env-boolmasks-ok goalenv boolmasks) (subsetp (intersection-equal (svexlist-vars x) (alist-keys (svex-env-fix goalenv))) (svarlist-fix vars))) (equal (a4veclist-eval a4vecs env) (svexlist-eval x goalenv)))) :hints (("goal" :use svexlist->a4vec-correct-for-varmasks-aig-env :in-theory (disable svexlist->a4vec-correct-for-varmasks-aig-env))))) (define svex-env-check-boolmasks ((boolmasks svar-boolmasks-p) (env svex-env-p)) :prepwork ((local (in-theory (enable svar-boolmasks-p svar-boolmasks-fix)))) ;; :hooks nil (b* (((when (atom boolmasks)) t) ((unless (mbt (svar-p (caar boolmasks)))) (svex-env-check-boolmasks (cdr boolmasks) env)) ((cons var mask) (car boolmasks)) (val (svex-env-lookup var env)) (ok (4vec-boolmaskp val mask)) (?ign (and (not ok) (cw "not 4vec-boolmaskp: ~x0~%" var)))) (and (svex-env-check-boolmasks (cdr boolmasks) env) ok)) /// (acl2::defexample svex-env-boolmasks-ok-example :pattern (svex-env-lookup v env) :templates (v) :instance-rulename svex-env-boolmasks-ok-instancing) (defthm svex-env-check-boolmasks-correct (implies (and (svex-env-check-boolmasks boolmasks env) ;; (svex-env-p env) (svar-boolmasks-p boolmasks)) (svex-env-boolmasks-ok env boolmasks)) :hints (("goal" :induct (svex-env-check-boolmasks boolmasks env)) (acl2::witness :ruleset (svex-env-boolmasks-ok-witnessing svex-env-boolmasks-ok-example)) (and stable-under-simplificationp '(:in-theory (enable svar-boolmasks-lookup) :expand ((:free (x) (4vec-boolmaskp x 0)))))))) (define svexlist-mask-alist-memo ((x svexlist-p)) :enabled t (svexlist-mask-alist x) /// (memoize 'svexlist-mask-alist-memo)) (define svexlist-vars-memo ((x svexlist-p)) :enabled t (svexlist-collect-vars x) /// (memoize 'svexlist-vars-memo)) (define svexlist->a4vecs-for-varlist ((x svexlist-p) (vars svarlist-p) (boolmasks svar-boolmasks-p)) :returns (mv (err (iff err (not (svex-maskbits-ok vars (svexlist-mask-alist x))))) (a4vecs a4veclist-p)) :short "Creates a symbolic bit-level representation for x, assuming that vars are the only vars relevant to x and that the bits of vars given in boolmasks are Boolean-valued." :long "<p>Steps: First creates a symbolic environment mapping the variables to a4vec structures, each bit of which is a free variable. (For bits constrained to be Boolean by boolmasks, the same variable is shared for upper/lower.) Then uses @('svexlist->a4vec-top') to generate a4vecs corresponding to the svexes.</p>" (b* (;; (- (sneaky-push 'svexlist x)) (masks (svexlist-mask-alist-memo x)) ((mv err a4env) (svex-varmasks->a4env vars masks boolmasks)) ((when err) (mv err nil)) (a4env (make-fast-alist a4env)) (res (svexlist->a4vec-top x a4env masks)) (?ign (fast-alist-free a4env))) (mv nil res)) /// (memoize 'svexlist->a4vecs-for-varlist)) (define svexlist-variable-mask-alist ((x svexlist-p)) ;; We've seen problems in GL where we get a stack overflow in ;; gobject-hierarchy-lite traversing the full masks inside ;; svexlist->a4vec-aig-env-for-varlist. But we don't need the full set of ;; masks there, only those for the variables. So to work around this ;; problem, this function extracts only the variables from the mask alist, ;; producing a much smaller alist. :returns (varmasks svex-mask-alist-p) :enabled t (b* ((masks-full (svexlist-mask-alist-memo x))) (svex-mask-alist-extract-vars masks-full)) /// (memoize 'svexlist-variable-mask-alist)) (define svexlist->a4vec-aig-env-for-varlist ((x svexlist-p) (vars svarlist-p) (boolmasks svar-boolmasks-p) (env svex-env-p)) :returns (mv (err (iff err (not (svex-maskbits-ok vars (svexlist-mask-alist x))))) (aig-env)) :hooks ((:fix :args (x vars))) ;; We use svexlist-variable-mask-alist here rather than ;; svexlist-mask-alist-memo so that GL won't have to traverse the full mask ;; alist with gobject-hierarchy-lite, which we've seen cause stack overflows. (b* ((masks (svexlist-variable-mask-alist x))) (svex-varmasks/env->aig-env vars masks boolmasks env)) /// ;; (local (defthm svex-envs-mask-equiv-lemma ;; (iff (svex-envs-mask-equiv ;; (svexlist-mask-alist x) y z) ;; (svex-envs-mask-equiv ;; (svexlist-variable-mask-alist x) y z)) ;; :hints ((witness)))) ;; This is directly proved by svexlist->a4vec-top-correct-for-varmasks-aig-env-top (defthm svexlist->a4vec-for-varlist-correct (b* (((mv err a4vecs) (svexlist->a4vecs-for-varlist x vars boolmasks)) ((mv ?err1 aig-env) (svexlist->a4vec-aig-env-for-varlist x vars boolmasks env))) (implies (and (not err) ;; (svex-env-p env) (svar-boolmasks-p boolmasks) (svex-env-boolmasks-ok env boolmasks) (subsetp (intersection-equal (svexlist-vars x) (alist-keys (svex-env-fix env))) (svarlist-fix vars))) (equal (a4veclist-eval a4vecs aig-env) (svexlist-eval x env)))) :hints(("Goal" :in-theory (e/d (svexlist->a4vecs-for-varlist) (svexlist-eval-of-mask-equiv-on-vars-envs)))) :otf-flg t)) (local (defthm subset-of-mergesorts-is-subsetp (iff (subset (mergesort a) (mergesort b)) (subsetp a b)) :hints(("Goal" :in-theory (enable* set::definitions))))) (define svexlist-rewrite-fixpoint-memo ((x svexlist-p)) :enabled t (time$ (svexlist-rewrite-fixpoint x :verbosep t :count 2) :msg "; svex rewriting: ~st sec, ~sa bytes.~%") /// (memoize 'svexlist-rewrite-fixpoint-memo)) (define maybe-svexlist-rewrite-fixpoint ((x svexlist-p) (do-it)) :returns (new-x svexlist-p) (if do-it (svexlist-rewrite-fixpoint-memo x) (hons-copy (svexlist-fix x))) /// (defret maybe-svexlist-rewrite-fixpoint-correct (equal (svexlist-eval new-x env) (svexlist-eval x env))) (defret maybe-svexlist-rewrite-fixpoint-len (equal (len new-x) (len x))) (defret vars-of-maybe-svexlist-rewrite-fixpoint (implies (not (member v (svexlist-vars x))) (not (member v (svexlist-vars new-x)))))) (local (defthm svarlist-p-of-alist-keys-when-svex-env-p (implies (svex-env-p env) (svarlist-p (alist-keys env))) :hints(("Goal" :in-theory (enable svex-env-p svarlist-p alist-keys))))) (define svexlist-vars-for-symbolic-eval ((x svexlist-p) (env svex-env-p) (symbolic-params alistp)) :returns (vars svarlist-p) :guard-hints (("goal" :in-theory (e/d (SET::UNION-WITH-SUBSET-LEFT double-containment set::subset-to-subsetp) (SUBSET-OF-MERGESORTS-IS-SUBSETP)))) (b* ((allvars (assoc :allvars symbolic-params)) (vars (if allvars (svexlist-vars-memo x) (ec-call (svarlist-fix (cdr (assoc :vars symbolic-params)))))) (svars (mbe :logic (set::mergesort vars) :exec (if (set::setp vars) vars (set::mergesort vars)))) ((when allvars) (hons-copy svars)) (keys (svarlist-filter (alist-keys env))) (keys (mbe :logic (set::mergesort keys) :exec (if (set::setp keys) keys (set::mergesort keys))))) (hons-copy (mbe :logic (union keys svars) :exec (if (set::subset keys svars) svars (if (eq svars nil) keys (union keys svars)))))) /// (local (defthm alist-keys-of-svex-env-fix (equal (alist-keys (svex-env-fix env)) (svarlist-filter (alist-keys env))) :hints(("Goal" :in-theory (enable svex-env-fix svarlist-filter))))) (defret svexlist-vars-for-symbolic-eval-sufficient (subsetp (intersection-equal (svexlist-vars x) (alist-keys (svex-env-fix env))) vars) :hints ((set-reasoning))) (defret member-of-svexlist-vars-for-symbolic-eval (implies (and (member v (svexlist-vars x)) (hons-assoc-equal v (svex-env-fix env))) (member v vars)) :hints (("goal" :use svexlist-vars-for-symbolic-eval-sufficient :in-theory (disable svexlist-vars-for-symbolic-eval-sufficient svexlist-vars-for-symbolic-eval alist-keys-of-svex-env-fix)) (set-reasoning)))) (defines svex-fastsubst :verify-guards nil (define svex-fastsubst :parents (svex-subst) :short "Substitution for @(see svex)es, identical to @(see svex-subst), except that we memoize the results and we use fast alist lookups." ((pat svex-p) (al svex-alist-p)) :returns (x (equal x (svex-subst pat al)) :hints ((and stable-under-simplificationp '(:expand ((svex-subst pat al)))))) :measure (svex-count pat) (svex-case pat :var (or (svex-fastlookup pat.name al) (svex-quote (4vec-x))) :quote (svex-fix pat) :call (svex-call pat.fn (svexlist-fastsubst pat.args al)))) (define svexlist-fastsubst ((pat svexlist-p) (al svex-alist-p)) :returns (x (equal x (svexlist-subst pat al)) :hints ((and stable-under-simplificationp '(:expand ((svexlist-subst pat al)))))) :measure (svexlist-count pat) (if (atom pat) nil (cons (svex-fastsubst (car pat) al) (svexlist-fastsubst (cdr pat) al)))) /// (verify-guards svex-fastsubst) (memoize 'svex-fastsubst :condition '(eq (svex-kind pat) :call))) (define svexlist-x-out-unused-vars ((x svexlist-p) (svars svarlist-p) (do-it)) :returns (new-x svexlist-p) (if do-it (b* ((subst (make-fast-alist (pairlis$ (svarlist-fix svars) (svarlist-svex-vars svars)))) (ans (svexlist-fastsubst x subst))) (clear-memoize-table 'svex-fastsubst) (fast-alist-free subst) ans) (svexlist-fix x)) /// (defthm svex-alist-eval-of-svarlist-svex-vars (equal (svex-alist-eval (pairlis$ (svarlist-fix svars) (svarlist-svex-vars svars)) env) (svex-env-extract svars env)) :hints(("Goal" :in-theory (enable svex-env-extract svex-alist-eval svarlist-fix svarlist-svex-vars) :induct (len svars) :expand ((:free (x) (svex-eval (svex-var x) env)))))) (defthm-svex-eval-flag (defthm svex-eval-of-svex-env-extract-when-intersection-subset (implies (subsetp (intersection$ (svex-vars x) (alist-keys (svex-env-fix env))) (svarlist-fix svars)) (equal (svex-eval x (svex-env-extract svars env)) (svex-eval x env))) :hints ('(:expand ((:free (env) (svex-eval x env)) (svex-vars x))) (and stable-under-simplificationp '(:in-theory (enable svex-env-lookup) :expand ((:free (x y) (subsetp-equal (list x) y)) (:free (x y) (intersection-equal (list x) y)))))) :flag expr) (defthm svexlist-eval-of-svex-env-extract-when-intersection-subset (implies (subsetp (intersection$ (svexlist-vars x) (alist-keys (svex-env-fix env))) (svarlist-fix svars)) (equal (svexlist-eval x (svex-env-extract svars env)) (svexlist-eval x env))) :hints ('(:expand ((:free (env) (svexlist-eval x env)) (svexlist-vars x)))) :flag list)) (defret svex-eval-of-svexlist-x-out-unused-vars (implies (subsetp (intersection-equal (svexlist-vars x) (alist-keys (svex-env-fix env))) (svarlist-fix svars)) (equal (svexlist-eval new-x env) (svexlist-eval x env)))) (local (defthm hons-assoc-equal-of-pair-svex-vars (equal (hons-assoc-equal v (pairlis$ (svarlist-fix vars1) (svarlist-svex-vars vars1))) (and (member v (svarlist-fix vars1)) (cons v (svex-var (svar-fix v))))) :hints(("Goal" :in-theory (enable hons-assoc-equal pairlis$ svarlist-svex-vars svarlist-fix))))) (local (defthm svex-lookup-of-pair-svex-vars (implies (equal vars (svarlist-fix vars1)) (equal (svex-lookup v (pairlis$ vars (svarlist-svex-vars vars1))) (and (member (svar-fix v) vars) (svex-var (svar-fix v))))) :hints(("Goal" :in-theory (enable svex-lookup))))) (local (defthm-svex-eval-flag (defthm vars-of-svex-subst-lemma (implies (and (not (member v (svex-vars x))) (equal vars (svarlist-fix vars1))) (not (member v (svex-vars (svex-subst x (pairlis$ vars (svarlist-svex-vars vars1))))))) :flag expr :hints ('(:expand ((:free (al) (svex-subst x al)))))) (defthm vars-of-svexlist-subst-lemma (implies (and (not (member v (svexlist-vars x))) (equal vars (svarlist-fix vars1))) (not (member v (svexlist-vars (svexlist-subst x (pairlis$ vars (svarlist-svex-vars vars1))))))) :flag list :hints ('(:expand ((:free (al) (svexlist-subst x al)))))))) (defret svex-vars-of-svexlist-x-out-unused-vars (implies (not (member v (svexlist-vars x))) (not (member v (svexlist-vars new-x))))) (local (defthm len-of-svexlist-subst (equal (len (svexlist-subst x subst)) (len x)) :hints (("goal" :induct (len x) :in-theory (enable svexlist-subst))))) (defret len-of-<fn> (equal (len new-x) (len x)))) (define symbolic-params-x-out-cond ((symbolic-params alistp)) ;; Only makes sense to x out unused variables if ;; - we're simplifying, so they'll get constant propagated, and ;; - we're not using all vars, so there will be some substitutions. (and (cdr (assoc :simplify symbolic-params)) (not (cdr (assoc :all-vars symbolic-params))))) (define svexlist-eval-gl ((x svexlist-p "Svex expressions to evaluate.") (env svex-env-p "Bindings of variables to @(see 4vec) values.") (symbolic-params alistp "Alist giving symbolic execution parameters; see below.")) :short "Equivalent of svexlist-eval intended to work well under GL symbolic execution." :long " <p>This function is provably equivalent to @(see svexlist-eval), but is tailored to perform well under symbolic execution. For symbolic execution, we assume that the inputs to this function other than @('env') are fully concrete, and that @('env') is symbolic only in its values, not its keys or its shape.</p> <p>The @('symbolic-params') input is logically irrelevant, but allows important optimizations for symbolic execution performance, discussed further below. It is safe (but not necessarily optimal) to call this with symbolic-params equal @('NIL').</p> <h4>Behavior under Symbolic Execution</h4> <ol> <li>Applies rewriting to the supplied svex expressions, if @(':SIMPLIFY') is bound to a non-nil value in the @('symbolic-params') input -- see @(see svexlist-rewrite-fixpoint).</li> <li>If @(':boolmasks') is bound in the symbolic-params, compares the given @('env') with the bound value, which should be an alist. If there is a pair @('(name . mask)') in the boolmasks alist for which the binding for @('name') in env is not Boolean-valued on the bits set to 1 in @('mask'), then fail out of symbolic simulation. (In AIG mode, the masked bits must be <i>syntactically</i> Boolean-valued -- practically speaking, this means the upper/lower parts should result from the same computation.)</li> <li>If @(':VARS') is bound in symbolic-params, it should be bound to a list of input variables of the SVTV. Unions this list with the variables bound in @('env') to obtain the full list of variables to bind as inputs to the SVTV. Or if @(':ALLVARS') is bound in symbolic params, all the variables in the svex expressions are used instead.</li> <li>Compiles the svex list @('x') into @(see a4vec) objects, a symbolic analogue of @(see 4vec) but with each bit an AIG -- see @(see svexlist->a4vecs-for-varlist). This computation uses the assumptions, checked in the two steps above, that only the variables in @('vars') are non-X, and that the masked bits in @('boolmasks') are Boolean-valued. These assumptions can reduce the complexity of the generated AIGs. (Note everything used in this computation is concrete -- the @('env') isn't involved.)</li> <li>Creates an alist binding the AIG variables used in the above step to the appropriate symbolic bits from @('env').</li> <li>Symbolically evaluates each of the a4vec objects from step 4 under the bindings from step 5 using GL's symbolic simulator of @(see acl2::aig-eval). This results in GL-native symbolic 4vec objects, which is the result we want.</li> </ol> <h4>Optimization using the Extra Arguments</h4> <p>Performance of symbolic execution (and SAT solving, when in AIG mode) is related to the size of the AIGs produced by the svex to AIG transformation (step 4, above). Two ways to decrease that size are (1) to turn certain variables into constant Xes, if it is known that they're irrelevant, and (2) to assume certain bits of some variables are Boolean-valued, which means it can be represented by just one AIG variable rather than two.</p> <p>Another performance consideration is that the transformation to AIGs is itself sometimes significant. Especially for theorems proved by case-splitting, it is important not to need to repeat this transformation for each case. The function that does the transformation is memoized, but it is important in this case that it always be called with the same arguments.</p> <p>The @('vars') list pertains to optimization (1): if not present in the list, a variable in the svex expressions will just be replaced with an X. Therefore, in general it's best to use exactly the set of variables bound in the environment. However, it may not be worth it to redo the AIG conversion each time the environment's bound variables changes, so we take @('vars') separately.</p> <p>The @('boolmasks') allows optimization (2). It is best for symbolic execution performance to bind every variable in @('vars') to -1, but this may fail if the @('env') is not constructed in such a way that the values are obviously 2-vectors.</p>" :guard-hints (("goal" :in-theory (e/d (SET::UNION-WITH-SUBSET-LEFT) (SUBSET-OF-MERGESORTS-IS-SUBSETP)))) (b* ((env (make-fast-alist (svex-env-fix env))) (svars (svexlist-vars-for-symbolic-eval x env symbolic-params)) (x (svexlist-x-out-unused-vars x svars (symbolic-params-x-out-cond symbolic-params))) (x (maybe-svexlist-rewrite-fixpoint x (cdr (assoc :simplify symbolic-params)))) (boolmasks (make-fast-alist (hons-copy (ec-call (svar-boolmasks-fix (cdr (assoc :boolmasks symbolic-params))))))) ((unless (svex-env-check-boolmasks boolmasks env)) (b* ((?ign (cw "ERROR: some bits assumed to be Boolean were not~%")) (?ign (gl::gl-error 'boolcheck-failed))) (gl::gl-hide (svexlist-eval x env)))) ;; (?ign (cw "Boolmasks: ~x0~%" boolmasks)) ;; (?ign (bitops::sneaky-push 'boolmasks boolmasks)) ;; (?ign (bitops::sneaky-push 'vars vars)) ;; (?ign (bitops::sneaky-push 'x x)) ((mv err a4vecs) (time$ (svexlist->a4vecs-for-varlist x svars boolmasks) :msg "; svex->aigs: ~st sec, ~sa bytes.~%")) ((when err) (b* ((?ign (cw "ERROR gathering AIG bits for variables: ~@0~%" err)) (?ign (gl::gl-error 'a4env-failed))) (gl::gl-hide (svexlist-eval x env)))) ((mv ?err aig-env) ;; ignore the error; it can't exist if the above doesn't (time$ (svexlist->a4vec-aig-env-for-varlist x svars boolmasks env) :msg "; env -> aig env: ~st sec, ~sa bytes.~%")) (?ign (fast-alist-free env)) (aig-env (make-fast-alist aig-env)) (ans (a4veclist-eval a4vecs aig-env))) (fast-alist-free aig-env) ans) /// (defthm svexlist-eval-gl-is-svexlist-eval (equal (svexlist-eval-gl x env symbolic-params) (svexlist-eval x env)) :hints (("goal" :use ((:instance svexlist->a4vec-for-varlist-correct (boolmasks (svar-boolmasks-fix (cdr (assoc :boolmasks symbolic-params)))) (vars (svexlist-vars-for-symbolic-eval x env symbolic-params)) (x (maybe-svexlist-rewrite-fixpoint (svexlist-x-out-unused-vars x (svexlist-vars-for-symbolic-eval x env symbolic-params) (symbolic-params-x-out-cond symbolic-params)) (cdr (assoc :simplify symbolic-params)))) (env (svex-env-fix env)))) :in-theory (disable svexlist->a4vec-for-varlist-correct SVEXLIST->A4VECS-FOR-VARLIST-SVAR-BOOLMASKS-EQUIV-CONGRUENCE-ON-BOOLMASKS)) (set-reasoning) (and stable-under-simplificationp '(:cases ((member acl2::k0 (svexlist-vars x))))))) (gl::def-gl-rewrite svexlist-eval-for-symbolic-redef (equal (svexlist-eval-for-symbolic x env symbolic-params) (svexlist-eval-gl x env symbolic-params)))) ;;; Now rework a4veclist-eval to phrase it in terms of a single call to aig-eval-list (define a4vec->aiglist ((x a4vec-p)) :returns (lst true-listp :rule-classes :type-prescription) (b* (((a4vec x) x)) (append x.upper x.lower))) ;; (define v2i-alt ((v true-listp)) ;; :returns (v2i (equal v2i (gl::v2i v)) ;; :hints(("Goal" :in-theory (enable gl::scdr gl::s-endp)))) ;; :hooks nil ;; (if (atom (cdr v)) ;; (gl::bool->sign (car v)) ;; (logcons (acl2::bool->bit (car v)) ;; (v2i-alt (cdr v))))) (local (defthm v2i-of-aig-eval-list (equal (gl::v2i (aig-eval-list x env)) (aig-list->s x env)) :hints(("Goal" :in-theory (enable (:i aig-list->s) gl::v2i gl::scdr gl::s-endp) :induct (aig-list->s x env) :expand ((aig-list->s x env) (aig-eval-list x env) (:free (A b) (gl::v2i (cons a b)))))))) (define v2i-first-n ((n natp) (v true-listp)) :returns (v2i (equal v2i (gl::v2i (take n v))) :hints(("Goal" :in-theory (e/d (acl2::take) (acl2::take-of-too-many)) :induct t))) :prepwork ((local (defthm v2i-of-singleton (equal (gl::v2i (list x)) (gl::bool->sign x)) :hints(("Goal" :in-theory (enable gl::s-endp gl::v2i))))) (local (defthm v2i-of-cons (implies (consp y) (equal (gl::v2i (cons x y)) (logapp 1 (bool->bit x) (gl::v2i y)))) :hints(("Goal" :in-theory (enable gl::v2i logapp** gl::s-endp gl::scdr)))))) (cond ((zp n) (gl::bool->sign nil)) ((eql n 1) (gl::bool->sign (car v))) (t (logapp 1 (acl2::bool->bit (car v)) (v2i-first-n (1- n) (cdr v)))))) (define 4vec-from-bitlist ((upper-len natp) (lower-len natp) (bits true-listp)) :hooks ((:fix :omit (bits))) :returns (mv (vec 4vec-p) (rest true-listp :hyp (true-listp bits) :rule-classes :type-prescription)) ;; note: list-fixing bits is bad here because it's not even linear in the ;; number of bits we're operating on (b* ((upper (v2i-first-n upper-len bits)) (rest (nthcdr upper-len bits)) (lower (v2i-first-n lower-len rest)) (rest (nthcdr lower-len rest))) (mv (4vec upper lower) rest)) /// (defthm 4vec-from-bitlist-correct (b* (((a4vec x) x)) (equal (4vec-from-bitlist (len x.upper) (len x.lower) (append (aig-eval-list (a4vec->aiglist x) env) rest)) (mv (a4vec-eval x env) rest))) :hints(("Goal" :in-theory (enable a4vec->aiglist))))) (define a4veclist->aiglist ((x a4veclist-p)) :returns (aigs true-listp :rule-classes :type-prescription) (if (atom x) nil (append (a4vec->aiglist (car x)) (a4veclist->aiglist (cdr x))))) (define 4veclist-from-bitlist ((origs a4veclist-p) (bits true-listp)) :returns (4vecs 4veclist-p) :hooks ((:fix :omit (bits))) (b* (((when (atom origs)) nil) ((a4vec x) (car origs)) ((mv first restbits) (4vec-from-bitlist (len x.upper) (len x.lower) bits))) (cons first (4veclist-from-bitlist (cdr origs) restbits))) /// (defthm 4veclist-from-bitlist-correct (equal (4veclist-from-bitlist x (aig-eval-list (a4veclist->aiglist x) env)) (a4veclist-eval x env)) :hints(("Goal" :in-theory (enable a4veclist-eval a4veclist->aiglist))))) (define a4veclist-eval-gl ((x a4veclist-p) (env)) :returns (res 4veclist-p) (b* ((aiglist (time$ (a4veclist->aiglist x) :msg "; SV bit-blasting: a4veclist->aiglist: ~st sec, ~sa bytes.~%")) (bitlist (time$ (aig-eval-list aiglist env) :msg "; SV bit-blasting: aig-eval-list: ~st sec, ~sa bytes.~%"))) (time$ (4veclist-from-bitlist x bitlist) :msg "; bits->4vecs: ~st sec, ~sa bytes.~%")) /// (defthm a4veclist-eval-gl-correct (equal (a4veclist-eval-gl x env) (a4veclist-eval x env))) (gl::def-gl-rewrite a4veclist-eval-redef (equal (a4veclist-eval x env) (a4veclist-eval-gl x env)))) (gl::def-gl-rewrite svex-alist-eval-gl-rewrite (equal (svex-alist-eval x env) (pairlis$ (svex-alist-keys x) (svexlist-eval-for-symbolic (svex-alist-vals x) env nil))) :hints(("Goal" :in-theory (enable svex-alist-eval pairlis$ svex-alist-keys svex-alist-vals svexlist-eval)))) (gl::def-gl-rewrite svex-eval-gl-rewrite (equal (svex-eval x env) (car (svexlist-eval-for-symbolic (list x) env nil)))) (define svex-envlist-keyset ((x svex-envlist-p)) :returns (keys (and (svarlist-p keys) (set::setp keys))) (if (atom x) nil (set::union (set::mergesort (svarlist-filter (alist-keys (car x)))) (svex-envlist-keyset (cdr x)))) /// (local (defthm alist-keys-of-svex-env-fix (equal (alist-keys (svex-env-fix env)) (svarlist-filter (alist-keys env))) :hints(("Goal" :in-theory (enable svex-env-fix svarlist-filter))))) (defret svex-envlist-keyset-sufficient (implies (member env x) (subsetp (alist-keys (svex-env-fix env)) keys)))) (define svexlist/env-list-vars-for-symbolic-eval ((x svexlist-p) (envs svex-envlist-p) (symbolic-params alistp)) :returns (vars svarlist-p) :guard-hints (("goal" :in-theory (e/d (SET::UNION-WITH-SUBSET-LEFT double-containment set::subset-to-subsetp) (SUBSET-OF-MERGESORTS-IS-SUBSETP)))) (b* ((allvars (assoc :allvars symbolic-params)) (vars (if allvars (svexlist-vars-memo x) (ec-call (svarlist-fix (cdr (assoc :vars symbolic-params)))))) (svars (mbe :logic (set::mergesort vars) :exec (if (set::setp vars) vars (set::mergesort vars)))) ((when allvars) (hons-copy svars)) (keys (svex-envlist-keyset envs))) (hons-copy (mbe :logic (union keys svars) :exec (if (set::subset keys svars) svars (if (eq svars nil) keys (union keys svars)))))) /// (defret svexlist/env-list-vars-for-symbolic-eval-sufficient (subsetp (intersection-equal (svexlist-vars x) (svex-envlist-keyset envs)) vars) :hints ((set-reasoning)))) (define svex-envlist-check-boolmasks ((boolmasks svar-boolmasks-p) (envs svex-envlist-p)) (if (atom envs) t (and (svex-env-check-boolmasks boolmasks (make-fast-alist (car envs))) (svex-envlist-check-boolmasks boolmasks (cdr envs)))) /// (defthm svex-envlist-check-boolmasks-correct (implies (and (svex-envlist-check-boolmasks boolmasks envs) (member env envs) ;; (svex-env-p env) (svar-boolmasks-p boolmasks)) (svex-env-boolmasks-ok env boolmasks)))) (fty::deflist a4veclistlist :elt-type a4veclist :true-listp t) (define a4veclist/env-list-eval ((x a4veclistlist-p) (envs)) :guard (equal (len envs) (len x)) :returns (4vecs 4veclistlist-p) (if (atom x) nil (cons (a4veclist-eval (car x) (car envs)) (a4veclist/env-list-eval (cdr x) (cdr envs))))) (define svexlistlist->a4vec ((x svexlistlist-p) (env svex-a4vec-env-p) (masks svex-mask-alist-p)) :returns (a4vecs a4veclistlist-p) (if (atom x) nil (cons (svexlist->a4vec (car x) env masks) (svexlistlist->a4vec (cdr x) env masks)))) (define a4vec/svex-env-eval ((x a4veclist-p) (env svex-env-p) (svexes svexlist-p) (svars svarlist-p) (boolmasks svar-boolmasks-p)) :guard (svex-maskbits-ok svars (svexlist-mask-alist svexes)) :returns (4vecs 4veclist-p) :hooks ((:fix :args (x svexes svars))) (b* ((env (make-fast-alist env)) ((mv ?err aig-env) ;; ignore the error; it can't exist svex-maskbits-ok (svexlist->a4vec-aig-env-for-varlist svexes svars boolmasks env)) (?ign (fast-alist-free env)) (aig-env (make-fast-alist aig-env)) (ans (a4veclist-eval x aig-env))) (fast-alist-free aig-env) ans) /// (local (defthm not-svexlist-full-masks-p-by-member (implies (And (not (equal (sparseint-val (svex-mask-lookup x masks)) -1)) (member x svexes)) (not (svexlist-full-masks-p svexes masks))) :hints(("Goal" :in-theory (enable member svexlist-full-masks-p))))) (defthm svexlist-full-masks-p-when-subset (implies (and (subsetp-equal some-svexes svexes) (svexlist-full-masks-p svexes masks)) (svexlist-full-masks-p some-svexes masks)) :hints(("Goal" :in-theory (enable subsetp-equal svexlist-full-masks-p)))) (defret a4vec/svex-env-eval-correct :pre-bind ((masks (svexlist-mask-alist svexes)) ((mv ?err a4env) (svex-varmasks->a4env svars masks boolmasks1)) (x (svexlist->a4vec some-svexes a4env masks))) (implies (and (svex-maskbits-ok svars masks) (subsetp some-svexes svexes) (equal boolmasks (svar-boolmasks-fix boolmasks1)) (svex-env-boolmasks-ok env boolmasks) (subsetp (intersection-equal (svexlist-vars some-svexes) (alist-keys (svex-env-fix env))) (svarlist-fix svars))) (equal 4vecs (svexlist-eval some-svexes env))) :hints(("Goal" :in-theory (e/d (svexlist->a4vec-aig-env-for-varlist) (SVEXLIST->A4VEC-CORRECT)))))) (define a4veclist/svex-env-list-eval ((x a4veclistlist-p) (envs svex-envlist-p) (svexes svexlist-p) (svars svarlist-p) (boolmasks svar-boolmasks-p)) :guard (and (equal (len envs) (len x)) (svex-maskbits-ok svars (svexlist-mask-alist svexes))) :returns (4vecs 4veclistlist-p) :hooks ((:fix :args (x svexes svars))) (if (atom x) nil (cons (a4vec/svex-env-eval (car x) (car envs) svexes svars boolmasks) (a4veclist/svex-env-list-eval (cdr x) (cdr envs) svexes svars boolmasks))) /// (local (defthm alist-keys-of-svex-env-fix (equal (alist-keys (svex-env-fix env)) (svarlist-filter (alist-keys env))) :hints(("Goal" :in-theory (enable svex-env-fix svarlist-filter))))) (defret a4veclist/svex-env-list-eval-correct :pre-bind ((masks (svexlist-mask-alist svexes)) ((mv ?err a4env) (svex-varmasks->a4env svars masks boolmasks1)) (x (svexlistlist->a4vec some-svexes a4env masks))) (implies (and (svex-maskbits-ok svars masks) (equal (len envs) (len some-svexes)) (subsetp (append-lists some-svexes) svexes) (equal boolmasks (svar-boolmasks-fix boolmasks1)) (svex-envlist-check-boolmasks boolmasks envs) (subsetp (intersection-equal (svexlist-vars (append-lists some-svexes)) (svex-envlist-keyset envs)) (svarlist-fix svars))) (equal 4vecs (svexlist/env-list-eval some-svexes envs))) :hints (("goal" :induct (svexlist/env-list-eval some-svexes envs) :in-theory (e/d (svexlist/env-list-eval svex-envlist-check-boolmasks append-lists svex-envlist-keyset svexlistlist->a4vec)))))) (local (in-theory (enable svexlist->a4vecs-for-varlist))) (local (defthm a4veclistlist-p-of-extract-lists (implies (and (a4veclist-p list) (<= (sum-of-lengths x) (len list))) (a4veclistlist-p (extract-lists x list))) :hints (("goal" :use ((:functional-instance element-listlist-p-of-extract-lists (acl2::element-p a4vec-p) (acl2::element-list-p a4veclist-p) (acl2::element-list-final-cdr-p (lambda (x) (eq x nil))) (element-listlist-p a4veclistlist-p))))))) (defsection svexlist/env-list-eval-of-extract-of-rewrite (local (include-book "svex-equivs")) (local (define svex-eval-same-on-envs (x y envs) :verify-guards nil (if (atom envs) t (and (equal (svex-eval x (car envs)) (svex-eval y (car envs))) (svex-eval-same-on-envs x y (cdr envs)))) /// (defthm svex-eval-same-on-envs-implies-eval-same-with-member (implies (and (svex-eval-same-on-envs x y envs) (member env envs)) (equal (svex-eval x env) (svex-eval y env)))) (defthm svex-eval-same-on-envs-when-svex-eval-equiv (implies (svex-eval-equiv x y) (svex-eval-same-on-envs x y envs))))) (local (define svexlist-eval-same-on-envs (x y envs) :verify-guards nil (if (atom x) t (and (svex-eval-same-on-envs (car x) (car y) envs) (svexlist-eval-same-on-envs (cdr x) (cdr y) envs))) /// (defthm svexlist-eval-same-on-envs-implies-svexlist-eval-same-with-member (implies (and (svexlist-eval-same-on-envs x y envs) (member env envs) (equal (len x) (len y))) (equal (svexlist-eval x env) (svexlist-eval y env)))) (local (defun ind (n x y) (if (zp n) (list x y) (ind (1- n) (cdr x) (cdr y))))) (defthm svex-eval-same-on-envs-of-nth-when-svexlist-eval-same-on-envs (implies (and (svexlist-eval-same-on-envs x y envs) (< (nfix n) (len x))) (svex-eval-same-on-envs (nth n x) (nth n y) envs)) :hints(("Goal" :in-theory (enable nth svex-eval-same-on-envs) :induct (ind n x y)))) (local (defthm svexlist-eval-equiv-implies-svex-eval-equiv-car (implies (and (svexlist-eval-equiv x y) (consp x)) (equal (svex-eval-equiv (car x) (car y)) t)) :hints (("goal" :in-theory (enable svex-eval-equiv))))) (defthm svexlist-eval-same-on-envs-when-svexlist-eval-equiv (implies (svexlist-eval-equiv x y) (svexlist-eval-same-on-envs x y envs))) (defthm svexlist-eval-same-on-envs-of-atom (implies (atom envs) (svexlist-eval-same-on-envs x y envs)) :hints(("Goal" :in-theory (enable svex-eval-same-on-envs)))) (defthm svexlist-eval-same-on-envs-of-consp (implies (and (consp envs) (equal (len x) (len y)) (svexlist-eval-same-on-envs x y (cdr envs))) (iff (svexlist-eval-same-on-envs x y envs) (equal (svexlist-eval x (car envs)) (svexlist-eval y (car envs))))) :hints(("Goal" :in-theory (enable svex-eval-same-on-envs)))))) (local (define svexlistlist-eval-same-on-envs (x y envs) :verify-guards nil (if (atom x) t (and (svexlist-eval-same-on-envs (car x) (car y) envs) (svexlistlist-eval-same-on-envs (cdr x) (cdr y) envs))) /// (local (defun ind (x y envs1) (if (atom x) (list y envs1) (ind (cdr x) (cdr y) (cdr envs1))))) ;; (defthm svexlistlist-eval-same-on-envs-implies-svexlist-eval-same-with-member ;; (implies (and (svexlistlist-eval-same-on-envs x y envs) ;; (member env envs) ;; (equal (len x) (len y))) ;; (equal (svexlist-eval x env) ;; (svexlist-eval y env)))) (defthm svexlist/env-list-eval-when-svexlistlist-eval-same-on-envs (implies (and (svexlistlist-eval-same-on-envs x y envs) (subsetp envs1 envs) (equal (len x) (len y)) (lengths-equal x y) (equal (len x) (len envs1))) (equal (svexlist/env-list-eval x envs1) (svexlist/env-list-eval y envs1))) :hints(("Goal" :in-theory (enable svexlist/env-list-eval subsetp-equal lengths-equal) :induct (ind x y envs1)))))) (local (defthm svexlist-eval-equiv-of-maybe-svexlist-rewrite-fixpoint (svexlist-eval-equiv (maybe-svexlist-rewrite-fixpoint x do-it) x) :hints(("Goal" :in-theory (enable svexlist-eval-equiv))))) (local (defthm alist-keys-of-svex-env-fix (equal (alist-keys (svex-env-fix env)) (svarlist-filter (alist-keys env))) :hints(("Goal" :in-theory (enable svex-env-fix svarlist-filter))))) (local (defthm svexlist-eval-equiv-of-svexlist-x-out-unused-vars (implies (subsetp (intersection-equal (svexlist-vars x) (svex-envlist-keyset envs)) (svarlist-fix svars)) (svexlist-eval-same-on-envs x (maybe-svexlist-rewrite-fixpoint (svexlist-x-out-unused-vars x svars do-it) do-it1) envs)) :hints(("Goal" :in-theory (e/d (svex-envlist-keyset) ()) :induct (len envs))))) (local (defthm svex-eval-equiv-listlist-of-extract-lists-of-rewrite (implies (subsetp (intersection-equal (svexlist-vars (append-lists x)) (svex-envlist-keyset envs)) (svarlist-fix svars)) (svexlistlist-eval-same-on-envs x (extract-lists x (maybe-svexlist-rewrite-fixpoint (svexlist-x-out-unused-vars (append-lists x) svars do-it1) do-it)) envs)) :hints (("goal" :use ((:functional-instance extract-lists-of-pseudoproj (pseudoproj (lambda (x) (if (subsetp (intersection-equal (svexlist-vars x) (svex-envlist-keyset envs)) (svarlist-fix svars)) (maybe-svexlist-rewrite-fixpoint (svexlist-x-out-unused-vars x svars do-it1) do-it) x))) (pseudoproj-relation (lambda (x y) (svex-eval-same-on-envs x y envs))) (pseudoproj-relation-list (lambda (x y) (svexlist-eval-same-on-envs x y envs))) (pseudoproj-relation-listlist (lambda (x y) (svexlistlist-eval-same-on-envs x y envs)))))) (and stable-under-simplificationp '(:in-theory (enable svexlist-eval-same-on-envs svexlistlist-eval-same-on-envs)))))) (defthm svexlist/env-list-eval-of-extract-lists-of-rewrite (implies (and (subsetp (intersection-equal (svexlist-vars (append-lists x)) (svex-envlist-keyset envs)) (svarlist-fix svars)) (equal (len envs) (len x))) (equal (svexlist/env-list-eval (extract-lists x (maybe-svexlist-rewrite-fixpoint (svexlist-x-out-unused-vars (append-lists x) svars do-it1) do-it)) envs) (svexlist/env-list-eval x envs))) :hints (("goal" :use ((:instance svexlist/env-list-eval-when-svexlistlist-eval-same-on-envs (x x) (y (extract-lists x (maybe-svexlist-rewrite-fixpoint (svexlist-x-out-unused-vars (append-lists x) svars do-it1) do-it))) (envs envs) (envs1 envs))) :in-theory (disable svexlist/env-list-eval-when-svexlistlist-eval-same-on-envs) :do-not-induct t)))) (define svexlist/env-list-eval-gl ((x svexlistlist-p "Svex expressions to evaluate.") (envs svex-envlist-p "Bindings of variables to @(see 4vec) values.") (symbolic-params alistp "Alist giving symbolic execution parameters; see below.")) :short "Equivalent of svexlist/env-list-eval intended to work well under GL symbolic execution." :long " <p>This function is provably equivalent to @('svexlist/env-list-eval'), but is tailored to perform well under symbolic execution. For symbolic execution, we assume that the inputs to this function other than @('envs') are fully concrete, and that each @('envs') are symbolic only in its values, not its keys or its shape.</p> <p>It is analogous to @(see svexlist-eval-gl), but the individual lists of svexes within @('x') are each evaluated with the corresponding element of @('envs'). Symbolic execution is set up so that the svexes are all rendered into AIGs in a batch with memoization between all the lists.</p> <p>The @('symbolic-params') input behaves as it does in @(see svexlist-eval-gl). However, the @(':boolmasks') and @(':vars') entries must be applicable to all environments in the list. That is, for each entry in the boolmasks, the corresponding key must be bound in every entry in the envs to a symbolic 4vec value that is (syntactically) Boolean-valued in the masked bits. Similarly, the @(':vars') entry, if given, is unioned with the variables bound in all environments.</p>" :guard-hints (("goal" :in-theory (e/d (SET::UNION-WITH-SUBSET-LEFT) (SUBSET-OF-MERGESORTS-IS-SUBSETP)))) :guard-debug t (b* ((envs (take (len x) envs)) (x (svexlistlist-fix x)) (svexes (append-lists x)) (svars (svexlist/env-list-vars-for-symbolic-eval svexes envs symbolic-params)) (svexes (svexlist-x-out-unused-vars svexes svars (symbolic-params-x-out-cond symbolic-params))) (svexes (maybe-svexlist-rewrite-fixpoint svexes (cdr (assoc :simplify symbolic-params)))) (boolmasks (make-fast-alist (hons-copy (ec-call (svar-boolmasks-fix (cdr (assoc :boolmasks symbolic-params))))))) ((unless (svex-envlist-check-boolmasks boolmasks envs)) (b* ((?ign (cw "ERROR: some bits assumed to be Boolean were not~%")) (?ign (gl::gl-error 'boolcheck-failed))) (gl::gl-hide (svexlist/env-list-eval x envs)))) ((mv err a4vecs) (time$ (svexlist->a4vecs-for-varlist svexes svars boolmasks) :msg "; svex->aigs: ~st sec, ~sa bytes.~%")) ((when err) (b* ((?ign (cw "ERROR gathering AIG bits for variables: ~@0~%" err)) (?ign (gl::gl-error 'a4env-failed))) (gl::gl-hide (svexlist/env-list-eval x envs)))) (a4veclist-list (extract-lists x a4vecs))) (a4veclist/svex-env-list-eval a4veclist-list envs svexes svars boolmasks)) /// (local (defthm svexlist/env-list-eval-of-take (equal (svexlist/env-list-eval x (take (len x) envs)) (svexlist/env-list-eval x envs)) :hints(("Goal" :in-theory (enable svexlist/env-list-eval))))) (local (defthm extract-lists-of-svexlist->a4vec (implies (<= (sum-of-lengths x) (len y)) (equal (extract-lists x (svexlist->a4vec y env masks)) (svexlistlist->a4vec (extract-lists x y) env masks))) :hints (("goal" :use ((:functional-instance extract-lists-of-projection (acl2::element-p (lambda (x) t)) (acl2::outelement-p (lambda (x) t)) (acl2::outelement-example (lambda () t)) (acl2::element-xformer (lambda (x) (svex->a4vec x env masks))) (acl2::elementlist-projection (lambda (x) (svexlist->a4vec x env masks))) (elementlistlist-projection (lambda (x) (svexlistlist->a4vec x env masks))))) :in-theory (enable svexlistlist->a4vec svexlist->a4vec))))) (local (defthm vars-subset-lemma (b* ((vars (SVEXLIST/ENV-LIST-VARS-FOR-SYMBOLIC-EVAL svexes envs params))) (SUBSETP-EQUAL (INTERSECTION-EQUAL (SVEXLIST-VARS (MAYBE-SVEXLIST-REWRITE-FIXPOINT (SVEXLIST-X-OUT-UNUSED-VARS svexes vars x-out) simp)) (SVEX-ENVLIST-KEYSET envs)) vars)) :hints (("goal" :use ((:instance svexlist/env-list-vars-for-symbolic-eval-sufficient (x svexes) (symbolic-params params))) :in-theory (disable svexlist/env-list-vars-for-symbolic-eval-sufficient)) (set-reasoning)))) (defthm svexlist/env-list-eval-gl-correct (equal (svexlist/env-list-eval-gl x envs symbolic-params) (svexlist/env-list-eval x envs)) :hints (("goal" :do-not-induct t))) (gl::def-gl-rewrite svexlist/env-list-eval-for-symbolic-redef (equal (svexlist/env-list-eval x envs) (svexlist/env-list-eval-gl x envs nil))))
true
; SV - Symbolic Vector Hardware Analysis Framework ; Copyright (C) 2014-2015 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 "SV") (include-book "eval") (include-book "a4vec-ops") (include-book "rewrite") (include-book "lists") (include-book "env-ops") (include-book "centaur/gl/gl-mbe" :dir :system) (include-book "centaur/gl/def-gl-rewrite" :dir :system) (local (include-book "arithmetic/top-with-meta" :dir :system)) (local (include-book "centaur/bitops/ihsext-basics" :dir :system)) (local (include-book "std/alists/alist-keys" :dir :System)) (local (include-book "centaur/bitops/equal-by-logbitp" :dir :system)) (local (include-book "clause-processors/just-expand" :dir :system)) (local (std::add-default-post-define-hook :fix)) (local (std::deflist svarlist-p (x) (svar-p x) :true-listp t :elementp-of-nil nil)) (local (defthm true-listp-nthcdr (implies (true-listp x) (true-listp (nthcdr n x))) :hints(("Goal" :in-theory (e/d (nthcdr) (acl2::cdr-nthcdr)) :induct (nthcdr n x))) :rule-classes :type-prescription)) (local (defthm nthcdr-of-append-equal-len (implies (equal (nfix n) (len x)) (equal (nthcdr n (append x y)) y)) :hints(("Goal" :in-theory (e/d (nthcdr) (acl2::cdr-nthcdr)) :induct (nthcdr n x))))) (local (defthm take-of-append-equal-len (implies (equal (nfix n) (len x)) (equal (take n (append x y)) (list-fix x))) :hints(("Goal" :in-theory (e/d (acl2::take)) :induct (nthcdr n x))))) (local (in-theory (disable double-containment))) (local (defthm 3vec-p-of-4vec-mask (implies (3vec-p x) (3vec-p (4vec-mask mask x))) :hints(("Goal" :in-theory (enable 4vec-mask 3vec-p)) (acl2::logbitp-reasoning)))) (local (defthm true-listp-of-scdr (implies (true-listp x) (true-listp (gl::scdr x))) :hints(("Goal" :in-theory (enable gl::scdr))) :rule-classes :type-prescription)) (local (in-theory (disable gl::s-endp-of-bfr-scons aig-list->s))) (local (defthm aig-list->s-open-quote (implies (syntaxp (quotep x)) (equal (aig-list->s x env) (B* (((MV FIRST REST GL::END) (GL::FIRST/REST/END X))) (IF GL::END (GL::BOOL->SIGN (AIG-EVAL FIRST ENV)) (BITOPS::LOGCONS (BOOL->BIT (AIG-EVAL FIRST ENV)) (AIG-LIST->S REST ENV)))))) :hints(("Goal" :in-theory (enable aig-list->s))))) (local (defthm aig-list->s-of-bfr-snorm (equal (aig-list->s (gl::bfr-snorm x) env) (aig-list->s x env)) :hints(("Goal" :in-theory (enable aig-list->s gl::bfr-snorm))))) (local (defthm aig-list->s-of-bfr-scons (equal (aig-list->s (gl::bfr-scons a b) env) (bitops::logcons (bool->bit (aig-eval a env)) (aig-list->s b env))) :hints(("Goal" :expand ((aig-list->s (gl::bfr-scons a b) env) (aig-list->s b env)) :in-theory (enable gl::s-endp-of-bfr-scons) :do-not-induct t)))) (defxdoc bit-blasting :parents (expressions) :short "We implement an efficient translation from @(see svex) expressions into @(see acl2::aig)s, to support symbolic simulation with @(see acl2::gl).") (local (xdoc::set-default-parents bit-blasting)) (defalist svex-a4vec-env :key-type svar :val-type a4vec) (define svex-a4vec-env-eval ((x svex-a4vec-env-p) env) :returns (xx svex-env-p) :measure (len (svex-a4vec-env-fix x)) (b* ((x (svex-a4vec-env-fix x))) (if (atom x) nil (cons (cons (svar-fix (caar x)) (a4vec-eval (cdar x) env)) (svex-a4vec-env-eval (cdr x) env)))) /// (defret alist-keys-of-svex-a4vec-env-eval (equal (alist-keys xx) (alist-keys (svex-a4vec-env-fix x))) :hints(("Goal" :in-theory (enable svex-a4vec-env-fix alist-keys))))) (define a4veclist-nth ((n natp) (x a4veclist-p)) :returns (elt a4vec-p) :guard-hints (("goal" :in-theory (enable nth a4veclist-p))) (mbe :logic (if (< (nfix n) (len x)) (a4vec-fix (nth n x)) (a4vec-x)) :exec (or (nth n x) (a4vec-x))) /// (defthm a4veclist-nth-out-of-bounds (implies (<= (len x) (nfix n)) (equal (a4veclist-nth n x) (a4vec-x)))) (defthm a4veclist-nth-in-of-bounds (implies (< (nfix n) (len x)) (equal (a4veclist-nth n x) (a4vec-fix (nth n x)))))) (define svexlist-nth ((n natp) (x svexlist-p)) :returns (elt svex-p) :guard-hints (("goal" :in-theory (enable nth svexlist-p))) (mbe :logic (if (< (nfix n) (len x)) (svex-fix (nth n x)) (svex-x)) :exec (or (nth n x) (svex-x))) /// (defthm svexlist-nth-out-of-bounds (implies (<= (len x) (nfix n)) (equal (svexlist-nth n x) (svex-x)))) (defthm svexlist-nth-in-of-bounds (implies (< (nfix n) (len x)) (equal (svexlist-nth n x) (svex-fix (nth n x)))))) (local (defthm nth-of-svexlist-eval (equal (nth n (svexlist-eval x env)) (and (< (nfix n) (len x)) (svex-eval (nth n x) env))) :hints(("Goal" :in-theory (enable nth svexlist-eval) :induct (nth n x))))) (local (defthm nth-of-a4veclist-eval (equal (nth n (a4veclist-eval x env)) (and (< (nfix n) (len x)) (a4vec-eval (nth n x) env))) :hints(("Goal" :in-theory (enable nth a4veclist-eval) :induct (nth n x))))) (define maybe-a3vec-fix ((v (a4vec-p v)) (x svex-p)) :returns (vv a4vec-p) (if (3valued-syntaxp (svex-fix x)) (a4vec-fix v) (a3vec-fix v)) /// (local (defthm nth-under-iff-when-a4veclist-p (implies (a4veclist-p x) (iff (nth n x) (< (nfix n) (len x)))) :hints(("Goal" :in-theory (enable a4veclist-p nth))))) (local (defthm nth-out-of-bounds (implies (<= (len x) (nfix n)) (not (nth n x))) :hints(("Goal" :in-theory (enable nth))))) (defthm maybe-a3vec-fix-when-implies (implies (case-split (implies (3valued-syntaxp x) (3vec-p (a4vec-eval v env)))) (equal (a4vec-eval (maybe-a3vec-fix v x) env) (3vec-fix (a4vec-eval v env))))) (defthm maybe-a3vec-fix-of-nths (implies (equal (a4veclist-eval vals env) (svexlist-eval x (svex-a4vec-env-eval a4env env))) (equal (a4vec-eval (maybe-a3vec-fix (nth n vals) (nth n x)) env) (3vec-fix (a4vec-eval (nth n vals) env)))) :hints(("Goal" :in-theory (e/d (a4veclist-nth) (nth-of-svexlist-eval) (nth-of-a4veclist-eval)) :use ((:instance nth-of-svexlist-eval (env (svex-a4vec-env-eval a4env env))) (:instance nth-of-a4veclist-eval))))) (defthm maybe-a3vec-fix-of-a3vec (implies (a4vec-syntactic-3vec-p v) (equal (maybe-a3vec-fix v x) (a4vec-fix v))) :hints(("Goal" :in-theory (enable a3vec-fix))))) ;; (define 4vmask-nth ((n natp) (x 4vmasklist-p)) ;; :returns (mask 4vmask-p :rule-classes (:rewrite :type-prescription)) ;; (b* ((x (4vmasklist-fix x))) ;; (if (< (lnfix n) (len x)) ;; (4vmask-fix (nth n x)) ;; -1))) ;; (define maybe-a4vec-fix ((v (or (a4vec-p v) (not v)))) ;; :returns (vv a4vec-p) ;; (if v (a4vec-fix v) (a4vec-x))) (defconst *svex-aig-op-table* ;; fn name, non-3vec-fixing function, args (with notation for 3vec-fixed ones and masks) '((id a4vec-fix (x) "identity function") (bitsel a4vec-bit-extract (index x) "bit select") (unfloat a4vec-fix ((3v x)) "change Z bits to Xes") (bitnot a3vec-bitnot ((3v x)) "bitwise negation") (onp a4vec-onset (x) "bitwise onset") (offp a4vec-offset (x) "bitwise offset") (bitand a3vec-bitand ((3v x) (3v y)) "bitwise AND") (bitor a3vec-bitor ((3v x) (3v y)) "bitwise OR") (bitxor a3vec-bitxor ((3v x) (3v y)) "bitwise XOR") (res a4vec-res (x y) "resolve (short together)") (resand a4vec-resand (x y) "resolve wired AND") (resor a4vec-resor (x y) "resolve wired OR") (override a4vec-override (x y) "resolve different strengths") (uand a3vec-reduction-and ((3v x)) "unary (reduction) AND") (uor a3vec-reduction-or ((3v x)) "unary (reduction) OR") (uxor a4vec-parity (x) "reduction XOR, i.e. parity") (zerox a4vec-zero-ext (width x (mask m)) "zero extend") (signx a4vec-sign-ext (width x (mask m)) "sign extend") (concat a4vec-concat (width x y (mask m)) "concatenate at a given bit width") (partsel a4vec-part-select (lsb width in (mask m)) "part select") (partinst a4vec-part-install (lsb width in val (mask m)) "part install") (blkrev a4vec-rev-blocks (width blksz x) "reverse block order") (rsh a4vec-rsh (shift x (mask m)) "right shift") (lsh a4vec-lsh (shift x (mask m)) "left shift") (+ a4vec-plus (x y) "addition") (b- a4vec-minus (x y) "subtraction") (u- a4vec-uminus (x) "unary minus") (xdet a4vec-xdet (x) "x detect") (countones a4vec-countones (x) "count of set bits") (onehot a4vec-onehot (x) "one-hot check") (onehot0 a4vec-onehot0 (x) "one-hot check (zero-hot allowed)") (* a4vec-times (x y) "multiplication") (/ a4vec-quotient (x y) "division") (% a4vec-remainder (x y) "modulus") (< a4vec-< (x y) "less than") (clog2 a4vec-clog2 (x) "ceiling of log2") (pow a4vec-pow (x y) "exponentiation") (== a3vec-== ((3v x) (3v y)) "equality") (=== a4vec-=== (x y) "case equality") (===* a4vec-===* (x y) "modified case equality") (==? a4vec-wildeq (x y) "wildcard equality") (safer-==? a4vec-wildeq-safe (x y) "wildcard equality (monotonic version)") (==?? a4vec-symwildeq (x y) "symmetric wildcard equality") (? a3vec-? ((3v test) (3vp then) (3vp else)) "if-then-else") (?* a3vec-?* ((3v test) (3vp then) (3vp else)) "if-then-else") (bit? a3vec-bit? ((3v test) (3vp then) (3vp else)) "bitwise if-then-else") (?! a4vec-?! (test them else) "procedural if-then-else") (bit?! a4vec-bit?! ((3v test) (3vp then) (3vp else)) "bitwise if-then-else"))) #|| (loop for lst in sv::*svex-aig-op-table* do (let ((fn (cadr lst))) (unless (eq fn 'sv::a4vec-fix) (profile-fn fn)))) ||# (defun svex-apply-aig-collect-args (n restargs argsvar svvar maskvar ;; argmasks-var ) (let* ((n (nfix n))) (if (atom restargs) nil (append (if (consp (car restargs)) (case (caar restargs) (3v `((maybe-a3vec-fix ;; (a4vec-mask (4vmask-nth ,n ,argmasks-var) (a4veclist-nth ,n ,argsvar) (svexlist-nth ,n ,svvar)))) (3vp `(;; (a4vec-mask (4vmask-nth ,n ,argmasks-var) (a4veclist-nth ,n ,argsvar) (3valued-syntaxp (svexlist-nth ,n ,svvar)))) (mask `(,maskvar)) (t (prog2$ (er hard? 'svex-apply-aig-collect-args "bad formal expr") `((a4veclist-nth ,n ,argsvar))))) `((a4veclist-nth ,n ,argsvar))) (svex-apply-aig-collect-args (+ 1 n) (cdr restargs) argsvar svvar maskvar ;; argmasks-var ))))) ;; (defun svex-apply-aig-uses-argmasks (args) ;; (if (atom args) ;; nil ;; (or (and (consp (car args)) ;; (or (eq (caar args) '3v) ;; (eq (caar args) '3vp))) ;; (svex-apply-aig-uses-argmasks (cdr args))))) (defun svex-apply-aig-cases-fn (argsvar svvar maskvar optable) (b* (((when (atom optable)) '((otherwise (a4vec-x)))) ((list sym fn args) (car optable)) (acc-args (svex-apply-aig-collect-args 0 args argsvar svvar maskvar ;; 'tmp-argmasks )) (call `(,fn . ,acc-args)) (full ;; (if (svex-apply-aig-uses-argmasks args) ;; `(let ((tmp-argmasks (svex-argmasks ,maskvar ',sym ,svvar))) ;; ,call) call)) (cons `(,sym ,full) (svex-apply-aig-cases-fn argsvar svvar maskvar (cdr optable))))) (defmacro svex-apply-aig-cases (fn args svex mask) `(case ,fn . ,(svex-apply-aig-cases-fn args svex mask *svex-aig-op-table*))) (defthm svex-p-when-nth (implies (and (svexlist-p x) (nth n x)) (svex-p (nth n x))) :hints(("Goal" :in-theory (enable nth svexlist-p)))) (defthm a4vec-p-when-nth (implies (and (a4veclist-p x) (nth n x)) (a4vec-p (nth n x))) :hints(("Goal" :in-theory (enable nth svexlist-p)))) ;; (defthm a4vec-eval-of-maybe-a4vec-fix-nth-out-of-bounds ;; (implies (<= (len x) (nfix n)) ;; (equal (a4vec-eval (maybe-a4vec-fix (nth n x)) env) ;; (4vec-x))) ;; :hints(("Goal" :in-theory (enable maybe-a4vec-fix nth)))) (local (in-theory (disable nth))) (local (defthm 4vec-bit?!-of-3vec-fix (equal (4vec-bit?! (3vec-fix test) then else) (4vec-bit?! test then else)) :hints(("Goal" :in-theory (enable 4vec-bit?! 3vec-fix))))) (define svex-apply-aig ((fn fnsym-p) (args a4veclist-p) (terms svexlist-p) (mask 4vmask-p)) :prepwork ((local (Defthm 4veclist-nth-safe-of-a4veclist-eval (equal (a4vec-eval (a4veclist-nth n x) aigenv) (4veclist-nth-safe n (a4veclist-eval x aigenv))) :hints(("Goal" :in-theory (enable a4veclist-eval a4veclist-nth 4veclist-nth-safe))))) (local (defun ind (n vals x) (if (zp n) (list vals x) (ind (1- n) (cdr vals) (cdr x))))) (local (defthm 3vec-p-when-3valued-syntaxp-nth (implies (and (EQUAL (A4VECLIST-EVAL VALS AIGENV) (SVEXLIST-EVAL X (SVEX-A4VEC-ENV-EVAL A4ENV AIGENV))) (3valued-syntaxp (svexlist-nth n x))) (3vec-p (a4vec-eval (nth n vals) aigenv))) :hints(("Goal" :in-theory (enable a4veclist-eval svexlist-eval svexlist-nth nth) :induct (ind n vals x) :expand ((a4veclist-eval vals aigenv) (:free (env) (svexlist-eval x env)))) (and stable-under-simplificationp '(:use ((:instance 3vec-p-of-eval-when-3valued-syntaxp (x (car x)) (env (svex-a4vec-env-eval a4env aigenv))))))))) (local (encapsulate nil (local (defun ind2 (n masks vals x) (if (zp n) (list masks vals x) (ind2 (1- n) (cdr masks) (cdr vals) (cdr x))))) ;; BOZO do we need this? ;; (defthm 4vmask-of-nths ;; (implies (equal (len masks) (len vecs)) ;; (equal (4vec-mask (4vmask-nth n masks) ;; (4veclist-nth-safe n vecs)) ;; (4veclist-nth-safe n (4veclist-mask masks vecs)))) ;; :hints(("Goal" :in-theory (enable 4vmask-nth 4veclist-nth-safe 4veclist-mask nth ;; 4vmasklist-fix) ;; :induct (ind2 n masks vecs nil)))) (defthm svex-eval-of-nth-rev (equal (svex-eval (nth n x) env) (4veclist-nth-safe n (svexlist-eval x env)))) (in-theory (disable svex-eval-of-nth 4veclist-nth-safe-of-svexlist-eval)) (local (defthm 3vec-p-of-eval-by-equal (implies (and (equal x (svex-eval y env)) (3valued-syntaxp y)) (3vec-p x)))) (local (defthm 3vec-p-of-eval-by-equal-with-mask (implies (and (equal x (4vec-mask mask (svex-eval y env))) (3valued-syntaxp y)) (3vec-p x)))) (defthm 4veclist-masked-idempotent (implies (equal x (4veclist-mask masks y)) (equal (4veclist-mask masks x) x))) (defthm dumb (implies (and (EQUAL (A4VECLIST-EVAL VALS AIGENV) (4VECLIST-MASK masks (SVEXLIST-EVAL X (SVEX-A4VEC-ENV-EVAL A4ENV AIGENV)))) (3valued-syntaxp (svexlist-nth n x))) (3vec-p (4veclist-nth-safe n (a4veclist-eval vals aigenv))) ;; (3vec-p (4vec-mask (4vmask-nth n masks) ;; (a4vec-eval (a4veclist-nth n vals) aigenv))) ) :hints (("goal" :in-theory (e/d (nth len 4veclist-nth-safe a4veclist-eval 4veclist-mask svexlist-eval a4veclist-eval svexlist-nth) (4veclist-nth-safe-of-a4veclist-eval)) :expand ((:free (env) (svexlist-eval x env)) (a4veclist-eval vals aigenv) (:free (a b) (4veclist-mask masks (cons a b)))) :induct (ind2 n masks vals x)))) ))) :verbosep t :guard-debug t :returns (res a4vec-p) (b* ((fn (fnsym-fix fn)) (args (a4veclist-fix args)) (res (svex-apply-aig-cases fn args terms mask))) ;; ;; This cleverly masks out any bits of the result that we don't care about, ;; ;; replacing them with Xes. This might be a great way to get a lot more ;; ;; constant propagation... (a4vec-mask mask res)) /// (defthm svex-apply-aig-correct (implies (and (fnsym-p fn) (bind-free '((a4env . env)) (a4env)) (equal (a4veclist-eval vals aigenv) (4veclist-mask argmasks (svexlist-eval x (svex-a4vec-env-eval a4env aigenv)))) (svex-argmasks-okp (svex-call fn x) mask argmasks)) (equal (a4vec-eval (svex-apply-aig fn vals x mask) aigenv) (4vec-mask mask (svex-apply fn (svexlist-eval x (svex-a4vec-env-eval a4env aigenv)))))) :hints(("Goal" :in-theory (disable len-of-4veclist-mask svex-apply-aig) ;; Establish that (len vals) = (len x). :use ((:instance len-of-4veclist-mask (masks (svex-argmasks mask fn x)) (values (a4veclist-eval vals aigenv))) (:instance len-of-4veclist-mask (masks (svex-argmasks mask fn x)) (values (svexlist-eval x (svex-a4vec-env-eval a4env aigenv)))))) (and stable-under-simplificationp '( :in-theory (e/d (svex-apply svexlist-eval ;; 4veclist-nth-safe ;; 4veclist-mask 4veclist-mask? 4vec-bitnot 4vec-bitand 4vec-bitor 4vec-bitxor-redef 4vec-reduction-and 4vec-reduction-or 4vec-? 4vec-?* 4vec-bit? 4vec-==) (;; len-of-svexlist-eval ;; len-of-a4veclist-eval ;; len-of-4veclist-mask svex-argmasks-correct svex-argmasks-remove-mask)) :use ;; ((:instance len-of-svexlist-eval ;; (env (svex-a4vec-env-eval a4env aigenv))) ;; (:instance len-of-a4veclist-eval ;; (x vals) (env aigenv))) ((:instance svex-argmasks-okp-necc (x (svex-call fn x)) (vals (a4veclist-eval vals aigenv)) (env (svex-a4vec-env-eval a4env aigenv))) ;; (:instance svex-argmasks-remove-mask ;; (fn fn) ;; (args x) ;; (env (svex-a4vec-env-eval a4env aigenv))) ) :do-not-induct t :do-not '(fertilize generalize eliminate-destructors) ))) :otf-flg t)) (defalist svex-aig-memotable :key-type svex :val-type a4vec) (defthm a4vec-p-of-svex-a4vec-env-lookup (implies (and (svex-a4vec-env-p x) (hons-assoc-equal k x)) (a4vec-p (cdr (hons-assoc-equal k x))))) (defthm a4vec-p-of-svex-aig-memotable-lookup (implies (and (svex-aig-memotable-p x) (hons-assoc-equal k x)) (a4vec-p (cdr (hons-assoc-equal k x))))) ;; (SVEX->A4VEC ;; '(RSH (? (< 0 (* 32 (B- (CONCAT 16 CNST 0) 0))) (* 32 (B- (CONCAT 16 CNST 0) 0)) 0) '(-71265535176078871931497435759850128999 . 269016831744859591531877171671918082457)) ;; (make-fast-alist `((cnst ,(acl2::numlist 0 2 16) . ,(acl2::numlist 1 2 16)))) ;; nil) (define svex-is-const-concat ((x svex-p)) :returns (is-concat) :guard-hints (("goal" :in-theory (enable nth))) (svex-case x :call (and (eq x.fn 'concat) (eql (len x.args) 3) (let ((arg1 (mbe :logic (nth 0 x.args) :exec (car x.args)))) (svex-case arg1 :quote))) :otherwise nil)) (define svex-const-concat-args ((x svex-p)) :guard (svex-is-const-concat x) :guard-hints (("goal" :expand ((:free (n) (nth n (svex-call->args x))) (:free (n) (nth n (cdr (svex-call->args x)))) (:free (n) (nth n (cddr (svex-call->args x))))))) :prepwork ((local (in-theory (enable svex-is-const-concat)))) :returns (mv (width 4vec-p) (lsbs svex-p) (msbs svex-p)) (b* (((svex-call x))) (mv (svex-quote->val (mbe :logic (svex-fix (nth 0 x.args)) :exec (first x.args))) (mbe :logic (svex-fix (nth 1 x.args)) :exec (second x.args)) (mbe :logic (svex-fix (nth 2 x.args)) :exec (third x.args)))) /// (local (defthm nth-when-n-too-big (implies (<= (len x) (nfix n)) (equal (nth n x) nil)) :hints(("Goal" :in-theory (enable nth))))) (local (defthm 4vec-zero-ext-is-concat (equal (4vec-zero-ext n x) (4vec-concat n x 0)) :hints(("Goal" :in-theory (enable 4vec-zero-ext 4vec-concat))))) (defretd svex-const-concat-args-correct-rw (implies (svex-is-const-concat x) (equal (svex-eval x env) (4vec-concat width (svex-eval lsbs env) (svex-eval msbs env)))) :hints(("Goal" :in-theory (enable svex-apply svexlist-eval)))) (local (defthm svex-count-of-nth (<= (svex-count (nth n x)) (svexlist-count x)) :hints(("Goal" :in-theory (enable nth svexlist-count))) :rule-classes :linear)) (local (defthm svex-count-of-svexlist-nth (<= (svex-count (svexlist-nth n x)) (svexlist-count x)) :hints(("Goal" :in-theory (enable svexlist-nth))) :rule-classes :linear)) (defret svex-count-of-svex-const-concat-args-lsbs (implies (svex-is-const-concat x) (< (svex-count lsbs) (svex-count x))) :rule-classes :linear) (defret svex-count-of-svex-const-concat-args-msbs (implies (svex-is-const-concat x) (< (svex-count msbs) (svex-count x))) :hints ((and stable-under-simplificationp '(:expand ((svex-count x))))) :rule-classes :linear)) (progn (local (defthm 4vec-zero-ext-of-4vec-mask? (equal (4vec-zero-ext w (4vec-mask? mask x y)) (4vec-mask? (if (and (2vec-p w) (<= 0 (2vec->val w))) (sparseint-concatenate (2vec->val w) (4vmask-fix mask) 0) mask) (4vec-zero-ext w x) (4vec-zero-ext w y))) :hints(("Goal" :in-theory (enable 4vec-mask? 4vec-bit? 3vec-bit? 4vec-zero-ext)) (logbitp-reasoning)))) (local (defthm 4vec-zero-ext-of-equal-4vec-mask? (implies (equal z (4vec-mask? mask x y)) (equal (4vec-zero-ext w z) (4vec-mask? (if (and (2vec-p w) (<= 0 (2vec->val w))) (sparseint-concatenate (2vec->val w) (4vmask-fix mask) 0) mask) (4vec-zero-ext w x) (4vec-zero-ext w y)))))) (local (defthm 4vec-zero-ext-of-zero-ext (equal (4vec-zero-ext w (4vec-zero-ext w x)) (4vec-zero-ext w x)) :hints(("Goal" :in-theory (enable 4vec-zero-ext)))))) (defines svex->a4vec ;; Self-memoized version of svex-eval, for GL :verify-guards nil :ruler-extenders :all (define svex->a4vec ((x svex-p) (env svex-a4vec-env-p) (masks svex-mask-alist-p)) :returns (res a4vec-p) :measure (two-nats-measure (svex-count x) 1) (b* ((env (svex-a4vec-env-fix env))) (svex-case x :quote (b* ((mask (svex-mask-lookup x masks))) (4vec->a4vec (4vec-mask mask x.val))) :var (let ((look (hons-get x.name env)) (mask (svex-mask-lookup x masks))) (a4vec-mask mask (if look (cdr look) (a4vec-x)))) :call (b* ((x (svex-fix x)) ((when (svex-is-const-concat x)) (b* (((mv upper lower) (svex-concat->a4vec x env masks)) (mask (svex-mask-lookup x masks))) (a4vec-mask mask (a4vec upper lower)))) (args (svexlist->a4vec x.args env masks)) (mask (svex-mask-lookup x masks))) (svex-apply-aig x.fn args x.args mask))))) (define svexlist->a4vec ((x svexlist-p) (env svex-a4vec-env-p) (masks svex-mask-alist-p)) :returns (res a4veclist-p) :measure (two-nats-measure (svexlist-count x) 0) (if (atom x) nil (cons (svex->a4vec (car x) env masks) (svexlist->a4vec (cdr x) env masks)))) (define svex-concat->a4vec ((x svex-p) (env svex-a4vec-env-p) (masks svex-mask-alist-p)) :returns (mv (upper true-listp) (lower true-listp)) :measure (two-nats-measure (svex-count x) (if (svex-is-const-concat x) 0 2)) (b* (((unless (svex-is-const-concat x)) (b* ((res (svex->a4vec x env masks))) (mv (a4vec->upper res) (a4vec->lower res)))) ((mv width lsbs msbs) (svex-const-concat-args x)) ((unless (and (2vec-p width) (natp (2vec->val width)))) (mv (a4vec->upper (a4vec-x)) (a4vec->lower (a4vec-x)))) (width (2vec->val width)) (mask (svex-mask-lookup x masks)) ((unless (sparseint-test-bitand (sparseint-concatenate width 0 -1) mask)) (svex-concat->a4vec lsbs env masks)) ((mv upper2 lower2) (svex-concat->a4vec msbs env masks))) (svex-concat->a4vec-lower lsbs width upper2 lower2 env masks))) (define svex-concat->a4vec-lower ((x svex-p) (width natp) (upper-acc true-listp) (lower-acc true-listp) (env svex-a4vec-env-p) (masks svex-mask-alist-p)) :returns (mv (upper true-listp) (lower true-listp)) :measure (two-nats-measure (svex-count x) (if (svex-is-const-concat x) 0 2)) (b* ((upper-acc (llist-fix upper-acc)) (lower-acc (llist-fix lower-acc)) ((When (zp width)) (mv upper-acc lower-acc)) ((unless (svex-is-const-concat x)) (b* ((res (svex->a4vec x env masks))) (mv (aig-logapp-nss width (a4vec->upper res) upper-acc) (aig-logapp-nss width (a4vec->lower res) lower-acc)))) ((mv sub-width lsbs msbs) (svex-const-concat-args x)) ((unless (and (2vec-p sub-width) (natp (2vec->val sub-width)))) (mv (aig-logapp-nss width (a4vec->upper (a4vec-x)) upper-acc) (aig-logapp-nss width (a4vec->lower (a4vec-x)) lower-acc))) (sub-width (2vec->val sub-width)) (lsbs-width (min width sub-width)) (msbs-width (- width lsbs-width)) ((mv upper-acc lower-acc) (svex-concat->a4vec-lower msbs msbs-width upper-acc lower-acc env masks))) (svex-concat->a4vec-lower lsbs lsbs-width upper-acc lower-acc env masks))) /// (verify-guards svex->a4vec :guard-debug t) (local (in-theory (disable svex->a4vec svexlist->a4vec))) (encapsulate nil (local (defthm lookup-in-svex-a4vec-env-eval-lemma (implies (svex-a4vec-env-p env) (equal (hons-assoc-equal k (svex-a4vec-env-eval env aigenv)) (and (hons-assoc-equal k env) (cons k (a4vec-eval (cdr (hons-assoc-equal k env)) aigenv))))) :hints(("Goal" :in-theory (enable svex-a4vec-env-eval svex-a4vec-env-p) :induct (svex-a4vec-env-eval env aigenv) :do-not-induct t)) :rule-classes nil)) (defthm lookup-in-svex-a4vec-env-eval (equal (hons-assoc-equal k (svex-a4vec-env-eval env aigenv)) (and (hons-assoc-equal k (svex-a4vec-env-fix env)) (cons k (a4vec-eval (cdr (hons-assoc-equal k (svex-a4vec-env-fix env))) aigenv)))) :hints(("Goal" :use ((:instance lookup-in-svex-a4vec-env-eval-lemma (env (svex-a4vec-env-fix env)))))))) (defthm svex-env-lookup-in-svex-a4vec-env-eval (equal (svex-env-lookup k (svex-a4vec-env-eval env aigenv)) (if (hons-assoc-equal (svar-fix k) (svex-a4vec-env-fix env)) (a4vec-eval (cdr (hons-assoc-equal (svar-fix k) (svex-a4vec-env-fix env))) aigenv) (4vec-x))) :hints(("Goal" :in-theory (enable svex-env-lookup)))) ;; (local (defthm svex-apply-aig-correct-rw ;; (implies (and (fnsym-p fn) ;; (bind-free '((a4env . env)) (a4env)) ;; (equal (a4veclist-eval vals aigenv) ;; (4veclist-mask argmasks (svexlist-eval x (svex-a4vec-env-eval a4env aigenv)))) ;; (svex-argmasks-okp (svex-call fn x) mask argmasks)) ;; (equal (a4vec-eval (svex-apply-aig fn vals x mask) aigenv) ;; (4vec-mask mask (svex-apply fn (svexlist-eval x (svex-a4vec-env-eval a4env aigenv)))))) (local (in-theory (enable svex-mask-alist-complete-necc))) (local (defthm 4vec-concat-when-not-2vec (implies (not (equal (4vec->upper width) (4vec->lower width))) (equal (4vec-concat width x y) (4vec-x))) :hints(("Goal" :in-theory (enable 4vec-concat))))) (local (defthm 4vec-concat-when-not-natp (implies (< (4vec->lower width) 0) (equal (4vec-concat width x y) (4vec-x))) :hints(("Goal" :in-theory (enable 4vec-concat))))) (local (defthm 4vec-mask-idempotence-rw (implies (equal y (4vec-mask mask x)) (equal (4vec-mask mask y) y)))) (local (defthm 4vec-concat-when-width-0 (implies (and (equal 0 (4vec->upper width)) (equal 0 (4vec->lower width))) (equal (4vec-concat width x y) (4vec-fix y))) :hints(("Goal" :in-theory (enable 4vec-concat))))) (local (define 4vec-change-all-bits ((x 4vec-p)) :returns (new-x 4vec-p) (4vec (lognot (4vec->upper x)) (lognot (4vec->lower x))))) (local (encapsulate nil (local (in-theory (disable* (:rules-of-class :linear :here) bitops::logand-natp-type-2 bitops::logand-natp-type-1 bitops::logior-natp-type bitops::lognot-negp bitops::lognot-natp member-svex-mask-alist-keys acl2::loghead-identity))) (defthm mask-of-bit?-logand-lognot (implies (4vmask-p mask) (equal (4vec-mask mask (4vec-bit? (2vec (logand a (lognot (sparseint-val mask)))) x y)) (4vec-mask mask y))) :hints(("Goal" :in-theory (e/d* (4vec-mask 4vec-bit? 3vec-bit?))) (logbitp-reasoning))) (defthm mask-of-bit?-logand-lognot2 (implies (4vmask-p mask) (equal (4vec-mask mask (4vec-bit? (2vec (logand (lognot (sparseint-val mask)) a)) x y)) (4vec-mask mask y))) :hints(("Goal" :in-theory (e/d* (4vec-mask 4vec-bit? 3vec-bit?))) (logbitp-reasoning))) (defthm argmasks-okp-for-const-concat-implies-lsb-mask-subsumes-outer (b* (((mv width lsbs msbs) (svex-const-concat-args x))) (implies (and (svex-is-const-concat x) (svex-mask-alist-complete masks) (2vec-p width) (<= (nfix w) (2vec->val width))) (4vmask-subsumes (sparseint-concatenate w (svex-mask-lookup lsbs masks) 0) (sparseint-concatenate w (svex-mask-lookup x masks) 0)))) :hints (("goal" :use ((:instance svex-mask-alist-complete-necc (y x) (mask-al masks)) (:instance svex-argmasks-okp-necc (vals (b* (((mv width lsbs msbs) (svex-const-concat-args x))) (list width (4vec-bit? (2vec (logandc1 (sparseint-val (svex-mask-lookup lsbs masks)) (sparseint-val (svex-mask-lookup x masks)))) (4vec-change-all-bits (svex-eval lsbs env)) (svex-eval lsbs env)) (svex-eval msbs env)))) (mask (svex-mask-lookup x masks)) (argmasks (svex-argmasks-lookup (svex-call->args x) masks)))) :in-theory (enable svex-argmasks-lookup svex-apply 4vmask-subsumes svexlist-eval 4veclist-mask len nth) :expand ((svex-is-const-concat x) (svex-const-concat-args x) (len (svex-call->args x)) (len (cdr (svex-call->args x))) (len (cddr (svex-call->args x))) (len (cdddr (svex-call->args x))) (:free (n) (nth n (svex-call->args x))) (:free (n) (nth n (cdr (svex-call->args x)))) (:free (n) (nth n (cddr (svex-call->args x)))) (:free (n) (nth n (cdddr (svex-call->args x)))))) (and stable-under-simplificationp '(:in-theory (enable 4vec-mask 4vec-bit? 3vec-bit? 4vec-change-all-bits 4vec-concat))) (logbitp-reasoning :add-hints (:in-theory (enable* logbitp-case-splits)) :simp-hint (:in-theory (enable* logbitp-case-splits))) ) :otf-flg t) (local (in-theory (disable iff not))) (defthm argmasks-okp-for-const-concat-implies-msb-mask-subsumes-outer (b* (((mv width lsbs msbs) (svex-const-concat-args x))) (implies (and (svex-is-const-concat x) (svex-mask-alist-complete masks) (2vec-p width) (<= 0 (2vec->val width))) (4vmask-subsumes (svex-mask-lookup msbs masks) (sparseint-rightshift (4vec->lower width) (svex-mask-lookup x masks))))) :hints (("goal" :use ((:instance svex-mask-alist-complete-necc (y x) (mask-al masks)) (:instance svex-argmasks-okp-necc (vals (b* (((mv width lsbs msbs) (svex-const-concat-args x))) (list width (svex-eval lsbs env) (4vec-bit? (2vec (logandc1 (sparseint-val (svex-mask-lookup msbs masks)) (logtail (2vec->val width) (sparseint-val (svex-mask-lookup x masks))))) (4vec-change-all-bits (svex-eval msbs env)) (svex-eval msbs env))))) (mask (svex-mask-lookup x masks)) (argmasks (svex-argmasks-lookup (svex-call->args x) masks)))) :in-theory (enable svex-argmasks-lookup svex-apply 4vmask-subsumes svexlist-eval 4veclist-mask len nth) :expand ((svex-is-const-concat x) (svex-const-concat-args x) (len (svex-call->args x)) (len (cdr (svex-call->args x))) (len (cddr (svex-call->args x))) (len (cdddr (svex-call->args x))) (:free (n) (nth n (svex-call->args x))) (:free (n) (nth n (cdr (svex-call->args x)))) (:free (n) (nth n (cddr (svex-call->args x)))) (:free (n) (nth n (cdddr (svex-call->args x)))))) (and stable-under-simplificationp '(:in-theory (enable 4vec-mask 4vec-bit? 3vec-bit? 4vec-change-all-bits 4vec-concat))) (logbitp-reasoning :add-hints (:in-theory (enable* logbitp-case-splits)) :simp-hint (:in-theory (enable* logbitp-case-splits))) ) :otf-flg t) (defthm argmasks-okp-for-const-concat-implies-lsb-mask-subsumes-outer-when-tail-0 (b* (((mv width lsbs msbs) (svex-const-concat-args x))) (implies (and (svex-is-const-concat x) (svex-mask-alist-complete masks) (2vec-p width) (<= 0 (2vec->val width)) (equal 0 (logtail (2vec->val width) (sparseint-val (svex-mask-lookup x masks))))) (4vmask-subsumes (svex-mask-lookup lsbs masks) (svex-mask-lookup x masks)))) :hints (("goal" :use ((:instance argmasks-okp-for-const-concat-implies-lsb-mask-subsumes-outer (w (2vec->val (mv-nth 0 (svex-const-concat-args x)))))) :in-theory (e/d (4vmask-subsumes) (argmasks-okp-for-const-concat-implies-lsb-mask-subsumes-outer))) (logbitp-reasoning :prune-examples nil) ) :otf-flg t))) (local (defthmd 4vec-mask-over-4vec-zero-ext (implies (and (2vec-p width) (<= 0 (2vec->val width))) (equal (4vec-mask mask (4vec-zero-ext width x)) (4vec-concat width (4vec-mask mask x) (4vec-mask (sparseint-rightshift (2vec->val width) (4vmask-fix mask)) 0)))) :hints(("Goal" :in-theory (enable 4vec-mask 4vec-zero-ext 4vec-concat)) (logbitp-reasoning :prune-examples nil)))) (local (defthmd 4vec-mask-over-4vec-concat (implies (and (2vec-p width) (<= 0 (2vec->val width))) (equal (4vec-mask mask (4vec-concat width x y)) (4vec-concat width (4vec-mask mask x) (4vec-mask (sparseint-rightshift (2vec->val width) (4vmask-fix mask)) y)))) :hints(("Goal" :in-theory (enable 4vec-mask 4vec-concat)) (logbitp-reasoning :prune-examples nil)))) (local (defthmd 4vec-concat-of-4vec-mask-identity (implies (and (equal mask1 (4vmask-fix mask)) (2vec-p w) (<= 0 (2vec->val w)) (equal w1 (2vec->val w))) (equal (4vec-concat w (4vec-mask mask x) (4vec-mask (sparseint-rightshift w1 mask1) (4vec-rsh w x))) (4vec-mask mask x))) :hints(("Goal" :in-theory (enable 4vec-mask 4vec-concat 4vec-rsh 4vec-shift-core)) (logbitp-reasoning :prune-examples nil)))) (local (defthmd 4vec-concat-of-equal-4vec-conct (implies (and (equal x (4vec-concat w a b)) (2vec-p w) (<= 0 (2vec->val w))) (equal (4vec-concat w x y) (4vec-concat w a y))))) (local (defthm min-gte-zero (implies (and (<= 0 x) (<= 0 y)) (<= 0 (min x y))))) (local (defthm 2vec-of-4vec-acc (implies (2vec-p x) (and (equal (2vec (4vec->lower x)) (4vec-fix x)) (equal (2vec (4vec->upper x)) (4vec-fix x)))) :hints(("Goal" :in-theory (enable 2vec))))) (local (defthmd 4vec-concat-identity (implies (and (2vec-p w) (<= 0 (2vec->val w))) (equal (4vec-concat w x (4vec-rsh w x)) (4vec-fix x))) :hints(("Goal" :in-theory (enable 4vec-concat 4vec-rsh 4vec-shift-core)) (logbitp-reasoning :prune-examples nil)))) (local (defthmd equal-of-4vec-concat2 (implies (and (2vec-p w) (<= 0 (2vec->val w))) (equal (equal (4vec-concat w x y) z) (and (4vec-p z) (equal (4vec-zero-ext w x) (4vec-zero-ext w z)) (equal (4vec-fix y) (4vec-rsh w z))))) :hints(("Goal" :in-theory (enable 4vec-concat 4vec-zero-ext 4vec-rsh 4vec-shift-core)) (logbitp-reasoning)) :otf-flg t)) (local (defthm 4vec-zero-ext-of-concat (implies (and (2vec-p w1) (2vec-p w2) (<= 0 (2vec->val w1)) (<= (2vec->val w1) (2vec->val w2))) (equal (4vec-zero-ext w1 (4vec-concat w2 x y)) (4vec-zero-ext w1 x))) :hints(("Goal" :in-theory (enable 4vec-zero-ext 4vec-concat))))) (local (defthm 4vec-rsh-of-4vec-mask (implies (and (2vec-p shift) (<= 0 (2vec->val shift))) (equal (4vec-rsh shift (4vec-mask mask x)) (4vec-mask (sparseint-rightshift (2vec->val shift) (4vmask-fix mask)) (4vec-rsh shift x)))) :hints(("Goal" :in-theory (enable 4vec-mask 4vec-rsh 4vec-shift-core))))) (local (defthm equal-zero-ext-of-mask (implies (and (2vec-p w) (<= 0 (2vec->val w))) (equal (equal (4vec-zero-ext w (4vec-mask m x)) (4vec-zero-ext w (4vec-mask m y))) (equal (4vec-mask (sparseint-concatenate (2vec->val w) (4vmask-fix m) 0) x) (4vec-mask (sparseint-concatenate (2vec->val w) (4vmask-fix m) 0) y)))) :hints(("Goal" :in-theory (enable 4vec-zero-ext 4vec-mask)) (logbitp-reasoning)))) (local (defthmd 4vec-mask-of-4vec-concat-under-mask (implies (and (equal (logtail (2vec->val width) (sparseint-val (4vmask-fix mask))) 0) (2vec-p width) (<= 0 (2vec->val width))) (equal (4vec-mask mask (4vec-concat width x y)) (4vec-mask mask x))) :hints(("Goal" :in-theory (enable 4vec-mask 4vec-concat)) (logbitp-reasoning :prune-examples nil)))) (local (defthmd 4vec-concat-of-4vec (equal (4vec (logapp w a b) (logapp w c d)) (4vec-concat (2vec (nfix w)) (4vec a c) (4vec b d))) :hints(("Goal" :in-theory (enable 4vec-concat))))) (local (defthmd 4vec-zero-ext-of-4vec (equal (4vec (loghead w a) (loghead w c)) (4vec-zero-ext (2vec (nfix w)) (4vec a c))) :hints(("Goal" :in-theory (enable 4vec-zero-ext))))) (local (defthmd 4vec-zero-ext-of-4vec/0 (equal (4vec (loghead w a) 0) (4vec-zero-ext (2vec (nfix w)) (4vec a 0))) :hints(("Goal" :in-theory (enable 4vec-zero-ext))))) (local (defthmd 4vec-of-aig-list->s-of-upper/lower (equal (4vec (aig-list->s (a4vec->upper x) env) (aig-list->s (a4vec->lower x) env)) (a4vec-eval x env)) :hints(("Goal" :in-theory (enable a4vec-eval))))) (local (defthm aig-list->s-of-list-fix (equal (aig-list->s (list-fix x) env) (aig-list->s x env)) :hints(("Goal" :in-theory (enable aig-list->s))))) (local (defthm 4vec-mask-of-loghead-4vec-mask (implies (equal mask1 (4vmask-fix mask)) (Equal (4vec-mask (sparseint-concatenate n mask1 0) (4vec-mask mask x)) (4vec-mask (sparseint-concatenate n mask1 0) x))) :hints(("Goal" :in-theory (enable 4vec-mask)) (logbitp-reasoning)))) (local (defun aig-logapp-nss-ind (w1 w2 x y) (declare (xargs :measure (nfix w1))) (if (or (zp w1) (zp w2)) (list x y) (aig-logapp-nss-ind (1- w1) (1- w2) (gl::scdr x) y)))) (local (defthm aig-logapp-nss-of-nfix (Equal (aig-logapp-nss (nfix w) x y) (aig-logapp-nss w x y)) :hints(("Goal" :in-theory (enable aig-logapp-nss))))) (local (defthm aig-logapp-nss-of-list-fix (Equal (aig-logapp-nss w (list-fix x) y) (aig-logapp-nss w x y)) :hints(("Goal" :in-theory (enable aig-logapp-nss))))) (local (defthm aig-logapp-nss-of-snorm (Equal (aig-logapp-nss w (gl::bfr-snorm x) y) (aig-logapp-nss w x y)) :hints(("Goal" :in-theory (enable aig-logapp-nss))))) (local (defthm aig-logapp-nss-of-aig-logapp-nss (equal (aig-logapp-nss w1 (aig-logapp-nss w2 x y) z) (let* ((wa (min (nfix w1) (nfix w2))) (wb (- (nfix w1) wa))) (aig-logapp-nss wa x (aig-logapp-nss wb y z)))) :hints(("Goal" :in-theory (enable aig-logapp-nss) :induct (aig-logapp-nss-ind w1 w2 x y) :expand ((:free (x y) (aig-logapp-nss w1 x y)) (:free (x y) (aig-logapp-nss w2 x y))))))) (local (defthm aig-logapp-nss-when-zp (implies (zp w) (equal (aig-logapp-nss w x y) (list-fix y))) :hints(("Goal" :in-theory (enable aig-logapp-nss))))) (local (defun-sk svex-concat->a4vec-lower-acc-elim-correct (x width env masks) (forall (upper-acc lower-acc) (implies (syntaxp (not (and (equal upper-acc ''nil) (equal lower-acc ''nil)))) (b* (((mv upper-impl lower-impl) (svex-concat->a4vec-lower x width upper-acc lower-acc env masks)) ((mv upper-spec lower-spec) (svex-concat->a4vec-lower x width nil nil env masks))) (and (equal upper-impl (aig-logapp-nss width upper-spec (list-fix upper-acc))) (equal lower-impl (aig-logapp-nss width lower-spec (list-fix lower-acc))))))) :rewrite :direct)) (local (in-theory (disable svex-concat->a4vec-lower-acc-elim-correct))) (local (std::defret-mutual svex-concat->a4vec-lower-acc-elim-lemma (defret svex-concat->a4vec-lower-acc-elim-lemma (svex-concat->a4vec-lower-acc-elim-correct x width env masks) :hints ((and stable-under-simplificationp `(:expand (,(car (last clause)) (:free (upper-acc lower-acc) <call>))))) :fn svex-concat->a4vec-lower :rule-classes nil) :skip-others t)) (defthm svex-concat->a4vec-lower-acc-elim (implies (syntaxp (not (and (equal upper-acc ''nil) (equal lower-acc ''nil)))) (b* (((mv upper-impl lower-impl) (svex-concat->a4vec-lower x width upper-acc lower-acc env masks)) ((mv upper-spec lower-spec) (svex-concat->a4vec-lower x width nil nil env masks))) (and (equal upper-impl (aig-logapp-nss width upper-spec (list-fix upper-acc))) (equal lower-impl (aig-logapp-nss width lower-spec (list-fix lower-acc)))))) :hints (("goal" :use svex-concat->a4vec-lower-acc-elim-lemma))) ;; (define svex-concat->a4vec-lower-zero ((x svex-p) ;; (width natp) ;; (env svex-a4vec-env-p) ;; (masks svex-mask-alist-p) ;; (memo svex-aig-memotable-p)) ;; :returns (mv (upper true-listp) ;; (lower true-listp) ;; (memo1 svex-aig-memotable-p)) ;; :measure (svex-count x) ;; :hooks nil ;; :verify-guards nil ;; (b* ((memo (svex-aig-memotable-fix memo)) ;; ((When (zp width)) ;; (mv nil nil memo)) ;; ((unless (svex-is-const-concat x)) ;; (b* (((mv res memo) (svex->a4vec x env masks memo))) ;; (mv (aig-logapp-nss width (a4vec->upper res) nil) ;; (aig-logapp-nss width (a4vec->lower res) nil) ;; memo))) ;; ((mv sub-width lsbs msbs) ;; (svex-const-concat-args x)) ;; ((unless (and (2vec-p sub-width) (natp (2vec->val sub-width)))) ;; (mv (aig-logapp-nss width (a4vec->upper (a4vec-x)) nil) ;; (aig-logapp-nss width (a4vec->lower (a4vec-x)) nil) ;; (svex-aig-memotable-fix memo))) ;; (sub-width (2vec->val sub-width)) ;; (lsbs-width (min width sub-width)) ;; (msbs-width (- width lsbs-width)) ;; ((mv upper2 lower2 memo) ;; (svex-concat->a4vec-lower-zero msbs msbs-width env masks memo)) ;; ((mv upper1 lower1 memo) ;; (svex-concat->a4vec-lower-zero lsbs lsbs-width env masks memo))) ;; (mv (aig-logapp-nss lsbs-width upper1 upper2) ;; (aig-logapp-nss lsbs-width lower1 lower2) ;; memo)) ;; /// ;; (defthm-svex->a4vec-flag ;; (defthm svex-concat->a4vec-lower-in-terms-of-zero ;; (b* (((mv upper-impl lower-impl memo-impl) ;; (svex-concat->a4vec-lower x width upper-acc lower-acc env masks memo)) ;; ((mv upper-spec lower-spec memo-spec) ;; (svex-concat->a4vec-lower-zero x width env masks memo))) ;; (and (equal memo-impl memo-spec) ;; (equal upper-impl (aig-logapp-nss width upper-spec (list-fix upper-acc))) ;; (equal lower-impl (aig-logapp-nss width lower-spec (list-fix lower-acc))))) ;; :flag svex-concat->a4vec-lower ;; :hints ('(:expand ((svex-concat->a4vec-lower x width upper-acc lower-acc env masks memo) ;; (svex-concat->a4vec-lower-zero x width env masks memo))))) ;; :skip-others t)) (local (defthm 4vec-mask-of-loghead-zero-ext (implies (natp width) (equal (4vec-mask (sparseint-concatenate width mask 0) (4vec-zero-ext (2vec width) x)) (4vec-mask (sparseint-concatenate width mask 0) x))) :hints(("Goal" :in-theory (enable 4vec-mask 4vec-zero-ext)) (logbitp-reasoning)))) (local (defthm 4vec-mask-zero-ext-mask (equal (4vec-mask mask (4vec-zero-ext w (4vec-mask mask x))) (4vec-mask mask (4vec-zero-ext w x))) :hints(("Goal" :in-theory (enable 4vec-mask 4vec-zero-ext)) (logbitp-reasoning)))) (local (defthm 4vec-zero-ext-0 (equal (4vec-zero-ext 0 x) 0) :hints(("Goal" :in-theory (enable 4vec-zero-ext))))) ;; (local (Defthm 4vec-zero-ext-of-zp ;; (equal (4vec-zero-ext (2vec width) x) 0)) ;; :hints(("Goal" :in-theory (enable* 4vec-zero-ext ;; ihsext-recursive-redefs)))) (local (defthm 4vec-concat-0 (equal (4vec-concat width x 0) (4vec-zero-ext width x)) :hints(("Goal" :in-theory (enable 4vec-concat 4vec-zero-ext))))) (local (defthm 4vec-of-equal-upper-lower (implies (and (equal a (4vec->upper x)) (equal b (4vec->lower x))) (equal (4vec a b) (4vec-fix x))))) (local (defthm 4vec-mask?-of-4vec-mask?-when-subsumes (implies (4vmask-subsumes m1 m2) (equal (4vec-mask? m2 a (4vec-mask? m1 a b)) (4vec-mask? m1 a b))) :hints(("Goal" :in-theory (enable 4vec-mask? 4vec-bit? 3vec-bit? 4vmask-subsumes)) (logbitp-reasoning)))) (local (defthm zero-ext-of-zero-ext (implies (and (2vec-p a) (2vec-p b) (<= 0 (2vec->val a)) (<= (2vec->val a) (2vec->val b))) (and (equal (4vec-zero-ext a (4vec-zero-ext b x)) (4vec-zero-ext a x)) (equal (4vec-zero-ext b (4vec-zero-ext a x)) (4vec-zero-ext a x)))) :hints(("Goal" :in-theory (enable 4vec-zero-ext))))) (local (Defthm 4vec-rsh-of-4vec-mask? (implies (and (2vec-p sh) (<= 0 (2vec->val sh))) (equal (4vec-rsh sh (4vec-mask? mask a b)) (4vec-mask? (sparseint-rightshift (2vec->val sh) (4vmask-fix mask)) (4vec-rsh sh a) (4vec-rsh sh b)))) :hints(("Goal" :in-theory (enable 4vec-rsh 4vec-shift-core 4vec-mask? 4vec-bit? 3vec-bit?))))) (local (defthm 4vec-rsh-of-4vec-zero-ext (implies (and (2vec-p a) (2vec-p b) (<= 0 (2vec->val a)) (<= (2vec->val a) (2vec->val b))) (and (equal (4vec-rsh a (4vec-zero-ext b x)) (4vec-zero-ext (2vec (- (2vec->val b) (2vec->val a))) (4vec-rsh a x))) (equal (4vec-rsh b (4vec-zero-ext a x)) 0))) :hints(("Goal" :in-theory (enable 4vec-rsh 4vec-shift-core 4vec-zero-ext)) (and stable-under-simplificationp '(:in-theory (enable* ihsext-recursive-redefs)))))) (local (defthm 4vmask-subsumes-of-loghead (implies (and (4vmask-subsumes a b) (4vmask-p a) (4vmask-p b)) (4vmask-subsumes (sparseint-concatenate w a 0) (sparseint-concatenate w b 0))) :hints(("Goal" :in-theory (enable 4vmask-subsumes)) (logbitp-reasoning)))) (local (defthm 4vec-mask?-of-concat-same (implies (and (2vec-p w) (<= 0 (2vec->val w))) (equal (4vec-mask? mask (4vec-concat w a b) (4vec-concat w c d)) (4vec-concat w (4vec-mask? (sparseint-concatenate (2vec->val w) (4vmask-fix mask) 0) (4vec-zero-ext w a) (4vec-zero-ext w c)) (4vec-mask? (sparseint-rightshift (2vec->val w) (4vmask-fix mask)) b d)))) :hints(("Goal" :in-theory (enable 4vec-mask? 4vec-bit? 3vec-bit? 4vec-concat 4vec-zero-ext)) (logbitp-reasoning)))) (local (defthm 4vec-mask?-of-concat-when-logtail-0 (implies (and (equal 0 (logtail (2vec->val w) (sparseint-val (4vmask-fix mask)))) (2vec-p w) (<= 0 (2vec->val w))) (equal (4vec-mask? mask (4vec-concat w a b) c) (4vec-mask? mask a c))) :hints(("Goal" :in-theory (enable 4vec-mask? 4vec-bit? 3vec-bit? 4vec-concat)) (logbitp-reasoning :prune-examples nil)))) ;; (local (defthm 4vec-mask?-of-zero-ext-when-logtail-0 ;; (implies (and (equal 0 (logtail (2vec->val w) (sparseint-val (4vmask-fix mask)))) ;; (2vec-p w) (<= 0 (2vec->val w))) ;; (equal (4vec-mask? mask (4vec-zero-ext w a) c) ;; (4vec-mask? mask a c))) ;; :hints(("Goal" :in-theory (enable 4vec-mask? 4vec-bit? 3vec-bit? 4vec-zero-ext)) ;; (logbitp-reasoning :prune-examples nil)))) ;; (local (defthm 4vec-mask?-of-zero-ext-when-logtail-0-2 ;; (implies (and (equal 0 (logtail (2vec->val w) (sparseint-val (4vmask-fix mask)))) ;; (2vec-p w) (<= 0 (2vec->val w))) ;; (equal (4vec-mask? mask a (4vec-zero-ext w c)) ;; (4vec-mask? mask a c))) ;; :hints(("Goal" :in-theory (enable 4vec-mask? 4vec-bit? 3vec-bit? 4vec-zero-ext)) ;; (logbitp-reasoning :prune-examples nil)))) (local (defthm 4veclist-mask?-of-conses (equal (4veclist-mask? (cons c1 c2) (cons t1 t2) (cons f1 f2)) (cons (4vec-mask? c1 t1 f1) (4veclist-mask? c2 t2 f2))) :hints(("Goal" :in-theory (enable 4veclist-mask?))))) (local (progn (defcong 4vmask-equal equal (4vec-mask? mask a b) 1 :hints(("Goal" :in-theory (enable 4vec-mask?)))) (defthm sparseint-concatenate-self-under-4vmask-equal (4vmask-equal (sparseint-concatenate width (sparseint-concatenate width a b) c) (sparseint-concatenate width a c)) :hints(("Goal" :in-theory (enable bitops::logapp-right-assoc)))) (defcong sparseint-equal 4vmask-equal (sparseint-concatenate width a b) 2) (defcong sparseint-equal 4vmask-equal (sparseint-concatenate width a b) 3) (defthm sparseint-equal-rightshift-0 (sparseint-equal (sparseint-rightshift 0 x) x)))) (local (defthm logand-ash-neg1-equal-0 (implies (natp n) (equal (equal 0 (logand (ash -1 n) x)) (equal 0 (logtail n x)))) :hints ((logbitp-reasoning :prune-examples nil)))) (local (defthm loghead-when-width-zp (implies (zp width) (equal (loghead width x) 0)))) (local (defthm 4vec-mask-of-4vec-mask?-when-subsumes (implies (4vmask-subsumes m1 m2) (equal (4vec-mask m2 (4vec-mask? m1 b c)) (4vec-mask m2 b))) :hints(("Goal" :in-theory (enable 4vec-mask? 4vec-mask 4vec-bit? 3vec-bit? 4vmask-subsumes)) (logbitp-reasoning)))) ;; (local (defthm 4vec-zero-ext-to-concat ;; (equal (4vec-zero-ext w x) ;; (4vec-concat w x 0)))) ;; (local (in-theory (disable 4vec-concat-0))) (std::defret-mutual svex->a4vec-correct (defret svex->a4vec-correct (implies (svex-mask-alist-complete masks) (equal (a4vec-eval res aigenv) (4vec-mask (svex-mask-lookup x masks) (svex-eval x (svex-a4vec-env-eval env aigenv))))) :hints ('(:expand (<call> (:free (env) (svex-eval x env))))) :fn svex->a4vec) (defret svexlist->a4vec-correct (implies (svex-mask-alist-complete masks) (equal (a4veclist-eval res aigenv) (4veclist-mask (svex-argmasks-lookup x masks) (svexlist-eval x (svex-a4vec-env-eval env aigenv))))) :hints ('(:expand (<call> (:free (env) (svexlist-eval x env)) (a4veclist-eval nil aigenv) (svex-argmasks-lookup x masks) (:free (a b) (a4veclist-eval (cons a b) aigenv))) :in-theory (enable 4veclist-mask))) :fn svexlist->a4vec) (defret svex-concat->a4vec-correct (implies (svex-mask-alist-complete masks) (4vec-mask-equiv (a4vec-eval (a4vec upper lower) aigenv) (svex-eval x (svex-a4vec-env-eval env aigenv)) (svex-mask-lookup x masks))) :hints ((acl2::just-expand ((:free (x) (hide x))) :last-only t :lambdasp t) '(:expand (<call>) :in-theory (e/d (svex-const-concat-args-correct-rw 4vec-concat-of-4vec)))) :fn svex-concat->a4vec) (defret svex-concat->a4vec-lower-correct :pre-bind ((lower-acc nil) (upper-acc nil)) (implies (svex-mask-alist-complete masks) (let ((ans (a4vec-eval (a4vec upper lower) aigenv))) (equal ans (4vec-zero-ext (2vec (nfix width)) (4vec-mask? (svex-mask-lookup x masks) (svex-eval x (svex-a4vec-env-eval env aigenv)) (hide ans)))))) :hints ((acl2::just-expand ((:free (x) (hide x))) :last-only t :lambdasp t) '(:expand ((svex-concat->a4vec-lower x width nil nil env masks)) :in-theory (e/d (svex-const-concat-args-correct-rw 4vec-concat-of-4vec 4vec-zero-ext-of-4vec 4vec-zero-ext-of-4vec/0 4vec-of-aig-list->s-of-upper/lower ;; 4vec-mask-over-4vec-concat ;; 4vec-mask-over-4vec-zero-ext ) (BITOPS::LOGAPP-OF-I-0 a4vec-eval-of-var))) (and stable-under-simplificationp '(:in-theory (e/d (equal-of-4vec-concat2 4vec-mask-of-4vec-concat-under-mask svex-const-concat-args-correct-rw 4vec-concat-of-4vec 4vec-zero-ext-of-4vec 4vec-zero-ext-of-4vec/0 4vec-of-aig-list->s-of-upper/lower) (a4vec-eval-of-var)) :do-not-induct t))) :fn svex-concat->a4vec-lower) ) (std::defret-mutual svexlist->a4vec-true-listp (defret svexlist->a4vec-true-listp (true-listp res) :hints ('(:expand (<call>))) :fn svexlist->a4vec) :skip-others t) (std::defret-mutual len-of-svexlist->a4vec (defret len-of-svexlist->a4vec (equal (len res) (len x)) :hints ('(:expand (<call>))) :fn svexlist->a4vec) :skip-others t) (deffixequiv-mutual svex->a4vec)) (define svex->a4vec-memotable-correctp ((memo svex-aig-memotable-p) (env svex-a4vec-env-p) (masks svex-mask-alist-p)) (if (atom memo) t (and (or (not (mbt (consp (car memo)))) (equal (svex->a4vec (caar memo) env masks) (a4vec-fix (cdar memo)))) (svex->a4vec-memotable-correctp (cdr memo) env masks))) /// (defthm svex->a4vec-memotable-correctp-implies-lookup (implies (and (svex->a4vec-memotable-correctp memo env masks) (hons-assoc-equal x memo)) (a4vec-equiv (cdr (hons-assoc-equal x memo)) (svex->a4vec x env masks)))) (defthm svex->a4vec-memotable-correctp-implies-lookup-fix (implies (and (svex->a4vec-memotable-correctp memo env masks) (hons-assoc-equal x (svex-aig-memotable-fix memo))) (equal (cdr (hons-assoc-equal x (svex-aig-memotable-fix memo))) (svex->a4vec x env masks))) :hints(("Goal" :in-theory (enable svex-aig-memotable-fix)))) (defthm svex->a4vec-memotable-correctp-of-cons (implies (and (svex->a4vec-memotable-correctp memo env masks) (a4vec-equiv val (svex->a4vec x env masks))) (svex->a4vec-memotable-correctp (cons (cons x val) memo) env masks))) (defthm svex->a4vec-memotable-correctp-of-nil (svex->a4vec-memotable-correctp nil env masks)) (local (in-theory (enable svex-aig-memotable-fix)))) (defines svex->a4vec-memo ;; Self-memoized version of svex-eval, for GL :verify-guards nil :ruler-extenders :all (define svex->a4vec-memo ((x svex-p) (env svex-a4vec-env-p) (masks svex-mask-alist-p) (memo svex-aig-memotable-p)) :returns (mv (res a4vec-p) (memo1 svex-aig-memotable-p)) :measure (two-nats-measure (svex-count x) 1) (b* ((memo (svex-aig-memotable-fix memo)) (env (svex-a4vec-env-fix env))) (svex-case x :quote (b* ((mask (svex-mask-lookup x masks))) (mv (4vec->a4vec (4vec-mask mask x.val)) memo)) :var (mv (let ((look (hons-get x.name env)) (mask (svex-mask-lookup x masks))) (a4vec-mask mask (if look (cdr look) (a4vec-x)))) memo) :call (b* ((x (svex-fix x)) (look (hons-get x memo)) ((when look) (mv (cdr look) memo)) ((mv res memo) (b* (((when (svex-is-const-concat x)) (b* (((mv upper lower memo) (svex-concat->a4vec-memo x env masks memo)) (mask (svex-mask-lookup x masks))) (mv (a4vec-mask mask (a4vec upper lower)) memo))) ((mv args memo) (svexlist->a4vec-memo x.args env masks memo)) (mask (svex-mask-lookup x masks)) (res (svex-apply-aig x.fn args x.args mask))) (mv res memo))) (memo (hons-acons x res memo))) (mv res memo))))) (define svexlist->a4vec-memo ((x svexlist-p) (env svex-a4vec-env-p) (masks svex-mask-alist-p) (memo svex-aig-memotable-p)) :returns (mv (res a4veclist-p) (memo1 svex-aig-memotable-p)) :measure (two-nats-measure (svexlist-count x) 0) (b* (((when (atom x)) (mv nil (svex-aig-memotable-fix memo))) ((mv first memo) (svex->a4vec-memo (car x) env masks memo)) ((mv rest memo) (svexlist->a4vec-memo (cdr x) env masks memo))) (mv (cons first rest) memo))) (define svex-concat->a4vec-memo ((x svex-p) (env svex-a4vec-env-p) (masks svex-mask-alist-p) (memo svex-aig-memotable-p)) :returns (mv (upper true-listp) (lower true-listp) (memo1 svex-aig-memotable-p)) :measure (two-nats-measure (svex-count x) (if (svex-is-const-concat x) 0 2)) (b* (((unless (svex-is-const-concat x)) (b* (((mv res memo) (svex->a4vec-memo x env masks memo))) (mv (a4vec->upper res) (a4vec->lower res) memo))) ((mv width lsbs msbs) (svex-const-concat-args x)) ((unless (and (2vec-p width) (natp (2vec->val width)))) (mv (a4vec->upper (a4vec-x)) (a4vec->lower (a4vec-x)) (svex-aig-memotable-fix memo))) (width (2vec->val width)) (mask (svex-mask-lookup x masks)) ((unless (sparseint-test-bitand (sparseint-concatenate width 0 -1) mask)) (svex-concat->a4vec-memo lsbs env masks memo)) ((mv upper2 lower2 memo) (svex-concat->a4vec-memo msbs env masks memo))) (svex-concat->a4vec-memo-lower lsbs width upper2 lower2 env masks memo))) (define svex-concat->a4vec-memo-lower ((x svex-p) (width natp) (upper-acc true-listp) (lower-acc true-listp) (env svex-a4vec-env-p) (masks svex-mask-alist-p) (memo svex-aig-memotable-p)) :returns (mv (upper true-listp) (lower true-listp) (memo1 svex-aig-memotable-p)) :measure (two-nats-measure (svex-count x) (if (svex-is-const-concat x) 0 2)) (b* ((upper-acc (llist-fix upper-acc)) (lower-acc (llist-fix lower-acc)) (memo (svex-aig-memotable-fix memo)) ((When (zp width)) (mv upper-acc lower-acc memo)) ((unless (svex-is-const-concat x)) (b* (((mv res memo) (svex->a4vec-memo x env masks memo))) (mv (aig-logapp-nss width (a4vec->upper res) upper-acc) (aig-logapp-nss width (a4vec->lower res) lower-acc) memo))) ((mv sub-width lsbs msbs) (svex-const-concat-args x)) ((unless (and (2vec-p sub-width) (natp (2vec->val sub-width)))) (mv (aig-logapp-nss width (a4vec->upper (a4vec-x)) upper-acc) (aig-logapp-nss width (a4vec->lower (a4vec-x)) lower-acc) (svex-aig-memotable-fix memo))) (sub-width (2vec->val sub-width)) (lsbs-width (min width sub-width)) (msbs-width (- width lsbs-width)) ((mv upper-acc lower-acc memo) (svex-concat->a4vec-memo-lower msbs msbs-width upper-acc lower-acc env masks memo))) (svex-concat->a4vec-memo-lower lsbs lsbs-width upper-acc lower-acc env masks memo))) /// (verify-guards svex->a4vec-memo :guard-debug t) (local (in-theory (disable svex-concat->a4vec-lower-acc-elim))) (std::defret-mutual svex->a4vec-memo-correct (defret svex->a4vec-memo-correct (implies (svex->a4vec-memotable-correctp memo env masks) (and (equal res (svex->a4vec x env masks)) (svex->a4vec-memotable-correctp memo1 env masks))) :hints ('(:expand (<call> (svex->a4vec x env masks)))) :fn svex->a4vec-memo) (defret svexlist->a4vec-memo-correct (implies (svex->a4vec-memotable-correctp memo env masks) (and (equal res (svexlist->a4vec x env masks)) (svex->a4vec-memotable-correctp memo1 env masks))) :hints ('(:expand (<call> (svexlist->a4vec x env masks)))) :fn svexlist->a4vec-memo) (defret svex-concat->a4vec-memo-correct (implies (svex->a4vec-memotable-correctp memo env masks) (b* (((mv upper-spec lower-spec) (svex-concat->a4vec x env masks))) (and (equal upper upper-spec) (equal lower lower-spec) (svex->a4vec-memotable-correctp memo1 env masks)))) :hints ('(:expand (<call> (svex-concat->a4vec x env masks)))) :fn svex-concat->a4vec-memo) (defret svex-concat->a4vec-memo-lower-correct (implies (svex->a4vec-memotable-correctp memo env masks) (b* (((mv upper-spec lower-spec) (svex-concat->a4vec-lower x width upper-acc lower-acc env masks))) (and (equal upper upper-spec) (equal lower lower-spec) (svex->a4vec-memotable-correctp memo1 env masks)))) :hints ('(:expand ((:free (width) <call>) (:free (width) (svex-concat->a4vec-lower x width upper-acc lower-acc env masks))))) :fn svex-concat->a4vec-memo-lower)) (deffixequiv-mutual svex->a4vec-memo)) (define svexlist->a4vec-nrev ((x svexlist-p) (env svex-a4vec-env-p) (masks svex-mask-alist-p) (memo svex-aig-memotable-p) (acl2::nrev)) :returns (mv (new-nrev) (memo1 svex-aig-memotable-p)) (if (atom x) (b* ((acl2::nrev (acl2::nrev-fix acl2::nrev))) (mv acl2::nrev (svex-aig-memotable-fix memo))) (b* (((mv first memo) (svex->a4vec-memo (car x) env masks memo)) (acl2::nrev (acl2::nrev-push first acl2::nrev))) (svexlist->a4vec-nrev (cdr x) env masks memo acl2::nrev))) /// (defret svexlist->a4vec-nrev-removal (b* (((mv out-spec memo1-spec) (svexlist->a4vec-memo x env masks memo))) (and (equal new-nrev (append acl2::nrev out-spec)) (equal memo1 memo1-spec))) :hints(("Goal" :induct t :expand ((svexlist->a4vec-memo x env masks memo)))))) (define svexlist->a4vec-top ((x svexlist-p) (env svex-a4vec-env-p) (masks svex-mask-alist-p)) ;; note: env must be fast ;; :prepwork ((local (defthm svexlist->a4vec-decomp ;; (equal (list (mv-nth 0 (svexlist->a4vec x env masks memo)) ;; (mv-nth 1 (svexlist->a4vec x env masks memo))) ;; (svexlist->a4vec x env masks memo)) ;; :hints (("goal" :expand ((svexlist->a4vec x env masks memo))))))) :enabled t (mbe :logic (svexlist->a4vec x env masks) :exec (b* (((mv res memo) (with-local-stobj acl2::nrev (mv-let (res memo acl2::nrev) (b* (((mv acl2::nrev memo) (svexlist->a4vec-nrev x env masks nil acl2::nrev)) ((mv res acl2::nrev) (acl2::nrev-finish acl2::nrev))) (mv res memo acl2::nrev)) (mv res memo))))) (fast-alist-free memo) res))) ;; There are a few possible approaches to generating the a4vec-env to use in ;; building AIGs. Basically, we're going to generate a pair of Boolean ;; variables for each bit that matters (mask-wise) in x; the masks for the ;; variables of x must be finite so that we can determine which bits matter. ;; (The don't-care bits will be assigned X.) ;; But there are still a few options: ;; 1. Always assign AIG variables to every care bit of every variable. This ;; has the advantage that the input and output to svexlist->a4vec is always ;; identical for a given svexlist, so we can memoize, which may improve ;; performance if we run several simulations with the same svex but different ;; environments. But the complete set of variables might be overkill, ;; e.g. svtvs have lots of variables for don't-care inputs and initial ;; states. ;; 2. Assign AIG variables to the care bits of all the variables bound in the ;; environment. This could still allow good memoization as long as the same ;; variables are going to be assigned basically all the time. We can extract ;; and sort the variables so that the order of the bindings doesn't matter. ;; 3. In between 1 and 2: Take a list of variables as an extra argument, ;; ignored in the logic, which should be a superset of the variables in the ;; environment; only generate AIG vars for these variables. This care list ;; could be provided e.g. by the SVTV. This has the advantage over 2 that ;; memoization still works if different subsets of the care variables are ;; used in different runs. ;; The implementations of 1,2,3 would be quite similar and could basically ;; all be based on 3. ;; 4. More extreme than 2, more difficult to implement, and little chance of ;; memoization working: in the symbolic environment provided, we only really ;; need AIG variables for non-constant bits. So ignore masks and just ;; produce an a4vec environment that replicates the constants assigned in env ;; and generates AIG variables for the non-constant bits. This would mean ;; we'd need to get a hold of the symbolic environment, which probably would ;; mean we'd need a symbolic counterpart function, not just an alternate ;; definition. ;; The following implements option 3 above. We provide the svexlist and the ;; list of care vars. The function returns the a4veclist and the a4vec-env. (define nat-bool-listp (x) (if (atom x) (eq x nil) (and (or (natp (car x)) (booleanp (car x))) (nat-bool-listp (cdr x)))) /// (defthm nat-bool-listp-of-aig-sterm (implies (or (booleanp x) (natp x)) (nat-bool-listp (aig-sterm x))) :hints(("Goal" :in-theory (enable gl::bfr-sterm)))) (defthm nat-bool-listp-of-aig-scons (implies (and (or (booleanp x) (natp x)) (nat-bool-listp y)) (nat-bool-listp (aig-scons x y))) :hints(("Goal" :in-theory (enable gl::bfr-scons)))) (defthm nat-bool-listp-of-list-fix (implies (nat-bool-listp x) (nat-bool-listp (list-fix x))))) (define nat-bool-list-nats ((x nat-bool-listp)) :prepwork ((local (in-theory (enable nat-bool-listp)))) (if (atom x) nil (if (booleanp (car x)) (nat-bool-list-nats (cdr x)) (cons (lnfix (car x)) (nat-bool-list-nats (cdr x))))) /// (defthm nat-bool-list-nats-of-list-fix (equal (nat-bool-list-nats (list-fix x)) (nat-bool-list-nats x))) (defthm nat-bool-list-nats-of-aig-sterm (equal (nat-bool-list-nats (aig-sterm x)) (if (booleanp x) nil (list (nfix x)))) :hints(("Goal" :in-theory (enable gl::bfr-sterm)))) (defthm nat-bool-list-nats-of-aig-scons-bool (implies (booleanp x) (equal (nat-bool-list-nats (aig-scons x y)) (nat-bool-list-nats y))) :hints(("Goal" :in-theory (enable gl::bfr-scons)))) (defthm nat-bool-list-nats-of-aig-scons-nat (implies (and (natp x) (not (member x (nat-bool-list-nats y)))) (equal (nat-bool-list-nats (aig-scons x y)) (cons x (nat-bool-list-nats y)))) :hints(("Goal" :in-theory (enable gl::bfr-scons))))) (define nat-bool-list-lower-boundp ((bound natp) (x nat-bool-listp)) :prepwork ((local (in-theory (enable nat-bool-listp)))) (if (atom x) t (and (or (booleanp (car x)) (<= (lnfix bound) (lnfix (car x)))) (nat-bool-list-lower-boundp bound (cdr x)))) /// (defthm nat-bool-list-lower-boundp-of-list-fix (equal (nat-bool-list-lower-boundp bound (list-fix x)) (nat-bool-list-lower-boundp bound x))) (defthm nat-bool-list-nonmember-by-lower-bound (implies (and (nat-bool-list-lower-boundp bound x) (< v (nfix bound)) (nat-bool-listp x)) (not (member v (nat-bool-list-nats x)))) :hints(("Goal" :in-theory (enable nat-bool-list-nats)))) (Defthm nat-bool-list-lower-boundp-lower (implies (and (nat-bool-list-lower-boundp bound x) (<= (nfix n) (nfix bound))) (nat-bool-list-lower-boundp n x)))) (define nat-bool-list-upper-boundp ((bound natp) (x nat-bool-listp)) :prepwork ((local (in-theory (enable nat-bool-listp)))) (if (atom x) t (and (or (booleanp (car x)) (< (lnfix (car x)) (lnfix bound))) (nat-bool-list-upper-boundp bound (cdr x)))) /// (defthm nat-bool-list-upper-boundp-of-list-fix (equal (nat-bool-list-upper-boundp bound (list-fix x)) (nat-bool-list-upper-boundp bound x))) (defthm nat-bool-list-nonmember-by-upper-bound (implies (and (nat-bool-list-upper-boundp bound x) (<= (nfix bound) v) (nat-bool-listp x)) (not (member v (nat-bool-list-nats x)))) :hints(("Goal" :in-theory (enable nat-bool-list-nats)))) (defthm nat-bool-list-no-intersection-by-bounds (implies (and (nat-bool-list-upper-boundp bound0 x0) (nat-bool-list-lower-boundp bound1 x1) (<= (nfix bound0) (nfix bound1)) (nat-bool-listp x0) (nat-bool-listp x1)) (not (intersectp (nat-bool-list-nats x0) (nat-bool-list-nats x1)))) :hints(("Goal" :in-theory (e/d (intersectp-equal nat-bool-listp nat-bool-list-nats) (acl2::intersectp-equal-commute))))) (Defthm nat-bool-list-upper-boundp-higher (implies (and (nat-bool-list-upper-boundp bound x) (<= (nfix bound) (nfix n))) (nat-bool-list-upper-boundp n x)))) (define nat-bool-a4vec-p ((x a4vec-p)) (b* (((a4vec x) x)) (and (nat-bool-listp x.upper) (nat-bool-listp x.lower))) /// (deffixtype nba4vec :pred nat-bool-a4vec-p! :fix a4vec-fix :equiv a4vec-equiv)) (defmacro nat-bool-a4vec-p! (x) `(and (a4vec-p ,x) (nat-bool-a4vec-p ,x))) (define nat-bool-a4vec-vars ((x nat-bool-a4vec-p!)) :prepwork ((local (in-theory (enable nat-bool-a4vec-p)))) (b* (((a4vec x) x)) (append (nat-bool-list-nats x.upper) (nat-bool-list-nats x.lower)))) (define nat-bool-a4vec-lower-boundp ((bound natp) (x nat-bool-a4vec-p!)) :prepwork ((local (in-theory (enable nat-bool-a4vec-p)))) (b* (((a4vec x) x)) (and (nat-bool-list-lower-boundp bound x.upper) (nat-bool-list-lower-boundp bound x.lower))) /// (defthm nat-bool-a4vec-vars-nonmember-by-lower-bound (implies (and (nat-bool-a4vec-lower-boundp bound x) (< v (nfix bound)) (nat-bool-a4vec-p x)) (not (member v (nat-bool-a4vec-vars x)))) :hints(("Goal" :in-theory (enable nat-bool-a4vec-vars nat-bool-a4vec-p nat-bool-list-nonmember-by-lower-bound)))) (Defthm nat-bool-a4vec-lower-boundp-lower (implies (and (nat-bool-a4vec-lower-boundp bound x) (<= (nfix n) (nfix bound))) (nat-bool-a4vec-lower-boundp n x)))) (define nat-bool-a4vec-upper-boundp ((bound natp) (x nat-bool-a4vec-p!)) :prepwork ((local (in-theory (enable nat-bool-a4vec-p)))) (b* (((a4vec x) x)) (and (nat-bool-list-upper-boundp bound x.upper) (nat-bool-list-upper-boundp bound x.lower))) /// (defthm nat-bool-a4vec-vars-nonmember-by-upper-bound (implies (and (nat-bool-a4vec-upper-boundp bound x) (<= (nfix bound) v) (nat-bool-a4vec-p x)) (not (member v (nat-bool-a4vec-vars x)))) :hints(("Goal" :in-theory (enable nat-bool-a4vec-vars nat-bool-a4vec-p nat-bool-list-nonmember-by-upper-bound)))) (defthm nat-bool-a4vec-no-intersection-by-bounds (implies (and (nat-bool-a4vec-upper-boundp bound0 x0) (nat-bool-a4vec-lower-boundp bound1 x1) (<= (nfix bound0) (nfix bound1)) (nat-bool-a4vec-p x0) (nat-bool-a4vec-p x1)) (not (intersectp (nat-bool-a4vec-vars x0) (nat-bool-a4vec-vars x1)))) :hints(("Goal" :in-theory (e/d (intersectp-equal nat-bool-a4vec-p nat-bool-a4vec-vars nat-bool-a4vec-upper-boundp nat-bool-a4vec-lower-boundp) (acl2::intersectp-equal-commute))))) (Defthm nat-bool-a4vec-upper-boundp-higher (implies (and (nat-bool-a4vec-upper-boundp bound x) (<= (nfix bound) (nfix n))) (nat-bool-a4vec-upper-boundp n x)))) (define nat-bool-a4env-p ((x svex-a4vec-env-p)) :prepwork ((local (in-theory (enable svex-a4vec-env-fix)))) (if (atom x) t (and (if (mbt (consp (car x))) (nat-bool-a4vec-p (cdar x)) t) (nat-bool-a4env-p (cdr x)))) /// (deffixtype nba4env :pred nat-bool-a4env-p! :fix svex-a4vec-env-fix :equiv svex-a4vec-env-equiv)) (defmacro nat-bool-a4env-p! (x) `(and (svex-a4vec-env-p ,x) (nat-bool-a4env-p ,x))) (define nat-bool-a4env-vars ((x nat-bool-a4env-p!)) :prepwork ((local (in-theory (enable nat-bool-a4env-p svex-a4vec-env-fix)))) (if (atom x) nil (append (and (mbt (consp (car x))) (nat-bool-a4vec-vars (cdar x))) (nat-bool-a4env-vars (cdr x))))) (define nat-bool-a4env-lower-boundp ((bound natp) (x nat-bool-a4env-p!)) :prepwork ((local (in-theory (enable nat-bool-a4env-p svex-a4vec-env-fix)))) (if (atom x) t (and (if (mbt (consp (car x))) (nat-bool-a4vec-lower-boundp bound (cdar x)) t) (nat-bool-a4env-lower-boundp bound (cdr x)))) /// (defthm nat-bool-a4env-vars-nonmember-by-lower-bound (implies (and (nat-bool-a4env-lower-boundp bound x) (< v (nfix bound)) (nat-bool-a4env-p x)) (not (member v (nat-bool-a4env-vars x)))) :hints(("Goal" :in-theory (enable nat-bool-a4env-vars nat-bool-a4env-p nat-bool-list-nonmember-by-lower-bound)))) (Defthm nat-bool-a4env-lower-boundp-lower (implies (and (nat-bool-a4env-lower-boundp bound x) (<= (nfix n) (nfix bound))) (nat-bool-a4env-lower-boundp n x)))) (define nat-bool-a4env-upper-boundp ((bound natp) (x nat-bool-a4env-p!)) :prepwork ((local (in-theory (enable nat-bool-a4env-p svex-a4vec-env-fix)))) (if (atom x) t (and (if (mbt (consp (car x))) (nat-bool-a4vec-upper-boundp bound (cdar x)) t) (nat-bool-a4env-upper-boundp bound (cdr x)))) /// (defthm nat-bool-a4env-vars-nonmember-by-upper-bound (implies (and (nat-bool-a4env-upper-boundp bound x) (<= (nfix bound) v) (nat-bool-a4env-p x)) (not (member v (nat-bool-a4env-vars x)))) :hints(("Goal" :in-theory (enable nat-bool-a4env-vars nat-bool-a4env-p nat-bool-list-nonmember-by-upper-bound)))) (defthm nat-bool-a4vec/env-no-intersection-by-bounds (implies (and (nat-bool-a4vec-upper-boundp bound0 x0) (nat-bool-a4env-lower-boundp bound1 x1) (<= (nfix bound0) (nfix bound1)) (nat-bool-a4vec-p x0) (nat-bool-a4env-p x1)) (not (intersectp (nat-bool-a4vec-vars x0) (nat-bool-a4env-vars x1)))) :hints(("Goal" :in-theory (e/d (intersectp-equal nat-bool-a4env-p nat-bool-a4env-lower-boundp) (acl2::intersectp-equal-commute)) :expand ((nat-bool-a4env-vars x1)) :induct (nat-bool-a4env-lower-boundp bound1 x1)))) (defthm nat-bool-a4env-no-intersection-by-bounds (implies (and (nat-bool-a4env-upper-boundp bound0 x0) (nat-bool-a4env-lower-boundp bound1 x1) (<= (nfix bound0) (nfix bound1)) (nat-bool-a4env-p x0) (nat-bool-a4env-p x1)) (not (intersectp (nat-bool-a4env-vars x0) (nat-bool-a4env-vars x1)))) :hints(("Goal" :in-theory (e/d (intersectp-equal nat-bool-a4env-p nat-bool-a4env-vars nat-bool-a4env-upper-boundp nat-bool-a4env-lower-boundp) (acl2::intersectp-equal-commute))))) (defthm nat-bool-a4env-a4vec-no-intersection-by-bounds (implies (and (nat-bool-a4env-upper-boundp bound0 x0) (nat-bool-a4vec-lower-boundp bound1 x1) (<= (nfix bound0) (nfix bound1)) (nat-bool-a4env-p x0) (nat-bool-a4vec-p x1)) (not (intersectp (nat-bool-a4env-vars x0) (nat-bool-a4vec-vars x1)))) :hints(("Goal" :in-theory (e/d (intersectp-equal nat-bool-a4env-p nat-bool-a4env-vars nat-bool-a4env-upper-boundp nat-bool-a4env-lower-boundp) (acl2::intersectp-equal-commute))))) (Defthm nat-bool-a4env-upper-boundp-higher (implies (and (nat-bool-a4env-upper-boundp bound x) (<= (nfix bound) (nfix n))) (nat-bool-a4env-upper-boundp n x)))) (local (defthm logcount-of-logand (implies (natp y) (<= (logcount (logand x y)) (logcount y))) :hints(("Goal" :in-theory (e/d* (bitops::logcount** bitops::logand** bitops::ihsext-inductions)))) :rule-classes :linear)) (define sparseint-nfix ((x sparseint-p)) :guard (not (sparseint-< x 0)) :returns (new-x sparseint-p) :inline t (mbe :logic (if (sparseint-< x 0) 0 (sparseint-fix x)) :exec x) /// (defret <fn>-correct (equal (sparseint-val new-x) (nfix (sparseint-val x))))) (define 4vmask-to-a4vec-varcount ((mask 4vmask-p) (boolmask integerp)) :guard (not (sparseint-< mask 0)) :returns (count natp :rule-classes :type-prescription) (b* ((mask (sparseint-nfix (4vmask-fix mask)))) (- (* 2 (sparseint-bitcount mask)) (sparseint-bitcount (sparseint-bitand mask (int-to-sparseint boolmask)))))) (local (defcong sparseint-equal sparseint-equal (sparseint-nfix x) 1)) (local (defthm integer-length-posp (implies (posp x) (posp (integer-length x))) :hints(("Goal" :in-theory (enable* ihsext-recursive-redefs ihsext-inductions))) :rule-classes :type-prescription)) (define 4vmask-to-a4vec-rec ((mask 4vmask-p) (boolmask integerp) (nextvar natp)) :guard (not (sparseint-< mask 0)) :returns (mv (upper nat-bool-listp) (lower nat-bool-listp)) :verify-guards nil :measure (sparseint-length (sparseint-nfix mask)) :hints(("Goal" :in-theory (enable bitops::integer-length** 4vmask-fix))) (b* ((mask (sparseint-nfix (4vmask-fix mask))) (nextvar (lnfix nextvar)) ((when (sparseint-equal mask 0)) (mv (aig-sterm t) (aig-sterm nil))) ((mv ubit0 ubit1 nextvar) (if (eql 1 (sparseint-bit 0 mask)) (if (logbitp 0 boolmask) (mv nextvar nextvar (+ 1 nextvar)) (mv nextvar (1+ nextvar) (+ 2 nextvar))) (mv t nil nextvar))) ((mv rest-upper rest-lower) (4vmask-to-a4vec-rec (sparseint-rightshift 1 mask) (logcdr boolmask) nextvar))) (mv (aig-scons ubit0 rest-upper) (aig-scons ubit1 rest-lower))) /// ;; (defthm 4vmask-to-a4vec-rec-nextvar ;; (equal (mv-nth 2 (4vmask-to-a4vec-rec mask nextvar)) ;; (+ (* 2 (logcount (nfix mask))) (nfix nextvar))) ;; :hints(("Goal" :in-theory (enable bitops::logcount**)))) (defret true-listp-of-<fn>-upper (true-listp upper) :rule-classes :type-prescription) (defret true-listp-of-<fn>-lower (true-listp lower) :rule-classes :type-prescription) (verify-guards 4vmask-to-a4vec-rec) (defthm 4vmask-to-a4vec-rec-lower-bounds (and (nat-bool-list-lower-boundp nextvar (mv-nth 0 (4vmask-to-a4vec-rec mask boolmask nextvar))) (nat-bool-list-lower-boundp nextvar (mv-nth 1 (4vmask-to-a4vec-rec mask boolmask nextvar)))) :hints(("Goal" :in-theory (enable nat-bool-list-lower-boundp gl::bfr-scons))) :rule-classes ((:forward-chaining :trigger-terms ((4vmask-to-a4vec-rec mask boolmask nextvar))))) (defthm 4vmask-to-a4vec-rec-upper-bounds (and (nat-bool-list-upper-boundp (+ (nfix nextvar) (4vmask-to-a4vec-varcount mask boolmask)) (mv-nth 0 (4vmask-to-a4vec-rec mask boolmask nextvar))) (nat-bool-list-upper-boundp (+ (nfix nextvar) (4vmask-to-a4vec-varcount mask boolmask)) (mv-nth 1 (4vmask-to-a4vec-rec mask boolmask nextvar)))) :hints(("Goal" :in-theory (enable gl::bfr-scons 4vmask-to-a4vec-varcount bitops::logand** bitops::logbitp** bitops::logcount**) :induct (4vmask-to-a4vec-rec mask boolmask nextvar) :expand ((:free (bound a b) (nat-bool-list-upper-boundp bound (cons a b))) (:free (bound) (nat-bool-list-upper-boundp bound nil)) (:free (x) (logtail 1 x))) :do-not-induct t)) :rule-classes ((:forward-chaining :trigger-terms ((4vmask-to-a4vec-rec mask boolmask nextvar))))) ;; (defthm 4vmask-to-a4vec-rec-no-duplicate-vars ;; (b* (((mv upper lower) ;; (4vmask-to-a4vec-rec mask boolmask nextvar))) ;; (and (no-duplicatesp (nat-bool-list-nats upper)) ;; (no-duplicatesp (nat-bool-list-nats lower)) ;; (not (intersectp (nat-bool-list-nats upper) ;; (nat-bool-list-nats lower))))) ;; :hints(("Goal" :in-theory (enable nat-bool-list-nats ;; intersectp-equal)))) (defthm member-4vmask-to-a4vec-rec-vars ;; not a good rewrite rule but useful for the next phase (iff (member v (append (nat-bool-list-nats (mv-nth 0 (4vmask-to-a4vec-rec mask boolmask nextvar))) (nat-bool-list-nats (mv-nth 1 (4vmask-to-a4vec-rec mask boolmask nextvar))))) (and (natp v) (<= (nfix nextvar) v) (< v (+ (nfix nextvar) (4vmask-to-a4vec-varcount mask boolmask))))) :hints(("Goal" :in-theory (enable nat-bool-list-nats 4vmask-to-a4vec-varcount bitops::logand** bitops::logcount** bitops::logbitp**) :induct (4vmask-to-a4vec-rec mask boolmask nextvar)) (and stable-under-simplificationp '(:expand ((logcount (sparseint-val (4vmask-fix mask))) (:free (x) (logtail 1 x)))))) :rule-classes nil)) ;; (defthm eval-4vmask-to-a4vec-rec-cons-greater ;; (b* (((mv ?err upper lower nextvar1) ;; (4vmask-to-a4vec-rec mask nextvar))) ;; (implies (<= nextvar1 var) ;; (and (equal (aig-list->s upper (cons (cons var val) env)) ;; (aig-list->s upper env)) ;; (equal (aig-list->s lower (cons (cons var val) env)) ;; (aig-list->s lower env)))))) ;; (defthm eval-4vmask-to-a4vec-rec-cons-lesser ;; (b* (((mv ?err upper lower ?nextvar1) ;; (4vmask-to-a4vec-rec mask nextvar))) ;; (implies (< var (nfix nextvar)) ;; (and (equal (aig-list->s upper (cons (cons var val) env)) ;; (aig-list->s upper env)) ;; (equal (aig-list->s lower (cons (cons var val) env)) ;; (aig-list->s lower env))))))) (define 4vmask-to-a4vec-rec-env ((mask 4vmask-p) (boolmask integerp) (upper integerp) (lower integerp) (nextvar natp)) :guard (not (sparseint-< mask 0)) :returns (env "environment for the resulting 4vmask") :measure (sparseint-length (sparseint-nfix (4vmask-fix mask))) :hints(("Goal" :in-theory (enable bitops::integer-length** 4vmask-fix))) (b* ((mask (sparseint-nfix (4vmask-fix mask))) (nextvar (lnfix nextvar)) ((when (sparseint-equal mask 0)) nil) (rest-env (4vmask-to-a4vec-rec-env (sparseint-rightshift 1 mask) (logcdr boolmask) (logcdr upper) (logcdr lower) (if (eql 1 (sparseint-bit 0 mask)) (if (logbitp 0 boolmask) (+ 1 nextvar) (+ 2 nextvar)) nextvar)))) (if (eql 1 (sparseint-bit 0 mask)) (cons (cons nextvar (logbitp 0 upper)) (if (logbitp 0 boolmask) rest-env (cons (cons (1+ nextvar) (logbitp 0 lower)) rest-env))) rest-env)) /// (defthm key-exists-in-4vmask-to-a4vec-rec-env (iff (hons-assoc-equal v (4vmask-to-a4vec-rec-env mask boolmask upper lower nextvar)) (and (natp v) (<= (nfix nextvar) v) (< v (+ (nfix nextvar) (4vmask-to-a4vec-varcount mask boolmask))))) :hints(("Goal" :in-theory (enable bitops::logcount** bitops::logbitp** 4vmask-to-a4vec-varcount bitops::logand**) :do-not-induct t :induct (4vmask-to-a4vec-rec-env mask boolmask upper lower nextvar)) (and stable-under-simplificationp '(:expand ((:free (x) (logtail 1 x)) (logcount (sparseint-val (4vmask-fix mask)))))))) (defthm nat-bool-aig-list->s-of-cons-nonmember (implies (and (nat-bool-listp x) (not (member n (nat-bool-list-nats x)))) (equal (aig-list->s x (cons (cons n v) env)) (aig-list->s x env))) :hints(("Goal" :in-theory (enable aig-list->s nat-bool-listp nat-bool-list-nats gl::scdr gl::s-endp) :induct (aig-list->s x env) :expand ((:Free (env) (aig-list->s x env)))))) (local (defthm equal-nfix-plus-1 (not (equal x (+ 1 (nfix x)))) :hints(("Goal" :in-theory (enable nfix))))) (defthm eval-4vmask-to-a4vec-rec-with-env (b* (((mv uppera lowera) (4vmask-to-a4vec-rec mask boolmask nextvar)) (env (4vmask-to-a4vec-rec-env mask boolmask upper lower nextvar))) (and (equal (logand (nfix (sparseint-val (4vmask-fix mask))) (aig-list->s uppera env)) (logand (nfix (sparseint-val (4vmask-fix mask))) upper)) (implies (eql 0 (logand boolmask (logxor upper lower))) (equal (logand (nfix (sparseint-val (4vmask-fix mask))) (aig-list->s lowera env)) (logand (nfix (sparseint-val (4vmask-fix mask))) lower))))) :hints(("Goal" :in-theory (enable 4vmask-to-a4vec-rec bitops::logand** bitops::logxor** bitops::logbitp** 4vmask-fix) :induct (4vmask-to-a4vec-rec-env mask boolmask upper lower nextvar) :expand ((:free (x) (logtail 1 x)))) (and stable-under-simplificationp '(:in-theory (enable bitops::b-xor))) (and stable-under-simplificationp '(:in-theory (enable nfix)))))) (define 4vec-boolmaskp ((x 4vec-p) (mask integerp)) (b* (((4vec x) x)) (eql 0 (logand mask (logxor x.upper x.lower))))) (define 4vmask-to-a4vec ((mask 4vmask-p) (boolmask integerp) (nextvar natp)) :guard (not (sparseint-< mask 0)) :returns (res nat-bool-a4vec-p! :hints(("Goal" :in-theory (enable nat-bool-a4vec-p)))) :prepwork ((local (defthm true-listp-when-nat-bool-listp (implies (nat-bool-listp x) (true-listp x)) :hints(("Goal" :in-theory (enable nat-bool-listp)))))) (b* (((mv upper lower) (4vmask-to-a4vec-rec mask boolmask nextvar))) (a4vec upper lower)) /// ;; (defthm 4vmask-to-a4vec-nextvar ;; (equal (mv-nth 1 (4vmask-to-a4vec mask nextvar)) ;; (+ (* 2 (logcount (nfix mask))) (nfix nextvar)))) (defthm member-vars-of-4vmask-to-a4vec (iff (member v (nat-bool-a4vec-vars (4vmask-to-a4vec mask boolmask nextvar))) (and (natp v) (<= (nfix nextvar) v) (< v (+ (nfix nextvar) (4vmask-to-a4vec-varcount mask boolmask))))) :hints (("goal" :use member-4vmask-to-a4vec-rec-vars :in-theory (enable nat-bool-a4vec-vars)))) (defthm 4vmask-to-a4vec-lower-bounds (nat-bool-a4vec-lower-boundp nextvar (4vmask-to-a4vec mask boolmask nextvar)) :hints(("Goal" :in-theory (enable nat-bool-a4vec-lower-boundp))) :rule-classes ((:forward-chaining :trigger-terms ((4vmask-to-a4vec mask boolmask nextvar))))) (defthm 4vmask-to-a4vec-upper-bounds (nat-bool-a4vec-upper-boundp (+ (nfix nextvar) (4vmask-to-a4vec-varcount mask boolmask)) (4vmask-to-a4vec mask boolmask nextvar)) :hints(("Goal" :in-theory (enable nat-bool-a4vec-upper-boundp))) :rule-classes ((:forward-chaining :trigger-terms ((4vmask-to-a4vec mask boolmask nextvar)))))) (define 4vmask-to-a4vec-env ((mask 4vmask-p) (boolmask integerp) (val 4vec-p) (nextvar natp)) :guard (not (sparseint-< mask 0)) :returns env :prepwork ((local (defthm true-listp-when-nat-bool-listp (implies (nat-bool-listp x) (true-listp x)) :hints(("Goal" :in-theory (enable nat-bool-listp)))))) (4vmask-to-a4vec-rec-env mask boolmask (4vec->upper val) (4vec->lower val) nextvar) /// (defthm key-exists-in-4vmask-to-a4vec-env (iff (hons-assoc-equal v (4vmask-to-a4vec-env mask boolmask val nextvar)) (and (natp v) (<= (nfix nextvar) v) (< v (+ (nfix nextvar) (4vmask-to-a4vec-varcount mask boolmask)))))) (local (defthm mask-lemma (IMPLIES (AND (EQUAL (LOGAND mask a) (LOGAND b mask))) (EQUAL (LOGIOR b (lognot mask)) (LOGIOR (LOGNOT mask) a))) :hints ((bitops::logbitp-reasoning)))) (defthm eval-4vmask-to-a4vec-with-env (b* ((vala (4vmask-to-a4vec mask boolmask nextvar)) (env (4vmask-to-a4vec-env mask boolmask val nextvar))) (implies (and (4vec-boolmaskp val boolmask) (4vmask-p mask) (natp (sparseint-val mask))) (equal (4vec-mask mask (a4vec-eval vala env)) (4vec-mask mask val)))) :hints(("Goal" :in-theory (e/d (4vmask-to-a4vec 4vec-boolmaskp 4vmask-fix 4vec-mask a4vec-eval) (eval-4vmask-to-a4vec-rec-with-env)) :use ((:instance eval-4vmask-to-a4vec-rec-with-env (upper (4vec->upper val)) (lower (4vec->lower val))))) ;; (bitops::logbitp-reasoning) ;; (and stable-under-simplificationp ;; '(:bdd (:vars nil))) )) ;; (defthm eval-4vmask-to-a4vec-with-env-mask-natp ;; (b* ((vala (4vmask-to-a4vec mask boolmask nextvar)) ;; (env (4vmask-to-a4vec-env mask boolmask val nextvar))) ;; (implies (and (4vec-boolmaskp val boolmask)) ;; (equal (4vec-mask mask (a4vec-eval vala env)) ;; (4vec-mask mask val)))) ;; :hints (("Goal" :use eval-4vmask-to-a4vec-with-env ;; :in-theory (disable eval-4vmask-to-a4vec-with-env)))) ) (local (in-theory (disable PICK-A-POINT-SUBSET-STRATEGY))) (define svex-maskbits-for-vars ((vars svarlist-p) (masks svex-mask-alist-p) (boolmasks svar-boolmasks-p)) :prepwork ((local (in-theory (enable svarlist-p svarlist-fix)))) :returns (incr natp :rule-classes :type-prescription) (b* (((when (atom vars)) 0) (mask (svex-mask-lookup (svex-var (car vars)) masks)) (boolmask (svar-boolmasks-lookup (car vars) boolmasks)) ((when (sparseint-< mask 0)) 0)) (+ (4vmask-to-a4vec-varcount mask boolmask) (svex-maskbits-for-vars (cdr vars) masks boolmasks)))) (define svex-maskbits-ok ((vars svarlist-p) (masks svex-mask-alist-p)) :prepwork ((local (in-theory (enable svarlist-p svarlist-fix)))) (b* (((when (atom vars)) t) (mask (svex-mask-lookup (svex-var (car vars)) masks)) ((when (sparseint-< mask 0)) nil)) (svex-maskbits-ok (cdr vars) masks))) (define svex-varmasks->a4env-rec ((vars svarlist-p) (masks svex-mask-alist-p) (boolmasks svar-boolmasks-p) (nextvar natp) (acc nat-bool-a4env-p!)) :prepwork ((local (in-theory (enable svarlist-p svarlist-fix nat-bool-a4env-p svex-mask-alist-fix svex-a4vec-env-fix)))) :returns (mv (err "some mask was negative" (iff err (not (svex-maskbits-ok vars masks))) :hints(("Goal" :in-theory (enable svex-maskbits-ok)))) (a4env nat-bool-a4env-p! :hyp (nat-bool-a4env-p! acc)) (nextvar1 (equal nextvar1 (+ (nfix nextvar) (svex-maskbits-for-vars vars masks boolmasks))) :hints(("Goal" :in-theory (enable svex-maskbits-for-vars))))) (b* ((acc (svex-a4vec-env-fix acc)) ((when (atom vars)) (mv nil acc (lnfix nextvar))) (mask (svex-mask-lookup (svex-var (car vars)) masks)) ((when (sparseint-< mask 0)) (mv (msg "Negative mask: ~x0~%" (svar-fix (car vars))) acc (lnfix nextvar))) (boolmask (svar-boolmasks-lookup (car vars) boolmasks)) (a4vec (4vmask-to-a4vec mask boolmask nextvar)) (nextvar (+ (lnfix nextvar) (4vmask-to-a4vec-varcount mask boolmask)))) (svex-varmasks->a4env-rec (cdr vars) masks boolmasks nextvar (cons (cons (svar-fix (car vars)) a4vec) acc))) /// (local (defun-sk svex-varmasks->a4env-rec-accumulator-elim-correct (vars masks boolmasks nextvar) (forall acc (implies (syntaxp (not (equal acc ''nil))) (b* (((mv err1 a4env1 nextvar1) (svex-varmasks->a4env-rec vars masks boolmasks nextvar acc)) ((mv err2 a4env2 nextvar2) (svex-varmasks->a4env-rec vars masks boolmasks nextvar nil))) (and (equal err1 err2) (equal a4env1 (append a4env2 (svex-a4vec-env-fix acc))) (equal nextvar1 nextvar2))))) :rewrite :direct)) (local (in-theory (disable svex-varmasks->a4env-rec-accumulator-elim-correct))) (local (defthmd svex-varmasks->a4env-rec-accumulator-elim-lemma (svex-varmasks->a4env-rec-accumulator-elim-correct vars masks boolmasks nextvar) :hints (("goal" :induct (svex-varmasks->a4env-rec vars masks boolmasks nextvar acc)) (and stable-under-simplificationp `(:expand (,(car (last clause)) (:free (acc) (svex-varmasks->a4env-rec vars masks boolmasks nextvar acc)))))))) (defthmd svex-varmasks->a4env-rec-accumulator-elim (implies (syntaxp (not (equal acc ''nil))) (b* (((mv err1 a4env1 nextvar1) (svex-varmasks->a4env-rec vars masks boolmasks nextvar acc)) ((mv err2 a4env2 nextvar2) (svex-varmasks->a4env-rec vars masks boolmasks nextvar nil))) (and (equal err1 err2) (equal a4env1 (append a4env2 (svex-a4vec-env-fix acc))) (equal nextvar1 nextvar2)))) :hints (("goal" :use svex-varmasks->a4env-rec-accumulator-elim-lemma))) (defthm member-vars-of-svex-varmasks->a4env-rec (iff (member v (nat-bool-a4env-vars (mv-nth 1 (svex-varmasks->a4env-rec vars masks boolmasks nextvar acc)))) (or (member v (nat-bool-a4env-vars acc)) (and (natp v) (<= (nfix nextvar) v) (< v (+ (nfix nextvar) (svex-maskbits-for-vars vars masks boolmasks)))))) :hints(("Goal" :in-theory (enable svex-maskbits-for-vars nat-bool-a4env-vars)))) (defthm svex-varmasks->a4env-rec-lower-bounds (implies (and (nat-bool-a4env-lower-boundp bound acc) (<= (nfix bound) (nfix nextvar))) (nat-bool-a4env-lower-boundp bound (mv-nth 1 (svex-varmasks->a4env-rec vars masks boolmasks nextvar acc)))) :hints(("Goal" :in-theory (enable nat-bool-a4env-lower-boundp)))) (defthm svex-varmasks->a4env-rec-upper-bounds (implies (and (nat-bool-a4env-upper-boundp bound acc) (<= (+ (nfix nextvar) (svex-maskbits-for-vars vars masks boolmasks)) (nfix bound))) (nat-bool-a4env-upper-boundp bound (mv-nth 1 (svex-varmasks->a4env-rec vars masks boolmasks nextvar acc)))) :hints(("Goal" :in-theory (enable nat-bool-a4env-upper-boundp svex-maskbits-for-vars)))) (defret key-exists-in-svex-varmasks->a4env-rec (implies (not err) (iff (hons-assoc-equal v a4env) (or (member v (svarlist-fix vars)) (hons-assoc-equal v (svex-a4vec-env-fix acc)))))) (defret alist-keys-of-svex-varmasks->a4env-rec (implies (not err) (equal (alist-keys a4env) (append (rev (svarlist-fix vars)) (alist-keys (svex-a4vec-env-fix acc))))) :hints(("Goal" :in-theory (enable svex-maskbits-ok))))) ;; (defsection svex-envs-masks-partly-equiv ;; (defquant svex-envs-masks-partly-equiv (vars masks env1 env2) ;; (forall v ;; (implies (not (member (svar-fix v) (svarlist-fix vars))) ;; (equal (4vec-mask (svex-mask-lookup (svex-var v) masks) ;; (svex-env-lookup v env1)) ;; (4vec-mask (svex-mask-lookup (svex-var v) masks) ;; (svex-env-lookup v env2))))) ;; :rewrite :direct) ;; (defexample svex-envs-masks-partly-equiv-example ;; :pattern (equal (4vec-mask (svex-mask-lookup (svex-var v) masks) ;; val1) ;; (4vec-mask mask2 val2)) ;; :templates (v) ;; :instance-rulename svex-envs-masks-partly-equiv-instancing)) (defsection svex-envs-mask-equiv-on-vars (defquant svex-envs-mask-equiv-on-vars (vars masks env1 env2) (forall v (implies (member (svar-fix v) (svarlist-fix vars)) (equal (4vec-mask (svex-mask-lookup (svex-var v) masks) (svex-env-lookup v env1)) (4vec-mask (svex-mask-lookup (svex-var v) masks) (svex-env-lookup v env2))))) :rewrite :direct) (defexample svex-envs-mask-equiv-on-vars-example :pattern (equal (4vec-mask (svex-mask-lookup (svex-var v) masks) val1) (4vec-mask mask2 val2)) :templates (v) :instance-rulename svex-envs-mask-equiv-on-vars-instancing) (local (defexample svex-envs-mask-equiv-on-vars-mask-look-example :pattern (svex-mask-lookup (svex-var var) masks) :templates (var) :instance-rulename svex-envs-mask-equiv-on-vars-instancing)) (local (defexample svex-envs-mask-equiv-on-vars-env-look-example :pattern (svex-env-lookup var env) :templates (var) :instance-rulename svex-envs-mask-equiv-on-vars-instancing)) (local (defexample svex-argmasks-okp-example :pattern (equal (4vec-mask mask (svex-apply fn (svexlist-eval args env1))) (4vec-mask mask (svex-apply fn (svexlist-eval args env2)))) :templates (env1 (svexlist-eval args env2)) :instance-rulename svex-argmasks-okp-instancing)) (local (acl2::def-witness-ruleset svex-mask-alist-reasoning '(svex-mask-alist-complete-witnessing svex-mask-alist-complete-instancing svex-mask-alist-complete-example svex-mask-alist-partly-complete-witnessing svex-mask-alist-partly-complete-instancing svex-mask-alist-partly-complete-example))) (local (acl2::def-witness-ruleset svex-env-reasoning '(svex-envs-mask-equiv-on-vars-instancing svex-envs-mask-equiv-on-vars-witnessing svex-envs-mask-equiv-on-vars-mask-look-example svex-envs-mask-equiv-on-vars-env-look-example svex-mask-alist-reasoning SVEX-ARGMASKS-OKP-WITNESSING SVEX-ARGMASKS-OKP-INSTANCING SVEX-ARGMASKS-OKP-EXAMPLE ))) (defthm-svex-eval-flag (defthm svex-eval-of-mask-equiv-on-vars-envs (implies (and (svex-mask-alist-complete masks) (svex-envs-mask-equiv-on-vars vars masks env1 env2) (subsetp-equal (intersection-equal (svex-vars x) (union-equal (alist-keys (svex-env-fix env1)) (alist-keys (svex-env-fix env2)))) (svarlist-fix vars))) (equal (equal (4vec-mask (svex-mask-lookup x masks) (svex-eval x env1)) (4vec-mask (svex-mask-lookup x masks) (svex-eval x env2))) t)) :hints ('(:expand ((:free (env) (svex-eval x env)) (svex-vars x)) :do-not-induct t) (witness :ruleset svex-env-reasoning) (witness :ruleset svex-env-reasoning) (set-reasoning) (and stable-under-simplificationp '(:in-theory (enable svex-env-lookup))) ;; (and stable-under-simplificationp ;; '(:use ((:instance svex-argmasks-okp-necc ;; (mask (svex-mask-lookup x masks)) ;; (argmasks (svex-argmasks-lookup ;; (svex-call->args x) masks)) ;; (env env1) ;; (vals (svexlist-eval (svex-call->args x) env2)))))) ) :flag expr) (defthm svexlist-eval-of-mask-equiv-on-vars-envs (implies (and (svex-mask-alist-complete masks) (svex-envs-mask-equiv-on-vars vars masks env1 env2) (subsetp-equal (intersection-equal (svexlist-vars x) (union-equal (alist-keys (svex-env-fix env1)) (alist-keys (svex-env-fix env2)))) (svarlist-fix vars))) (equal (equal (4veclist-mask (svex-argmasks-lookup x masks) (svexlist-eval x env1)) (4veclist-mask (svex-argmasks-lookup x masks) (svexlist-eval x env2))) t)) :hints ('(:expand ((:free (env) (svexlist-eval x env)) (svexlist-vars x) (svex-argmasks-lookup x masks)))) :flag list)) ) (local (defthm hons-assoc-equal-of-append (equal (hons-assoc-equal k (append a b)) (or (hons-assoc-equal k a) (hons-assoc-equal k b))))) (defthm aig-list->s-of-append-when-first-superset (implies (and (nat-bool-listp x) (subsetp (nat-bool-list-nats x) (alist-keys env))) (equal (aig-list->s x (append env rest)) (aig-list->s x env))) :hints(("Goal" :in-theory (e/d* (aig-list->s nat-bool-listp nat-bool-list-nats gl::scdr gl::s-endp) ((:rules-of-class :type-prescription :here))) :induct (aig-list->s x env) :expand ((:free (env) (aig-list->s x env)))))) (defthm a4vec-eval-of-append-when-first-superset (implies (and (nat-bool-a4vec-p x) (subsetp (nat-bool-a4vec-vars x) (alist-keys env))) (equal (a4vec-eval x (append env rest)) (a4vec-eval x env))) :hints(("Goal" :in-theory (enable a4vec-eval nat-bool-a4vec-p nat-bool-a4vec-vars)))) (defthm aig-list->s-of-append-when-first-not-intersect (implies (and (nat-bool-listp x) (not (intersectp (nat-bool-list-nats x) (alist-keys prev)))) (equal (aig-list->s x (append prev env)) (aig-list->s x env))) :hints(("Goal" :in-theory (e/d* (aig-list->s nat-bool-listp nat-bool-list-nats gl::scdr gl::s-endp) ((:rules-of-class :type-prescription :here))) :induct (aig-list->s x env) :expand ((:free (env) (aig-list->s x env)))))) (defthm a4vec-eval-of-append-when-first-not-intersect (implies (and (nat-bool-a4vec-p x) (not (intersectp (nat-bool-a4vec-vars x) (alist-keys prev)))) (equal (a4vec-eval x (append prev env)) (a4vec-eval x env))) :hints(("Goal" :in-theory (enable a4vec-eval nat-bool-a4vec-p nat-bool-a4vec-vars)))) (defthm nat-bool-a4vec-p-of-nat-bool-a4env (implies (and (nat-bool-a4env-p x) (hons-assoc-equal k x)) (nat-bool-a4vec-p (cdr (hons-assoc-equal k x)))) :hints(("Goal" :in-theory (enable nat-bool-a4env-p)))) ;; (define svex-env-lookup-nofix (x env) ;; (or (cdr (hons-get x env)) (4vec-x)) ;; /// ;; (defthm svex-env-lookup-nofix-when-right-types ;; (implies (and (svar-p x) ;; (svex-env-p env)) ;; (equal (svex-env-lookup-nofix x env) ;; (svex-env-lookup x env))) ;; :hints(("Goal" :in-theory (enable svex-env-lookup ;; svex-env-p)))) ;; ;; (local (defthm lookup-in-svex-env-fix-when-svar-p ;; ;; (implies (and (svar-p x) ;; ;; (not (cdr (hons-assoc-equal x env)))) ;; ;; (4vec-equiv (cdr (hons-assoc-equal x (svex-env-fix env))) ;; ;; (4vec-x))) ;; ;; :hints(("Goal" :in-theory (enable svex-env-fix))))) ;; (defthm svex-env-lookup-nofix-when-right-types-weak ;; (implies (svar-p x) ;; (4vec-equiv (svex-env-lookup-nofix x env) ;; (svex-env-lookup x env))) ;; :hints(("Goal" :in-theory (enable svex-env-lookup svex-env-fix))))) (define svex-mask-alist-extract-vars ((x svex-mask-alist-p)) :returns (new-x svex-mask-alist-p) :hooks nil (if (atom x) nil (if (and (mbt (svex-p (caar x))) (eq (svex-kind (caar x)) :var)) (hons-acons (caar x) (4vmask-fix (cdar x)) (svex-mask-alist-extract-vars (cdr x))) (svex-mask-alist-extract-vars (cdr x)))) /// (defret lookup-in-svex-mask-alist-extract-vars (equal (hons-assoc-equal s new-x) (and (svex-p s) (equal (svex-kind s) :var) (hons-assoc-equal s (svex-mask-alist-fix x))))) (local (defthm assoc-in-svex-mask-alist-p (implies (svex-mask-alist-p x) (equal (assoc k x) (hons-assoc-equal k x))) :hints(("Goal" :in-theory (enable svex-mask-alist-p))))) (defret svex-mask-lookup-in-svex-mask-alist-extract-vars (equal (svex-mask-lookup s new-x) (if (equal (svex-kind s) :var) (svex-mask-lookup s x) 0)) :hints(("Goal" :in-theory (enable svex-mask-lookup)))) (defret svex-maskbits-ok-of-svex-mask-alist-extract-vars (iff (svex-maskbits-ok vars new-x) (svex-maskbits-ok vars x)) :hints(("Goal" :in-theory (enable svex-maskbits-ok) :induct (svex-maskbits-ok vars x) :do-not-induct t))) (defret svex-maskbits-for-vars-of-svex-mask-alist-extract-vars (equal (svex-maskbits-for-vars vars new-x boolmasks) (svex-maskbits-for-vars vars x boolmasks)) :hints(("Goal" :in-theory (e/d (svex-maskbits-for-vars) (svex-mask-alist-extract-vars))))) (deffixequiv svex-mask-alist-extract-vars :hints(("Goal" :in-theory (enable svex-mask-alist-fix))))) (define svex-varmasks/env->aig-env-rec ((vars svarlist-p) (masks svex-mask-alist-p) (boolmasks svar-boolmasks-p) (env svex-env-p "look up variables in env to get 4vecs to assign -- symbolic") (nextvar natp) (acc "aig environment accumulator")) :prepwork ((local (in-theory (enable svarlist-p svarlist-fix)))) :returns (mv (err "some mask was negative" (implies (svex-mask-alist-p masks) (iff err (not (svex-maskbits-ok vars masks)))) :hints(("Goal" :in-theory (enable svex-maskbits-ok)))) (env) ;; binds AIG vars to Boolean values (nextvar1 (implies (and (svex-mask-alist-p masks) (svar-boolmasks-p boolmasks)) (equal nextvar1 (+ (nfix nextvar) (svex-maskbits-for-vars vars masks boolmasks)))) :hints(("Goal" :in-theory (enable svex-maskbits-for-vars))))) ;; :hooks ((:fix :args (vars nextvar))) (b* (((when (atom vars)) (mv nil acc (lnfix nextvar))) (mask (svex-mask-lookup (svex-var (car vars)) masks)) ((when (sparseint-< mask 0)) (mv (msg "Negative mask: ~x0~%" (svar-fix (car vars))) acc (lnfix nextvar))) (boolmask (svar-boolmasks-lookup (car vars) boolmasks)) (4vec (4vec-fix (svex-env-lookup (svar-fix (car vars)) env))) (env-part (4vmask-to-a4vec-env mask boolmask 4vec nextvar)) (nextvar (+ (lnfix nextvar) (4vmask-to-a4vec-varcount mask boolmask)))) (svex-varmasks/env->aig-env-rec (cdr vars) masks boolmasks env nextvar (append env-part acc))) /// (defthm key-exists-in-svex-varmasks/env->aig-env-rec (implies (and (svex-mask-alist-p masks) (svar-boolmasks-p boolmasks)) (iff (hons-assoc-equal v (mv-nth 1 (svex-varmasks/env->aig-env-rec vars masks boolmasks env nextvar acc))) (or (hons-assoc-equal v acc) (and (natp v) (<= (nfix nextvar) v) (< v (+ (nfix nextvar) (svex-maskbits-for-vars vars masks boolmasks))))))) :hints(("Goal" :in-theory (enable svex-maskbits-for-vars)))) (local (defun-sk svex-varmasks/env->aig-env-accumulator-elim-correct (vars masks boolmasks env nextvar) (forall acc (implies (syntaxp (not (equal acc ''nil))) (equal (mv-nth 1 (svex-varmasks/env->aig-env-rec vars masks boolmasks env nextvar acc)) (append (mv-nth 1 (svex-varmasks/env->aig-env-rec vars masks boolmasks env nextvar nil)) acc)))) :rewrite :direct)) (local (in-theory (disable svex-varmasks/env->aig-env-accumulator-elim-correct))) (local (defthmd svex-varmasks/env->aig-env-accumulator-elim-lemma (svex-varmasks/env->aig-env-accumulator-elim-correct vars masks boolmasks env nextvar) :hints (("goal" :induct (svex-varmasks/env->aig-env-rec vars masks boolmasks env nextvar acc)) (and stable-under-simplificationp `(:expand (,(car (last clause)) (:free (acc) (svex-varmasks/env->aig-env-rec vars masks boolmasks env nextvar acc)))))))) (defthm svex-varmasks/env->aig-env-accumulator-elim (implies (syntaxp (not (equal acc ''nil))) (equal (mv-nth 1 (svex-varmasks/env->aig-env-rec vars masks boolmasks env nextvar acc)) (append (mv-nth 1 (svex-varmasks/env->aig-env-rec vars masks boolmasks env nextvar nil)) acc))) :hints (("goal" :use svex-varmasks/env->aig-env-accumulator-elim-lemma))) (defthm 4vmask-to-a4vec-vars-subset-of-keys (SUBSETP-EQUAL (NAT-BOOL-A4VEC-VARS (4vmask-to-a4vec mask boolmask nextvar)) (ALIST-KEYS (4vmask-to-a4vec-env mask boolmask val nextvar))) :hints ((acl2::set-reasoning))) (defthm member-nat-bool-a4vec-vars-of-lookup-when-upper-bounded (implies (and (nat-bool-a4env-p a4acc) (nat-bool-a4env-upper-boundp nextvar a4acc) (<= (nfix nextvar) k)) (not (member k (nat-bool-a4vec-vars (cdr (hons-assoc-equal v a4acc)))))) :hints(("Goal" :in-theory (enable nat-bool-a4env-p nat-bool-a4env-upper-boundp)))) (defthm 4vmask-to-a4vec-env-vars-not-intersect-when-upper-bounded (implies (and (nat-bool-a4env-p a4acc) (double-rewrite (nat-bool-a4env-upper-boundp nextvar a4acc))) (not (intersectp (nat-bool-a4vec-vars (cdr (hons-assoc-equal v a4acc))) (alist-keys (4vmask-to-a4vec-env mask boolmask val nextvar))))) :hints ((acl2::set-reasoning))) (local (defthm 4vmask-to-a4vec-vars-not-intersect-svex-varmsks/env->aig-env-rec-keys (implies (and (svex-mask-alist-p masks) (svar-boolmasks-p boolmasks)) (NOT (INTERSECTP-EQUAL (NAT-BOOL-A4VEC-VARS (4VMASK-TO-A4VEC mask boolmask NEXTVAR)) (ALIST-KEYS (MV-NTH 1 (SVEX-VARMASKS/ENV->AIG-ENV-REC vars masks BOOLMASKS GOALENV (+ (NFIX NEXTVAR) (4VMASK-TO-A4VEC-VARCOUNT mask boolmask)) NIL)))))) :hints ((set-reasoning)))) (local (defthm not-member-a4vec-vars-lookup-when-not-member-a4env-vars (implies (not (member v (nat-bool-a4env-vars a4env))) (not (member v (nat-bool-a4vec-vars (cdr (hons-assoc-equal v0 a4env)))))) :hints(("Goal" :in-theory (enable nat-bool-a4env-vars))))) (local (defthm 4vmask-to-a4vec-vars-subset-svex-varmsks/env->aig-env-rec-keys-2 (implies (and (svex-mask-alist-p masks) (svar-boolmasks-p boolmasks)) (SUBSETP-EQUAL (NAT-BOOL-A4VEC-VARS (CDR (HONS-ASSOC-EQUAL v0 (MV-NTH 1 (SVEX-VARMASKS->A4ENV-REC vars MASKS BOOLMASKS nextvar NIL))))) (ALIST-KEYS (MV-NTH 1 (SVEX-VARMASKS/ENV->AIG-ENV-REC vars (SVEX-MASK-ALIST-EXTRACT-VARS MASKS) BOOLMASKS GOALENV nextvar NIL))))) :hints ((set-reasoning)))) (acl2::defquant svex-env-boolmasks-ok (env boolmasks) (forall v (4vec-boolmaskp (svex-env-lookup v env) (svar-boolmasks-lookup v boolmasks))) :rewrite :direct) (local (defthm svex-env-lookup-of-cons (equal (svex-env-lookup k (cons (cons k0 v0) rest)) (if (and (svar-p k0) (equal (svar-fix k) k0)) (4vec-fix v0) (svex-env-lookup k rest))) :hints(("Goal" :in-theory (enable svex-env-lookup svex-env-fix))))) (local (in-theory (enable svex-env-boolmasks-ok-necc svex-varmasks->a4env-rec-accumulator-elim))) (defthm eval-svex-varmasks->a4env-rec-with-env (b* (((mv err a4env ?nextvar1) ;; Assigns AIG variable numbers to each SVEX var. Ignores goalenv (does ;; not need to know anything about the values of the svex vars to do ;; this, just their caremasks/boolmasks). (svex-varmasks->a4env-rec vars masks boolmasks nextvar nil)) ((mv ?err1 env ?nextvar1) ;; Binds AIG variable numbers to (symbolic) bits extracted from the goalenv. (svex-varmasks/env->aig-env-rec vars (svex-mask-alist-extract-vars masks) boolmasks goalenv nextvar nil))) (implies (and (not err) ;; (nat-bool-a4env-p a4acc) ;; (nat-bool-a4env-upper-boundp nextvar a4acc) (svex-mask-alist-p masks) (svar-boolmasks-p boolmasks) (svex-env-boolmasks-ok goalenv boolmasks) ;; (svex-env-p goalenv) ;; (svex-envs-masks-partly-equiv ;; vars masks ;; (svex-a4vec-env-eval a4acc envacc) ;; goalenv) ;; (subsetp (alist-keys (svex-env-fix goalenv)) ;; (append (svarlist-fix vars) ;; (alist-keys (svex-a4vec-env-fix a4acc)))) ) (svex-envs-mask-equiv-on-vars vars masks (svex-a4vec-env-eval a4env env) goalenv))) :hints(("Goal" :in-theory (enable svex-varmasks->a4env-rec svarlist-fix svex-maskbits-ok nat-bool-a4env-p nat-bool-a4env-upper-boundp svex-a4vec-env-fix svex-a4vec-env-eval alist-keys svex-alist-keys) :induct (svex-varmasks->a4env-rec vars masks boolmasks nextvar nil) ;; (svex-varmasks->a4env-rec-induct ;; vars masks boolmasks nextvar a4acc goalenv envacc) :expand ((:free (a4acc) (svex-varmasks->a4env-rec vars masks boolmasks nextvar a4acc)) (:free (envacc masks) (svex-varmasks/env->aig-env-rec vars masks boolmasks goalenv nextvar envacc)))) (and stable-under-simplificationp (cond ((assoc 'subsetp-equal clause) ;; has a (not (subsetp-equal... lit (acl2::set-reasoning)) ;; ((assoc 'svex-envs-masks-partly-equiv clause) ;; '(:computed-hint-replacement ;; ((acl2::witness :ruleset (svex-envs-masks-partly-equiv-witnessing)) ;; (acl2::witness :ruleset (svex-envs-masks-partly-equiv-example))) ;; :in-theory (enable ;; svex-env-lookup ;; svex-env-fix))) ;; (t '(:computed-hint-replacement ;; ((acl2::witness :ruleset (svex-envs-mask-equiv-witnessing)) ;; (acl2::witness :ruleset (svex-envs-masks-partly-equiv-example))) ;; :no-op t)) (t '(:computed-hint-replacement ((acl2::witness :ruleset (svex-envs-mask-equiv-on-vars-witnessing)) (acl2::witness :ruleset (svex-envs-mask-equiv-on-vars-example))) :no-op t)) ))))) (define svex-varmasks->a4env ((vars svarlist-p) (masks svex-mask-alist-p) (boolmasks svar-boolmasks-p)) :returns (mv (err "some mask was negative" (iff err (not (svex-maskbits-ok vars masks)))) (a4env nat-bool-a4env-p!)) (b* (((mv err res &) (svex-varmasks->a4env-rec vars masks boolmasks 0 nil))) (mv err res)) /// (defret alist-keys-of-svex-varmasks->a4env (implies (not err) (equal (alist-keys a4env) (rev (svarlist-fix vars)))))) (define svex-varmasks/env->aig-env ((vars svarlist-p) (masks svex-mask-alist-p) (boolmasks svar-boolmasks-p) (env svex-env-p "look up variables in env to get 4vecs to assign")) :returns (mv (err "some mask was negative" (implies (svex-mask-alist-p masks) (iff err (not (svex-maskbits-ok vars masks)))) :hints(("Goal" :in-theory (enable svex-maskbits-ok)))) (env "binds AIG vars to Boolean values")) :hooks ((:fix :args (vars))) (b* (((mv err res &) (svex-varmasks/env->aig-env-rec vars masks boolmasks env 0 nil))) (mv err res)) /// (defthm eval-svex-varmasks->a4env-with-env (b* (((mv err a4env) (svex-varmasks->a4env vars masks boolmasks1)) ((mv ?err1 env) (svex-varmasks/env->aig-env vars (svex-mask-alist-extract-vars masks) boolmasks goalenv))) (implies (and (not err) (svex-mask-alist-p masks) (equal boolmasks (svar-boolmasks-fix boolmasks1)) ;; (svex-env-p goalenv) (svex-env-boolmasks-ok goalenv boolmasks)) (svex-envs-mask-equiv-on-vars vars masks (svex-a4vec-env-eval a4env env) goalenv))) :hints (("goal" :use ((:instance eval-svex-varmasks->a4env-rec-with-env (nextvar 0))) :in-theory (e/d (svex-varmasks->a4env svex-env-lookup svex-lookup) (eval-svex-varmasks->a4env-rec-with-env))) ;; (acl2::witness :ruleset (svex-envs-mask-equiv-on-vars)) ;; (acl2::set-reasoning) ))) (define svexlist-full-masks-p ((x svexlist-p) (masks svex-mask-alist-p)) (if (atom x) t (and (equal -1 (sparseint-val (svex-mask-lookup (car x) masks))) (svexlist-full-masks-p (cdr x) masks))) /// (defthm svexlist-full-masks-p-of-take (implies (and (svexlist-full-masks-p x masks) (<= (nfix n) (len x))) (svexlist-full-masks-p (take n x) masks))) (defthm svexlist-full-masks-p-of-nthcdr (implies (svexlist-full-masks-p x masks) (svexlist-full-masks-p (nthcdr n x) masks))) (defthmd svexlist-full-masks-p-of-svexlist-mask-alist-lemma (implies (subsetp (svexlist-fix y) (svexlist-fix x)) (svexlist-full-masks-p y (svexlist-mask-alist x))) :hints(("Goal" :in-theory (enable subsetp svexlist-fix)))) (defthm svexlist-full-masks-p-of-svexlist-mask-alist (svexlist-full-masks-p x (svexlist-mask-alist x)) :hints(("Goal" :in-theory (enable svexlist-full-masks-p-of-svexlist-mask-alist-lemma)))) (local (defun cdr2 (x y) (if (atom x) y (cdr2 (Cdr x) (cdr y))))) (defthm 4veclist-mask-when-full-masksp (implies (and (svexlist-full-masks-p x masks) (equal (len 4vecs) (len x))) (equal (4veclist-mask (svex-argmasks-lookup x masks) 4vecs) (4veclist-fix 4vecs))) :hints(("Goal" :in-theory (enable 4veclist-mask svex-argmasks-lookup 4veclist-fix 4vec-mask) :induct (cdr2 x 4vecs))))) (defsection general-correctness-theorems (local (defthm subsetp-intersection (subsetp (intersection$ x y) y) :hints ((set-reasoning)))) (defthm svexlist->a4vec-correct-for-varmasks-aig-env (b* (((mv err a4env) (svex-varmasks->a4env vars masks boolmasks1)) ((mv ?err1 env) (svex-varmasks/env->aig-env vars (svex-mask-alist-extract-vars masks) boolmasks goalenv)) (a4vecs (svexlist->a4vec x a4env masks))) (implies (and (not err) (svex-mask-alist-p masks) (svex-mask-alist-complete masks) (equal boolmasks (svar-boolmasks-fix boolmasks1)) (svex-env-boolmasks-ok goalenv boolmasks) (subsetp (intersection-equal (svexlist-vars x) (alist-keys (svex-env-fix goalenv))) (svarlist-fix vars))) (equal (4veclist-mask (svex-argmasks-lookup x masks) (a4veclist-eval a4vecs env)) (4veclist-mask (svex-argmasks-lookup x masks) (svexlist-eval x goalenv))))) :hints (("goal" :use ((:instance svexlist-eval-of-mask-equiv-on-vars-envs (env2 goalenv) (env1 (svex-a4vec-env-eval (mv-nth 1 (svex-varmasks->a4env vars masks boolmasks)) (mv-nth 1 (svex-varmasks/env->aig-env vars (svex-mask-alist-extract-vars masks) boolmasks goalenv)))))) :in-theory (disable svexlist-eval-of-mask-equiv-on-vars-envs)))) (defthm svexlist->a4vec-correct-for-varmasks-aig-env-top (b* (((mv err a4env) (svex-varmasks->a4env vars masks boolmasks1)) ((mv ?err1 env) (svex-varmasks/env->aig-env vars (svex-mask-alist-extract-vars masks) boolmasks goalenv)) (a4vecs (svexlist->a4vec x a4env masks))) (implies (and (not err) (svexlist-full-masks-p x masks) (svex-mask-alist-p masks) (svex-mask-alist-complete masks) (equal boolmasks (svar-boolmasks-fix boolmasks1)) (svex-env-boolmasks-ok goalenv boolmasks) (subsetp (intersection-equal (svexlist-vars x) (alist-keys (svex-env-fix goalenv))) (svarlist-fix vars))) (equal (a4veclist-eval a4vecs env) (svexlist-eval x goalenv)))) :hints (("goal" :use svexlist->a4vec-correct-for-varmasks-aig-env :in-theory (disable svexlist->a4vec-correct-for-varmasks-aig-env))))) (define svex-env-check-boolmasks ((boolmasks svar-boolmasks-p) (env svex-env-p)) :prepwork ((local (in-theory (enable svar-boolmasks-p svar-boolmasks-fix)))) ;; :hooks nil (b* (((when (atom boolmasks)) t) ((unless (mbt (svar-p (caar boolmasks)))) (svex-env-check-boolmasks (cdr boolmasks) env)) ((cons var mask) (car boolmasks)) (val (svex-env-lookup var env)) (ok (4vec-boolmaskp val mask)) (?ign (and (not ok) (cw "not 4vec-boolmaskp: ~x0~%" var)))) (and (svex-env-check-boolmasks (cdr boolmasks) env) ok)) /// (acl2::defexample svex-env-boolmasks-ok-example :pattern (svex-env-lookup v env) :templates (v) :instance-rulename svex-env-boolmasks-ok-instancing) (defthm svex-env-check-boolmasks-correct (implies (and (svex-env-check-boolmasks boolmasks env) ;; (svex-env-p env) (svar-boolmasks-p boolmasks)) (svex-env-boolmasks-ok env boolmasks)) :hints (("goal" :induct (svex-env-check-boolmasks boolmasks env)) (acl2::witness :ruleset (svex-env-boolmasks-ok-witnessing svex-env-boolmasks-ok-example)) (and stable-under-simplificationp '(:in-theory (enable svar-boolmasks-lookup) :expand ((:free (x) (4vec-boolmaskp x 0)))))))) (define svexlist-mask-alist-memo ((x svexlist-p)) :enabled t (svexlist-mask-alist x) /// (memoize 'svexlist-mask-alist-memo)) (define svexlist-vars-memo ((x svexlist-p)) :enabled t (svexlist-collect-vars x) /// (memoize 'svexlist-vars-memo)) (define svexlist->a4vecs-for-varlist ((x svexlist-p) (vars svarlist-p) (boolmasks svar-boolmasks-p)) :returns (mv (err (iff err (not (svex-maskbits-ok vars (svexlist-mask-alist x))))) (a4vecs a4veclist-p)) :short "Creates a symbolic bit-level representation for x, assuming that vars are the only vars relevant to x and that the bits of vars given in boolmasks are Boolean-valued." :long "<p>Steps: First creates a symbolic environment mapping the variables to a4vec structures, each bit of which is a free variable. (For bits constrained to be Boolean by boolmasks, the same variable is shared for upper/lower.) Then uses @('svexlist->a4vec-top') to generate a4vecs corresponding to the svexes.</p>" (b* (;; (- (sneaky-push 'svexlist x)) (masks (svexlist-mask-alist-memo x)) ((mv err a4env) (svex-varmasks->a4env vars masks boolmasks)) ((when err) (mv err nil)) (a4env (make-fast-alist a4env)) (res (svexlist->a4vec-top x a4env masks)) (?ign (fast-alist-free a4env))) (mv nil res)) /// (memoize 'svexlist->a4vecs-for-varlist)) (define svexlist-variable-mask-alist ((x svexlist-p)) ;; We've seen problems in GL where we get a stack overflow in ;; gobject-hierarchy-lite traversing the full masks inside ;; svexlist->a4vec-aig-env-for-varlist. But we don't need the full set of ;; masks there, only those for the variables. So to work around this ;; problem, this function extracts only the variables from the mask alist, ;; producing a much smaller alist. :returns (varmasks svex-mask-alist-p) :enabled t (b* ((masks-full (svexlist-mask-alist-memo x))) (svex-mask-alist-extract-vars masks-full)) /// (memoize 'svexlist-variable-mask-alist)) (define svexlist->a4vec-aig-env-for-varlist ((x svexlist-p) (vars svarlist-p) (boolmasks svar-boolmasks-p) (env svex-env-p)) :returns (mv (err (iff err (not (svex-maskbits-ok vars (svexlist-mask-alist x))))) (aig-env)) :hooks ((:fix :args (x vars))) ;; We use svexlist-variable-mask-alist here rather than ;; svexlist-mask-alist-memo so that GL won't have to traverse the full mask ;; alist with gobject-hierarchy-lite, which we've seen cause stack overflows. (b* ((masks (svexlist-variable-mask-alist x))) (svex-varmasks/env->aig-env vars masks boolmasks env)) /// ;; (local (defthm svex-envs-mask-equiv-lemma ;; (iff (svex-envs-mask-equiv ;; (svexlist-mask-alist x) y z) ;; (svex-envs-mask-equiv ;; (svexlist-variable-mask-alist x) y z)) ;; :hints ((witness)))) ;; This is directly proved by svexlist->a4vec-top-correct-for-varmasks-aig-env-top (defthm svexlist->a4vec-for-varlist-correct (b* (((mv err a4vecs) (svexlist->a4vecs-for-varlist x vars boolmasks)) ((mv ?err1 aig-env) (svexlist->a4vec-aig-env-for-varlist x vars boolmasks env))) (implies (and (not err) ;; (svex-env-p env) (svar-boolmasks-p boolmasks) (svex-env-boolmasks-ok env boolmasks) (subsetp (intersection-equal (svexlist-vars x) (alist-keys (svex-env-fix env))) (svarlist-fix vars))) (equal (a4veclist-eval a4vecs aig-env) (svexlist-eval x env)))) :hints(("Goal" :in-theory (e/d (svexlist->a4vecs-for-varlist) (svexlist-eval-of-mask-equiv-on-vars-envs)))) :otf-flg t)) (local (defthm subset-of-mergesorts-is-subsetp (iff (subset (mergesort a) (mergesort b)) (subsetp a b)) :hints(("Goal" :in-theory (enable* set::definitions))))) (define svexlist-rewrite-fixpoint-memo ((x svexlist-p)) :enabled t (time$ (svexlist-rewrite-fixpoint x :verbosep t :count 2) :msg "; svex rewriting: ~st sec, ~sa bytes.~%") /// (memoize 'svexlist-rewrite-fixpoint-memo)) (define maybe-svexlist-rewrite-fixpoint ((x svexlist-p) (do-it)) :returns (new-x svexlist-p) (if do-it (svexlist-rewrite-fixpoint-memo x) (hons-copy (svexlist-fix x))) /// (defret maybe-svexlist-rewrite-fixpoint-correct (equal (svexlist-eval new-x env) (svexlist-eval x env))) (defret maybe-svexlist-rewrite-fixpoint-len (equal (len new-x) (len x))) (defret vars-of-maybe-svexlist-rewrite-fixpoint (implies (not (member v (svexlist-vars x))) (not (member v (svexlist-vars new-x)))))) (local (defthm svarlist-p-of-alist-keys-when-svex-env-p (implies (svex-env-p env) (svarlist-p (alist-keys env))) :hints(("Goal" :in-theory (enable svex-env-p svarlist-p alist-keys))))) (define svexlist-vars-for-symbolic-eval ((x svexlist-p) (env svex-env-p) (symbolic-params alistp)) :returns (vars svarlist-p) :guard-hints (("goal" :in-theory (e/d (SET::UNION-WITH-SUBSET-LEFT double-containment set::subset-to-subsetp) (SUBSET-OF-MERGESORTS-IS-SUBSETP)))) (b* ((allvars (assoc :allvars symbolic-params)) (vars (if allvars (svexlist-vars-memo x) (ec-call (svarlist-fix (cdr (assoc :vars symbolic-params)))))) (svars (mbe :logic (set::mergesort vars) :exec (if (set::setp vars) vars (set::mergesort vars)))) ((when allvars) (hons-copy svars)) (keys (svarlist-filter (alist-keys env))) (keys (mbe :logic (set::mergesort keys) :exec (if (set::setp keys) keys (set::mergesort keys))))) (hons-copy (mbe :logic (union keys svars) :exec (if (set::subset keys svars) svars (if (eq svars nil) keys (union keys svars)))))) /// (local (defthm alist-keys-of-svex-env-fix (equal (alist-keys (svex-env-fix env)) (svarlist-filter (alist-keys env))) :hints(("Goal" :in-theory (enable svex-env-fix svarlist-filter))))) (defret svexlist-vars-for-symbolic-eval-sufficient (subsetp (intersection-equal (svexlist-vars x) (alist-keys (svex-env-fix env))) vars) :hints ((set-reasoning))) (defret member-of-svexlist-vars-for-symbolic-eval (implies (and (member v (svexlist-vars x)) (hons-assoc-equal v (svex-env-fix env))) (member v vars)) :hints (("goal" :use svexlist-vars-for-symbolic-eval-sufficient :in-theory (disable svexlist-vars-for-symbolic-eval-sufficient svexlist-vars-for-symbolic-eval alist-keys-of-svex-env-fix)) (set-reasoning)))) (defines svex-fastsubst :verify-guards nil (define svex-fastsubst :parents (svex-subst) :short "Substitution for @(see svex)es, identical to @(see svex-subst), except that we memoize the results and we use fast alist lookups." ((pat svex-p) (al svex-alist-p)) :returns (x (equal x (svex-subst pat al)) :hints ((and stable-under-simplificationp '(:expand ((svex-subst pat al)))))) :measure (svex-count pat) (svex-case pat :var (or (svex-fastlookup pat.name al) (svex-quote (4vec-x))) :quote (svex-fix pat) :call (svex-call pat.fn (svexlist-fastsubst pat.args al)))) (define svexlist-fastsubst ((pat svexlist-p) (al svex-alist-p)) :returns (x (equal x (svexlist-subst pat al)) :hints ((and stable-under-simplificationp '(:expand ((svexlist-subst pat al)))))) :measure (svexlist-count pat) (if (atom pat) nil (cons (svex-fastsubst (car pat) al) (svexlist-fastsubst (cdr pat) al)))) /// (verify-guards svex-fastsubst) (memoize 'svex-fastsubst :condition '(eq (svex-kind pat) :call))) (define svexlist-x-out-unused-vars ((x svexlist-p) (svars svarlist-p) (do-it)) :returns (new-x svexlist-p) (if do-it (b* ((subst (make-fast-alist (pairlis$ (svarlist-fix svars) (svarlist-svex-vars svars)))) (ans (svexlist-fastsubst x subst))) (clear-memoize-table 'svex-fastsubst) (fast-alist-free subst) ans) (svexlist-fix x)) /// (defthm svex-alist-eval-of-svarlist-svex-vars (equal (svex-alist-eval (pairlis$ (svarlist-fix svars) (svarlist-svex-vars svars)) env) (svex-env-extract svars env)) :hints(("Goal" :in-theory (enable svex-env-extract svex-alist-eval svarlist-fix svarlist-svex-vars) :induct (len svars) :expand ((:free (x) (svex-eval (svex-var x) env)))))) (defthm-svex-eval-flag (defthm svex-eval-of-svex-env-extract-when-intersection-subset (implies (subsetp (intersection$ (svex-vars x) (alist-keys (svex-env-fix env))) (svarlist-fix svars)) (equal (svex-eval x (svex-env-extract svars env)) (svex-eval x env))) :hints ('(:expand ((:free (env) (svex-eval x env)) (svex-vars x))) (and stable-under-simplificationp '(:in-theory (enable svex-env-lookup) :expand ((:free (x y) (subsetp-equal (list x) y)) (:free (x y) (intersection-equal (list x) y)))))) :flag expr) (defthm svexlist-eval-of-svex-env-extract-when-intersection-subset (implies (subsetp (intersection$ (svexlist-vars x) (alist-keys (svex-env-fix env))) (svarlist-fix svars)) (equal (svexlist-eval x (svex-env-extract svars env)) (svexlist-eval x env))) :hints ('(:expand ((:free (env) (svexlist-eval x env)) (svexlist-vars x)))) :flag list)) (defret svex-eval-of-svexlist-x-out-unused-vars (implies (subsetp (intersection-equal (svexlist-vars x) (alist-keys (svex-env-fix env))) (svarlist-fix svars)) (equal (svexlist-eval new-x env) (svexlist-eval x env)))) (local (defthm hons-assoc-equal-of-pair-svex-vars (equal (hons-assoc-equal v (pairlis$ (svarlist-fix vars1) (svarlist-svex-vars vars1))) (and (member v (svarlist-fix vars1)) (cons v (svex-var (svar-fix v))))) :hints(("Goal" :in-theory (enable hons-assoc-equal pairlis$ svarlist-svex-vars svarlist-fix))))) (local (defthm svex-lookup-of-pair-svex-vars (implies (equal vars (svarlist-fix vars1)) (equal (svex-lookup v (pairlis$ vars (svarlist-svex-vars vars1))) (and (member (svar-fix v) vars) (svex-var (svar-fix v))))) :hints(("Goal" :in-theory (enable svex-lookup))))) (local (defthm-svex-eval-flag (defthm vars-of-svex-subst-lemma (implies (and (not (member v (svex-vars x))) (equal vars (svarlist-fix vars1))) (not (member v (svex-vars (svex-subst x (pairlis$ vars (svarlist-svex-vars vars1))))))) :flag expr :hints ('(:expand ((:free (al) (svex-subst x al)))))) (defthm vars-of-svexlist-subst-lemma (implies (and (not (member v (svexlist-vars x))) (equal vars (svarlist-fix vars1))) (not (member v (svexlist-vars (svexlist-subst x (pairlis$ vars (svarlist-svex-vars vars1))))))) :flag list :hints ('(:expand ((:free (al) (svexlist-subst x al)))))))) (defret svex-vars-of-svexlist-x-out-unused-vars (implies (not (member v (svexlist-vars x))) (not (member v (svexlist-vars new-x))))) (local (defthm len-of-svexlist-subst (equal (len (svexlist-subst x subst)) (len x)) :hints (("goal" :induct (len x) :in-theory (enable svexlist-subst))))) (defret len-of-<fn> (equal (len new-x) (len x)))) (define symbolic-params-x-out-cond ((symbolic-params alistp)) ;; Only makes sense to x out unused variables if ;; - we're simplifying, so they'll get constant propagated, and ;; - we're not using all vars, so there will be some substitutions. (and (cdr (assoc :simplify symbolic-params)) (not (cdr (assoc :all-vars symbolic-params))))) (define svexlist-eval-gl ((x svexlist-p "Svex expressions to evaluate.") (env svex-env-p "Bindings of variables to @(see 4vec) values.") (symbolic-params alistp "Alist giving symbolic execution parameters; see below.")) :short "Equivalent of svexlist-eval intended to work well under GL symbolic execution." :long " <p>This function is provably equivalent to @(see svexlist-eval), but is tailored to perform well under symbolic execution. For symbolic execution, we assume that the inputs to this function other than @('env') are fully concrete, and that @('env') is symbolic only in its values, not its keys or its shape.</p> <p>The @('symbolic-params') input is logically irrelevant, but allows important optimizations for symbolic execution performance, discussed further below. It is safe (but not necessarily optimal) to call this with symbolic-params equal @('NIL').</p> <h4>Behavior under Symbolic Execution</h4> <ol> <li>Applies rewriting to the supplied svex expressions, if @(':SIMPLIFY') is bound to a non-nil value in the @('symbolic-params') input -- see @(see svexlist-rewrite-fixpoint).</li> <li>If @(':boolmasks') is bound in the symbolic-params, compares the given @('env') with the bound value, which should be an alist. If there is a pair @('(name . mask)') in the boolmasks alist for which the binding for @('name') in env is not Boolean-valued on the bits set to 1 in @('mask'), then fail out of symbolic simulation. (In AIG mode, the masked bits must be <i>syntactically</i> Boolean-valued -- practically speaking, this means the upper/lower parts should result from the same computation.)</li> <li>If @(':VARS') is bound in symbolic-params, it should be bound to a list of input variables of the SVTV. Unions this list with the variables bound in @('env') to obtain the full list of variables to bind as inputs to the SVTV. Or if @(':ALLVARS') is bound in symbolic params, all the variables in the svex expressions are used instead.</li> <li>Compiles the svex list @('x') into @(see a4vec) objects, a symbolic analogue of @(see 4vec) but with each bit an AIG -- see @(see svexlist->a4vecs-for-varlist). This computation uses the assumptions, checked in the two steps above, that only the variables in @('vars') are non-X, and that the masked bits in @('boolmasks') are Boolean-valued. These assumptions can reduce the complexity of the generated AIGs. (Note everything used in this computation is concrete -- the @('env') isn't involved.)</li> <li>Creates an alist binding the AIG variables used in the above step to the appropriate symbolic bits from @('env').</li> <li>Symbolically evaluates each of the a4vec objects from step 4 under the bindings from step 5 using GL's symbolic simulator of @(see acl2::aig-eval). This results in GL-native symbolic 4vec objects, which is the result we want.</li> </ol> <h4>Optimization using the Extra Arguments</h4> <p>Performance of symbolic execution (and SAT solving, when in AIG mode) is related to the size of the AIGs produced by the svex to AIG transformation (step 4, above). Two ways to decrease that size are (1) to turn certain variables into constant Xes, if it is known that they're irrelevant, and (2) to assume certain bits of some variables are Boolean-valued, which means it can be represented by just one AIG variable rather than two.</p> <p>Another performance consideration is that the transformation to AIGs is itself sometimes significant. Especially for theorems proved by case-splitting, it is important not to need to repeat this transformation for each case. The function that does the transformation is memoized, but it is important in this case that it always be called with the same arguments.</p> <p>The @('vars') list pertains to optimization (1): if not present in the list, a variable in the svex expressions will just be replaced with an X. Therefore, in general it's best to use exactly the set of variables bound in the environment. However, it may not be worth it to redo the AIG conversion each time the environment's bound variables changes, so we take @('vars') separately.</p> <p>The @('boolmasks') allows optimization (2). It is best for symbolic execution performance to bind every variable in @('vars') to -1, but this may fail if the @('env') is not constructed in such a way that the values are obviously 2-vectors.</p>" :guard-hints (("goal" :in-theory (e/d (SET::UNION-WITH-SUBSET-LEFT) (SUBSET-OF-MERGESORTS-IS-SUBSETP)))) (b* ((env (make-fast-alist (svex-env-fix env))) (svars (svexlist-vars-for-symbolic-eval x env symbolic-params)) (x (svexlist-x-out-unused-vars x svars (symbolic-params-x-out-cond symbolic-params))) (x (maybe-svexlist-rewrite-fixpoint x (cdr (assoc :simplify symbolic-params)))) (boolmasks (make-fast-alist (hons-copy (ec-call (svar-boolmasks-fix (cdr (assoc :boolmasks symbolic-params))))))) ((unless (svex-env-check-boolmasks boolmasks env)) (b* ((?ign (cw "ERROR: some bits assumed to be Boolean were not~%")) (?ign (gl::gl-error 'boolcheck-failed))) (gl::gl-hide (svexlist-eval x env)))) ;; (?ign (cw "Boolmasks: ~x0~%" boolmasks)) ;; (?ign (bitops::sneaky-push 'boolmasks boolmasks)) ;; (?ign (bitops::sneaky-push 'vars vars)) ;; (?ign (bitops::sneaky-push 'x x)) ((mv err a4vecs) (time$ (svexlist->a4vecs-for-varlist x svars boolmasks) :msg "; svex->aigs: ~st sec, ~sa bytes.~%")) ((when err) (b* ((?ign (cw "ERROR gathering AIG bits for variables: ~@0~%" err)) (?ign (gl::gl-error 'a4env-failed))) (gl::gl-hide (svexlist-eval x env)))) ((mv ?err aig-env) ;; ignore the error; it can't exist if the above doesn't (time$ (svexlist->a4vec-aig-env-for-varlist x svars boolmasks env) :msg "; env -> aig env: ~st sec, ~sa bytes.~%")) (?ign (fast-alist-free env)) (aig-env (make-fast-alist aig-env)) (ans (a4veclist-eval a4vecs aig-env))) (fast-alist-free aig-env) ans) /// (defthm svexlist-eval-gl-is-svexlist-eval (equal (svexlist-eval-gl x env symbolic-params) (svexlist-eval x env)) :hints (("goal" :use ((:instance svexlist->a4vec-for-varlist-correct (boolmasks (svar-boolmasks-fix (cdr (assoc :boolmasks symbolic-params)))) (vars (svexlist-vars-for-symbolic-eval x env symbolic-params)) (x (maybe-svexlist-rewrite-fixpoint (svexlist-x-out-unused-vars x (svexlist-vars-for-symbolic-eval x env symbolic-params) (symbolic-params-x-out-cond symbolic-params)) (cdr (assoc :simplify symbolic-params)))) (env (svex-env-fix env)))) :in-theory (disable svexlist->a4vec-for-varlist-correct SVEXLIST->A4VECS-FOR-VARLIST-SVAR-BOOLMASKS-EQUIV-CONGRUENCE-ON-BOOLMASKS)) (set-reasoning) (and stable-under-simplificationp '(:cases ((member acl2::k0 (svexlist-vars x))))))) (gl::def-gl-rewrite svexlist-eval-for-symbolic-redef (equal (svexlist-eval-for-symbolic x env symbolic-params) (svexlist-eval-gl x env symbolic-params)))) ;;; Now rework a4veclist-eval to phrase it in terms of a single call to aig-eval-list (define a4vec->aiglist ((x a4vec-p)) :returns (lst true-listp :rule-classes :type-prescription) (b* (((a4vec x) x)) (append x.upper x.lower))) ;; (define v2i-alt ((v true-listp)) ;; :returns (v2i (equal v2i (gl::v2i v)) ;; :hints(("Goal" :in-theory (enable gl::scdr gl::s-endp)))) ;; :hooks nil ;; (if (atom (cdr v)) ;; (gl::bool->sign (car v)) ;; (logcons (acl2::bool->bit (car v)) ;; (v2i-alt (cdr v))))) (local (defthm v2i-of-aig-eval-list (equal (gl::v2i (aig-eval-list x env)) (aig-list->s x env)) :hints(("Goal" :in-theory (enable (:i aig-list->s) gl::v2i gl::scdr gl::s-endp) :induct (aig-list->s x env) :expand ((aig-list->s x env) (aig-eval-list x env) (:free (A b) (gl::v2i (cons a b)))))))) (define v2i-first-n ((n natp) (v true-listp)) :returns (v2i (equal v2i (gl::v2i (take n v))) :hints(("Goal" :in-theory (e/d (acl2::take) (acl2::take-of-too-many)) :induct t))) :prepwork ((local (defthm v2i-of-singleton (equal (gl::v2i (list x)) (gl::bool->sign x)) :hints(("Goal" :in-theory (enable gl::s-endp gl::v2i))))) (local (defthm v2i-of-cons (implies (consp y) (equal (gl::v2i (cons x y)) (logapp 1 (bool->bit x) (gl::v2i y)))) :hints(("Goal" :in-theory (enable gl::v2i logapp** gl::s-endp gl::scdr)))))) (cond ((zp n) (gl::bool->sign nil)) ((eql n 1) (gl::bool->sign (car v))) (t (logapp 1 (acl2::bool->bit (car v)) (v2i-first-n (1- n) (cdr v)))))) (define 4vec-from-bitlist ((upper-len natp) (lower-len natp) (bits true-listp)) :hooks ((:fix :omit (bits))) :returns (mv (vec 4vec-p) (rest true-listp :hyp (true-listp bits) :rule-classes :type-prescription)) ;; note: list-fixing bits is bad here because it's not even linear in the ;; number of bits we're operating on (b* ((upper (v2i-first-n upper-len bits)) (rest (nthcdr upper-len bits)) (lower (v2i-first-n lower-len rest)) (rest (nthcdr lower-len rest))) (mv (4vec upper lower) rest)) /// (defthm 4vec-from-bitlist-correct (b* (((a4vec x) x)) (equal (4vec-from-bitlist (len x.upper) (len x.lower) (append (aig-eval-list (a4vec->aiglist x) env) rest)) (mv (a4vec-eval x env) rest))) :hints(("Goal" :in-theory (enable a4vec->aiglist))))) (define a4veclist->aiglist ((x a4veclist-p)) :returns (aigs true-listp :rule-classes :type-prescription) (if (atom x) nil (append (a4vec->aiglist (car x)) (a4veclist->aiglist (cdr x))))) (define 4veclist-from-bitlist ((origs a4veclist-p) (bits true-listp)) :returns (4vecs 4veclist-p) :hooks ((:fix :omit (bits))) (b* (((when (atom origs)) nil) ((a4vec x) (car origs)) ((mv first restbits) (4vec-from-bitlist (len x.upper) (len x.lower) bits))) (cons first (4veclist-from-bitlist (cdr origs) restbits))) /// (defthm 4veclist-from-bitlist-correct (equal (4veclist-from-bitlist x (aig-eval-list (a4veclist->aiglist x) env)) (a4veclist-eval x env)) :hints(("Goal" :in-theory (enable a4veclist-eval a4veclist->aiglist))))) (define a4veclist-eval-gl ((x a4veclist-p) (env)) :returns (res 4veclist-p) (b* ((aiglist (time$ (a4veclist->aiglist x) :msg "; SV bit-blasting: a4veclist->aiglist: ~st sec, ~sa bytes.~%")) (bitlist (time$ (aig-eval-list aiglist env) :msg "; SV bit-blasting: aig-eval-list: ~st sec, ~sa bytes.~%"))) (time$ (4veclist-from-bitlist x bitlist) :msg "; bits->4vecs: ~st sec, ~sa bytes.~%")) /// (defthm a4veclist-eval-gl-correct (equal (a4veclist-eval-gl x env) (a4veclist-eval x env))) (gl::def-gl-rewrite a4veclist-eval-redef (equal (a4veclist-eval x env) (a4veclist-eval-gl x env)))) (gl::def-gl-rewrite svex-alist-eval-gl-rewrite (equal (svex-alist-eval x env) (pairlis$ (svex-alist-keys x) (svexlist-eval-for-symbolic (svex-alist-vals x) env nil))) :hints(("Goal" :in-theory (enable svex-alist-eval pairlis$ svex-alist-keys svex-alist-vals svexlist-eval)))) (gl::def-gl-rewrite svex-eval-gl-rewrite (equal (svex-eval x env) (car (svexlist-eval-for-symbolic (list x) env nil)))) (define svex-envlist-keyset ((x svex-envlist-p)) :returns (keys (and (svarlist-p keys) (set::setp keys))) (if (atom x) nil (set::union (set::mergesort (svarlist-filter (alist-keys (car x)))) (svex-envlist-keyset (cdr x)))) /// (local (defthm alist-keys-of-svex-env-fix (equal (alist-keys (svex-env-fix env)) (svarlist-filter (alist-keys env))) :hints(("Goal" :in-theory (enable svex-env-fix svarlist-filter))))) (defret svex-envlist-keyset-sufficient (implies (member env x) (subsetp (alist-keys (svex-env-fix env)) keys)))) (define svexlist/env-list-vars-for-symbolic-eval ((x svexlist-p) (envs svex-envlist-p) (symbolic-params alistp)) :returns (vars svarlist-p) :guard-hints (("goal" :in-theory (e/d (SET::UNION-WITH-SUBSET-LEFT double-containment set::subset-to-subsetp) (SUBSET-OF-MERGESORTS-IS-SUBSETP)))) (b* ((allvars (assoc :allvars symbolic-params)) (vars (if allvars (svexlist-vars-memo x) (ec-call (svarlist-fix (cdr (assoc :vars symbolic-params)))))) (svars (mbe :logic (set::mergesort vars) :exec (if (set::setp vars) vars (set::mergesort vars)))) ((when allvars) (hons-copy svars)) (keys (svex-envlist-keyset envs))) (hons-copy (mbe :logic (union keys svars) :exec (if (set::subset keys svars) svars (if (eq svars nil) keys (union keys svars)))))) /// (defret svexlist/env-list-vars-for-symbolic-eval-sufficient (subsetp (intersection-equal (svexlist-vars x) (svex-envlist-keyset envs)) vars) :hints ((set-reasoning)))) (define svex-envlist-check-boolmasks ((boolmasks svar-boolmasks-p) (envs svex-envlist-p)) (if (atom envs) t (and (svex-env-check-boolmasks boolmasks (make-fast-alist (car envs))) (svex-envlist-check-boolmasks boolmasks (cdr envs)))) /// (defthm svex-envlist-check-boolmasks-correct (implies (and (svex-envlist-check-boolmasks boolmasks envs) (member env envs) ;; (svex-env-p env) (svar-boolmasks-p boolmasks)) (svex-env-boolmasks-ok env boolmasks)))) (fty::deflist a4veclistlist :elt-type a4veclist :true-listp t) (define a4veclist/env-list-eval ((x a4veclistlist-p) (envs)) :guard (equal (len envs) (len x)) :returns (4vecs 4veclistlist-p) (if (atom x) nil (cons (a4veclist-eval (car x) (car envs)) (a4veclist/env-list-eval (cdr x) (cdr envs))))) (define svexlistlist->a4vec ((x svexlistlist-p) (env svex-a4vec-env-p) (masks svex-mask-alist-p)) :returns (a4vecs a4veclistlist-p) (if (atom x) nil (cons (svexlist->a4vec (car x) env masks) (svexlistlist->a4vec (cdr x) env masks)))) (define a4vec/svex-env-eval ((x a4veclist-p) (env svex-env-p) (svexes svexlist-p) (svars svarlist-p) (boolmasks svar-boolmasks-p)) :guard (svex-maskbits-ok svars (svexlist-mask-alist svexes)) :returns (4vecs 4veclist-p) :hooks ((:fix :args (x svexes svars))) (b* ((env (make-fast-alist env)) ((mv ?err aig-env) ;; ignore the error; it can't exist svex-maskbits-ok (svexlist->a4vec-aig-env-for-varlist svexes svars boolmasks env)) (?ign (fast-alist-free env)) (aig-env (make-fast-alist aig-env)) (ans (a4veclist-eval x aig-env))) (fast-alist-free aig-env) ans) /// (local (defthm not-svexlist-full-masks-p-by-member (implies (And (not (equal (sparseint-val (svex-mask-lookup x masks)) -1)) (member x svexes)) (not (svexlist-full-masks-p svexes masks))) :hints(("Goal" :in-theory (enable member svexlist-full-masks-p))))) (defthm svexlist-full-masks-p-when-subset (implies (and (subsetp-equal some-svexes svexes) (svexlist-full-masks-p svexes masks)) (svexlist-full-masks-p some-svexes masks)) :hints(("Goal" :in-theory (enable subsetp-equal svexlist-full-masks-p)))) (defret a4vec/svex-env-eval-correct :pre-bind ((masks (svexlist-mask-alist svexes)) ((mv ?err a4env) (svex-varmasks->a4env svars masks boolmasks1)) (x (svexlist->a4vec some-svexes a4env masks))) (implies (and (svex-maskbits-ok svars masks) (subsetp some-svexes svexes) (equal boolmasks (svar-boolmasks-fix boolmasks1)) (svex-env-boolmasks-ok env boolmasks) (subsetp (intersection-equal (svexlist-vars some-svexes) (alist-keys (svex-env-fix env))) (svarlist-fix svars))) (equal 4vecs (svexlist-eval some-svexes env))) :hints(("Goal" :in-theory (e/d (svexlist->a4vec-aig-env-for-varlist) (SVEXLIST->A4VEC-CORRECT)))))) (define a4veclist/svex-env-list-eval ((x a4veclistlist-p) (envs svex-envlist-p) (svexes svexlist-p) (svars svarlist-p) (boolmasks svar-boolmasks-p)) :guard (and (equal (len envs) (len x)) (svex-maskbits-ok svars (svexlist-mask-alist svexes))) :returns (4vecs 4veclistlist-p) :hooks ((:fix :args (x svexes svars))) (if (atom x) nil (cons (a4vec/svex-env-eval (car x) (car envs) svexes svars boolmasks) (a4veclist/svex-env-list-eval (cdr x) (cdr envs) svexes svars boolmasks))) /// (local (defthm alist-keys-of-svex-env-fix (equal (alist-keys (svex-env-fix env)) (svarlist-filter (alist-keys env))) :hints(("Goal" :in-theory (enable svex-env-fix svarlist-filter))))) (defret a4veclist/svex-env-list-eval-correct :pre-bind ((masks (svexlist-mask-alist svexes)) ((mv ?err a4env) (svex-varmasks->a4env svars masks boolmasks1)) (x (svexlistlist->a4vec some-svexes a4env masks))) (implies (and (svex-maskbits-ok svars masks) (equal (len envs) (len some-svexes)) (subsetp (append-lists some-svexes) svexes) (equal boolmasks (svar-boolmasks-fix boolmasks1)) (svex-envlist-check-boolmasks boolmasks envs) (subsetp (intersection-equal (svexlist-vars (append-lists some-svexes)) (svex-envlist-keyset envs)) (svarlist-fix svars))) (equal 4vecs (svexlist/env-list-eval some-svexes envs))) :hints (("goal" :induct (svexlist/env-list-eval some-svexes envs) :in-theory (e/d (svexlist/env-list-eval svex-envlist-check-boolmasks append-lists svex-envlist-keyset svexlistlist->a4vec)))))) (local (in-theory (enable svexlist->a4vecs-for-varlist))) (local (defthm a4veclistlist-p-of-extract-lists (implies (and (a4veclist-p list) (<= (sum-of-lengths x) (len list))) (a4veclistlist-p (extract-lists x list))) :hints (("goal" :use ((:functional-instance element-listlist-p-of-extract-lists (acl2::element-p a4vec-p) (acl2::element-list-p a4veclist-p) (acl2::element-list-final-cdr-p (lambda (x) (eq x nil))) (element-listlist-p a4veclistlist-p))))))) (defsection svexlist/env-list-eval-of-extract-of-rewrite (local (include-book "svex-equivs")) (local (define svex-eval-same-on-envs (x y envs) :verify-guards nil (if (atom envs) t (and (equal (svex-eval x (car envs)) (svex-eval y (car envs))) (svex-eval-same-on-envs x y (cdr envs)))) /// (defthm svex-eval-same-on-envs-implies-eval-same-with-member (implies (and (svex-eval-same-on-envs x y envs) (member env envs)) (equal (svex-eval x env) (svex-eval y env)))) (defthm svex-eval-same-on-envs-when-svex-eval-equiv (implies (svex-eval-equiv x y) (svex-eval-same-on-envs x y envs))))) (local (define svexlist-eval-same-on-envs (x y envs) :verify-guards nil (if (atom x) t (and (svex-eval-same-on-envs (car x) (car y) envs) (svexlist-eval-same-on-envs (cdr x) (cdr y) envs))) /// (defthm svexlist-eval-same-on-envs-implies-svexlist-eval-same-with-member (implies (and (svexlist-eval-same-on-envs x y envs) (member env envs) (equal (len x) (len y))) (equal (svexlist-eval x env) (svexlist-eval y env)))) (local (defun ind (n x y) (if (zp n) (list x y) (ind (1- n) (cdr x) (cdr y))))) (defthm svex-eval-same-on-envs-of-nth-when-svexlist-eval-same-on-envs (implies (and (svexlist-eval-same-on-envs x y envs) (< (nfix n) (len x))) (svex-eval-same-on-envs (nth n x) (nth n y) envs)) :hints(("Goal" :in-theory (enable nth svex-eval-same-on-envs) :induct (ind n x y)))) (local (defthm svexlist-eval-equiv-implies-svex-eval-equiv-car (implies (and (svexlist-eval-equiv x y) (consp x)) (equal (svex-eval-equiv (car x) (car y)) t)) :hints (("goal" :in-theory (enable svex-eval-equiv))))) (defthm svexlist-eval-same-on-envs-when-svexlist-eval-equiv (implies (svexlist-eval-equiv x y) (svexlist-eval-same-on-envs x y envs))) (defthm svexlist-eval-same-on-envs-of-atom (implies (atom envs) (svexlist-eval-same-on-envs x y envs)) :hints(("Goal" :in-theory (enable svex-eval-same-on-envs)))) (defthm svexlist-eval-same-on-envs-of-consp (implies (and (consp envs) (equal (len x) (len y)) (svexlist-eval-same-on-envs x y (cdr envs))) (iff (svexlist-eval-same-on-envs x y envs) (equal (svexlist-eval x (car envs)) (svexlist-eval y (car envs))))) :hints(("Goal" :in-theory (enable svex-eval-same-on-envs)))))) (local (define svexlistlist-eval-same-on-envs (x y envs) :verify-guards nil (if (atom x) t (and (svexlist-eval-same-on-envs (car x) (car y) envs) (svexlistlist-eval-same-on-envs (cdr x) (cdr y) envs))) /// (local (defun ind (x y envs1) (if (atom x) (list y envs1) (ind (cdr x) (cdr y) (cdr envs1))))) ;; (defthm svexlistlist-eval-same-on-envs-implies-svexlist-eval-same-with-member ;; (implies (and (svexlistlist-eval-same-on-envs x y envs) ;; (member env envs) ;; (equal (len x) (len y))) ;; (equal (svexlist-eval x env) ;; (svexlist-eval y env)))) (defthm svexlist/env-list-eval-when-svexlistlist-eval-same-on-envs (implies (and (svexlistlist-eval-same-on-envs x y envs) (subsetp envs1 envs) (equal (len x) (len y)) (lengths-equal x y) (equal (len x) (len envs1))) (equal (svexlist/env-list-eval x envs1) (svexlist/env-list-eval y envs1))) :hints(("Goal" :in-theory (enable svexlist/env-list-eval subsetp-equal lengths-equal) :induct (ind x y envs1)))))) (local (defthm svexlist-eval-equiv-of-maybe-svexlist-rewrite-fixpoint (svexlist-eval-equiv (maybe-svexlist-rewrite-fixpoint x do-it) x) :hints(("Goal" :in-theory (enable svexlist-eval-equiv))))) (local (defthm alist-keys-of-svex-env-fix (equal (alist-keys (svex-env-fix env)) (svarlist-filter (alist-keys env))) :hints(("Goal" :in-theory (enable svex-env-fix svarlist-filter))))) (local (defthm svexlist-eval-equiv-of-svexlist-x-out-unused-vars (implies (subsetp (intersection-equal (svexlist-vars x) (svex-envlist-keyset envs)) (svarlist-fix svars)) (svexlist-eval-same-on-envs x (maybe-svexlist-rewrite-fixpoint (svexlist-x-out-unused-vars x svars do-it) do-it1) envs)) :hints(("Goal" :in-theory (e/d (svex-envlist-keyset) ()) :induct (len envs))))) (local (defthm svex-eval-equiv-listlist-of-extract-lists-of-rewrite (implies (subsetp (intersection-equal (svexlist-vars (append-lists x)) (svex-envlist-keyset envs)) (svarlist-fix svars)) (svexlistlist-eval-same-on-envs x (extract-lists x (maybe-svexlist-rewrite-fixpoint (svexlist-x-out-unused-vars (append-lists x) svars do-it1) do-it)) envs)) :hints (("goal" :use ((:functional-instance extract-lists-of-pseudoproj (pseudoproj (lambda (x) (if (subsetp (intersection-equal (svexlist-vars x) (svex-envlist-keyset envs)) (svarlist-fix svars)) (maybe-svexlist-rewrite-fixpoint (svexlist-x-out-unused-vars x svars do-it1) do-it) x))) (pseudoproj-relation (lambda (x y) (svex-eval-same-on-envs x y envs))) (pseudoproj-relation-list (lambda (x y) (svexlist-eval-same-on-envs x y envs))) (pseudoproj-relation-listlist (lambda (x y) (svexlistlist-eval-same-on-envs x y envs)))))) (and stable-under-simplificationp '(:in-theory (enable svexlist-eval-same-on-envs svexlistlist-eval-same-on-envs)))))) (defthm svexlist/env-list-eval-of-extract-lists-of-rewrite (implies (and (subsetp (intersection-equal (svexlist-vars (append-lists x)) (svex-envlist-keyset envs)) (svarlist-fix svars)) (equal (len envs) (len x))) (equal (svexlist/env-list-eval (extract-lists x (maybe-svexlist-rewrite-fixpoint (svexlist-x-out-unused-vars (append-lists x) svars do-it1) do-it)) envs) (svexlist/env-list-eval x envs))) :hints (("goal" :use ((:instance svexlist/env-list-eval-when-svexlistlist-eval-same-on-envs (x x) (y (extract-lists x (maybe-svexlist-rewrite-fixpoint (svexlist-x-out-unused-vars (append-lists x) svars do-it1) do-it))) (envs envs) (envs1 envs))) :in-theory (disable svexlist/env-list-eval-when-svexlistlist-eval-same-on-envs) :do-not-induct t)))) (define svexlist/env-list-eval-gl ((x svexlistlist-p "Svex expressions to evaluate.") (envs svex-envlist-p "Bindings of variables to @(see 4vec) values.") (symbolic-params alistp "Alist giving symbolic execution parameters; see below.")) :short "Equivalent of svexlist/env-list-eval intended to work well under GL symbolic execution." :long " <p>This function is provably equivalent to @('svexlist/env-list-eval'), but is tailored to perform well under symbolic execution. For symbolic execution, we assume that the inputs to this function other than @('envs') are fully concrete, and that each @('envs') are symbolic only in its values, not its keys or its shape.</p> <p>It is analogous to @(see svexlist-eval-gl), but the individual lists of svexes within @('x') are each evaluated with the corresponding element of @('envs'). Symbolic execution is set up so that the svexes are all rendered into AIGs in a batch with memoization between all the lists.</p> <p>The @('symbolic-params') input behaves as it does in @(see svexlist-eval-gl). However, the @(':boolmasks') and @(':vars') entries must be applicable to all environments in the list. That is, for each entry in the boolmasks, the corresponding key must be bound in every entry in the envs to a symbolic 4vec value that is (syntactically) Boolean-valued in the masked bits. Similarly, the @(':vars') entry, if given, is unioned with the variables bound in all environments.</p>" :guard-hints (("goal" :in-theory (e/d (SET::UNION-WITH-SUBSET-LEFT) (SUBSET-OF-MERGESORTS-IS-SUBSETP)))) :guard-debug t (b* ((envs (take (len x) envs)) (x (svexlistlist-fix x)) (svexes (append-lists x)) (svars (svexlist/env-list-vars-for-symbolic-eval svexes envs symbolic-params)) (svexes (svexlist-x-out-unused-vars svexes svars (symbolic-params-x-out-cond symbolic-params))) (svexes (maybe-svexlist-rewrite-fixpoint svexes (cdr (assoc :simplify symbolic-params)))) (boolmasks (make-fast-alist (hons-copy (ec-call (svar-boolmasks-fix (cdr (assoc :boolmasks symbolic-params))))))) ((unless (svex-envlist-check-boolmasks boolmasks envs)) (b* ((?ign (cw "ERROR: some bits assumed to be Boolean were not~%")) (?ign (gl::gl-error 'boolcheck-failed))) (gl::gl-hide (svexlist/env-list-eval x envs)))) ((mv err a4vecs) (time$ (svexlist->a4vecs-for-varlist svexes svars boolmasks) :msg "; svex->aigs: ~st sec, ~sa bytes.~%")) ((when err) (b* ((?ign (cw "ERROR gathering AIG bits for variables: ~@0~%" err)) (?ign (gl::gl-error 'a4env-failed))) (gl::gl-hide (svexlist/env-list-eval x envs)))) (a4veclist-list (extract-lists x a4vecs))) (a4veclist/svex-env-list-eval a4veclist-list envs svexes svars boolmasks)) /// (local (defthm svexlist/env-list-eval-of-take (equal (svexlist/env-list-eval x (take (len x) envs)) (svexlist/env-list-eval x envs)) :hints(("Goal" :in-theory (enable svexlist/env-list-eval))))) (local (defthm extract-lists-of-svexlist->a4vec (implies (<= (sum-of-lengths x) (len y)) (equal (extract-lists x (svexlist->a4vec y env masks)) (svexlistlist->a4vec (extract-lists x y) env masks))) :hints (("goal" :use ((:functional-instance extract-lists-of-projection (acl2::element-p (lambda (x) t)) (acl2::outelement-p (lambda (x) t)) (acl2::outelement-example (lambda () t)) (acl2::element-xformer (lambda (x) (svex->a4vec x env masks))) (acl2::elementlist-projection (lambda (x) (svexlist->a4vec x env masks))) (elementlistlist-projection (lambda (x) (svexlistlist->a4vec x env masks))))) :in-theory (enable svexlistlist->a4vec svexlist->a4vec))))) (local (defthm vars-subset-lemma (b* ((vars (SVEXLIST/ENV-LIST-VARS-FOR-SYMBOLIC-EVAL svexes envs params))) (SUBSETP-EQUAL (INTERSECTION-EQUAL (SVEXLIST-VARS (MAYBE-SVEXLIST-REWRITE-FIXPOINT (SVEXLIST-X-OUT-UNUSED-VARS svexes vars x-out) simp)) (SVEX-ENVLIST-KEYSET envs)) vars)) :hints (("goal" :use ((:instance svexlist/env-list-vars-for-symbolic-eval-sufficient (x svexes) (symbolic-params params))) :in-theory (disable svexlist/env-list-vars-for-symbolic-eval-sufficient)) (set-reasoning)))) (defthm svexlist/env-list-eval-gl-correct (equal (svexlist/env-list-eval-gl x envs symbolic-params) (svexlist/env-list-eval x envs)) :hints (("goal" :do-not-induct t))) (gl::def-gl-rewrite svexlist/env-list-eval-for-symbolic-redef (equal (svexlist/env-list-eval x envs) (svexlist/env-list-eval-gl x envs nil))))
[ { "context": "ncodings and mappings.\n;;;\n;;; Copyright (C) 2007, Luis Oliveira <[email protected]>\n;;;\n;;; Permission i", "end": 149, "score": 0.9998555183410645, "start": 136, "tag": "NAME", "value": "Luis Oliveira" }, { "context": "ings.\n;;;\n;;; Copyright (C) 2007, Luis Oliveira <[email protected]>\n;;;\n;;; Permission is hereby granted, free of ch", "end": 177, "score": 0.9999306797981262, "start": 152, "tag": "EMAIL", "value": "[email protected]" } ]
libs/babel_0.3.0/src/encodings.lisp
mtstickney/plain-odbc
0
;;;; -*- Mode: lisp; indent-tabs-mode: nil -*- ;;; ;;; encodings.lisp --- Character encodings and mappings. ;;; ;;; Copyright (C) 2007, Luis Oliveira <[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 #:babel-encodings) ;;;; Character Encodings (defclass character-encoding () ((name :initarg :name :reader enc-name :initform (error "Must specify a NAME for this character encoding.")) ;; Most of these documentation strings are taken from OpenMCL. (documentation :initarg :documentation :reader enc-documentation :initform nil) ;; A non-exhaustive list of aliases for the encoding. (aliases :initarg :aliases :initform nil :reader enc-aliases) ;; Specified in bits. Usually 8, 16 or 32. (code-unit-size :initarg :code-unit-size :reader enc-code-unit-size :initform 8) (max-units-per-char :initarg :max-units-per-char :reader enc-max-units-per-char :initform 1) ;; If NIL, it is necessary to swap 16- and 32-bit units. (native-endianness :initarg :native-endianness :reader enc-native-endianness :initform t) ;; Code units less than this value map to themselves on input. (decode-literal-code-unit-limit :initarg :decode-literal-code-unit-limit :initform 0 :reader enc-decode-literal-code-unit-limit) ;; Code points less than this value map to themselves on output. (encode-literal-code-unit-limit :initarg :encode-literal-code-unit-limit :initform 0 :reader enc-encode-literal-code-unit-limit) ;; Defines whether it is necessary to prepend a byte-order-mark to ;; determine the endianness. (use-bom :initarg :use-bom :initform nil :reader enc-use-bom) ;; How the byte-order-mark should be encoded, specified as a ;; sequence of octets. NIL if it cannot be encoded. (bom-encoding :initarg :bom-encoding :reader enc-bom-encoding :initform nil) ;; How should NUL be encoded, specified as sequence of octets. (nul-encoding :initarg :nul-encoding :reader enc-nul-encoding :initform #(0)) ;; Preferred replacement character code point. (default-replacement :initarg :default-replacement :reader enc-default-replacement :initform #x1a))) ;;; I'm too lazy to write all the identical limits twice. (defmethod initialize-instance :after ((enc character-encoding) &key literal-char-code-limit) (when literal-char-code-limit (setf (slot-value enc 'encode-literal-code-unit-limit) literal-char-code-limit) (setf (slot-value enc 'decode-literal-code-unit-limit) literal-char-code-limit))) #-(and) (defmethod describe-object ((enc character-encoding) s) "Prints out the name, aliases and documentation slots of a character encoding object." (with-slots (name aliases documentation) enc (format s "~&~S" name) (when aliases (format s " [Aliases:~{ ~S~}]" aliases)) (format s "~&~A~%~%" documentation)) (call-next-method)) (defvar *supported-character-encodings* nil) (defun list-character-encodings () "List of keyword symbols denoting supported character encodings. This list does not include aliases." *supported-character-encodings*) (defvar *character-encodings* (make-hash-table :test 'eq)) (defvar *default-character-encoding* :utf-8 "Special variable used to determine the default character encoding.") (defun get-character-encoding (name) "Lookups the character encoding denoted by the keyword symbol NAME. Signals an error if one is not found. If NAME is already a CHARACTER-ENCONDING object, it is returned unmodified." (when (typep name 'character-encoding) (return-from get-character-encoding name)) (when (eq name :default) (setq name *default-character-encoding*)) (or (gethash name *character-encodings*) (error "Unknown character encoding: ~S" name))) (defun notice-character-encoding (enc) (pushnew (enc-name enc) *supported-character-encodings*) (dolist (kw (cons (enc-name enc) (enc-aliases enc))) (setf (gethash kw *character-encodings*) enc)) (enc-name enc)) (defmacro define-character-encoding (name docstring &body options) `(notice-character-encoding (make-instance 'character-encoding :name ,name ,@options :documentation ,docstring))) ;;;; Mappings ;;; TODO: describe what mappings are (defun 8-bit-fixed-width-counter (getter type) (declare (ignore getter type)) `(lambda (seq start end max) (declare (ignore seq) (fixnum start end max)) (if (plusp max) (let ((count (the fixnum (min max (the fixnum (- end start)))))) (values count (the fixnum (+ start count)))) (values (the fixnum (- end start)) end)))) ;;; Useful to develop new encodings incrementally starting with octet ;;; and code-unit counters. (defun dummy-coder (sg st ds dt) (declare (ignore sg st ds dt)) `(lambda (src s e dest i) (declare (ignore src s e dest i)) (error "this encoder/decoder hasn't been implemented yet"))) (defclass mapping () ((encoder :accessor encoder :initform #'dummy-coder) (decoder :accessor decoder :initform #'dummy-coder) (octet-counter :accessor octet-counter :initform #'8-bit-fixed-width-counter) (code-point-counter :accessor code-point-counter :initform #'8-bit-fixed-width-counter))) ;;; TODO: document here ;;; ;;; ENCODER -- (lambda (src-getter src-type dest-setter dest-type) ...) ;;; DECODER -- (lambda (src-getter src-type dest-setter dest-type) ...) ;;; ;;; OCTET-COUNTER -- (lambda (getter type) ...) ;;; CODE-POINT-COUNTER -- (lambda (getter type) ...) (defclass abstract-mapping (mapping) ()) ;;; TODO: document these ;;; ;;; ENCODER -- (lambda (src start end dest d-start) ...) ;;; DECODER -- (lambda (src start end dest d-start) ...) ;;; ;;; OCTET-COUNTER -- (lambda (seq start end max-octets) ...) ;;; CODE-POINT-COUNTER -- (lambda (seq start end max-chars) ...) ;;; => N-CHARS NEW-END ;;; (important: describe NEW-END) (defclass concrete-mapping (mapping) ()) (defvar *abstract-mappings* (make-hash-table :test 'eq)) (defun get-abstract-mapping (encoding) (gethash encoding *abstract-mappings*)) (defun (setf get-abstract-mapping) (value encoding) (setf (gethash encoding *abstract-mappings*) value)) (defun register-mapping (encoding slot-name fn) (let ((m (get-abstract-mapping encoding))) (when (null m) (setq m (make-instance 'abstract-mapping)) (setf (get-abstract-mapping encoding) m)) (setf (slot-value m slot-name) fn))) ;;; See enc-*.lisp for example usages of these 4 macros. (defmacro define-encoder (encoding (sa st da dt) &body body) `(register-mapping ,encoding 'encoder (lambda (,sa ,st ,da ,dt) ,@body))) (defmacro define-decoder (encoding (sa st da dt) &body body) `(register-mapping ,encoding 'decoder (lambda (,sa ,st ,da ,dt) ,@body))) (defmacro define-octet-counter (encoding (acc type) &body body) `(register-mapping ,encoding 'octet-counter (lambda (,acc ,type) ,@body))) (defmacro define-code-point-counter (encoding (acc type) &body body) `(register-mapping ,encoding 'code-point-counter (lambda (,acc ,type) ,@body))) ;;; Funcalls (at macro-expansion time) the abstract mappings with the ;;; src/dest accessors and types which generate the appropriate code ;;; for the concrete mappings. These functions are then saved in ;;; their respective slots of the CONCRETE-MAPPING object. (defun %am-to-cm (cm am osg oss ost cpsg cpss cpst) `(setf (encoder ,cm) ,(funcall (encoder am) cpsg cpst oss ost) (decoder ,cm) ,(funcall (decoder am) osg ost cpss cpst) (code-point-counter ,cm) ,(funcall (code-point-counter am) osg ost) (octet-counter ,cm) ,(funcall (octet-counter am) cpsg cpst))) ;;; Expands into code generated by the available abstract mappings ;;; that will be compiled into concrete mappings. This is used in ;;; e.g. strings.lisp to define mappings between strings and ;;; (unsigned-byte 8) vectors. (defmacro instantiate-concrete-mappings (&key optimize octet-seq-getter octet-seq-setter octet-seq-type code-point-seq-getter code-point-seq-setter code-point-seq-type) `(let ((ht (make-hash-table :test 'eq))) (declare (optimize ,@optimize)) (flet ((notice-mapping (enc-name cm) (let ((aliases (enc-aliases (get-character-encoding enc-name)))) (dolist (kw (cons enc-name aliases)) (setf (gethash kw ht) cm))))) ,@(loop for am being the hash-values of *abstract-mappings* using (hash-key enc) collect `(let ((cm (make-instance 'concrete-mapping))) ,(%am-to-cm 'cm am octet-seq-getter octet-seq-setter octet-seq-type code-point-seq-getter code-point-seq-setter code-point-seq-type) (notice-mapping ,enc cm)))) ht)) ;;;; Utilities used in enc-*.lisp (defconstant +sub+ #x1a "ASCII substitution character code point.") ;;; We're converting between objects of the (UNSIGNED-BYTE 8) and ;;; (MOD #x110000) types which are aliased here to UB8 and CODE-POINT ;;; for convenience. (deftype ub8 () '(unsigned-byte 8)) (deftype code-point () '(mod #x110000)) ;;; Utility macro around DEFINE-ENCODER that takes care of most of the ;;; work need to deal with an 8-bit, fixed-width character encoding. ;;; ;;; BODY will be inside a loop and its return value will placed in the ;;; destination buffer. BODY will be surounded by lexical BLOCK which ;;; will have the ENCODING's name, usually a keyword. It handles all ;;; sorts of type declarations. ;;; ;;; See enc-ascii.lisp for a simple usage example. (defmacro define-unibyte-encoder (encoding (code) &body body) (with-unique-names (s-getter s-type d-setter d-type src start end dest d-start i di) `(define-encoder ,encoding (,s-getter ,s-type ,d-setter ,d-type) `(lambda (,',src ,',start ,',end ,',dest ,',d-start) (declare (type ,,s-type ,',src) (type ,,d-type ,',dest) (fixnum ,',start ,',end ,',d-start)) (loop for ,',i fixnum from ,',start below ,',end and ,',di fixnum from ,',d-start do (,,d-setter (macrolet ;; this should probably be a function... ((handle-error (&optional (c ''character-encoding-error)) `(encoding-error ,',',code ,',',encoding ,',',src ,',',i +sub+ ,c))) (let ((,',code (,,s-getter ,',src ,',i))) (declare (type code-point ,',code)) (block ,',encoding ,@',body))) ,',dest ,',di) finally (return (the fixnum (- ,',d-start ,',di)))))))) ;;; The decoder version of the above macro. (defmacro define-unibyte-decoder (encoding (octet) &body body) (with-unique-names (s-getter s-type d-setter d-type src start end dest d-start i di) `(define-decoder ,encoding (,s-getter ,s-type ,d-setter ,d-type) `(lambda (,',src ,',start ,',end ,',dest ,',d-start) (declare (type ,,s-type ,',src) (type ,,d-type ,',dest) (fixnum ,',start ,',end ,',d-start)) (loop for ,',i fixnum from ,',start below ,',end and ,',di fixnum from ,',d-start do (,,d-setter (macrolet ;; this should probably be a function... ((handle-error (&optional (c ''character-decoding-error)) `(decoding-error (vector ,',',octet) ,',',encoding ,',',src ,',',i +sub+ ,c))) (let ((,',octet (,,s-getter ,',src ,',i))) (declare (type ub8 ,',octet)) (block ,',encoding ,@',body))) ,',dest ,',di) finally (return (the fixnum (- ,',d-start ,',di)))))))) ;;;; Error Conditions ;;; ;;; For now, we don't define any actual restarts. The only mechanism ;;; for "restarting" a coding error is the ;;; *SUPPRESS-CHARACTER-CODING-ERRORS* special variable which, when ;;; bound to T (the default), suppresses any error and uses a default ;;; replacement character instead. ;;; ;;; If it turns out that other more options are necessary, possible ;;; alternative approaches include: ;;; ;;; a) use a *REPLACEMENT-CHARACTER* special variable that lets us ;;; pick our own replacement character. The encoder must do ;;; additional work to check if this is character is encodable. ;;; ;;; b) offer a restart to pick a replacement character. Same ;;; problem as above. ;;; ;;; Both approaches pose encoding problems when dealing with a ;;; variable-width encodings because different replacement characters ;;; will need different numbers of octets. This is not a problem for ;;; UTF but will be a problem for the CJK charsets. Approach (a) is ;;; nevertheless easier since the replacement character is known in ;;; advance and therefore the octet-counter can account for it. ;;; ;;; For more complex restarts like SBCL's -- that'll let you specify ;;; _several_ replacement characters for a single character error -- ;;; will probably need extra support code outside the encoder/decoder ;;; (i.e. in the string-to-octets function, for example) since the ;;; encoders/decoders deal with pre-allocated fixed-length buffers. ;;; ;;; SBCL has ASCII-specific (MALFORMED-ASCII) and UTF8-specific ;;; errors. Why? Do we want to add some of those too? ;;; FIXME: We used to deal with this with an extra ERRORP argument for ;;; encoders, decoders, etc... Still undecided on the best way to do ;;; it. We could also use a simple restart instead of this... ;;; ;;; In any case, this is not for the users to bind and it's not ;;; exported from the BABEL package. (defvar *suppress-character-coding-errors* nil "If non-NIL, encoding or decoding errors are suppressed and the the current character encoding's default replacement character is used.") ;;; All of Babel's error conditions are subtypes of ;;; CHARACTER-CODING-ERROR. This error hierarchy is based on SBCL's. (define-condition character-coding-error (error) ((buffer :initarg :buffer :reader character-coding-error-buffer) (position :initarg :position :reader character-coding-error-position) (encoding :initarg :encoding :reader character-coding-error-encoding))) (define-condition character-encoding-error (character-coding-error) ((code :initarg :code :reader character-encoding-error-code)) (:report (lambda (c s) (format s "Unable to encode character code point ~A as ~S." (character-encoding-error-code c) (character-coding-error-encoding c))))) (declaim (inline encoding-error)) (defun encoding-error (code enc buf pos &optional (sub +sub+) (e 'character-encoding-error)) (unless *suppress-character-coding-errors* (error e :encoding enc :buffer buf :position pos :code code)) sub) (define-condition character-decoding-error (character-coding-error) ((octets :initarg :octets :reader character-decoding-error-octets)) (:report (lambda (c s) (format s "Illegal ~S character starting at position ~D." (character-coding-error-encoding c) (character-coding-error-position c))))) (define-condition end-of-input-in-character (character-decoding-error) () (:documentation "Signalled by DECODERs or CODE-POINT-COUNTERs of variable-width character encodings.")) (define-condition character-out-of-range (character-decoding-error) () (:documentation "Signalled when the character being decoded is out of range.")) (declaim (inline decoding-error)) (defun decoding-error (octets enc buf pos &optional (sub +sub+) (e 'character-decoding-error)) (unless *suppress-character-coding-errors* (error e :octets octets :encoding enc :buffer buf :position pos)) sub)
49926
;;;; -*- Mode: lisp; indent-tabs-mode: nil -*- ;;; ;;; encodings.lisp --- Character encodings and mappings. ;;; ;;; Copyright (C) 2007, <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 #:babel-encodings) ;;;; Character Encodings (defclass character-encoding () ((name :initarg :name :reader enc-name :initform (error "Must specify a NAME for this character encoding.")) ;; Most of these documentation strings are taken from OpenMCL. (documentation :initarg :documentation :reader enc-documentation :initform nil) ;; A non-exhaustive list of aliases for the encoding. (aliases :initarg :aliases :initform nil :reader enc-aliases) ;; Specified in bits. Usually 8, 16 or 32. (code-unit-size :initarg :code-unit-size :reader enc-code-unit-size :initform 8) (max-units-per-char :initarg :max-units-per-char :reader enc-max-units-per-char :initform 1) ;; If NIL, it is necessary to swap 16- and 32-bit units. (native-endianness :initarg :native-endianness :reader enc-native-endianness :initform t) ;; Code units less than this value map to themselves on input. (decode-literal-code-unit-limit :initarg :decode-literal-code-unit-limit :initform 0 :reader enc-decode-literal-code-unit-limit) ;; Code points less than this value map to themselves on output. (encode-literal-code-unit-limit :initarg :encode-literal-code-unit-limit :initform 0 :reader enc-encode-literal-code-unit-limit) ;; Defines whether it is necessary to prepend a byte-order-mark to ;; determine the endianness. (use-bom :initarg :use-bom :initform nil :reader enc-use-bom) ;; How the byte-order-mark should be encoded, specified as a ;; sequence of octets. NIL if it cannot be encoded. (bom-encoding :initarg :bom-encoding :reader enc-bom-encoding :initform nil) ;; How should NUL be encoded, specified as sequence of octets. (nul-encoding :initarg :nul-encoding :reader enc-nul-encoding :initform #(0)) ;; Preferred replacement character code point. (default-replacement :initarg :default-replacement :reader enc-default-replacement :initform #x1a))) ;;; I'm too lazy to write all the identical limits twice. (defmethod initialize-instance :after ((enc character-encoding) &key literal-char-code-limit) (when literal-char-code-limit (setf (slot-value enc 'encode-literal-code-unit-limit) literal-char-code-limit) (setf (slot-value enc 'decode-literal-code-unit-limit) literal-char-code-limit))) #-(and) (defmethod describe-object ((enc character-encoding) s) "Prints out the name, aliases and documentation slots of a character encoding object." (with-slots (name aliases documentation) enc (format s "~&~S" name) (when aliases (format s " [Aliases:~{ ~S~}]" aliases)) (format s "~&~A~%~%" documentation)) (call-next-method)) (defvar *supported-character-encodings* nil) (defun list-character-encodings () "List of keyword symbols denoting supported character encodings. This list does not include aliases." *supported-character-encodings*) (defvar *character-encodings* (make-hash-table :test 'eq)) (defvar *default-character-encoding* :utf-8 "Special variable used to determine the default character encoding.") (defun get-character-encoding (name) "Lookups the character encoding denoted by the keyword symbol NAME. Signals an error if one is not found. If NAME is already a CHARACTER-ENCONDING object, it is returned unmodified." (when (typep name 'character-encoding) (return-from get-character-encoding name)) (when (eq name :default) (setq name *default-character-encoding*)) (or (gethash name *character-encodings*) (error "Unknown character encoding: ~S" name))) (defun notice-character-encoding (enc) (pushnew (enc-name enc) *supported-character-encodings*) (dolist (kw (cons (enc-name enc) (enc-aliases enc))) (setf (gethash kw *character-encodings*) enc)) (enc-name enc)) (defmacro define-character-encoding (name docstring &body options) `(notice-character-encoding (make-instance 'character-encoding :name ,name ,@options :documentation ,docstring))) ;;;; Mappings ;;; TODO: describe what mappings are (defun 8-bit-fixed-width-counter (getter type) (declare (ignore getter type)) `(lambda (seq start end max) (declare (ignore seq) (fixnum start end max)) (if (plusp max) (let ((count (the fixnum (min max (the fixnum (- end start)))))) (values count (the fixnum (+ start count)))) (values (the fixnum (- end start)) end)))) ;;; Useful to develop new encodings incrementally starting with octet ;;; and code-unit counters. (defun dummy-coder (sg st ds dt) (declare (ignore sg st ds dt)) `(lambda (src s e dest i) (declare (ignore src s e dest i)) (error "this encoder/decoder hasn't been implemented yet"))) (defclass mapping () ((encoder :accessor encoder :initform #'dummy-coder) (decoder :accessor decoder :initform #'dummy-coder) (octet-counter :accessor octet-counter :initform #'8-bit-fixed-width-counter) (code-point-counter :accessor code-point-counter :initform #'8-bit-fixed-width-counter))) ;;; TODO: document here ;;; ;;; ENCODER -- (lambda (src-getter src-type dest-setter dest-type) ...) ;;; DECODER -- (lambda (src-getter src-type dest-setter dest-type) ...) ;;; ;;; OCTET-COUNTER -- (lambda (getter type) ...) ;;; CODE-POINT-COUNTER -- (lambda (getter type) ...) (defclass abstract-mapping (mapping) ()) ;;; TODO: document these ;;; ;;; ENCODER -- (lambda (src start end dest d-start) ...) ;;; DECODER -- (lambda (src start end dest d-start) ...) ;;; ;;; OCTET-COUNTER -- (lambda (seq start end max-octets) ...) ;;; CODE-POINT-COUNTER -- (lambda (seq start end max-chars) ...) ;;; => N-CHARS NEW-END ;;; (important: describe NEW-END) (defclass concrete-mapping (mapping) ()) (defvar *abstract-mappings* (make-hash-table :test 'eq)) (defun get-abstract-mapping (encoding) (gethash encoding *abstract-mappings*)) (defun (setf get-abstract-mapping) (value encoding) (setf (gethash encoding *abstract-mappings*) value)) (defun register-mapping (encoding slot-name fn) (let ((m (get-abstract-mapping encoding))) (when (null m) (setq m (make-instance 'abstract-mapping)) (setf (get-abstract-mapping encoding) m)) (setf (slot-value m slot-name) fn))) ;;; See enc-*.lisp for example usages of these 4 macros. (defmacro define-encoder (encoding (sa st da dt) &body body) `(register-mapping ,encoding 'encoder (lambda (,sa ,st ,da ,dt) ,@body))) (defmacro define-decoder (encoding (sa st da dt) &body body) `(register-mapping ,encoding 'decoder (lambda (,sa ,st ,da ,dt) ,@body))) (defmacro define-octet-counter (encoding (acc type) &body body) `(register-mapping ,encoding 'octet-counter (lambda (,acc ,type) ,@body))) (defmacro define-code-point-counter (encoding (acc type) &body body) `(register-mapping ,encoding 'code-point-counter (lambda (,acc ,type) ,@body))) ;;; Funcalls (at macro-expansion time) the abstract mappings with the ;;; src/dest accessors and types which generate the appropriate code ;;; for the concrete mappings. These functions are then saved in ;;; their respective slots of the CONCRETE-MAPPING object. (defun %am-to-cm (cm am osg oss ost cpsg cpss cpst) `(setf (encoder ,cm) ,(funcall (encoder am) cpsg cpst oss ost) (decoder ,cm) ,(funcall (decoder am) osg ost cpss cpst) (code-point-counter ,cm) ,(funcall (code-point-counter am) osg ost) (octet-counter ,cm) ,(funcall (octet-counter am) cpsg cpst))) ;;; Expands into code generated by the available abstract mappings ;;; that will be compiled into concrete mappings. This is used in ;;; e.g. strings.lisp to define mappings between strings and ;;; (unsigned-byte 8) vectors. (defmacro instantiate-concrete-mappings (&key optimize octet-seq-getter octet-seq-setter octet-seq-type code-point-seq-getter code-point-seq-setter code-point-seq-type) `(let ((ht (make-hash-table :test 'eq))) (declare (optimize ,@optimize)) (flet ((notice-mapping (enc-name cm) (let ((aliases (enc-aliases (get-character-encoding enc-name)))) (dolist (kw (cons enc-name aliases)) (setf (gethash kw ht) cm))))) ,@(loop for am being the hash-values of *abstract-mappings* using (hash-key enc) collect `(let ((cm (make-instance 'concrete-mapping))) ,(%am-to-cm 'cm am octet-seq-getter octet-seq-setter octet-seq-type code-point-seq-getter code-point-seq-setter code-point-seq-type) (notice-mapping ,enc cm)))) ht)) ;;;; Utilities used in enc-*.lisp (defconstant +sub+ #x1a "ASCII substitution character code point.") ;;; We're converting between objects of the (UNSIGNED-BYTE 8) and ;;; (MOD #x110000) types which are aliased here to UB8 and CODE-POINT ;;; for convenience. (deftype ub8 () '(unsigned-byte 8)) (deftype code-point () '(mod #x110000)) ;;; Utility macro around DEFINE-ENCODER that takes care of most of the ;;; work need to deal with an 8-bit, fixed-width character encoding. ;;; ;;; BODY will be inside a loop and its return value will placed in the ;;; destination buffer. BODY will be surounded by lexical BLOCK which ;;; will have the ENCODING's name, usually a keyword. It handles all ;;; sorts of type declarations. ;;; ;;; See enc-ascii.lisp for a simple usage example. (defmacro define-unibyte-encoder (encoding (code) &body body) (with-unique-names (s-getter s-type d-setter d-type src start end dest d-start i di) `(define-encoder ,encoding (,s-getter ,s-type ,d-setter ,d-type) `(lambda (,',src ,',start ,',end ,',dest ,',d-start) (declare (type ,,s-type ,',src) (type ,,d-type ,',dest) (fixnum ,',start ,',end ,',d-start)) (loop for ,',i fixnum from ,',start below ,',end and ,',di fixnum from ,',d-start do (,,d-setter (macrolet ;; this should probably be a function... ((handle-error (&optional (c ''character-encoding-error)) `(encoding-error ,',',code ,',',encoding ,',',src ,',',i +sub+ ,c))) (let ((,',code (,,s-getter ,',src ,',i))) (declare (type code-point ,',code)) (block ,',encoding ,@',body))) ,',dest ,',di) finally (return (the fixnum (- ,',d-start ,',di)))))))) ;;; The decoder version of the above macro. (defmacro define-unibyte-decoder (encoding (octet) &body body) (with-unique-names (s-getter s-type d-setter d-type src start end dest d-start i di) `(define-decoder ,encoding (,s-getter ,s-type ,d-setter ,d-type) `(lambda (,',src ,',start ,',end ,',dest ,',d-start) (declare (type ,,s-type ,',src) (type ,,d-type ,',dest) (fixnum ,',start ,',end ,',d-start)) (loop for ,',i fixnum from ,',start below ,',end and ,',di fixnum from ,',d-start do (,,d-setter (macrolet ;; this should probably be a function... ((handle-error (&optional (c ''character-decoding-error)) `(decoding-error (vector ,',',octet) ,',',encoding ,',',src ,',',i +sub+ ,c))) (let ((,',octet (,,s-getter ,',src ,',i))) (declare (type ub8 ,',octet)) (block ,',encoding ,@',body))) ,',dest ,',di) finally (return (the fixnum (- ,',d-start ,',di)))))))) ;;;; Error Conditions ;;; ;;; For now, we don't define any actual restarts. The only mechanism ;;; for "restarting" a coding error is the ;;; *SUPPRESS-CHARACTER-CODING-ERRORS* special variable which, when ;;; bound to T (the default), suppresses any error and uses a default ;;; replacement character instead. ;;; ;;; If it turns out that other more options are necessary, possible ;;; alternative approaches include: ;;; ;;; a) use a *REPLACEMENT-CHARACTER* special variable that lets us ;;; pick our own replacement character. The encoder must do ;;; additional work to check if this is character is encodable. ;;; ;;; b) offer a restart to pick a replacement character. Same ;;; problem as above. ;;; ;;; Both approaches pose encoding problems when dealing with a ;;; variable-width encodings because different replacement characters ;;; will need different numbers of octets. This is not a problem for ;;; UTF but will be a problem for the CJK charsets. Approach (a) is ;;; nevertheless easier since the replacement character is known in ;;; advance and therefore the octet-counter can account for it. ;;; ;;; For more complex restarts like SBCL's -- that'll let you specify ;;; _several_ replacement characters for a single character error -- ;;; will probably need extra support code outside the encoder/decoder ;;; (i.e. in the string-to-octets function, for example) since the ;;; encoders/decoders deal with pre-allocated fixed-length buffers. ;;; ;;; SBCL has ASCII-specific (MALFORMED-ASCII) and UTF8-specific ;;; errors. Why? Do we want to add some of those too? ;;; FIXME: We used to deal with this with an extra ERRORP argument for ;;; encoders, decoders, etc... Still undecided on the best way to do ;;; it. We could also use a simple restart instead of this... ;;; ;;; In any case, this is not for the users to bind and it's not ;;; exported from the BABEL package. (defvar *suppress-character-coding-errors* nil "If non-NIL, encoding or decoding errors are suppressed and the the current character encoding's default replacement character is used.") ;;; All of Babel's error conditions are subtypes of ;;; CHARACTER-CODING-ERROR. This error hierarchy is based on SBCL's. (define-condition character-coding-error (error) ((buffer :initarg :buffer :reader character-coding-error-buffer) (position :initarg :position :reader character-coding-error-position) (encoding :initarg :encoding :reader character-coding-error-encoding))) (define-condition character-encoding-error (character-coding-error) ((code :initarg :code :reader character-encoding-error-code)) (:report (lambda (c s) (format s "Unable to encode character code point ~A as ~S." (character-encoding-error-code c) (character-coding-error-encoding c))))) (declaim (inline encoding-error)) (defun encoding-error (code enc buf pos &optional (sub +sub+) (e 'character-encoding-error)) (unless *suppress-character-coding-errors* (error e :encoding enc :buffer buf :position pos :code code)) sub) (define-condition character-decoding-error (character-coding-error) ((octets :initarg :octets :reader character-decoding-error-octets)) (:report (lambda (c s) (format s "Illegal ~S character starting at position ~D." (character-coding-error-encoding c) (character-coding-error-position c))))) (define-condition end-of-input-in-character (character-decoding-error) () (:documentation "Signalled by DECODERs or CODE-POINT-COUNTERs of variable-width character encodings.")) (define-condition character-out-of-range (character-decoding-error) () (:documentation "Signalled when the character being decoded is out of range.")) (declaim (inline decoding-error)) (defun decoding-error (octets enc buf pos &optional (sub +sub+) (e 'character-decoding-error)) (unless *suppress-character-coding-errors* (error e :octets octets :encoding enc :buffer buf :position pos)) sub)
true
;;;; -*- Mode: lisp; indent-tabs-mode: nil -*- ;;; ;;; encodings.lisp --- Character encodings and mappings. ;;; ;;; Copyright (C) 2007, 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 #:babel-encodings) ;;;; Character Encodings (defclass character-encoding () ((name :initarg :name :reader enc-name :initform (error "Must specify a NAME for this character encoding.")) ;; Most of these documentation strings are taken from OpenMCL. (documentation :initarg :documentation :reader enc-documentation :initform nil) ;; A non-exhaustive list of aliases for the encoding. (aliases :initarg :aliases :initform nil :reader enc-aliases) ;; Specified in bits. Usually 8, 16 or 32. (code-unit-size :initarg :code-unit-size :reader enc-code-unit-size :initform 8) (max-units-per-char :initarg :max-units-per-char :reader enc-max-units-per-char :initform 1) ;; If NIL, it is necessary to swap 16- and 32-bit units. (native-endianness :initarg :native-endianness :reader enc-native-endianness :initform t) ;; Code units less than this value map to themselves on input. (decode-literal-code-unit-limit :initarg :decode-literal-code-unit-limit :initform 0 :reader enc-decode-literal-code-unit-limit) ;; Code points less than this value map to themselves on output. (encode-literal-code-unit-limit :initarg :encode-literal-code-unit-limit :initform 0 :reader enc-encode-literal-code-unit-limit) ;; Defines whether it is necessary to prepend a byte-order-mark to ;; determine the endianness. (use-bom :initarg :use-bom :initform nil :reader enc-use-bom) ;; How the byte-order-mark should be encoded, specified as a ;; sequence of octets. NIL if it cannot be encoded. (bom-encoding :initarg :bom-encoding :reader enc-bom-encoding :initform nil) ;; How should NUL be encoded, specified as sequence of octets. (nul-encoding :initarg :nul-encoding :reader enc-nul-encoding :initform #(0)) ;; Preferred replacement character code point. (default-replacement :initarg :default-replacement :reader enc-default-replacement :initform #x1a))) ;;; I'm too lazy to write all the identical limits twice. (defmethod initialize-instance :after ((enc character-encoding) &key literal-char-code-limit) (when literal-char-code-limit (setf (slot-value enc 'encode-literal-code-unit-limit) literal-char-code-limit) (setf (slot-value enc 'decode-literal-code-unit-limit) literal-char-code-limit))) #-(and) (defmethod describe-object ((enc character-encoding) s) "Prints out the name, aliases and documentation slots of a character encoding object." (with-slots (name aliases documentation) enc (format s "~&~S" name) (when aliases (format s " [Aliases:~{ ~S~}]" aliases)) (format s "~&~A~%~%" documentation)) (call-next-method)) (defvar *supported-character-encodings* nil) (defun list-character-encodings () "List of keyword symbols denoting supported character encodings. This list does not include aliases." *supported-character-encodings*) (defvar *character-encodings* (make-hash-table :test 'eq)) (defvar *default-character-encoding* :utf-8 "Special variable used to determine the default character encoding.") (defun get-character-encoding (name) "Lookups the character encoding denoted by the keyword symbol NAME. Signals an error if one is not found. If NAME is already a CHARACTER-ENCONDING object, it is returned unmodified." (when (typep name 'character-encoding) (return-from get-character-encoding name)) (when (eq name :default) (setq name *default-character-encoding*)) (or (gethash name *character-encodings*) (error "Unknown character encoding: ~S" name))) (defun notice-character-encoding (enc) (pushnew (enc-name enc) *supported-character-encodings*) (dolist (kw (cons (enc-name enc) (enc-aliases enc))) (setf (gethash kw *character-encodings*) enc)) (enc-name enc)) (defmacro define-character-encoding (name docstring &body options) `(notice-character-encoding (make-instance 'character-encoding :name ,name ,@options :documentation ,docstring))) ;;;; Mappings ;;; TODO: describe what mappings are (defun 8-bit-fixed-width-counter (getter type) (declare (ignore getter type)) `(lambda (seq start end max) (declare (ignore seq) (fixnum start end max)) (if (plusp max) (let ((count (the fixnum (min max (the fixnum (- end start)))))) (values count (the fixnum (+ start count)))) (values (the fixnum (- end start)) end)))) ;;; Useful to develop new encodings incrementally starting with octet ;;; and code-unit counters. (defun dummy-coder (sg st ds dt) (declare (ignore sg st ds dt)) `(lambda (src s e dest i) (declare (ignore src s e dest i)) (error "this encoder/decoder hasn't been implemented yet"))) (defclass mapping () ((encoder :accessor encoder :initform #'dummy-coder) (decoder :accessor decoder :initform #'dummy-coder) (octet-counter :accessor octet-counter :initform #'8-bit-fixed-width-counter) (code-point-counter :accessor code-point-counter :initform #'8-bit-fixed-width-counter))) ;;; TODO: document here ;;; ;;; ENCODER -- (lambda (src-getter src-type dest-setter dest-type) ...) ;;; DECODER -- (lambda (src-getter src-type dest-setter dest-type) ...) ;;; ;;; OCTET-COUNTER -- (lambda (getter type) ...) ;;; CODE-POINT-COUNTER -- (lambda (getter type) ...) (defclass abstract-mapping (mapping) ()) ;;; TODO: document these ;;; ;;; ENCODER -- (lambda (src start end dest d-start) ...) ;;; DECODER -- (lambda (src start end dest d-start) ...) ;;; ;;; OCTET-COUNTER -- (lambda (seq start end max-octets) ...) ;;; CODE-POINT-COUNTER -- (lambda (seq start end max-chars) ...) ;;; => N-CHARS NEW-END ;;; (important: describe NEW-END) (defclass concrete-mapping (mapping) ()) (defvar *abstract-mappings* (make-hash-table :test 'eq)) (defun get-abstract-mapping (encoding) (gethash encoding *abstract-mappings*)) (defun (setf get-abstract-mapping) (value encoding) (setf (gethash encoding *abstract-mappings*) value)) (defun register-mapping (encoding slot-name fn) (let ((m (get-abstract-mapping encoding))) (when (null m) (setq m (make-instance 'abstract-mapping)) (setf (get-abstract-mapping encoding) m)) (setf (slot-value m slot-name) fn))) ;;; See enc-*.lisp for example usages of these 4 macros. (defmacro define-encoder (encoding (sa st da dt) &body body) `(register-mapping ,encoding 'encoder (lambda (,sa ,st ,da ,dt) ,@body))) (defmacro define-decoder (encoding (sa st da dt) &body body) `(register-mapping ,encoding 'decoder (lambda (,sa ,st ,da ,dt) ,@body))) (defmacro define-octet-counter (encoding (acc type) &body body) `(register-mapping ,encoding 'octet-counter (lambda (,acc ,type) ,@body))) (defmacro define-code-point-counter (encoding (acc type) &body body) `(register-mapping ,encoding 'code-point-counter (lambda (,acc ,type) ,@body))) ;;; Funcalls (at macro-expansion time) the abstract mappings with the ;;; src/dest accessors and types which generate the appropriate code ;;; for the concrete mappings. These functions are then saved in ;;; their respective slots of the CONCRETE-MAPPING object. (defun %am-to-cm (cm am osg oss ost cpsg cpss cpst) `(setf (encoder ,cm) ,(funcall (encoder am) cpsg cpst oss ost) (decoder ,cm) ,(funcall (decoder am) osg ost cpss cpst) (code-point-counter ,cm) ,(funcall (code-point-counter am) osg ost) (octet-counter ,cm) ,(funcall (octet-counter am) cpsg cpst))) ;;; Expands into code generated by the available abstract mappings ;;; that will be compiled into concrete mappings. This is used in ;;; e.g. strings.lisp to define mappings between strings and ;;; (unsigned-byte 8) vectors. (defmacro instantiate-concrete-mappings (&key optimize octet-seq-getter octet-seq-setter octet-seq-type code-point-seq-getter code-point-seq-setter code-point-seq-type) `(let ((ht (make-hash-table :test 'eq))) (declare (optimize ,@optimize)) (flet ((notice-mapping (enc-name cm) (let ((aliases (enc-aliases (get-character-encoding enc-name)))) (dolist (kw (cons enc-name aliases)) (setf (gethash kw ht) cm))))) ,@(loop for am being the hash-values of *abstract-mappings* using (hash-key enc) collect `(let ((cm (make-instance 'concrete-mapping))) ,(%am-to-cm 'cm am octet-seq-getter octet-seq-setter octet-seq-type code-point-seq-getter code-point-seq-setter code-point-seq-type) (notice-mapping ,enc cm)))) ht)) ;;;; Utilities used in enc-*.lisp (defconstant +sub+ #x1a "ASCII substitution character code point.") ;;; We're converting between objects of the (UNSIGNED-BYTE 8) and ;;; (MOD #x110000) types which are aliased here to UB8 and CODE-POINT ;;; for convenience. (deftype ub8 () '(unsigned-byte 8)) (deftype code-point () '(mod #x110000)) ;;; Utility macro around DEFINE-ENCODER that takes care of most of the ;;; work need to deal with an 8-bit, fixed-width character encoding. ;;; ;;; BODY will be inside a loop and its return value will placed in the ;;; destination buffer. BODY will be surounded by lexical BLOCK which ;;; will have the ENCODING's name, usually a keyword. It handles all ;;; sorts of type declarations. ;;; ;;; See enc-ascii.lisp for a simple usage example. (defmacro define-unibyte-encoder (encoding (code) &body body) (with-unique-names (s-getter s-type d-setter d-type src start end dest d-start i di) `(define-encoder ,encoding (,s-getter ,s-type ,d-setter ,d-type) `(lambda (,',src ,',start ,',end ,',dest ,',d-start) (declare (type ,,s-type ,',src) (type ,,d-type ,',dest) (fixnum ,',start ,',end ,',d-start)) (loop for ,',i fixnum from ,',start below ,',end and ,',di fixnum from ,',d-start do (,,d-setter (macrolet ;; this should probably be a function... ((handle-error (&optional (c ''character-encoding-error)) `(encoding-error ,',',code ,',',encoding ,',',src ,',',i +sub+ ,c))) (let ((,',code (,,s-getter ,',src ,',i))) (declare (type code-point ,',code)) (block ,',encoding ,@',body))) ,',dest ,',di) finally (return (the fixnum (- ,',d-start ,',di)))))))) ;;; The decoder version of the above macro. (defmacro define-unibyte-decoder (encoding (octet) &body body) (with-unique-names (s-getter s-type d-setter d-type src start end dest d-start i di) `(define-decoder ,encoding (,s-getter ,s-type ,d-setter ,d-type) `(lambda (,',src ,',start ,',end ,',dest ,',d-start) (declare (type ,,s-type ,',src) (type ,,d-type ,',dest) (fixnum ,',start ,',end ,',d-start)) (loop for ,',i fixnum from ,',start below ,',end and ,',di fixnum from ,',d-start do (,,d-setter (macrolet ;; this should probably be a function... ((handle-error (&optional (c ''character-decoding-error)) `(decoding-error (vector ,',',octet) ,',',encoding ,',',src ,',',i +sub+ ,c))) (let ((,',octet (,,s-getter ,',src ,',i))) (declare (type ub8 ,',octet)) (block ,',encoding ,@',body))) ,',dest ,',di) finally (return (the fixnum (- ,',d-start ,',di)))))))) ;;;; Error Conditions ;;; ;;; For now, we don't define any actual restarts. The only mechanism ;;; for "restarting" a coding error is the ;;; *SUPPRESS-CHARACTER-CODING-ERRORS* special variable which, when ;;; bound to T (the default), suppresses any error and uses a default ;;; replacement character instead. ;;; ;;; If it turns out that other more options are necessary, possible ;;; alternative approaches include: ;;; ;;; a) use a *REPLACEMENT-CHARACTER* special variable that lets us ;;; pick our own replacement character. The encoder must do ;;; additional work to check if this is character is encodable. ;;; ;;; b) offer a restart to pick a replacement character. Same ;;; problem as above. ;;; ;;; Both approaches pose encoding problems when dealing with a ;;; variable-width encodings because different replacement characters ;;; will need different numbers of octets. This is not a problem for ;;; UTF but will be a problem for the CJK charsets. Approach (a) is ;;; nevertheless easier since the replacement character is known in ;;; advance and therefore the octet-counter can account for it. ;;; ;;; For more complex restarts like SBCL's -- that'll let you specify ;;; _several_ replacement characters for a single character error -- ;;; will probably need extra support code outside the encoder/decoder ;;; (i.e. in the string-to-octets function, for example) since the ;;; encoders/decoders deal with pre-allocated fixed-length buffers. ;;; ;;; SBCL has ASCII-specific (MALFORMED-ASCII) and UTF8-specific ;;; errors. Why? Do we want to add some of those too? ;;; FIXME: We used to deal with this with an extra ERRORP argument for ;;; encoders, decoders, etc... Still undecided on the best way to do ;;; it. We could also use a simple restart instead of this... ;;; ;;; In any case, this is not for the users to bind and it's not ;;; exported from the BABEL package. (defvar *suppress-character-coding-errors* nil "If non-NIL, encoding or decoding errors are suppressed and the the current character encoding's default replacement character is used.") ;;; All of Babel's error conditions are subtypes of ;;; CHARACTER-CODING-ERROR. This error hierarchy is based on SBCL's. (define-condition character-coding-error (error) ((buffer :initarg :buffer :reader character-coding-error-buffer) (position :initarg :position :reader character-coding-error-position) (encoding :initarg :encoding :reader character-coding-error-encoding))) (define-condition character-encoding-error (character-coding-error) ((code :initarg :code :reader character-encoding-error-code)) (:report (lambda (c s) (format s "Unable to encode character code point ~A as ~S." (character-encoding-error-code c) (character-coding-error-encoding c))))) (declaim (inline encoding-error)) (defun encoding-error (code enc buf pos &optional (sub +sub+) (e 'character-encoding-error)) (unless *suppress-character-coding-errors* (error e :encoding enc :buffer buf :position pos :code code)) sub) (define-condition character-decoding-error (character-coding-error) ((octets :initarg :octets :reader character-decoding-error-octets)) (:report (lambda (c s) (format s "Illegal ~S character starting at position ~D." (character-coding-error-encoding c) (character-coding-error-position c))))) (define-condition end-of-input-in-character (character-decoding-error) () (:documentation "Signalled by DECODERs or CODE-POINT-COUNTERs of variable-width character encodings.")) (define-condition character-out-of-range (character-decoding-error) () (:documentation "Signalled when the character being decoded is out of range.")) (declaim (inline decoding-error)) (defun decoding-error (octets enc buf pos &optional (sub +sub+) (e 'character-decoding-error)) (unless *suppress-character-coding-errors* (error e :octets octets :encoding enc :buffer buf :position pos)) sub)
[ { "context": "SSIBILITY OF SUCH DAMAGE.\n\n; Original Author(s):\n; Mertcan Temel <[email protected]>\n\n(in-package \"RP\")\n\n(in", "end": 1701, "score": 0.9998629689216614, "start": 1688, "tag": "NAME", "value": "Mertcan Temel" }, { "context": ".\n\n; Original Author(s):\n; Mertcan Temel <[email protected]>\n\n(in-package \"RP\")\n\n(include-book \"fnc-defs\")\n\n(", "end": 1726, "score": 0.9999331831932068, "start": 1711, "tag": "EMAIL", "value": "[email protected]" } ]
books/projects/rp-rewriter/lib/mult3/lemmas.lisp
kazarmy/acl2
9
; Note: The license below is based on the template at: ; http://opensource.org/licenses/BSD-3-Clause ; Copyright (C) 2019, Regents of the University of Texas ; 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): ; Mertcan Temel <[email protected]> (in-package "RP") (include-book "fnc-defs") (local (include-book "projects/rp-rewriter/proofs/rp-equal-lemmas" :dir :system)) (local (fetch-new-events (include-book "arithmetic-5/top" :dir :system) use-arithmetic-5)) (defthm ifix-opener (implies (integerp x) (equal (ifix x) x)) :hints (("Goal" :in-theory (e/d (ifix) ())))) (defthm integerp-m2-f2-d2 (and (integerp (m2 x)) (integerp (d2 x)) (integerp (f2 x)) (integerp (sum x y)) (integerp (sum-list x))) :hints (("Goal" :in-theory (e/d (m2 f2 sum-list sum) ())))) (defthm integerp-ifix (integerp (ifix x))) (defthm m2-f2-d2-sum-of-ifix (and (equal (f2 (ifix x)) (f2 x)) (equal (d2 (ifix x)) (d2 x)) (equal (m2 (ifix x)) (m2 x)) (equal (sum (ifix x) b) (sum x b)) (equal (sum b (ifix x)) (sum x b))) :hints (("Goal" :in-theory (e/d (m2 f2 d2 sum) ( (:REWRITE ACL2::|(equal (if a b c) x)|) (:REWRITE ACL2::|(floor x 2)| . 1)))))) (defthm consp-of-rp-trans-lst (equal (CONSP (RP-TRANS-LST lst)) (consp lst)) :hints (("Goal" :induct (len lst) :do-not-induct t :in-theory (e/d () ())))) (progn (defun sum-comm-order-aux (x cnt) (case-match x (('m2 &) (mv 'm2 x)) (('f2 &) (mv 'f2 x)) (('d2 &) (mv 'd2 x)) (('-- x) (sum-comm-order-aux x (1+ cnt))) (('times2 x) (sum-comm-order-aux x (1+ cnt))) (('sum-list x) (sum-comm-order-aux x (1+ cnt))) (('sum-list-eval x &) (sum-comm-order-aux x (1+ cnt))) (('rp-evl x &) (sum-comm-order-aux x (1+ cnt))) (('rp-trans x) (sum-comm-order-aux x (1+ cnt))) (('mv-nth & &) (mv 'mv-nth (list (caddr x) (cadr x)))) (('pp-sum-merge & &) (mv 'merge x)) (('s-sum-merge & &) (mv 'merge x)) (('car x) (sum-comm-order-aux x (1+ cnt))) (('cdr x) (sum-comm-order-aux x (1+ cnt))) (('binary-sum & &) (mv 'binary-sum x)) (('binary-m2-chain & &) (mv 'binary-m2-chain x)) (('ex-from-rp/-- &) (mv 'm2 x)) (& (mv cnt x)))) (defun sum-comm-order (a b) (b* (((mv a-type a) (sum-comm-order-aux a 0)) ((mv b-type b) (sum-comm-order-aux b 0))) (cond ((or (equal a-type 'binary-sum) (equal a-type 'binary-m2-chain) (equal b-type 'binary-sum) (equal b-type 'binary-m2-chain)) nil) ((or (and (equal a-type 'm2) (equal b-type 'm2)) (and (equal a-type 'mv-nth) (equal b-type 'mv-nth)) (and (equal a-type 'merge) (equal b-type 'merge))) (b* (((mv res &) (lexorder2 a b))) res)) ((or (equal a-type 'm2) (equal b-type 'm2)) (not (equal b-type 'm2))) ((or (equal a-type 'mv-nth) (equal b-type 'mv-nth)) (not (equal b-type 'mv-nth))) ((or (equal a-type 'merge) (equal b-type 'merge)) (not (equal b-type 'merge))) ((or (and (equal a-type 'd2) (equal b-type 'd2)) (and (equal a-type 'f2) (equal b-type 'f2))) (b* (((mv res &) (lexorder2 a b))) res)) ((or (equal a-type 'd2) (equal b-type 'd2)) (not (equal a-type 'd2))) ((or (equal a-type 'f2) (equal b-type 'f2)) (not (equal a-type 'f2))) ((and (integerp a-type) (integerp b-type)) (b* (((mv res equals) (lexorder2 a b))) (if equals (> a-type b-type) res))) ((or (integerp a-type) (integerp b-type)) (not (integerp a-type))) (t (b* (((mv res &) (lexorder2 a b))) res))))) (defthm sum-comm-1 (implies (syntaxp (sum-comm-order a b)) (equal (sum b a) (sum a b))) :rule-classes ((:rewrite :loop-stopper nil)) :hints (("Goal" :in-theory (e/d (sum) ())))) (defthmd sum-comm-1-loop-stopper (implies t (equal (sum b a) (sum a b))) :hints (("Goal" :in-theory (e/d (sum) ())))) (defthm sum-comm-2 (implies (syntaxp (sum-comm-order a b)) (equal (sum b a c) (sum a b c))) :rule-classes ((:rewrite :loop-stopper nil)) :hints (("Goal" :in-theory (e/d (sum) ())))) (defthmd sum-comm-2-loop-stopper (implies t (equal (sum b a c) (sum a b c))) :hints (("Goal" :in-theory (e/d (sum) ())))) (defthm sum-assoc (equal (sum (sum a b) c) (sum a b c)) :hints (("Goal" :in-theory (e/d (sum) ())))) (defthm sum-of-0 (and (equal (sum 0 a) (ifix a)) (equal (sum a 0) (ifix a))) :hints (("Goal" :in-theory (e/d (sum) ())))) (defthm sum-of-ifix (and (equal (sum (ifix x) y) (sum x y)) (equal (sum x (ifix y)) (sum x y))) :hints (("Goal" :in-theory (e/d (ifix sum) ())))) ) (in-theory (disable ifix)) (defthm sum-list-of-append (EQUAL (SUM-LIST (APPEND lst1 lst2)) (SUM (sum-list lst1) (sum-list lst2))) :hints (("Goal" :in-theory (e/d (sum-list sum) ())))) (defthm sum-list-of-true-list-fix (equal (SUM-LIST (TRUE-LIST-FIX lst)) (SUM-LIST lst)) :hints (("Goal" :induct (true-list-fix lst) :do-not-induct t :in-theory (e/d (sum-list true-list-fix) ((:REWRITE ACL2::LIST-FIX-WHEN-TRUE-LISTP) (:REWRITE RP-TERM-LISTP-IS-TRUE-LISTP) (:DEFINITION ACL2::APPLY$-BADGEP) (:REWRITE ACL2::CDR-OF-LIST-FIX) (:DEFINITION TRUE-LISTP)))))) (defthmd and-list-is-and$ (implies (consp lst) (equal (and-list hash lst) (if (atom (cdr lst)) (bit-fix (car lst)) (and$ (car lst) (and-list hash (cdr lst)))))) :hints (("Goal" :in-theory (e/d (and$ and-list) ())))) (defthmd and$-is-and-list (implies t (equal (and$ a b) (and-list 0 (list a b)))) :hints (("Goal" :in-theory (e/d (and$ and-list) ())))) (defthm -of- (implies (integerp a) (equal (- (- a)) a))) (defthm sum-of-subtracted (and (equal (sum x (-- x)) 0) (equal (sum (-- x) x) 0) (equal (sum (-- x) x z) (ifix z)) (equal (sum x (-- x) z) (ifix z))) :hints (("Goal" :in-theory (e/d (sum --) ())))) (defthmd +-is-SUM (implies (and (integerp a) (integerp b)) (equal (+ a b) (sum a b))) :hints (("Goal" :in-theory (e/d (sum) ())))) (defthmd mod2-is-m2 (implies (integerp x) (equal (mod x 2) (m2 x))) :hints (("Goal" :in-theory (e/d (m2) (mod))))) (defthmd floor2-if-f2 (implies (integerp x) (equal (floor x 2) (f2 x))) :hints (("Goal" :in-theory (e/d (f2) (floor))))) (defthm c-is-f2 (equal (c hash-code a b c) (f2 (sum (sum-list a) (sum-list b) (sum-list c)))) :hints (("Goal" :in-theory (e/d (c f2 sum sum-list) (+-is-SUM floor2-if-f2 mod2-is-m2))))) #|(defthm d-sum-to-sum (equal (d-sum x y z) (sum (sum-list x) (sum-list y) z)) :hints (("Goal" :in-theory (e/d (d-sum) ()))))||# #|(defthm d-is-d2 (equal (d x) (d2 x)) :hints (("Goal" :in-theory (e/d (d2 d -- FLOOR2-IF-F2 mod2-is-m2) (floor mod (:REWRITE ACL2::|(- (if a b c))|) (:REWRITE ACL2::|(floor x 2)| . 1) (:REWRITE ACL2::|(mod x 2)| . 1) (:REWRITE SUM-COMM-1))))))||# (defthm s-is-m2 (equal (s hash-code b c) (m2 (sum (sum-list b) (sum-list c)))) :hints (("Goal" :in-theory (e/d (s m2 sum sum-list) (+-is-SUM floor2-if-f2 mod2-is-m2))))) (defthm sum-list-is-sum (equal (sum-list (cons a b)) (sum a (sum-list b))) :hints (("Goal" :expand (sum-list (cons a b)) :in-theory (e/d (sum-list sum ) (SUM-OF-IFIX +-is-SUM))))) (defthm s-spec-is-m2 (equal (s-spec lst) (m2 (sum-list lst))) :hints (("Goal" :in-theory (e/d (s-spec mod2-is-m2) ((:REWRITE ACL2::|(equal (if a b c) x)|) (:REWRITE ACL2::|(mod x 2)| . 1)))))) (defthm c-spec-is-f2 (equal (c-spec lst) (f2 (sum-list lst))) :hints (("Goal" :in-theory (e/d (c-spec floor2-if-f2) ())))) (defthm s-c-spec-is-list-m2-f2 (equal (s-c-spec sum) (list (m2 (sum-list sum)) (f2 (sum-list sum)))) :hints (("Goal" :in-theory (e/d (s-c-spec) ())))) (defthm c-s-spec-is-list-m2-f2 (equal (c-s-spec sum) (list (f2 (sum-list sum)) (m2 (sum-list sum)))) :hints (("Goal" :in-theory (e/d (c-s-spec) ())))) (defthm s-of-c-trig-def (equal (s-of-c-trig x) x) :hints (("Goal" :in-theory (e/d (s-of-c-trig) ())))) (defthm s-of-s-lemma1 (implies t (equal (equal (m2 (sum x1 rest1)) (m2 (sum x1 rest2))) (equal (m2 rest1) (m2 rest2)))) :hints (("Goal" :in-theory (e/d (m2 sum) (mod2-is-m2 +-is-SUM))))) (defthm s-of-s-lemma2 (implies t (equal (equal (m2 x1) (m2 (sum x1 rest2))) (equal 0 (m2 rest2)))) :hints (("Goal" :in-theory (e/d (m2 sum) (mod2-is-m2 +-is-SUM))))) (encapsulate nil (defthm f2-of-times2 (and (equal (f2 (sum (times2 a) b)) (sum a (f2 (sum b)))) (equal (f2 (times2 a)) (ifix a))) :hints (("Goal" :do-not '(preprocess) :in-theory (e/d (sum f2 times2) ())))) (local (defthm f2-of-minus-lemma1 (equal (f2 (sum (-- a) b)) (f2 (sum (times2 (-- a)) a b))) :hints (("Goal" :in-theory (e/d (sum -- times2) ()))))) (defthm f2-of-minus (implies t ;(bitp a) (equal (f2 (sum (-- a) b)) (sum (-- a) (f2 (sum a b))))) :hints (("Goal" :in-theory (e/d () (SUM-COMM-1 SUM-COMM-2)))))) (encapsulate nil (defthm m2-of-times2 (and (equal (m2 (sum (times2 a) b)) (m2 b)) (equal (m2 (times2 a)) 0)) :hints (("Goal" :in-theory (e/d (m2 sum times2) ())))) (local (defthm s-of-minus-lemma (and (equal (m2 (sum (-- a) b)) (m2 (sum (times2 (-- a)) a b))) (equal (m2 (sum (-- a) b)) (m2 (sum (times2 (-- a)) a b)))) :hints (("Goal" :in-theory (e/d (sum times2 --) ()))))) (defthm s-of-minus (and (equal (m2 (sum (-- a) b)) (m2 (sum a b)))) :hints (("Goal" :in-theory (e/d () (SUM-COMM-1 SUM-COMM-2)))))) (encapsulate nil (defthm d2-of-times2 (and (equal (d2 (sum (times2 a) b)) (sum a (d2 (sum b)))) (equal (d2 (times2 a)) (ifix a))) :hints (("Goal" :do-not '(preprocess) :in-theory (e/d (d2) (SUM-COMM-1 SUM-COMM-2))))) (local (defthm d2-of-minus-lemma1 (equal (d2 (sum (-- a) b)) (d2 (sum (times2 (-- a)) a b))) :hints (("Goal" :in-theory (e/d (sum -- times2) ()))))) (defthm d2-of-minus (implies t ;(bitp a) (equal (d2 (sum (-- a) b)) (sum (-- a) (d2 (sum a b))))) :hints (("Goal" :in-theory (e/d () (SUM-COMM-1 SUM-COMM-2)))))) (defthm m2-of--- (and (equal (m2 (sum (-- x) rest)) (m2 (sum x rest))) (equal (m2 (sum rest1 (-- x) rest)) (m2 (sum x rest rest1))) (equal (m2 (sum rest1 (-- x))) (m2 (sum x rest1))) (equal (m2 (-- x)) (m2 x))) :hints (("Goal" :use ((:instance s-of-minus (a x) (b rest)) (:instance s-of-minus (a x) (b (sum rest rest1)))) :in-theory (e/d ( ) (s-of-minus))))) (defthm m2-of-ifix (equal (m2 (ifix x)) (m2 x)) :hints (("Goal" :in-theory (e/d (m2) ())))) (defthm f2-of-ifix (equal (f2 (ifix x)) (f2 x)) :hints (("Goal" :in-theory (e/d (f2) ())))) (defthm ifix-of-f2 (equal (ifix (f2 x)) (f2 x)) :hints (("Goal" :in-theory (e/d (ifix f2) ())))) (defthm ifix-of-m2 (equal (ifix (m2 x)) (m2 x)) :hints (("Goal" :in-theory (e/d (ifix) ())))) (defthm sum-of-equals (and (equal (equal (sum a b) (sum a c)) (equal (ifix b) (ifix c))) (equal (equal (sum b a) (sum a c)) (equal (ifix b) (ifix c))) (equal (equal (sum x a b) (sum a c)) (equal (sum b x) (ifix c))) (equal (equal (sum x a b) (sum y a c)) (equal (sum x b) (sum y c)))) :hints (("Goal" :in-theory (e/d (sum) (+-is-SUM))))) (defthm integerp-f2 (integerp (f2 x))) (defthm dummy-sum-cancel-lemma1 (implies (equal (sum a b) 0) (equal (sum a b c) (ifix c))) :hints (("Goal" :in-theory (e/d (sum) ())))) (defthm f2-of-bit (implies (bitp x) (equal (f2 x) 0)) :hints (("Goal" :in-theory (e/d (bitp) ())))) (def-rp-rule m2-of-m2 (and (equal (m2 (m2 x)) (m2 x)) (equal (m2 (sum (m2 x) y)) (m2 (sum x y)))) :hints (("Goal" :in-theory (e/d (m2 sum) ())))) (defthm m2-of-m2-extended (and (equal (m2 (sum a b c (m2 x))) (m2 (sum a b c x))) (equal (m2 (sum a b (m2 x))) (m2 (sum a b x)))) :hints (("Goal" :use ((:instance M2-OF-M2 (x x) (y (sum a b c))) (:instance M2-OF-M2 (x x) (y (sum a b)))) :in-theory (e/d () (M2-OF-M2))))) (defthmd sum-of-repeated-to-times2 (and (equal (sum x x) (times2 x)) (equal (sum x x y) (sum (times2 x) y))) :hints (("Goal" :in-theory (e/d (times2) ())))) (defthm times2-of-sum (equal (times2 (sum a b)) (sum (times2 a) (times2 b))) :hints (("Goal" :in-theory (e/d (times2) ())))) (defthm d2-to-f2 (and (EQUAL (d2 (sum (-- (m2 x)) x)) (f2 x)) (EQUAL (d2 (sum x (-- (m2 x)))) (f2 x))) :hints (("Goal" :in-theory (e/d (sum m2 d2 f2) ())))) (defthmd f2-to-d2 (EQUAL (f2 x) (d2 (sum (-- (m2 x)) x))) :hints (("Goal" :in-theory (e/d () (SUM-COMM-1 SUM-COMM-2 (:REWRITE ACL2::|(mod x 2)| . 1) (:REWRITE ACL2::|(equal (if a b c) x)|) (:REWRITE ACL2::|(floor x 2)| . 1)))))) (defthmd equal-sum-of-negated (and (equal (equal (sum x y) (sum (-- a) b)) (equal (sum x y a) (ifix b))) (equal (equal (sum x y) (sum k (-- a) b)) (equal (sum x y a) (sum k b))) (equal (equal (sum x y) (sum k (-- a))) (equal (sum x y a) (ifix k))) (equal (equal (sum x y) (sum k l (-- a) b)) (equal (sum x y a) (sum k l b)))) :hints (("Goal" :in-theory (e/d (sum --) ())))) (defthm evenpi-of-times2 (and (equal (evenpi (sum (times2 a) x)) (evenpi x)) (equal (evenpi (sum x (times2 a))) (evenpi x)) (equal (evenpi (sum x y (times2 a))) (evenpi (sum x y))) (equal (evenpi (times2 a)) t)) :hints (("Goal" :in-theory (e/d (sum evenpi times2) ())))) (defthmd sum-with-oddp (implies (and (not (evenp x)) (integerp x) (integerp other)) (equal (evenp (+ x other)) (not (evenp other))))) (defthmd sum-with-evenp (implies (and (evenp x) (integerp x) (integerp other)) (equal (evenp (+ x other)) (evenp other)))) (defthmd evenpi-lemma-1-lemma (IMPLIES (AND (EQUAL (EVENP (IFIX S1)) (EVENP (IFIX B1))) (EQUAL (EVENP (IFIX S2)) (EVENP (IFIX B2)))) (equal (EVENP (+ (IFIX S1) (IFIX S2))) (EVENP (+ (IFIX B1) (IFIX B2)))))) (defthmd evenpi-lemma-1 (implies (and (equal (evenpi s1) (evenpi b1)) (equal (evenpi s2) (evenpi b2)) (evenpi (sum a s1 s2))) (evenpi (sum a b1 b2))) :otf-flg t :hints (("Goal" :use ((:instance evenpi-lemma-1-lemma)) :cases ((evenpi a)) :in-theory (e/d (evenpi sum-with-evenp sum sum-with-oddp) (evenp))))) (add-invisible-fns binary-sum --) (add-invisible-fns binary-sum m2) (add-invisible-fns binary-sum sum-list) (add-invisible-fns binary-sum times2) (encapsulate nil (local (use-arithmetic-5 t)) (local (in-theory (disable mod floor))) (defthmd d2-is-divide-by-2 (implies (evenpi x) (equal (d2 x) (/ (ifix x) 2))) :hints (("Goal" :in-theory (e/d (d2 f2 m2 sum evenp evenpi) ())))) (defthm evenpi-of-sum (implies (and (evenpi x) (evenpi y)) (evenpi (sum x y))) :hints (("Goal" :in-theory (e/d (evenpi sum) ())))) (local (defthm sum-of-d2-lemma (IMPLIES (AND (EVENPI X) (EVENPI Y)) (EQUAL (SUM (* 1/2 (IFIX X)) (* 1/2 (IFIX Y))) (* 1/2 (SUM X Y)))) :hints (("Goal" :in-theory (e/d (sum evenpi) ()))))) (defthm sum-of-d2 (implies (and (evenpi x) (evenpi y)) (and (equal (sum (d2 x) (d2 y)) (d2 (sum x Y))) (equal (sum (d2 x) (d2 y) z) (sum (d2 (sum x Y)) z)))) :hints (("Goal" :use ((:instance sum-of-d2-lemma)) :in-theory (e/d (d2-is-divide-by-2) (sum-of-d2-lemma))))) (defthm evenpi-of-term-minus-its-mod (and (evenpi (SUM A (-- (M2 A)))) (evenpi (SUM (-- (M2 A)) A))) :hints (("Goal" :in-theory (e/d (m2 sum evenpi) ())))) (defthm sum-of-f2s (and (equal (sum (f2 a) (f2 b)) (d2 (sum (-- (m2 a)) (-- (m2 b)) a b))) (equal (sum (f2 a) (f2 b) c) (sum (d2 (sum (-- (m2 a)) (-- (m2 b)) a b)) c))) :hints (("Goal" :in-theory (e/d (f2-to-d2) (d2-to-f2 D2-OF-MINUS ))))) (defthm sum-of-f2s-and-d2 (implies (evenpi b) (and (equal (sum (f2 a) (d2 b)) (d2 (sum (-- (m2 a)) a b))) (equal (sum (d2 b) (f2 a)) (d2 (sum (-- (m2 a)) a b))) (equal (sum (f2 a) (d2 b) c) (sum (d2 (sum (-- (m2 a)) a b)) c)) (equal (sum (d2 b) (f2 a) c) (sum (d2 (sum (-- (m2 a)) a b)) c)))) :hints (("Goal" :in-theory (e/d (f2-to-d2) (d2-to-f2 D2-OF-MINUS )))))) (defthm evenpi-for-2-d2-arguments (evenpi (sum a b (-- (m2 (sum a b))))) :hints (("Goal" :in-theory (e/d (evenpi sum m2) ())))) (defthm evenpi-for-3-d2-arguments (evenpi (sum a b c (-- (m2 (sum a b c))))) :hints (("Goal" :in-theory (e/d (evenpi sum m2) ())))) (defthm evenpi-for-4-d2-arguments (evenpi (sum a b c d (-- (m2 (sum a b c d))))) :hints (("Goal" :in-theory (e/d (evenpi sum m2) ())))) (defthm evenpi-sum-clear (and (equal (evenpi (sum a a b)) (evenpi (ifix b))) (equal (evenpi (sum a a)) t) (equal (evenpi (sum c a a b)) (evenpi (sum b c))) (equal (evenpi (sum c a a)) (evenpi (sum c))) (equal (evenpi (sum c d a a b)) (evenpi (sum b c d))) (equal (evenpi (sum c d a a )) (evenpi (sum c d))) (equal (evenpi (sum c d e a a b)) (evenpi (sum b c d e))) (equal (evenpi (sum c d e a a)) (evenpi (sum c d e)))) :hints (("Goal" :in-theory (e/d (sum evenpi) ())))) (defthm m2-with-extra (implies (equal (m2 x) (m2 y)) (equal (equal (m2 (sum x other)) (m2 (sum y other))) t)) :hints (("Goal" :in-theory (e/d (m2 sum) ())))) (defthm m2-with-extra-dummy-lemma (implies (equal (m2 (sum a b)) (m2 (sum x y z))) (equal (equal (m2 (sum other a b)) (m2 (sum x y z other))) t)) :hints (("Goal" :use ((:instance m2-with-extra (x (sum a b)) (y (sum x y z)) (other other))) :in-theory (e/d ( ) (m2-with-extra))))) (defthm evenpi-with-other (implies (equal (evenpi x) (evenpi y)) (equal (equal (evenpi (sum x z)) (evenpi (sum y z))) t)) :hints (("Goal" :in-theory (e/d (evenpi sum) ())))) (defthm bitp-m2 (bitp (m2 x)) :hints (("Goal" :in-theory (e/d (m2 sum f2) ())))) (in-theory (enable +-is-SUM mod2-is-m2 floor2-if-f2)) (defthm sum-of-negated-elements (implies (equal (-- a) b) (and (equal (sum a b) 0) (equal (sum b a) 0) (equal (sum b a rest) (ifix rest)) (equal (sum a b rest) (ifix rest)))) :hints (("Goal" :in-theory (e/d (sum --) (+-IS-SUM))))) (defthmd f2-of-times2-reverse (implies (syntaxp (or (atom term) (not (equal (car term) 'f2)))) (and (equal (sum term (f2 term2)) (f2 (sum (times2 term) term2))) (equal (sum (f2 term2) term) (f2 (sum (times2 term) term2))) (equal (sum term (f2 term2) other) (sum other (f2 (sum (times2 term) term2)))))))
45336
; Note: The license below is based on the template at: ; http://opensource.org/licenses/BSD-3-Clause ; Copyright (C) 2019, Regents of the University of Texas ; 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>> (in-package "RP") (include-book "fnc-defs") (local (include-book "projects/rp-rewriter/proofs/rp-equal-lemmas" :dir :system)) (local (fetch-new-events (include-book "arithmetic-5/top" :dir :system) use-arithmetic-5)) (defthm ifix-opener (implies (integerp x) (equal (ifix x) x)) :hints (("Goal" :in-theory (e/d (ifix) ())))) (defthm integerp-m2-f2-d2 (and (integerp (m2 x)) (integerp (d2 x)) (integerp (f2 x)) (integerp (sum x y)) (integerp (sum-list x))) :hints (("Goal" :in-theory (e/d (m2 f2 sum-list sum) ())))) (defthm integerp-ifix (integerp (ifix x))) (defthm m2-f2-d2-sum-of-ifix (and (equal (f2 (ifix x)) (f2 x)) (equal (d2 (ifix x)) (d2 x)) (equal (m2 (ifix x)) (m2 x)) (equal (sum (ifix x) b) (sum x b)) (equal (sum b (ifix x)) (sum x b))) :hints (("Goal" :in-theory (e/d (m2 f2 d2 sum) ( (:REWRITE ACL2::|(equal (if a b c) x)|) (:REWRITE ACL2::|(floor x 2)| . 1)))))) (defthm consp-of-rp-trans-lst (equal (CONSP (RP-TRANS-LST lst)) (consp lst)) :hints (("Goal" :induct (len lst) :do-not-induct t :in-theory (e/d () ())))) (progn (defun sum-comm-order-aux (x cnt) (case-match x (('m2 &) (mv 'm2 x)) (('f2 &) (mv 'f2 x)) (('d2 &) (mv 'd2 x)) (('-- x) (sum-comm-order-aux x (1+ cnt))) (('times2 x) (sum-comm-order-aux x (1+ cnt))) (('sum-list x) (sum-comm-order-aux x (1+ cnt))) (('sum-list-eval x &) (sum-comm-order-aux x (1+ cnt))) (('rp-evl x &) (sum-comm-order-aux x (1+ cnt))) (('rp-trans x) (sum-comm-order-aux x (1+ cnt))) (('mv-nth & &) (mv 'mv-nth (list (caddr x) (cadr x)))) (('pp-sum-merge & &) (mv 'merge x)) (('s-sum-merge & &) (mv 'merge x)) (('car x) (sum-comm-order-aux x (1+ cnt))) (('cdr x) (sum-comm-order-aux x (1+ cnt))) (('binary-sum & &) (mv 'binary-sum x)) (('binary-m2-chain & &) (mv 'binary-m2-chain x)) (('ex-from-rp/-- &) (mv 'm2 x)) (& (mv cnt x)))) (defun sum-comm-order (a b) (b* (((mv a-type a) (sum-comm-order-aux a 0)) ((mv b-type b) (sum-comm-order-aux b 0))) (cond ((or (equal a-type 'binary-sum) (equal a-type 'binary-m2-chain) (equal b-type 'binary-sum) (equal b-type 'binary-m2-chain)) nil) ((or (and (equal a-type 'm2) (equal b-type 'm2)) (and (equal a-type 'mv-nth) (equal b-type 'mv-nth)) (and (equal a-type 'merge) (equal b-type 'merge))) (b* (((mv res &) (lexorder2 a b))) res)) ((or (equal a-type 'm2) (equal b-type 'm2)) (not (equal b-type 'm2))) ((or (equal a-type 'mv-nth) (equal b-type 'mv-nth)) (not (equal b-type 'mv-nth))) ((or (equal a-type 'merge) (equal b-type 'merge)) (not (equal b-type 'merge))) ((or (and (equal a-type 'd2) (equal b-type 'd2)) (and (equal a-type 'f2) (equal b-type 'f2))) (b* (((mv res &) (lexorder2 a b))) res)) ((or (equal a-type 'd2) (equal b-type 'd2)) (not (equal a-type 'd2))) ((or (equal a-type 'f2) (equal b-type 'f2)) (not (equal a-type 'f2))) ((and (integerp a-type) (integerp b-type)) (b* (((mv res equals) (lexorder2 a b))) (if equals (> a-type b-type) res))) ((or (integerp a-type) (integerp b-type)) (not (integerp a-type))) (t (b* (((mv res &) (lexorder2 a b))) res))))) (defthm sum-comm-1 (implies (syntaxp (sum-comm-order a b)) (equal (sum b a) (sum a b))) :rule-classes ((:rewrite :loop-stopper nil)) :hints (("Goal" :in-theory (e/d (sum) ())))) (defthmd sum-comm-1-loop-stopper (implies t (equal (sum b a) (sum a b))) :hints (("Goal" :in-theory (e/d (sum) ())))) (defthm sum-comm-2 (implies (syntaxp (sum-comm-order a b)) (equal (sum b a c) (sum a b c))) :rule-classes ((:rewrite :loop-stopper nil)) :hints (("Goal" :in-theory (e/d (sum) ())))) (defthmd sum-comm-2-loop-stopper (implies t (equal (sum b a c) (sum a b c))) :hints (("Goal" :in-theory (e/d (sum) ())))) (defthm sum-assoc (equal (sum (sum a b) c) (sum a b c)) :hints (("Goal" :in-theory (e/d (sum) ())))) (defthm sum-of-0 (and (equal (sum 0 a) (ifix a)) (equal (sum a 0) (ifix a))) :hints (("Goal" :in-theory (e/d (sum) ())))) (defthm sum-of-ifix (and (equal (sum (ifix x) y) (sum x y)) (equal (sum x (ifix y)) (sum x y))) :hints (("Goal" :in-theory (e/d (ifix sum) ())))) ) (in-theory (disable ifix)) (defthm sum-list-of-append (EQUAL (SUM-LIST (APPEND lst1 lst2)) (SUM (sum-list lst1) (sum-list lst2))) :hints (("Goal" :in-theory (e/d (sum-list sum) ())))) (defthm sum-list-of-true-list-fix (equal (SUM-LIST (TRUE-LIST-FIX lst)) (SUM-LIST lst)) :hints (("Goal" :induct (true-list-fix lst) :do-not-induct t :in-theory (e/d (sum-list true-list-fix) ((:REWRITE ACL2::LIST-FIX-WHEN-TRUE-LISTP) (:REWRITE RP-TERM-LISTP-IS-TRUE-LISTP) (:DEFINITION ACL2::APPLY$-BADGEP) (:REWRITE ACL2::CDR-OF-LIST-FIX) (:DEFINITION TRUE-LISTP)))))) (defthmd and-list-is-and$ (implies (consp lst) (equal (and-list hash lst) (if (atom (cdr lst)) (bit-fix (car lst)) (and$ (car lst) (and-list hash (cdr lst)))))) :hints (("Goal" :in-theory (e/d (and$ and-list) ())))) (defthmd and$-is-and-list (implies t (equal (and$ a b) (and-list 0 (list a b)))) :hints (("Goal" :in-theory (e/d (and$ and-list) ())))) (defthm -of- (implies (integerp a) (equal (- (- a)) a))) (defthm sum-of-subtracted (and (equal (sum x (-- x)) 0) (equal (sum (-- x) x) 0) (equal (sum (-- x) x z) (ifix z)) (equal (sum x (-- x) z) (ifix z))) :hints (("Goal" :in-theory (e/d (sum --) ())))) (defthmd +-is-SUM (implies (and (integerp a) (integerp b)) (equal (+ a b) (sum a b))) :hints (("Goal" :in-theory (e/d (sum) ())))) (defthmd mod2-is-m2 (implies (integerp x) (equal (mod x 2) (m2 x))) :hints (("Goal" :in-theory (e/d (m2) (mod))))) (defthmd floor2-if-f2 (implies (integerp x) (equal (floor x 2) (f2 x))) :hints (("Goal" :in-theory (e/d (f2) (floor))))) (defthm c-is-f2 (equal (c hash-code a b c) (f2 (sum (sum-list a) (sum-list b) (sum-list c)))) :hints (("Goal" :in-theory (e/d (c f2 sum sum-list) (+-is-SUM floor2-if-f2 mod2-is-m2))))) #|(defthm d-sum-to-sum (equal (d-sum x y z) (sum (sum-list x) (sum-list y) z)) :hints (("Goal" :in-theory (e/d (d-sum) ()))))||# #|(defthm d-is-d2 (equal (d x) (d2 x)) :hints (("Goal" :in-theory (e/d (d2 d -- FLOOR2-IF-F2 mod2-is-m2) (floor mod (:REWRITE ACL2::|(- (if a b c))|) (:REWRITE ACL2::|(floor x 2)| . 1) (:REWRITE ACL2::|(mod x 2)| . 1) (:REWRITE SUM-COMM-1))))))||# (defthm s-is-m2 (equal (s hash-code b c) (m2 (sum (sum-list b) (sum-list c)))) :hints (("Goal" :in-theory (e/d (s m2 sum sum-list) (+-is-SUM floor2-if-f2 mod2-is-m2))))) (defthm sum-list-is-sum (equal (sum-list (cons a b)) (sum a (sum-list b))) :hints (("Goal" :expand (sum-list (cons a b)) :in-theory (e/d (sum-list sum ) (SUM-OF-IFIX +-is-SUM))))) (defthm s-spec-is-m2 (equal (s-spec lst) (m2 (sum-list lst))) :hints (("Goal" :in-theory (e/d (s-spec mod2-is-m2) ((:REWRITE ACL2::|(equal (if a b c) x)|) (:REWRITE ACL2::|(mod x 2)| . 1)))))) (defthm c-spec-is-f2 (equal (c-spec lst) (f2 (sum-list lst))) :hints (("Goal" :in-theory (e/d (c-spec floor2-if-f2) ())))) (defthm s-c-spec-is-list-m2-f2 (equal (s-c-spec sum) (list (m2 (sum-list sum)) (f2 (sum-list sum)))) :hints (("Goal" :in-theory (e/d (s-c-spec) ())))) (defthm c-s-spec-is-list-m2-f2 (equal (c-s-spec sum) (list (f2 (sum-list sum)) (m2 (sum-list sum)))) :hints (("Goal" :in-theory (e/d (c-s-spec) ())))) (defthm s-of-c-trig-def (equal (s-of-c-trig x) x) :hints (("Goal" :in-theory (e/d (s-of-c-trig) ())))) (defthm s-of-s-lemma1 (implies t (equal (equal (m2 (sum x1 rest1)) (m2 (sum x1 rest2))) (equal (m2 rest1) (m2 rest2)))) :hints (("Goal" :in-theory (e/d (m2 sum) (mod2-is-m2 +-is-SUM))))) (defthm s-of-s-lemma2 (implies t (equal (equal (m2 x1) (m2 (sum x1 rest2))) (equal 0 (m2 rest2)))) :hints (("Goal" :in-theory (e/d (m2 sum) (mod2-is-m2 +-is-SUM))))) (encapsulate nil (defthm f2-of-times2 (and (equal (f2 (sum (times2 a) b)) (sum a (f2 (sum b)))) (equal (f2 (times2 a)) (ifix a))) :hints (("Goal" :do-not '(preprocess) :in-theory (e/d (sum f2 times2) ())))) (local (defthm f2-of-minus-lemma1 (equal (f2 (sum (-- a) b)) (f2 (sum (times2 (-- a)) a b))) :hints (("Goal" :in-theory (e/d (sum -- times2) ()))))) (defthm f2-of-minus (implies t ;(bitp a) (equal (f2 (sum (-- a) b)) (sum (-- a) (f2 (sum a b))))) :hints (("Goal" :in-theory (e/d () (SUM-COMM-1 SUM-COMM-2)))))) (encapsulate nil (defthm m2-of-times2 (and (equal (m2 (sum (times2 a) b)) (m2 b)) (equal (m2 (times2 a)) 0)) :hints (("Goal" :in-theory (e/d (m2 sum times2) ())))) (local (defthm s-of-minus-lemma (and (equal (m2 (sum (-- a) b)) (m2 (sum (times2 (-- a)) a b))) (equal (m2 (sum (-- a) b)) (m2 (sum (times2 (-- a)) a b)))) :hints (("Goal" :in-theory (e/d (sum times2 --) ()))))) (defthm s-of-minus (and (equal (m2 (sum (-- a) b)) (m2 (sum a b)))) :hints (("Goal" :in-theory (e/d () (SUM-COMM-1 SUM-COMM-2)))))) (encapsulate nil (defthm d2-of-times2 (and (equal (d2 (sum (times2 a) b)) (sum a (d2 (sum b)))) (equal (d2 (times2 a)) (ifix a))) :hints (("Goal" :do-not '(preprocess) :in-theory (e/d (d2) (SUM-COMM-1 SUM-COMM-2))))) (local (defthm d2-of-minus-lemma1 (equal (d2 (sum (-- a) b)) (d2 (sum (times2 (-- a)) a b))) :hints (("Goal" :in-theory (e/d (sum -- times2) ()))))) (defthm d2-of-minus (implies t ;(bitp a) (equal (d2 (sum (-- a) b)) (sum (-- a) (d2 (sum a b))))) :hints (("Goal" :in-theory (e/d () (SUM-COMM-1 SUM-COMM-2)))))) (defthm m2-of--- (and (equal (m2 (sum (-- x) rest)) (m2 (sum x rest))) (equal (m2 (sum rest1 (-- x) rest)) (m2 (sum x rest rest1))) (equal (m2 (sum rest1 (-- x))) (m2 (sum x rest1))) (equal (m2 (-- x)) (m2 x))) :hints (("Goal" :use ((:instance s-of-minus (a x) (b rest)) (:instance s-of-minus (a x) (b (sum rest rest1)))) :in-theory (e/d ( ) (s-of-minus))))) (defthm m2-of-ifix (equal (m2 (ifix x)) (m2 x)) :hints (("Goal" :in-theory (e/d (m2) ())))) (defthm f2-of-ifix (equal (f2 (ifix x)) (f2 x)) :hints (("Goal" :in-theory (e/d (f2) ())))) (defthm ifix-of-f2 (equal (ifix (f2 x)) (f2 x)) :hints (("Goal" :in-theory (e/d (ifix f2) ())))) (defthm ifix-of-m2 (equal (ifix (m2 x)) (m2 x)) :hints (("Goal" :in-theory (e/d (ifix) ())))) (defthm sum-of-equals (and (equal (equal (sum a b) (sum a c)) (equal (ifix b) (ifix c))) (equal (equal (sum b a) (sum a c)) (equal (ifix b) (ifix c))) (equal (equal (sum x a b) (sum a c)) (equal (sum b x) (ifix c))) (equal (equal (sum x a b) (sum y a c)) (equal (sum x b) (sum y c)))) :hints (("Goal" :in-theory (e/d (sum) (+-is-SUM))))) (defthm integerp-f2 (integerp (f2 x))) (defthm dummy-sum-cancel-lemma1 (implies (equal (sum a b) 0) (equal (sum a b c) (ifix c))) :hints (("Goal" :in-theory (e/d (sum) ())))) (defthm f2-of-bit (implies (bitp x) (equal (f2 x) 0)) :hints (("Goal" :in-theory (e/d (bitp) ())))) (def-rp-rule m2-of-m2 (and (equal (m2 (m2 x)) (m2 x)) (equal (m2 (sum (m2 x) y)) (m2 (sum x y)))) :hints (("Goal" :in-theory (e/d (m2 sum) ())))) (defthm m2-of-m2-extended (and (equal (m2 (sum a b c (m2 x))) (m2 (sum a b c x))) (equal (m2 (sum a b (m2 x))) (m2 (sum a b x)))) :hints (("Goal" :use ((:instance M2-OF-M2 (x x) (y (sum a b c))) (:instance M2-OF-M2 (x x) (y (sum a b)))) :in-theory (e/d () (M2-OF-M2))))) (defthmd sum-of-repeated-to-times2 (and (equal (sum x x) (times2 x)) (equal (sum x x y) (sum (times2 x) y))) :hints (("Goal" :in-theory (e/d (times2) ())))) (defthm times2-of-sum (equal (times2 (sum a b)) (sum (times2 a) (times2 b))) :hints (("Goal" :in-theory (e/d (times2) ())))) (defthm d2-to-f2 (and (EQUAL (d2 (sum (-- (m2 x)) x)) (f2 x)) (EQUAL (d2 (sum x (-- (m2 x)))) (f2 x))) :hints (("Goal" :in-theory (e/d (sum m2 d2 f2) ())))) (defthmd f2-to-d2 (EQUAL (f2 x) (d2 (sum (-- (m2 x)) x))) :hints (("Goal" :in-theory (e/d () (SUM-COMM-1 SUM-COMM-2 (:REWRITE ACL2::|(mod x 2)| . 1) (:REWRITE ACL2::|(equal (if a b c) x)|) (:REWRITE ACL2::|(floor x 2)| . 1)))))) (defthmd equal-sum-of-negated (and (equal (equal (sum x y) (sum (-- a) b)) (equal (sum x y a) (ifix b))) (equal (equal (sum x y) (sum k (-- a) b)) (equal (sum x y a) (sum k b))) (equal (equal (sum x y) (sum k (-- a))) (equal (sum x y a) (ifix k))) (equal (equal (sum x y) (sum k l (-- a) b)) (equal (sum x y a) (sum k l b)))) :hints (("Goal" :in-theory (e/d (sum --) ())))) (defthm evenpi-of-times2 (and (equal (evenpi (sum (times2 a) x)) (evenpi x)) (equal (evenpi (sum x (times2 a))) (evenpi x)) (equal (evenpi (sum x y (times2 a))) (evenpi (sum x y))) (equal (evenpi (times2 a)) t)) :hints (("Goal" :in-theory (e/d (sum evenpi times2) ())))) (defthmd sum-with-oddp (implies (and (not (evenp x)) (integerp x) (integerp other)) (equal (evenp (+ x other)) (not (evenp other))))) (defthmd sum-with-evenp (implies (and (evenp x) (integerp x) (integerp other)) (equal (evenp (+ x other)) (evenp other)))) (defthmd evenpi-lemma-1-lemma (IMPLIES (AND (EQUAL (EVENP (IFIX S1)) (EVENP (IFIX B1))) (EQUAL (EVENP (IFIX S2)) (EVENP (IFIX B2)))) (equal (EVENP (+ (IFIX S1) (IFIX S2))) (EVENP (+ (IFIX B1) (IFIX B2)))))) (defthmd evenpi-lemma-1 (implies (and (equal (evenpi s1) (evenpi b1)) (equal (evenpi s2) (evenpi b2)) (evenpi (sum a s1 s2))) (evenpi (sum a b1 b2))) :otf-flg t :hints (("Goal" :use ((:instance evenpi-lemma-1-lemma)) :cases ((evenpi a)) :in-theory (e/d (evenpi sum-with-evenp sum sum-with-oddp) (evenp))))) (add-invisible-fns binary-sum --) (add-invisible-fns binary-sum m2) (add-invisible-fns binary-sum sum-list) (add-invisible-fns binary-sum times2) (encapsulate nil (local (use-arithmetic-5 t)) (local (in-theory (disable mod floor))) (defthmd d2-is-divide-by-2 (implies (evenpi x) (equal (d2 x) (/ (ifix x) 2))) :hints (("Goal" :in-theory (e/d (d2 f2 m2 sum evenp evenpi) ())))) (defthm evenpi-of-sum (implies (and (evenpi x) (evenpi y)) (evenpi (sum x y))) :hints (("Goal" :in-theory (e/d (evenpi sum) ())))) (local (defthm sum-of-d2-lemma (IMPLIES (AND (EVENPI X) (EVENPI Y)) (EQUAL (SUM (* 1/2 (IFIX X)) (* 1/2 (IFIX Y))) (* 1/2 (SUM X Y)))) :hints (("Goal" :in-theory (e/d (sum evenpi) ()))))) (defthm sum-of-d2 (implies (and (evenpi x) (evenpi y)) (and (equal (sum (d2 x) (d2 y)) (d2 (sum x Y))) (equal (sum (d2 x) (d2 y) z) (sum (d2 (sum x Y)) z)))) :hints (("Goal" :use ((:instance sum-of-d2-lemma)) :in-theory (e/d (d2-is-divide-by-2) (sum-of-d2-lemma))))) (defthm evenpi-of-term-minus-its-mod (and (evenpi (SUM A (-- (M2 A)))) (evenpi (SUM (-- (M2 A)) A))) :hints (("Goal" :in-theory (e/d (m2 sum evenpi) ())))) (defthm sum-of-f2s (and (equal (sum (f2 a) (f2 b)) (d2 (sum (-- (m2 a)) (-- (m2 b)) a b))) (equal (sum (f2 a) (f2 b) c) (sum (d2 (sum (-- (m2 a)) (-- (m2 b)) a b)) c))) :hints (("Goal" :in-theory (e/d (f2-to-d2) (d2-to-f2 D2-OF-MINUS ))))) (defthm sum-of-f2s-and-d2 (implies (evenpi b) (and (equal (sum (f2 a) (d2 b)) (d2 (sum (-- (m2 a)) a b))) (equal (sum (d2 b) (f2 a)) (d2 (sum (-- (m2 a)) a b))) (equal (sum (f2 a) (d2 b) c) (sum (d2 (sum (-- (m2 a)) a b)) c)) (equal (sum (d2 b) (f2 a) c) (sum (d2 (sum (-- (m2 a)) a b)) c)))) :hints (("Goal" :in-theory (e/d (f2-to-d2) (d2-to-f2 D2-OF-MINUS )))))) (defthm evenpi-for-2-d2-arguments (evenpi (sum a b (-- (m2 (sum a b))))) :hints (("Goal" :in-theory (e/d (evenpi sum m2) ())))) (defthm evenpi-for-3-d2-arguments (evenpi (sum a b c (-- (m2 (sum a b c))))) :hints (("Goal" :in-theory (e/d (evenpi sum m2) ())))) (defthm evenpi-for-4-d2-arguments (evenpi (sum a b c d (-- (m2 (sum a b c d))))) :hints (("Goal" :in-theory (e/d (evenpi sum m2) ())))) (defthm evenpi-sum-clear (and (equal (evenpi (sum a a b)) (evenpi (ifix b))) (equal (evenpi (sum a a)) t) (equal (evenpi (sum c a a b)) (evenpi (sum b c))) (equal (evenpi (sum c a a)) (evenpi (sum c))) (equal (evenpi (sum c d a a b)) (evenpi (sum b c d))) (equal (evenpi (sum c d a a )) (evenpi (sum c d))) (equal (evenpi (sum c d e a a b)) (evenpi (sum b c d e))) (equal (evenpi (sum c d e a a)) (evenpi (sum c d e)))) :hints (("Goal" :in-theory (e/d (sum evenpi) ())))) (defthm m2-with-extra (implies (equal (m2 x) (m2 y)) (equal (equal (m2 (sum x other)) (m2 (sum y other))) t)) :hints (("Goal" :in-theory (e/d (m2 sum) ())))) (defthm m2-with-extra-dummy-lemma (implies (equal (m2 (sum a b)) (m2 (sum x y z))) (equal (equal (m2 (sum other a b)) (m2 (sum x y z other))) t)) :hints (("Goal" :use ((:instance m2-with-extra (x (sum a b)) (y (sum x y z)) (other other))) :in-theory (e/d ( ) (m2-with-extra))))) (defthm evenpi-with-other (implies (equal (evenpi x) (evenpi y)) (equal (equal (evenpi (sum x z)) (evenpi (sum y z))) t)) :hints (("Goal" :in-theory (e/d (evenpi sum) ())))) (defthm bitp-m2 (bitp (m2 x)) :hints (("Goal" :in-theory (e/d (m2 sum f2) ())))) (in-theory (enable +-is-SUM mod2-is-m2 floor2-if-f2)) (defthm sum-of-negated-elements (implies (equal (-- a) b) (and (equal (sum a b) 0) (equal (sum b a) 0) (equal (sum b a rest) (ifix rest)) (equal (sum a b rest) (ifix rest)))) :hints (("Goal" :in-theory (e/d (sum --) (+-IS-SUM))))) (defthmd f2-of-times2-reverse (implies (syntaxp (or (atom term) (not (equal (car term) 'f2)))) (and (equal (sum term (f2 term2)) (f2 (sum (times2 term) term2))) (equal (sum (f2 term2) term) (f2 (sum (times2 term) term2))) (equal (sum term (f2 term2) other) (sum other (f2 (sum (times2 term) term2)))))))
true
; Note: The license below is based on the template at: ; http://opensource.org/licenses/BSD-3-Clause ; Copyright (C) 2019, Regents of the University of Texas ; 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> (in-package "RP") (include-book "fnc-defs") (local (include-book "projects/rp-rewriter/proofs/rp-equal-lemmas" :dir :system)) (local (fetch-new-events (include-book "arithmetic-5/top" :dir :system) use-arithmetic-5)) (defthm ifix-opener (implies (integerp x) (equal (ifix x) x)) :hints (("Goal" :in-theory (e/d (ifix) ())))) (defthm integerp-m2-f2-d2 (and (integerp (m2 x)) (integerp (d2 x)) (integerp (f2 x)) (integerp (sum x y)) (integerp (sum-list x))) :hints (("Goal" :in-theory (e/d (m2 f2 sum-list sum) ())))) (defthm integerp-ifix (integerp (ifix x))) (defthm m2-f2-d2-sum-of-ifix (and (equal (f2 (ifix x)) (f2 x)) (equal (d2 (ifix x)) (d2 x)) (equal (m2 (ifix x)) (m2 x)) (equal (sum (ifix x) b) (sum x b)) (equal (sum b (ifix x)) (sum x b))) :hints (("Goal" :in-theory (e/d (m2 f2 d2 sum) ( (:REWRITE ACL2::|(equal (if a b c) x)|) (:REWRITE ACL2::|(floor x 2)| . 1)))))) (defthm consp-of-rp-trans-lst (equal (CONSP (RP-TRANS-LST lst)) (consp lst)) :hints (("Goal" :induct (len lst) :do-not-induct t :in-theory (e/d () ())))) (progn (defun sum-comm-order-aux (x cnt) (case-match x (('m2 &) (mv 'm2 x)) (('f2 &) (mv 'f2 x)) (('d2 &) (mv 'd2 x)) (('-- x) (sum-comm-order-aux x (1+ cnt))) (('times2 x) (sum-comm-order-aux x (1+ cnt))) (('sum-list x) (sum-comm-order-aux x (1+ cnt))) (('sum-list-eval x &) (sum-comm-order-aux x (1+ cnt))) (('rp-evl x &) (sum-comm-order-aux x (1+ cnt))) (('rp-trans x) (sum-comm-order-aux x (1+ cnt))) (('mv-nth & &) (mv 'mv-nth (list (caddr x) (cadr x)))) (('pp-sum-merge & &) (mv 'merge x)) (('s-sum-merge & &) (mv 'merge x)) (('car x) (sum-comm-order-aux x (1+ cnt))) (('cdr x) (sum-comm-order-aux x (1+ cnt))) (('binary-sum & &) (mv 'binary-sum x)) (('binary-m2-chain & &) (mv 'binary-m2-chain x)) (('ex-from-rp/-- &) (mv 'm2 x)) (& (mv cnt x)))) (defun sum-comm-order (a b) (b* (((mv a-type a) (sum-comm-order-aux a 0)) ((mv b-type b) (sum-comm-order-aux b 0))) (cond ((or (equal a-type 'binary-sum) (equal a-type 'binary-m2-chain) (equal b-type 'binary-sum) (equal b-type 'binary-m2-chain)) nil) ((or (and (equal a-type 'm2) (equal b-type 'm2)) (and (equal a-type 'mv-nth) (equal b-type 'mv-nth)) (and (equal a-type 'merge) (equal b-type 'merge))) (b* (((mv res &) (lexorder2 a b))) res)) ((or (equal a-type 'm2) (equal b-type 'm2)) (not (equal b-type 'm2))) ((or (equal a-type 'mv-nth) (equal b-type 'mv-nth)) (not (equal b-type 'mv-nth))) ((or (equal a-type 'merge) (equal b-type 'merge)) (not (equal b-type 'merge))) ((or (and (equal a-type 'd2) (equal b-type 'd2)) (and (equal a-type 'f2) (equal b-type 'f2))) (b* (((mv res &) (lexorder2 a b))) res)) ((or (equal a-type 'd2) (equal b-type 'd2)) (not (equal a-type 'd2))) ((or (equal a-type 'f2) (equal b-type 'f2)) (not (equal a-type 'f2))) ((and (integerp a-type) (integerp b-type)) (b* (((mv res equals) (lexorder2 a b))) (if equals (> a-type b-type) res))) ((or (integerp a-type) (integerp b-type)) (not (integerp a-type))) (t (b* (((mv res &) (lexorder2 a b))) res))))) (defthm sum-comm-1 (implies (syntaxp (sum-comm-order a b)) (equal (sum b a) (sum a b))) :rule-classes ((:rewrite :loop-stopper nil)) :hints (("Goal" :in-theory (e/d (sum) ())))) (defthmd sum-comm-1-loop-stopper (implies t (equal (sum b a) (sum a b))) :hints (("Goal" :in-theory (e/d (sum) ())))) (defthm sum-comm-2 (implies (syntaxp (sum-comm-order a b)) (equal (sum b a c) (sum a b c))) :rule-classes ((:rewrite :loop-stopper nil)) :hints (("Goal" :in-theory (e/d (sum) ())))) (defthmd sum-comm-2-loop-stopper (implies t (equal (sum b a c) (sum a b c))) :hints (("Goal" :in-theory (e/d (sum) ())))) (defthm sum-assoc (equal (sum (sum a b) c) (sum a b c)) :hints (("Goal" :in-theory (e/d (sum) ())))) (defthm sum-of-0 (and (equal (sum 0 a) (ifix a)) (equal (sum a 0) (ifix a))) :hints (("Goal" :in-theory (e/d (sum) ())))) (defthm sum-of-ifix (and (equal (sum (ifix x) y) (sum x y)) (equal (sum x (ifix y)) (sum x y))) :hints (("Goal" :in-theory (e/d (ifix sum) ())))) ) (in-theory (disable ifix)) (defthm sum-list-of-append (EQUAL (SUM-LIST (APPEND lst1 lst2)) (SUM (sum-list lst1) (sum-list lst2))) :hints (("Goal" :in-theory (e/d (sum-list sum) ())))) (defthm sum-list-of-true-list-fix (equal (SUM-LIST (TRUE-LIST-FIX lst)) (SUM-LIST lst)) :hints (("Goal" :induct (true-list-fix lst) :do-not-induct t :in-theory (e/d (sum-list true-list-fix) ((:REWRITE ACL2::LIST-FIX-WHEN-TRUE-LISTP) (:REWRITE RP-TERM-LISTP-IS-TRUE-LISTP) (:DEFINITION ACL2::APPLY$-BADGEP) (:REWRITE ACL2::CDR-OF-LIST-FIX) (:DEFINITION TRUE-LISTP)))))) (defthmd and-list-is-and$ (implies (consp lst) (equal (and-list hash lst) (if (atom (cdr lst)) (bit-fix (car lst)) (and$ (car lst) (and-list hash (cdr lst)))))) :hints (("Goal" :in-theory (e/d (and$ and-list) ())))) (defthmd and$-is-and-list (implies t (equal (and$ a b) (and-list 0 (list a b)))) :hints (("Goal" :in-theory (e/d (and$ and-list) ())))) (defthm -of- (implies (integerp a) (equal (- (- a)) a))) (defthm sum-of-subtracted (and (equal (sum x (-- x)) 0) (equal (sum (-- x) x) 0) (equal (sum (-- x) x z) (ifix z)) (equal (sum x (-- x) z) (ifix z))) :hints (("Goal" :in-theory (e/d (sum --) ())))) (defthmd +-is-SUM (implies (and (integerp a) (integerp b)) (equal (+ a b) (sum a b))) :hints (("Goal" :in-theory (e/d (sum) ())))) (defthmd mod2-is-m2 (implies (integerp x) (equal (mod x 2) (m2 x))) :hints (("Goal" :in-theory (e/d (m2) (mod))))) (defthmd floor2-if-f2 (implies (integerp x) (equal (floor x 2) (f2 x))) :hints (("Goal" :in-theory (e/d (f2) (floor))))) (defthm c-is-f2 (equal (c hash-code a b c) (f2 (sum (sum-list a) (sum-list b) (sum-list c)))) :hints (("Goal" :in-theory (e/d (c f2 sum sum-list) (+-is-SUM floor2-if-f2 mod2-is-m2))))) #|(defthm d-sum-to-sum (equal (d-sum x y z) (sum (sum-list x) (sum-list y) z)) :hints (("Goal" :in-theory (e/d (d-sum) ()))))||# #|(defthm d-is-d2 (equal (d x) (d2 x)) :hints (("Goal" :in-theory (e/d (d2 d -- FLOOR2-IF-F2 mod2-is-m2) (floor mod (:REWRITE ACL2::|(- (if a b c))|) (:REWRITE ACL2::|(floor x 2)| . 1) (:REWRITE ACL2::|(mod x 2)| . 1) (:REWRITE SUM-COMM-1))))))||# (defthm s-is-m2 (equal (s hash-code b c) (m2 (sum (sum-list b) (sum-list c)))) :hints (("Goal" :in-theory (e/d (s m2 sum sum-list) (+-is-SUM floor2-if-f2 mod2-is-m2))))) (defthm sum-list-is-sum (equal (sum-list (cons a b)) (sum a (sum-list b))) :hints (("Goal" :expand (sum-list (cons a b)) :in-theory (e/d (sum-list sum ) (SUM-OF-IFIX +-is-SUM))))) (defthm s-spec-is-m2 (equal (s-spec lst) (m2 (sum-list lst))) :hints (("Goal" :in-theory (e/d (s-spec mod2-is-m2) ((:REWRITE ACL2::|(equal (if a b c) x)|) (:REWRITE ACL2::|(mod x 2)| . 1)))))) (defthm c-spec-is-f2 (equal (c-spec lst) (f2 (sum-list lst))) :hints (("Goal" :in-theory (e/d (c-spec floor2-if-f2) ())))) (defthm s-c-spec-is-list-m2-f2 (equal (s-c-spec sum) (list (m2 (sum-list sum)) (f2 (sum-list sum)))) :hints (("Goal" :in-theory (e/d (s-c-spec) ())))) (defthm c-s-spec-is-list-m2-f2 (equal (c-s-spec sum) (list (f2 (sum-list sum)) (m2 (sum-list sum)))) :hints (("Goal" :in-theory (e/d (c-s-spec) ())))) (defthm s-of-c-trig-def (equal (s-of-c-trig x) x) :hints (("Goal" :in-theory (e/d (s-of-c-trig) ())))) (defthm s-of-s-lemma1 (implies t (equal (equal (m2 (sum x1 rest1)) (m2 (sum x1 rest2))) (equal (m2 rest1) (m2 rest2)))) :hints (("Goal" :in-theory (e/d (m2 sum) (mod2-is-m2 +-is-SUM))))) (defthm s-of-s-lemma2 (implies t (equal (equal (m2 x1) (m2 (sum x1 rest2))) (equal 0 (m2 rest2)))) :hints (("Goal" :in-theory (e/d (m2 sum) (mod2-is-m2 +-is-SUM))))) (encapsulate nil (defthm f2-of-times2 (and (equal (f2 (sum (times2 a) b)) (sum a (f2 (sum b)))) (equal (f2 (times2 a)) (ifix a))) :hints (("Goal" :do-not '(preprocess) :in-theory (e/d (sum f2 times2) ())))) (local (defthm f2-of-minus-lemma1 (equal (f2 (sum (-- a) b)) (f2 (sum (times2 (-- a)) a b))) :hints (("Goal" :in-theory (e/d (sum -- times2) ()))))) (defthm f2-of-minus (implies t ;(bitp a) (equal (f2 (sum (-- a) b)) (sum (-- a) (f2 (sum a b))))) :hints (("Goal" :in-theory (e/d () (SUM-COMM-1 SUM-COMM-2)))))) (encapsulate nil (defthm m2-of-times2 (and (equal (m2 (sum (times2 a) b)) (m2 b)) (equal (m2 (times2 a)) 0)) :hints (("Goal" :in-theory (e/d (m2 sum times2) ())))) (local (defthm s-of-minus-lemma (and (equal (m2 (sum (-- a) b)) (m2 (sum (times2 (-- a)) a b))) (equal (m2 (sum (-- a) b)) (m2 (sum (times2 (-- a)) a b)))) :hints (("Goal" :in-theory (e/d (sum times2 --) ()))))) (defthm s-of-minus (and (equal (m2 (sum (-- a) b)) (m2 (sum a b)))) :hints (("Goal" :in-theory (e/d () (SUM-COMM-1 SUM-COMM-2)))))) (encapsulate nil (defthm d2-of-times2 (and (equal (d2 (sum (times2 a) b)) (sum a (d2 (sum b)))) (equal (d2 (times2 a)) (ifix a))) :hints (("Goal" :do-not '(preprocess) :in-theory (e/d (d2) (SUM-COMM-1 SUM-COMM-2))))) (local (defthm d2-of-minus-lemma1 (equal (d2 (sum (-- a) b)) (d2 (sum (times2 (-- a)) a b))) :hints (("Goal" :in-theory (e/d (sum -- times2) ()))))) (defthm d2-of-minus (implies t ;(bitp a) (equal (d2 (sum (-- a) b)) (sum (-- a) (d2 (sum a b))))) :hints (("Goal" :in-theory (e/d () (SUM-COMM-1 SUM-COMM-2)))))) (defthm m2-of--- (and (equal (m2 (sum (-- x) rest)) (m2 (sum x rest))) (equal (m2 (sum rest1 (-- x) rest)) (m2 (sum x rest rest1))) (equal (m2 (sum rest1 (-- x))) (m2 (sum x rest1))) (equal (m2 (-- x)) (m2 x))) :hints (("Goal" :use ((:instance s-of-minus (a x) (b rest)) (:instance s-of-minus (a x) (b (sum rest rest1)))) :in-theory (e/d ( ) (s-of-minus))))) (defthm m2-of-ifix (equal (m2 (ifix x)) (m2 x)) :hints (("Goal" :in-theory (e/d (m2) ())))) (defthm f2-of-ifix (equal (f2 (ifix x)) (f2 x)) :hints (("Goal" :in-theory (e/d (f2) ())))) (defthm ifix-of-f2 (equal (ifix (f2 x)) (f2 x)) :hints (("Goal" :in-theory (e/d (ifix f2) ())))) (defthm ifix-of-m2 (equal (ifix (m2 x)) (m2 x)) :hints (("Goal" :in-theory (e/d (ifix) ())))) (defthm sum-of-equals (and (equal (equal (sum a b) (sum a c)) (equal (ifix b) (ifix c))) (equal (equal (sum b a) (sum a c)) (equal (ifix b) (ifix c))) (equal (equal (sum x a b) (sum a c)) (equal (sum b x) (ifix c))) (equal (equal (sum x a b) (sum y a c)) (equal (sum x b) (sum y c)))) :hints (("Goal" :in-theory (e/d (sum) (+-is-SUM))))) (defthm integerp-f2 (integerp (f2 x))) (defthm dummy-sum-cancel-lemma1 (implies (equal (sum a b) 0) (equal (sum a b c) (ifix c))) :hints (("Goal" :in-theory (e/d (sum) ())))) (defthm f2-of-bit (implies (bitp x) (equal (f2 x) 0)) :hints (("Goal" :in-theory (e/d (bitp) ())))) (def-rp-rule m2-of-m2 (and (equal (m2 (m2 x)) (m2 x)) (equal (m2 (sum (m2 x) y)) (m2 (sum x y)))) :hints (("Goal" :in-theory (e/d (m2 sum) ())))) (defthm m2-of-m2-extended (and (equal (m2 (sum a b c (m2 x))) (m2 (sum a b c x))) (equal (m2 (sum a b (m2 x))) (m2 (sum a b x)))) :hints (("Goal" :use ((:instance M2-OF-M2 (x x) (y (sum a b c))) (:instance M2-OF-M2 (x x) (y (sum a b)))) :in-theory (e/d () (M2-OF-M2))))) (defthmd sum-of-repeated-to-times2 (and (equal (sum x x) (times2 x)) (equal (sum x x y) (sum (times2 x) y))) :hints (("Goal" :in-theory (e/d (times2) ())))) (defthm times2-of-sum (equal (times2 (sum a b)) (sum (times2 a) (times2 b))) :hints (("Goal" :in-theory (e/d (times2) ())))) (defthm d2-to-f2 (and (EQUAL (d2 (sum (-- (m2 x)) x)) (f2 x)) (EQUAL (d2 (sum x (-- (m2 x)))) (f2 x))) :hints (("Goal" :in-theory (e/d (sum m2 d2 f2) ())))) (defthmd f2-to-d2 (EQUAL (f2 x) (d2 (sum (-- (m2 x)) x))) :hints (("Goal" :in-theory (e/d () (SUM-COMM-1 SUM-COMM-2 (:REWRITE ACL2::|(mod x 2)| . 1) (:REWRITE ACL2::|(equal (if a b c) x)|) (:REWRITE ACL2::|(floor x 2)| . 1)))))) (defthmd equal-sum-of-negated (and (equal (equal (sum x y) (sum (-- a) b)) (equal (sum x y a) (ifix b))) (equal (equal (sum x y) (sum k (-- a) b)) (equal (sum x y a) (sum k b))) (equal (equal (sum x y) (sum k (-- a))) (equal (sum x y a) (ifix k))) (equal (equal (sum x y) (sum k l (-- a) b)) (equal (sum x y a) (sum k l b)))) :hints (("Goal" :in-theory (e/d (sum --) ())))) (defthm evenpi-of-times2 (and (equal (evenpi (sum (times2 a) x)) (evenpi x)) (equal (evenpi (sum x (times2 a))) (evenpi x)) (equal (evenpi (sum x y (times2 a))) (evenpi (sum x y))) (equal (evenpi (times2 a)) t)) :hints (("Goal" :in-theory (e/d (sum evenpi times2) ())))) (defthmd sum-with-oddp (implies (and (not (evenp x)) (integerp x) (integerp other)) (equal (evenp (+ x other)) (not (evenp other))))) (defthmd sum-with-evenp (implies (and (evenp x) (integerp x) (integerp other)) (equal (evenp (+ x other)) (evenp other)))) (defthmd evenpi-lemma-1-lemma (IMPLIES (AND (EQUAL (EVENP (IFIX S1)) (EVENP (IFIX B1))) (EQUAL (EVENP (IFIX S2)) (EVENP (IFIX B2)))) (equal (EVENP (+ (IFIX S1) (IFIX S2))) (EVENP (+ (IFIX B1) (IFIX B2)))))) (defthmd evenpi-lemma-1 (implies (and (equal (evenpi s1) (evenpi b1)) (equal (evenpi s2) (evenpi b2)) (evenpi (sum a s1 s2))) (evenpi (sum a b1 b2))) :otf-flg t :hints (("Goal" :use ((:instance evenpi-lemma-1-lemma)) :cases ((evenpi a)) :in-theory (e/d (evenpi sum-with-evenp sum sum-with-oddp) (evenp))))) (add-invisible-fns binary-sum --) (add-invisible-fns binary-sum m2) (add-invisible-fns binary-sum sum-list) (add-invisible-fns binary-sum times2) (encapsulate nil (local (use-arithmetic-5 t)) (local (in-theory (disable mod floor))) (defthmd d2-is-divide-by-2 (implies (evenpi x) (equal (d2 x) (/ (ifix x) 2))) :hints (("Goal" :in-theory (e/d (d2 f2 m2 sum evenp evenpi) ())))) (defthm evenpi-of-sum (implies (and (evenpi x) (evenpi y)) (evenpi (sum x y))) :hints (("Goal" :in-theory (e/d (evenpi sum) ())))) (local (defthm sum-of-d2-lemma (IMPLIES (AND (EVENPI X) (EVENPI Y)) (EQUAL (SUM (* 1/2 (IFIX X)) (* 1/2 (IFIX Y))) (* 1/2 (SUM X Y)))) :hints (("Goal" :in-theory (e/d (sum evenpi) ()))))) (defthm sum-of-d2 (implies (and (evenpi x) (evenpi y)) (and (equal (sum (d2 x) (d2 y)) (d2 (sum x Y))) (equal (sum (d2 x) (d2 y) z) (sum (d2 (sum x Y)) z)))) :hints (("Goal" :use ((:instance sum-of-d2-lemma)) :in-theory (e/d (d2-is-divide-by-2) (sum-of-d2-lemma))))) (defthm evenpi-of-term-minus-its-mod (and (evenpi (SUM A (-- (M2 A)))) (evenpi (SUM (-- (M2 A)) A))) :hints (("Goal" :in-theory (e/d (m2 sum evenpi) ())))) (defthm sum-of-f2s (and (equal (sum (f2 a) (f2 b)) (d2 (sum (-- (m2 a)) (-- (m2 b)) a b))) (equal (sum (f2 a) (f2 b) c) (sum (d2 (sum (-- (m2 a)) (-- (m2 b)) a b)) c))) :hints (("Goal" :in-theory (e/d (f2-to-d2) (d2-to-f2 D2-OF-MINUS ))))) (defthm sum-of-f2s-and-d2 (implies (evenpi b) (and (equal (sum (f2 a) (d2 b)) (d2 (sum (-- (m2 a)) a b))) (equal (sum (d2 b) (f2 a)) (d2 (sum (-- (m2 a)) a b))) (equal (sum (f2 a) (d2 b) c) (sum (d2 (sum (-- (m2 a)) a b)) c)) (equal (sum (d2 b) (f2 a) c) (sum (d2 (sum (-- (m2 a)) a b)) c)))) :hints (("Goal" :in-theory (e/d (f2-to-d2) (d2-to-f2 D2-OF-MINUS )))))) (defthm evenpi-for-2-d2-arguments (evenpi (sum a b (-- (m2 (sum a b))))) :hints (("Goal" :in-theory (e/d (evenpi sum m2) ())))) (defthm evenpi-for-3-d2-arguments (evenpi (sum a b c (-- (m2 (sum a b c))))) :hints (("Goal" :in-theory (e/d (evenpi sum m2) ())))) (defthm evenpi-for-4-d2-arguments (evenpi (sum a b c d (-- (m2 (sum a b c d))))) :hints (("Goal" :in-theory (e/d (evenpi sum m2) ())))) (defthm evenpi-sum-clear (and (equal (evenpi (sum a a b)) (evenpi (ifix b))) (equal (evenpi (sum a a)) t) (equal (evenpi (sum c a a b)) (evenpi (sum b c))) (equal (evenpi (sum c a a)) (evenpi (sum c))) (equal (evenpi (sum c d a a b)) (evenpi (sum b c d))) (equal (evenpi (sum c d a a )) (evenpi (sum c d))) (equal (evenpi (sum c d e a a b)) (evenpi (sum b c d e))) (equal (evenpi (sum c d e a a)) (evenpi (sum c d e)))) :hints (("Goal" :in-theory (e/d (sum evenpi) ())))) (defthm m2-with-extra (implies (equal (m2 x) (m2 y)) (equal (equal (m2 (sum x other)) (m2 (sum y other))) t)) :hints (("Goal" :in-theory (e/d (m2 sum) ())))) (defthm m2-with-extra-dummy-lemma (implies (equal (m2 (sum a b)) (m2 (sum x y z))) (equal (equal (m2 (sum other a b)) (m2 (sum x y z other))) t)) :hints (("Goal" :use ((:instance m2-with-extra (x (sum a b)) (y (sum x y z)) (other other))) :in-theory (e/d ( ) (m2-with-extra))))) (defthm evenpi-with-other (implies (equal (evenpi x) (evenpi y)) (equal (equal (evenpi (sum x z)) (evenpi (sum y z))) t)) :hints (("Goal" :in-theory (e/d (evenpi sum) ())))) (defthm bitp-m2 (bitp (m2 x)) :hints (("Goal" :in-theory (e/d (m2 sum f2) ())))) (in-theory (enable +-is-SUM mod2-is-m2 floor2-if-f2)) (defthm sum-of-negated-elements (implies (equal (-- a) b) (and (equal (sum a b) 0) (equal (sum b a) 0) (equal (sum b a rest) (ifix rest)) (equal (sum a b rest) (ifix rest)))) :hints (("Goal" :in-theory (e/d (sum --) (+-IS-SUM))))) (defthmd f2-of-times2-reverse (implies (syntaxp (or (atom term) (not (equal (car term) 'f2)))) (and (equal (sum term (f2 term2)) (f2 (sum (times2 term) term2))) (equal (sum (f2 term2) term) (f2 (sum (times2 term) term2))) (equal (sum term (f2 term2) other) (sum other (f2 (sum (times2 term) term2)))))))
[ { "context": "#|\nCopyright (c) 2016 Thomas W. Lynch and Reasoning Technology Inc.\nReleased under the ", "end": 37, "score": 0.9998531341552734, "start": 22, "tag": "NAME", "value": "Thomas W. Lynch" } ]
deprecated/src-second-level/ea-parked.lisp
Antigonus/tm
6
#| Copyright (c) 2016 Thomas W. Lynch and Reasoning Technology Inc. Released under the MIT License (MIT) See LICENSE.txt |# (in-package #:tm) ;;-------------------------------------------------------------------------------- ;; entanglements support ;; (defun-typed entangled-on-same-cell ((tm ea-parked) &optional ➜) (destructuring-bind (&key (➜∅ (be ∅)) &allow-other-keys ) ➜ [➜∅] )) (defun-typed entangled-on-right-neighbor-cell ((tm ea-parked) &optional ➜) (destructuring-bind (&key (➜t (be t)) (➜∅ (be ∅)) &allow-other-keys ) ➜ (entangled-on-leftmost (entanglements tm) ➜t ➜∅) )) ;;-------------------------------------------------------------------------------- ;; tm-decl-only ;; (defun-typed -s* ((tm ea-parked) &optional ➜) (destructuring-bind (&key (➜ok (be t)) &allow-other-keys ) ➜ (to-active tm) ;; address is already 0, and (base tm) already on leftmost -- by convention [➜ok] )) ;;-------------------------------------------------------------------------------- ;;tm-generic ;; (defun-typed s* ((tm ea-parked) &optional ➜) (destructuring-bind (&key (➜ok (be t)) &allow-other-keys ) ➜ (call-next-method tm { :ok (λ() (setf (address tm) (address-rightmost tm)) [➜ok] ) (o (remove-key-pair ➜ :➜ok)) } ))) ;;-------------------------------------------------------------------------------- ;; solo-tm-decl-only ;; ;; see ea-parked-active for epa, epd
138
#| Copyright (c) 2016 <NAME> and Reasoning Technology Inc. Released under the MIT License (MIT) See LICENSE.txt |# (in-package #:tm) ;;-------------------------------------------------------------------------------- ;; entanglements support ;; (defun-typed entangled-on-same-cell ((tm ea-parked) &optional ➜) (destructuring-bind (&key (➜∅ (be ∅)) &allow-other-keys ) ➜ [➜∅] )) (defun-typed entangled-on-right-neighbor-cell ((tm ea-parked) &optional ➜) (destructuring-bind (&key (➜t (be t)) (➜∅ (be ∅)) &allow-other-keys ) ➜ (entangled-on-leftmost (entanglements tm) ➜t ➜∅) )) ;;-------------------------------------------------------------------------------- ;; tm-decl-only ;; (defun-typed -s* ((tm ea-parked) &optional ➜) (destructuring-bind (&key (➜ok (be t)) &allow-other-keys ) ➜ (to-active tm) ;; address is already 0, and (base tm) already on leftmost -- by convention [➜ok] )) ;;-------------------------------------------------------------------------------- ;;tm-generic ;; (defun-typed s* ((tm ea-parked) &optional ➜) (destructuring-bind (&key (➜ok (be t)) &allow-other-keys ) ➜ (call-next-method tm { :ok (λ() (setf (address tm) (address-rightmost tm)) [➜ok] ) (o (remove-key-pair ➜ :➜ok)) } ))) ;;-------------------------------------------------------------------------------- ;; solo-tm-decl-only ;; ;; see ea-parked-active for epa, epd
true
#| Copyright (c) 2016 PI:NAME:<NAME>END_PI and Reasoning Technology Inc. Released under the MIT License (MIT) See LICENSE.txt |# (in-package #:tm) ;;-------------------------------------------------------------------------------- ;; entanglements support ;; (defun-typed entangled-on-same-cell ((tm ea-parked) &optional ➜) (destructuring-bind (&key (➜∅ (be ∅)) &allow-other-keys ) ➜ [➜∅] )) (defun-typed entangled-on-right-neighbor-cell ((tm ea-parked) &optional ➜) (destructuring-bind (&key (➜t (be t)) (➜∅ (be ∅)) &allow-other-keys ) ➜ (entangled-on-leftmost (entanglements tm) ➜t ➜∅) )) ;;-------------------------------------------------------------------------------- ;; tm-decl-only ;; (defun-typed -s* ((tm ea-parked) &optional ➜) (destructuring-bind (&key (➜ok (be t)) &allow-other-keys ) ➜ (to-active tm) ;; address is already 0, and (base tm) already on leftmost -- by convention [➜ok] )) ;;-------------------------------------------------------------------------------- ;;tm-generic ;; (defun-typed s* ((tm ea-parked) &optional ➜) (destructuring-bind (&key (➜ok (be t)) &allow-other-keys ) ➜ (call-next-method tm { :ok (λ() (setf (address tm) (address-rightmost tm)) [➜ok] ) (o (remove-key-pair ➜ :➜ok)) } ))) ;;-------------------------------------------------------------------------------- ;; solo-tm-decl-only ;; ;; see ea-parked-active for epa, epd
[ { "context": "he LICENSE file distributed with ACL2.\n;\n; Author: Alessandro Coglio ([email protected])\n\n;;;;;;;;;;;;;;;;;;;;;;;;;;;", "end": 202, "score": 0.9998771548271179, "start": 185, "tag": "NAME", "value": "Alessandro Coglio" }, { "context": "ributed with ACL2.\n;\n; Author: Alessandro Coglio ([email protected])\n\n;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;", "end": 222, "score": 0.9999303817749023, "start": 204, "tag": "EMAIL", "value": "[email protected]" } ]
books/kestrel/std/system/apply-term.lisp
kwancarl/acl2
0
; Standard System Library ; ; Copyright (C) 2019 Kestrel Institute (http://www.kestrel.edu) ; ; License: A 3-clause BSD license. See the LICENSE file distributed with ACL2. ; ; Author: Alessandro Coglio ([email protected]) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (in-package "ACL2") (include-book "pseudo-termfnp") ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (define apply-term ((fn pseudo-termfnp) (terms pseudo-term-listp)) :guard (or (symbolp fn) (= (len terms) (len (lambda-formals fn)))) :returns (term "A @(tsee pseudo-termp).") :parents (std/system/term-transformations) :short "Apply a function symbol or a lambda expression to a list of terms, obtaining a term." :long (xdoc::topstring-p "This utility is similar to @(tsee cons-term), but it performs a beta reduction when @('fn') is a lambda expression.") (cond ((symbolp fn) (cons-term fn terms)) (t (subcor-var (lambda-formals fn) terms (lambda-body fn)))) :guard-hints (("Goal" :in-theory (enable pseudo-termfnp pseudo-lambdap)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defsection apply-term* :parents (term-utilities) :short "Apply a function symbol or a lambda expression to zero or more terms, obtaining a term." :long (xdoc::topstring (xdoc::p "This utility is similar to @(tsee cons-term*), but it performs a beta reduction when @('fn') is a lambda expressions. It is a macro version of @(tsee apply-term).") (xdoc::@def "apply-term*")) (defmacro apply-term* (fn &rest terms) `(apply-term ,fn (list ,@terms))))
43947
; Standard System Library ; ; Copyright (C) 2019 Kestrel Institute (http://www.kestrel.edu) ; ; License: A 3-clause BSD license. See the LICENSE file distributed with ACL2. ; ; Author: <NAME> (<EMAIL>) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (in-package "ACL2") (include-book "pseudo-termfnp") ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (define apply-term ((fn pseudo-termfnp) (terms pseudo-term-listp)) :guard (or (symbolp fn) (= (len terms) (len (lambda-formals fn)))) :returns (term "A @(tsee pseudo-termp).") :parents (std/system/term-transformations) :short "Apply a function symbol or a lambda expression to a list of terms, obtaining a term." :long (xdoc::topstring-p "This utility is similar to @(tsee cons-term), but it performs a beta reduction when @('fn') is a lambda expression.") (cond ((symbolp fn) (cons-term fn terms)) (t (subcor-var (lambda-formals fn) terms (lambda-body fn)))) :guard-hints (("Goal" :in-theory (enable pseudo-termfnp pseudo-lambdap)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defsection apply-term* :parents (term-utilities) :short "Apply a function symbol or a lambda expression to zero or more terms, obtaining a term." :long (xdoc::topstring (xdoc::p "This utility is similar to @(tsee cons-term*), but it performs a beta reduction when @('fn') is a lambda expressions. It is a macro version of @(tsee apply-term).") (xdoc::@def "apply-term*")) (defmacro apply-term* (fn &rest terms) `(apply-term ,fn (list ,@terms))))
true
; Standard System Library ; ; Copyright (C) 2019 Kestrel Institute (http://www.kestrel.edu) ; ; License: A 3-clause BSD license. See the LICENSE file distributed with ACL2. ; ; Author: PI:NAME:<NAME>END_PI (PI:EMAIL:<EMAIL>END_PI) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (in-package "ACL2") (include-book "pseudo-termfnp") ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (define apply-term ((fn pseudo-termfnp) (terms pseudo-term-listp)) :guard (or (symbolp fn) (= (len terms) (len (lambda-formals fn)))) :returns (term "A @(tsee pseudo-termp).") :parents (std/system/term-transformations) :short "Apply a function symbol or a lambda expression to a list of terms, obtaining a term." :long (xdoc::topstring-p "This utility is similar to @(tsee cons-term), but it performs a beta reduction when @('fn') is a lambda expression.") (cond ((symbolp fn) (cons-term fn terms)) (t (subcor-var (lambda-formals fn) terms (lambda-body fn)))) :guard-hints (("Goal" :in-theory (enable pseudo-termfnp pseudo-lambdap)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defsection apply-term* :parents (term-utilities) :short "Apply a function symbol or a lambda expression to zero or more terms, obtaining a term." :long (xdoc::topstring (xdoc::p "This utility is similar to @(tsee cons-term*), but it performs a beta reduction when @('fn') is a lambda expressions. It is a macro version of @(tsee apply-term).") (xdoc::@def "apply-term*")) (defmacro apply-term* (fn &rest terms) `(apply-term ,fn (list ,@terms))))
[ { "context": "#|\n This file is a part of Chirp\n (c) 2014 Shirakumo http://tymoon.eu ([email protected])\n Author: Ni", "end": 52, "score": 0.979475200176239, "start": 43, "tag": "NAME", "value": "Shirakumo" }, { "context": "rt of Chirp\n (c) 2014 Shirakumo http://tymoon.eu ([email protected])\n Author: Nicolas Hafner <[email protected]>\n|#\n", "end": 89, "score": 0.9999110698699951, "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.tymoon", "end": 114, "score": 0.9998860955238342, "start": 100, "tag": "NAME", "value": "Nicolas Hafner" }, { "context": ".eu ([email protected])\n Author: Nicolas Hafner <[email protected]>\n|#\n\n(in-package #:org.tymoonnext.chirp)\n\n(defvar", "end": 134, "score": 0.9999178647994995, "start": 116, "tag": "EMAIL", "value": "[email protected]" } ]
stream.lisp
Ferada/chirp
59
#| This file is a part of Chirp (c) 2014 Shirakumo http://tymoon.eu ([email protected]) Author: Nicolas Hafner <[email protected]> |# (in-package #:org.tymoonnext.chirp) (defvar *stream/statuses/filter* "https://stream.twitter.com/1.1/statuses/filter.json") (defvar *stream/statuses/sample* "https://stream.twitter.com/1.1/statuses/sample.json") (defvar *stream/statuses/firehose* "https://stream.twitter.com/1.1/statuses/firehose.json") (defvar *stream/user* "https://userstream.twitter.com/1.1/user.json") (defvar *stream/site* "https://sitestream.twitter.com/1.1/site.json") (defclass message () () (:documentation "Superclass for all stream messages. According to spec https://dev.twitter.com/docs/streaming-apis/messages")) (defclass* stream-unknown (message) (data) (:documentation "Unknown stream object")) (defclass* stream-delete (message) (id user-id) (:documentation "Status deletion notice")) (defmethod print-object ((message stream-delete) stream) (print-unreadable-object (message stream :type T :identity T) (format stream "#~a" (id message))) message) (define-make-* (stream-delete parameters) (:id (cdr (assoc :id (cdr (assoc :status parameters))))) (:user-id (cdr (assoc :user-id (cdr (assoc :status parameters)))))) (defclass* stream-scrub-geo (message) (user-id up-to-status-id) (:documentation "Location deletion notice")) (defmethod print-object ((message stream-scrub-geo) stream) (print-unreadable-object (message stream :type T :identity T) (format stream "->#~a" (up-to-status-id message))) message) (define-make-* (stream-scrub-geo) :user-id :up-to-status-id) (defclass* stream-limit (message) (track) (:documentation "Limit notice")) (defmethod print-object ((message stream-limit) stream) (print-unreadable-object (message stream :type T :identity T) (format stream "F:~a" (track message))) message) (define-make-* (stream-limit) :track) (defclass* stream-status-withheld (message) (id withheld-in-countries) (:documentation "Status withheld notice")) (defmethod print-object ((message stream-status-withheld) stream) (print-unreadable-object (message stream :type T :identity T) (format stream "#~a (~{~a~^, ~})" (id message) (withheld-in-countries message))) message) (define-make-* (stream-status-withheld) :id :withheld-in-countries) (defclass* stream-user-withheld (message) (id withheld-in-countries) (:documentation "User withheld notice")) (defmethod print-object ((message stream-user-withheld) stream) (print-unreadable-object (message stream :type T :identity T) (format stream "#~a (~{~a~^, ~})" (id message) (withheld-in-countries message))) message) (define-make-* (stream-user-withheld) :id :withheld-in-countries) (defclass* stream-disconnect (message) (code stream-name reason) (:documentation "Disconnection notice")) (defmethod print-object ((message stream-disconnect) stream) (print-unreadable-object (message stream :type T :identity T) (format stream "~a (~a) #~a" (reason message) (code message) (stream-name message))) message) (define-make-* (stream-disconnect) :code :stream-name :reason) (defclass* stream-friends (message) (friends) (:documentation "Friends list notice")) (define-make-* (stream-friends) :friends) (defclass* stream-event (message) (target source target-object created-at) (:documentation "Stream event superclass")) (defmethod print-object ((message stream-event) stream) (print-unreadable-object (message stream :type T :identity T) (format stream "~a -> ~a ~a" (screen-name (source message)) (screen-name (target message)) (target-object message))) message) (defparameter *event->class-map* (alist-hash-table '(("access_revoked" . event-access-revoked) ("block" . event-block) ("unblock" . event-unblock) ("favorite" . event-favorite) ("unfavorite" . event-unfavorite) ("follow" . event-follow) ("unfollow" . event-unfollow) ("list_created" . event-list-create) ("list_destroyed" . event-list-destroy) ("list_updated" . event-list-update) ("list_member_added" . event-list-member-add) ("list_member_removed" . event-list-member-remove) ("list_user_subscribed" . event-list-user-subscribe) ("list_user_unsubscribed" . event-list-user-unsubscribe) ("user_update" . event-user-update)) :test 'equalp)) (defun make-stream-event (parameters) (let ((class (gethash (cdr (assoc :event parameters)) *event->class-map* 'event-unknown))) (make-instance class :target (make-user (cdr (assoc :target parameters))) :source (make-user (cdr (assoc :source parameters))) :target-object (cdr (assoc :target-object parameters)) :created-at (parse-twitter-time (cdr (assoc :created-at parameters)))))) (defclass* event-unknown (stream-event) () (:documentation "Unknown stream event")) (defclass* event-access-revoked (stream-event) () (:documentation "User deauthorize event")) (defclass* event-block (stream-event) () (:documentation " event")) (defclass* event-unblock (stream-event) () (:documentation " event")) (defclass* event-favorite (stream-event) () (:documentation " event")) (defclass* event-unfavorite (stream-event) () (:documentation " event")) (defclass* event-follow (stream-event) () (:documentation " event")) (defclass* event-unfollow (stream-event) () (:documentation " event")) (defclass* event-list-create (stream-event) () (:documentation " event")) (defclass* event-list-destroy (stream-event) () (:documentation " event")) (defclass* event-list-update (stream-event) () (:documentation " event")) (defclass* event-list-member-add (stream-event) () (:documentation " event")) (defclass* event-list-member-remove (stream-event) () (:documentation " event")) (defclass* event-list-user-subscribe (stream-event) () (:documentation " event")) (defclass* event-list-user-unsubscribe (stream-event) () (:documentation " event")) (defclass* event-user-update (stream-event) () (:documentation " event")) (defclass* stream-warning (message) (code message user-id) (:documentation "Warning notice")) (defmethod print-object ((message stream-warning) stream) (print-unreadable-object (message stream :type T :identity T) (format stream "~a (~a)" (message message) (code message))) message) (define-make-* (stream-warning) :code :message :user-id) (defclass* stream-control (message) (control-uri) (:documentation "Site stream control notice")) (defmethod print-object ((message stream-control) stream) (print-unreadable-object (message stream :type T :identity T) (format stream "~a" (control-uri message))) message) (define-make-* (stream-control) :control-uri) (defclass* stream-envelope (message) (for-user message) (:documentation "Container class for site streams")) (defmethod print-object ((message stream-envelope) stream) (print-unreadable-object (message stream :type T :identity T) (format stream "->#~a ~a" (for-user message) (message message))) message) (define-make-* (stream-envelope parameters) :for-user (:message (make-stream-object (cdr (assoc :message parameters))))) (defun make-stream-object (object) (flet ((p (param) (cdr (assoc param object)))) (cond ((p :control) (make-stream-control (p :control))) ((p :warning) (make-stream-warning (p :warning))) ((p :disconnect) (make-stream-disconnect (p :disconnect))) ((p :user-withheld) (make-stream-user-withheld (p :user-withheld))) ((p :status-withheld) (make-stream-status-withheld (p :status-withheld))) ((p :limit) (make-stream-limit (p :limit))) ((p :scrub-geo) (make-stream-scrub-geo (p :scrub-geo))) ((p :delete) (make-stream-delete (p :delete))) ((p :for-user) (make-stream-envelope object)) ((p :event) (make-stream-event object)) ((p :friends) (make-stream-friends object)) ((p :recipient) (make-direct-message object)) ((p :text) (make-status object)) ((p :direct-message) (make-direct-message (p :direct-message))) (T (make-instance 'stream-unknown :data object))))) (defun parse-stream-line (line) (unless (string= "" line) (make-stream-object (yason:parse line :object-as :alist :object-key-fn #'to-keyword)))) (defun trim-whitespace (string) (string-trim '(#\Tab #\Newline #\Linefeed #\Page #\Return #\Space) string)) (defun read-line-bytes (stream &optional buffer) (let ((octets (or buffer (make-array 4096 :fill-pointer 0 :element-type '(unsigned-byte 8))))) (setf (fill-pointer octets) 0) (block NIL (labels ((process-byte (byte) (case byte (13 (let ((next (read-byte stream NIL NIL))) (case next ((NIL 10) (return)) (T (vector-push-extend byte octets) (process-byte next))))) (T (vector-push-extend byte octets))))) (loop for byte = (read-byte stream NIL NIL) while byte do (process-byte byte)))) (babel:octets-to-string octets :end (fill-pointer octets) :encoding *external-format*))) (defun process-stream-inner (stream handler-function) (let ((octets (make-array 4096 :adjustable T :fill-pointer 0 :element-type '(unsigned-byte 8)))) (unwind-protect (loop for line = (read-line-bytes stream octets) for object = (parse-stream-line (trim-whitespace line)) while (funcall handler-function object)) (close stream)))) (defun stream/user (handler-function &key stall-warnings (filter-level :NONE) language (with :USER) replies count) "Streams messages for a single user, as described in User streams. Each line is parsed into an appropriate object (NIL for empty lines) and passed to the handler function. This is done as long as the handler function returns a non-NIL value. Once the handler returns NIL, the loop is stopped and the stream is closed. According to spec https://dev.twitter.com/docs/api/1.1/get/user https://dev.twitter.com/docs/streaming-apis/streams/user https://dev.twitter.com/docs/streaming-apis/messages" (assert (member filter-level '(:NONE :LOW :MEDIUM)) () "FILTER-LEVEL must be one of (:NONE :LOW :MEDIUM).") (assert (member with '(:USER :FOLLOWINGS)) () "WITH must be one of (:USER :FOLLOWINGS).") (when count (assert (< -150000 count 150000) () "COUNT must be NIL or between -150000 and 150000.")) (when language (assert (valid-language-p language) () "~a is not a supported language." language)) (when replies (setf replies "all")) (process-stream-inner (signed-stream-request *stream/user* :parameters (prepare* stall-warnings filter-level language with replies count) :method :GET :drakma-params (list :force-binary T)) handler-function)) (defun stream/site (handler-function follow &key stall-warnings (filter-level :NONE) language (with :FOLLOW) replies count) "Streams messages for a set of users, as described in Site streams. See STREAM/USER. According to spec https://dev.twitter.com/docs/api/1.1/get/site https://dev.twitter.com/docs/streaming-apis/streams/site https://dev.twitter.com/docs/streaming-apis/messages" (setf follow (format NIL "~{~a~^,~}" follow)) (assert (member filter-level '(:NONE :LOW :MEDIUM)) () "FILTER-LEVEL must be one of (:NONE :LOW :MEDIUM).") (assert (member with '(:USER :FOLLOWINGS)) () "WITH must be one of (:USER :FOLLOWINGS).") (when count (assert (< -150000 count 150000) () "COUNT must be NIL or between -150000 and 150000.")) (when language (assert (valid-language-p language) () "~a is not a supported language." language)) (when replies (setf replies "all")) (process-stream-inner (signed-stream-request *stream/site* :parameters (prepare* follow stall-warnings filter-level language with replies count) :method :GET :drakma-params (list :force-binary T)) handler-function)) (defun stream/statuses/filter (handler-function &key follow track locations stall-warnings (filter-level :NONE) language count) "Returns public statuses that match one or more filter predicates. Multiple parameters may be specified which allows most clients to use a single connection to the Streaming API. Both GET and POST requests are supported, but GET requests with too many parameters may cause the request to be rejected for excessive URL length. Use a POST request to avoid long URLs. See STREAM/USER. According to spec https://dev.twitter.com/docs/api/1.1/post/statuses/filter https://dev.twitter.com/docs/streaming-apis/messages" (setf follow (format NIL "~{~a~^,~}" follow)) (setf track (format NIL "~{~a~^,~}" track)) (setf locations (format NIL "~{~a~^,~}" locations)) (assert (member filter-level '(:NONE :LOW :MEDIUM)) () "FILTER-LEVEL must be one of (:NONE :LOW :MEDIUM).") (when count (assert (< -150000 count 150000) () "COUNT must be NIL or between -150000 and 150000.")) (when language (assert (valid-language-p language) () "~a is not a supported language." language)) (process-stream-inner (signed-stream-request *stream/statuses/filter* :parameters (prepare* follow track locations stall-warnings filter-level language count) :method :GET :drakma-params (list :force-binary T)) handler-function)) (defun stream/statuses/sample (handler-function &key stall-warnings (filter-level :NONE) language count) "Returns a small random sample of all public statuses. The Tweets returned by the default access level are the same, so if two different clients connect to this endpoint, they will see the same Tweets. According to spec https://dev.twitter.com/docs/api/1.1/get/statuses/sample https://dev.twitter.com/docs/streaming-apis/messages" (assert (member filter-level '(:NONE :LOW :MEDIUM)) () "FILTER-LEVEL must be one of (:NONE :LOW :MEDIUM).") (when count (assert (< -150000 count 150000) () "COUNT must be NIL or between -150000 and 150000.")) (when language (assert (valid-language-p language) () "~a is not a supported language." language)) (process-stream-inner (signed-stream-request *stream/statuses/sample* :parameters (prepare* stall-warnings filter-level language count) :method :GET :drakma-params (list :force-binary T)) handler-function)) (defun stream/statuses/firehose (handler-function &key stall-warnings (filter-level :NONE) language count) "Returns all public statuses. Few applications require this level of access. Creative use of a combination of other resources and various access levels can satisfy nearly every application use case. This endpoint requires special permission to access. According to spec https://dev.twitter.com/docs/api/1.1/get/statuses/firehose https://dev.twitter.com/docs/streaming-apis/messages" (assert (member filter-level '(:NONE :LOW :MEDIUM)) () "FILTER-LEVEL must be one of (:NONE :LOW :MEDIUM).") (when count (assert (< -150000 count 150000) () "COUNT must be NIL or between -150000 and 150000.")) (when language (assert (valid-language-p language) () "~a is not a supported language." language)) (process-stream-inner (signed-stream-request *stream/statuses/firehose* :parameters (prepare* count stall-warnings filter-level language) :method :GET :drakma-params (list :force-binary T)) handler-function))
32005
#| This file is a part of Chirp (c) 2014 <NAME> http://tymoon.eu (<EMAIL>) Author: <NAME> <<EMAIL>> |# (in-package #:org.tymoonnext.chirp) (defvar *stream/statuses/filter* "https://stream.twitter.com/1.1/statuses/filter.json") (defvar *stream/statuses/sample* "https://stream.twitter.com/1.1/statuses/sample.json") (defvar *stream/statuses/firehose* "https://stream.twitter.com/1.1/statuses/firehose.json") (defvar *stream/user* "https://userstream.twitter.com/1.1/user.json") (defvar *stream/site* "https://sitestream.twitter.com/1.1/site.json") (defclass message () () (:documentation "Superclass for all stream messages. According to spec https://dev.twitter.com/docs/streaming-apis/messages")) (defclass* stream-unknown (message) (data) (:documentation "Unknown stream object")) (defclass* stream-delete (message) (id user-id) (:documentation "Status deletion notice")) (defmethod print-object ((message stream-delete) stream) (print-unreadable-object (message stream :type T :identity T) (format stream "#~a" (id message))) message) (define-make-* (stream-delete parameters) (:id (cdr (assoc :id (cdr (assoc :status parameters))))) (:user-id (cdr (assoc :user-id (cdr (assoc :status parameters)))))) (defclass* stream-scrub-geo (message) (user-id up-to-status-id) (:documentation "Location deletion notice")) (defmethod print-object ((message stream-scrub-geo) stream) (print-unreadable-object (message stream :type T :identity T) (format stream "->#~a" (up-to-status-id message))) message) (define-make-* (stream-scrub-geo) :user-id :up-to-status-id) (defclass* stream-limit (message) (track) (:documentation "Limit notice")) (defmethod print-object ((message stream-limit) stream) (print-unreadable-object (message stream :type T :identity T) (format stream "F:~a" (track message))) message) (define-make-* (stream-limit) :track) (defclass* stream-status-withheld (message) (id withheld-in-countries) (:documentation "Status withheld notice")) (defmethod print-object ((message stream-status-withheld) stream) (print-unreadable-object (message stream :type T :identity T) (format stream "#~a (~{~a~^, ~})" (id message) (withheld-in-countries message))) message) (define-make-* (stream-status-withheld) :id :withheld-in-countries) (defclass* stream-user-withheld (message) (id withheld-in-countries) (:documentation "User withheld notice")) (defmethod print-object ((message stream-user-withheld) stream) (print-unreadable-object (message stream :type T :identity T) (format stream "#~a (~{~a~^, ~})" (id message) (withheld-in-countries message))) message) (define-make-* (stream-user-withheld) :id :withheld-in-countries) (defclass* stream-disconnect (message) (code stream-name reason) (:documentation "Disconnection notice")) (defmethod print-object ((message stream-disconnect) stream) (print-unreadable-object (message stream :type T :identity T) (format stream "~a (~a) #~a" (reason message) (code message) (stream-name message))) message) (define-make-* (stream-disconnect) :code :stream-name :reason) (defclass* stream-friends (message) (friends) (:documentation "Friends list notice")) (define-make-* (stream-friends) :friends) (defclass* stream-event (message) (target source target-object created-at) (:documentation "Stream event superclass")) (defmethod print-object ((message stream-event) stream) (print-unreadable-object (message stream :type T :identity T) (format stream "~a -> ~a ~a" (screen-name (source message)) (screen-name (target message)) (target-object message))) message) (defparameter *event->class-map* (alist-hash-table '(("access_revoked" . event-access-revoked) ("block" . event-block) ("unblock" . event-unblock) ("favorite" . event-favorite) ("unfavorite" . event-unfavorite) ("follow" . event-follow) ("unfollow" . event-unfollow) ("list_created" . event-list-create) ("list_destroyed" . event-list-destroy) ("list_updated" . event-list-update) ("list_member_added" . event-list-member-add) ("list_member_removed" . event-list-member-remove) ("list_user_subscribed" . event-list-user-subscribe) ("list_user_unsubscribed" . event-list-user-unsubscribe) ("user_update" . event-user-update)) :test 'equalp)) (defun make-stream-event (parameters) (let ((class (gethash (cdr (assoc :event parameters)) *event->class-map* 'event-unknown))) (make-instance class :target (make-user (cdr (assoc :target parameters))) :source (make-user (cdr (assoc :source parameters))) :target-object (cdr (assoc :target-object parameters)) :created-at (parse-twitter-time (cdr (assoc :created-at parameters)))))) (defclass* event-unknown (stream-event) () (:documentation "Unknown stream event")) (defclass* event-access-revoked (stream-event) () (:documentation "User deauthorize event")) (defclass* event-block (stream-event) () (:documentation " event")) (defclass* event-unblock (stream-event) () (:documentation " event")) (defclass* event-favorite (stream-event) () (:documentation " event")) (defclass* event-unfavorite (stream-event) () (:documentation " event")) (defclass* event-follow (stream-event) () (:documentation " event")) (defclass* event-unfollow (stream-event) () (:documentation " event")) (defclass* event-list-create (stream-event) () (:documentation " event")) (defclass* event-list-destroy (stream-event) () (:documentation " event")) (defclass* event-list-update (stream-event) () (:documentation " event")) (defclass* event-list-member-add (stream-event) () (:documentation " event")) (defclass* event-list-member-remove (stream-event) () (:documentation " event")) (defclass* event-list-user-subscribe (stream-event) () (:documentation " event")) (defclass* event-list-user-unsubscribe (stream-event) () (:documentation " event")) (defclass* event-user-update (stream-event) () (:documentation " event")) (defclass* stream-warning (message) (code message user-id) (:documentation "Warning notice")) (defmethod print-object ((message stream-warning) stream) (print-unreadable-object (message stream :type T :identity T) (format stream "~a (~a)" (message message) (code message))) message) (define-make-* (stream-warning) :code :message :user-id) (defclass* stream-control (message) (control-uri) (:documentation "Site stream control notice")) (defmethod print-object ((message stream-control) stream) (print-unreadable-object (message stream :type T :identity T) (format stream "~a" (control-uri message))) message) (define-make-* (stream-control) :control-uri) (defclass* stream-envelope (message) (for-user message) (:documentation "Container class for site streams")) (defmethod print-object ((message stream-envelope) stream) (print-unreadable-object (message stream :type T :identity T) (format stream "->#~a ~a" (for-user message) (message message))) message) (define-make-* (stream-envelope parameters) :for-user (:message (make-stream-object (cdr (assoc :message parameters))))) (defun make-stream-object (object) (flet ((p (param) (cdr (assoc param object)))) (cond ((p :control) (make-stream-control (p :control))) ((p :warning) (make-stream-warning (p :warning))) ((p :disconnect) (make-stream-disconnect (p :disconnect))) ((p :user-withheld) (make-stream-user-withheld (p :user-withheld))) ((p :status-withheld) (make-stream-status-withheld (p :status-withheld))) ((p :limit) (make-stream-limit (p :limit))) ((p :scrub-geo) (make-stream-scrub-geo (p :scrub-geo))) ((p :delete) (make-stream-delete (p :delete))) ((p :for-user) (make-stream-envelope object)) ((p :event) (make-stream-event object)) ((p :friends) (make-stream-friends object)) ((p :recipient) (make-direct-message object)) ((p :text) (make-status object)) ((p :direct-message) (make-direct-message (p :direct-message))) (T (make-instance 'stream-unknown :data object))))) (defun parse-stream-line (line) (unless (string= "" line) (make-stream-object (yason:parse line :object-as :alist :object-key-fn #'to-keyword)))) (defun trim-whitespace (string) (string-trim '(#\Tab #\Newline #\Linefeed #\Page #\Return #\Space) string)) (defun read-line-bytes (stream &optional buffer) (let ((octets (or buffer (make-array 4096 :fill-pointer 0 :element-type '(unsigned-byte 8))))) (setf (fill-pointer octets) 0) (block NIL (labels ((process-byte (byte) (case byte (13 (let ((next (read-byte stream NIL NIL))) (case next ((NIL 10) (return)) (T (vector-push-extend byte octets) (process-byte next))))) (T (vector-push-extend byte octets))))) (loop for byte = (read-byte stream NIL NIL) while byte do (process-byte byte)))) (babel:octets-to-string octets :end (fill-pointer octets) :encoding *external-format*))) (defun process-stream-inner (stream handler-function) (let ((octets (make-array 4096 :adjustable T :fill-pointer 0 :element-type '(unsigned-byte 8)))) (unwind-protect (loop for line = (read-line-bytes stream octets) for object = (parse-stream-line (trim-whitespace line)) while (funcall handler-function object)) (close stream)))) (defun stream/user (handler-function &key stall-warnings (filter-level :NONE) language (with :USER) replies count) "Streams messages for a single user, as described in User streams. Each line is parsed into an appropriate object (NIL for empty lines) and passed to the handler function. This is done as long as the handler function returns a non-NIL value. Once the handler returns NIL, the loop is stopped and the stream is closed. According to spec https://dev.twitter.com/docs/api/1.1/get/user https://dev.twitter.com/docs/streaming-apis/streams/user https://dev.twitter.com/docs/streaming-apis/messages" (assert (member filter-level '(:NONE :LOW :MEDIUM)) () "FILTER-LEVEL must be one of (:NONE :LOW :MEDIUM).") (assert (member with '(:USER :FOLLOWINGS)) () "WITH must be one of (:USER :FOLLOWINGS).") (when count (assert (< -150000 count 150000) () "COUNT must be NIL or between -150000 and 150000.")) (when language (assert (valid-language-p language) () "~a is not a supported language." language)) (when replies (setf replies "all")) (process-stream-inner (signed-stream-request *stream/user* :parameters (prepare* stall-warnings filter-level language with replies count) :method :GET :drakma-params (list :force-binary T)) handler-function)) (defun stream/site (handler-function follow &key stall-warnings (filter-level :NONE) language (with :FOLLOW) replies count) "Streams messages for a set of users, as described in Site streams. See STREAM/USER. According to spec https://dev.twitter.com/docs/api/1.1/get/site https://dev.twitter.com/docs/streaming-apis/streams/site https://dev.twitter.com/docs/streaming-apis/messages" (setf follow (format NIL "~{~a~^,~}" follow)) (assert (member filter-level '(:NONE :LOW :MEDIUM)) () "FILTER-LEVEL must be one of (:NONE :LOW :MEDIUM).") (assert (member with '(:USER :FOLLOWINGS)) () "WITH must be one of (:USER :FOLLOWINGS).") (when count (assert (< -150000 count 150000) () "COUNT must be NIL or between -150000 and 150000.")) (when language (assert (valid-language-p language) () "~a is not a supported language." language)) (when replies (setf replies "all")) (process-stream-inner (signed-stream-request *stream/site* :parameters (prepare* follow stall-warnings filter-level language with replies count) :method :GET :drakma-params (list :force-binary T)) handler-function)) (defun stream/statuses/filter (handler-function &key follow track locations stall-warnings (filter-level :NONE) language count) "Returns public statuses that match one or more filter predicates. Multiple parameters may be specified which allows most clients to use a single connection to the Streaming API. Both GET and POST requests are supported, but GET requests with too many parameters may cause the request to be rejected for excessive URL length. Use a POST request to avoid long URLs. See STREAM/USER. According to spec https://dev.twitter.com/docs/api/1.1/post/statuses/filter https://dev.twitter.com/docs/streaming-apis/messages" (setf follow (format NIL "~{~a~^,~}" follow)) (setf track (format NIL "~{~a~^,~}" track)) (setf locations (format NIL "~{~a~^,~}" locations)) (assert (member filter-level '(:NONE :LOW :MEDIUM)) () "FILTER-LEVEL must be one of (:NONE :LOW :MEDIUM).") (when count (assert (< -150000 count 150000) () "COUNT must be NIL or between -150000 and 150000.")) (when language (assert (valid-language-p language) () "~a is not a supported language." language)) (process-stream-inner (signed-stream-request *stream/statuses/filter* :parameters (prepare* follow track locations stall-warnings filter-level language count) :method :GET :drakma-params (list :force-binary T)) handler-function)) (defun stream/statuses/sample (handler-function &key stall-warnings (filter-level :NONE) language count) "Returns a small random sample of all public statuses. The Tweets returned by the default access level are the same, so if two different clients connect to this endpoint, they will see the same Tweets. According to spec https://dev.twitter.com/docs/api/1.1/get/statuses/sample https://dev.twitter.com/docs/streaming-apis/messages" (assert (member filter-level '(:NONE :LOW :MEDIUM)) () "FILTER-LEVEL must be one of (:NONE :LOW :MEDIUM).") (when count (assert (< -150000 count 150000) () "COUNT must be NIL or between -150000 and 150000.")) (when language (assert (valid-language-p language) () "~a is not a supported language." language)) (process-stream-inner (signed-stream-request *stream/statuses/sample* :parameters (prepare* stall-warnings filter-level language count) :method :GET :drakma-params (list :force-binary T)) handler-function)) (defun stream/statuses/firehose (handler-function &key stall-warnings (filter-level :NONE) language count) "Returns all public statuses. Few applications require this level of access. Creative use of a combination of other resources and various access levels can satisfy nearly every application use case. This endpoint requires special permission to access. According to spec https://dev.twitter.com/docs/api/1.1/get/statuses/firehose https://dev.twitter.com/docs/streaming-apis/messages" (assert (member filter-level '(:NONE :LOW :MEDIUM)) () "FILTER-LEVEL must be one of (:NONE :LOW :MEDIUM).") (when count (assert (< -150000 count 150000) () "COUNT must be NIL or between -150000 and 150000.")) (when language (assert (valid-language-p language) () "~a is not a supported language." language)) (process-stream-inner (signed-stream-request *stream/statuses/firehose* :parameters (prepare* count stall-warnings filter-level language) :method :GET :drakma-params (list :force-binary T)) handler-function))
true
#| This file is a part of Chirp (c) 2014 PI:NAME:<NAME>END_PI http://tymoon.eu (PI:EMAIL:<EMAIL>END_PI) Author: PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> |# (in-package #:org.tymoonnext.chirp) (defvar *stream/statuses/filter* "https://stream.twitter.com/1.1/statuses/filter.json") (defvar *stream/statuses/sample* "https://stream.twitter.com/1.1/statuses/sample.json") (defvar *stream/statuses/firehose* "https://stream.twitter.com/1.1/statuses/firehose.json") (defvar *stream/user* "https://userstream.twitter.com/1.1/user.json") (defvar *stream/site* "https://sitestream.twitter.com/1.1/site.json") (defclass message () () (:documentation "Superclass for all stream messages. According to spec https://dev.twitter.com/docs/streaming-apis/messages")) (defclass* stream-unknown (message) (data) (:documentation "Unknown stream object")) (defclass* stream-delete (message) (id user-id) (:documentation "Status deletion notice")) (defmethod print-object ((message stream-delete) stream) (print-unreadable-object (message stream :type T :identity T) (format stream "#~a" (id message))) message) (define-make-* (stream-delete parameters) (:id (cdr (assoc :id (cdr (assoc :status parameters))))) (:user-id (cdr (assoc :user-id (cdr (assoc :status parameters)))))) (defclass* stream-scrub-geo (message) (user-id up-to-status-id) (:documentation "Location deletion notice")) (defmethod print-object ((message stream-scrub-geo) stream) (print-unreadable-object (message stream :type T :identity T) (format stream "->#~a" (up-to-status-id message))) message) (define-make-* (stream-scrub-geo) :user-id :up-to-status-id) (defclass* stream-limit (message) (track) (:documentation "Limit notice")) (defmethod print-object ((message stream-limit) stream) (print-unreadable-object (message stream :type T :identity T) (format stream "F:~a" (track message))) message) (define-make-* (stream-limit) :track) (defclass* stream-status-withheld (message) (id withheld-in-countries) (:documentation "Status withheld notice")) (defmethod print-object ((message stream-status-withheld) stream) (print-unreadable-object (message stream :type T :identity T) (format stream "#~a (~{~a~^, ~})" (id message) (withheld-in-countries message))) message) (define-make-* (stream-status-withheld) :id :withheld-in-countries) (defclass* stream-user-withheld (message) (id withheld-in-countries) (:documentation "User withheld notice")) (defmethod print-object ((message stream-user-withheld) stream) (print-unreadable-object (message stream :type T :identity T) (format stream "#~a (~{~a~^, ~})" (id message) (withheld-in-countries message))) message) (define-make-* (stream-user-withheld) :id :withheld-in-countries) (defclass* stream-disconnect (message) (code stream-name reason) (:documentation "Disconnection notice")) (defmethod print-object ((message stream-disconnect) stream) (print-unreadable-object (message stream :type T :identity T) (format stream "~a (~a) #~a" (reason message) (code message) (stream-name message))) message) (define-make-* (stream-disconnect) :code :stream-name :reason) (defclass* stream-friends (message) (friends) (:documentation "Friends list notice")) (define-make-* (stream-friends) :friends) (defclass* stream-event (message) (target source target-object created-at) (:documentation "Stream event superclass")) (defmethod print-object ((message stream-event) stream) (print-unreadable-object (message stream :type T :identity T) (format stream "~a -> ~a ~a" (screen-name (source message)) (screen-name (target message)) (target-object message))) message) (defparameter *event->class-map* (alist-hash-table '(("access_revoked" . event-access-revoked) ("block" . event-block) ("unblock" . event-unblock) ("favorite" . event-favorite) ("unfavorite" . event-unfavorite) ("follow" . event-follow) ("unfollow" . event-unfollow) ("list_created" . event-list-create) ("list_destroyed" . event-list-destroy) ("list_updated" . event-list-update) ("list_member_added" . event-list-member-add) ("list_member_removed" . event-list-member-remove) ("list_user_subscribed" . event-list-user-subscribe) ("list_user_unsubscribed" . event-list-user-unsubscribe) ("user_update" . event-user-update)) :test 'equalp)) (defun make-stream-event (parameters) (let ((class (gethash (cdr (assoc :event parameters)) *event->class-map* 'event-unknown))) (make-instance class :target (make-user (cdr (assoc :target parameters))) :source (make-user (cdr (assoc :source parameters))) :target-object (cdr (assoc :target-object parameters)) :created-at (parse-twitter-time (cdr (assoc :created-at parameters)))))) (defclass* event-unknown (stream-event) () (:documentation "Unknown stream event")) (defclass* event-access-revoked (stream-event) () (:documentation "User deauthorize event")) (defclass* event-block (stream-event) () (:documentation " event")) (defclass* event-unblock (stream-event) () (:documentation " event")) (defclass* event-favorite (stream-event) () (:documentation " event")) (defclass* event-unfavorite (stream-event) () (:documentation " event")) (defclass* event-follow (stream-event) () (:documentation " event")) (defclass* event-unfollow (stream-event) () (:documentation " event")) (defclass* event-list-create (stream-event) () (:documentation " event")) (defclass* event-list-destroy (stream-event) () (:documentation " event")) (defclass* event-list-update (stream-event) () (:documentation " event")) (defclass* event-list-member-add (stream-event) () (:documentation " event")) (defclass* event-list-member-remove (stream-event) () (:documentation " event")) (defclass* event-list-user-subscribe (stream-event) () (:documentation " event")) (defclass* event-list-user-unsubscribe (stream-event) () (:documentation " event")) (defclass* event-user-update (stream-event) () (:documentation " event")) (defclass* stream-warning (message) (code message user-id) (:documentation "Warning notice")) (defmethod print-object ((message stream-warning) stream) (print-unreadable-object (message stream :type T :identity T) (format stream "~a (~a)" (message message) (code message))) message) (define-make-* (stream-warning) :code :message :user-id) (defclass* stream-control (message) (control-uri) (:documentation "Site stream control notice")) (defmethod print-object ((message stream-control) stream) (print-unreadable-object (message stream :type T :identity T) (format stream "~a" (control-uri message))) message) (define-make-* (stream-control) :control-uri) (defclass* stream-envelope (message) (for-user message) (:documentation "Container class for site streams")) (defmethod print-object ((message stream-envelope) stream) (print-unreadable-object (message stream :type T :identity T) (format stream "->#~a ~a" (for-user message) (message message))) message) (define-make-* (stream-envelope parameters) :for-user (:message (make-stream-object (cdr (assoc :message parameters))))) (defun make-stream-object (object) (flet ((p (param) (cdr (assoc param object)))) (cond ((p :control) (make-stream-control (p :control))) ((p :warning) (make-stream-warning (p :warning))) ((p :disconnect) (make-stream-disconnect (p :disconnect))) ((p :user-withheld) (make-stream-user-withheld (p :user-withheld))) ((p :status-withheld) (make-stream-status-withheld (p :status-withheld))) ((p :limit) (make-stream-limit (p :limit))) ((p :scrub-geo) (make-stream-scrub-geo (p :scrub-geo))) ((p :delete) (make-stream-delete (p :delete))) ((p :for-user) (make-stream-envelope object)) ((p :event) (make-stream-event object)) ((p :friends) (make-stream-friends object)) ((p :recipient) (make-direct-message object)) ((p :text) (make-status object)) ((p :direct-message) (make-direct-message (p :direct-message))) (T (make-instance 'stream-unknown :data object))))) (defun parse-stream-line (line) (unless (string= "" line) (make-stream-object (yason:parse line :object-as :alist :object-key-fn #'to-keyword)))) (defun trim-whitespace (string) (string-trim '(#\Tab #\Newline #\Linefeed #\Page #\Return #\Space) string)) (defun read-line-bytes (stream &optional buffer) (let ((octets (or buffer (make-array 4096 :fill-pointer 0 :element-type '(unsigned-byte 8))))) (setf (fill-pointer octets) 0) (block NIL (labels ((process-byte (byte) (case byte (13 (let ((next (read-byte stream NIL NIL))) (case next ((NIL 10) (return)) (T (vector-push-extend byte octets) (process-byte next))))) (T (vector-push-extend byte octets))))) (loop for byte = (read-byte stream NIL NIL) while byte do (process-byte byte)))) (babel:octets-to-string octets :end (fill-pointer octets) :encoding *external-format*))) (defun process-stream-inner (stream handler-function) (let ((octets (make-array 4096 :adjustable T :fill-pointer 0 :element-type '(unsigned-byte 8)))) (unwind-protect (loop for line = (read-line-bytes stream octets) for object = (parse-stream-line (trim-whitespace line)) while (funcall handler-function object)) (close stream)))) (defun stream/user (handler-function &key stall-warnings (filter-level :NONE) language (with :USER) replies count) "Streams messages for a single user, as described in User streams. Each line is parsed into an appropriate object (NIL for empty lines) and passed to the handler function. This is done as long as the handler function returns a non-NIL value. Once the handler returns NIL, the loop is stopped and the stream is closed. According to spec https://dev.twitter.com/docs/api/1.1/get/user https://dev.twitter.com/docs/streaming-apis/streams/user https://dev.twitter.com/docs/streaming-apis/messages" (assert (member filter-level '(:NONE :LOW :MEDIUM)) () "FILTER-LEVEL must be one of (:NONE :LOW :MEDIUM).") (assert (member with '(:USER :FOLLOWINGS)) () "WITH must be one of (:USER :FOLLOWINGS).") (when count (assert (< -150000 count 150000) () "COUNT must be NIL or between -150000 and 150000.")) (when language (assert (valid-language-p language) () "~a is not a supported language." language)) (when replies (setf replies "all")) (process-stream-inner (signed-stream-request *stream/user* :parameters (prepare* stall-warnings filter-level language with replies count) :method :GET :drakma-params (list :force-binary T)) handler-function)) (defun stream/site (handler-function follow &key stall-warnings (filter-level :NONE) language (with :FOLLOW) replies count) "Streams messages for a set of users, as described in Site streams. See STREAM/USER. According to spec https://dev.twitter.com/docs/api/1.1/get/site https://dev.twitter.com/docs/streaming-apis/streams/site https://dev.twitter.com/docs/streaming-apis/messages" (setf follow (format NIL "~{~a~^,~}" follow)) (assert (member filter-level '(:NONE :LOW :MEDIUM)) () "FILTER-LEVEL must be one of (:NONE :LOW :MEDIUM).") (assert (member with '(:USER :FOLLOWINGS)) () "WITH must be one of (:USER :FOLLOWINGS).") (when count (assert (< -150000 count 150000) () "COUNT must be NIL or between -150000 and 150000.")) (when language (assert (valid-language-p language) () "~a is not a supported language." language)) (when replies (setf replies "all")) (process-stream-inner (signed-stream-request *stream/site* :parameters (prepare* follow stall-warnings filter-level language with replies count) :method :GET :drakma-params (list :force-binary T)) handler-function)) (defun stream/statuses/filter (handler-function &key follow track locations stall-warnings (filter-level :NONE) language count) "Returns public statuses that match one or more filter predicates. Multiple parameters may be specified which allows most clients to use a single connection to the Streaming API. Both GET and POST requests are supported, but GET requests with too many parameters may cause the request to be rejected for excessive URL length. Use a POST request to avoid long URLs. See STREAM/USER. According to spec https://dev.twitter.com/docs/api/1.1/post/statuses/filter https://dev.twitter.com/docs/streaming-apis/messages" (setf follow (format NIL "~{~a~^,~}" follow)) (setf track (format NIL "~{~a~^,~}" track)) (setf locations (format NIL "~{~a~^,~}" locations)) (assert (member filter-level '(:NONE :LOW :MEDIUM)) () "FILTER-LEVEL must be one of (:NONE :LOW :MEDIUM).") (when count (assert (< -150000 count 150000) () "COUNT must be NIL or between -150000 and 150000.")) (when language (assert (valid-language-p language) () "~a is not a supported language." language)) (process-stream-inner (signed-stream-request *stream/statuses/filter* :parameters (prepare* follow track locations stall-warnings filter-level language count) :method :GET :drakma-params (list :force-binary T)) handler-function)) (defun stream/statuses/sample (handler-function &key stall-warnings (filter-level :NONE) language count) "Returns a small random sample of all public statuses. The Tweets returned by the default access level are the same, so if two different clients connect to this endpoint, they will see the same Tweets. According to spec https://dev.twitter.com/docs/api/1.1/get/statuses/sample https://dev.twitter.com/docs/streaming-apis/messages" (assert (member filter-level '(:NONE :LOW :MEDIUM)) () "FILTER-LEVEL must be one of (:NONE :LOW :MEDIUM).") (when count (assert (< -150000 count 150000) () "COUNT must be NIL or between -150000 and 150000.")) (when language (assert (valid-language-p language) () "~a is not a supported language." language)) (process-stream-inner (signed-stream-request *stream/statuses/sample* :parameters (prepare* stall-warnings filter-level language count) :method :GET :drakma-params (list :force-binary T)) handler-function)) (defun stream/statuses/firehose (handler-function &key stall-warnings (filter-level :NONE) language count) "Returns all public statuses. Few applications require this level of access. Creative use of a combination of other resources and various access levels can satisfy nearly every application use case. This endpoint requires special permission to access. According to spec https://dev.twitter.com/docs/api/1.1/get/statuses/firehose https://dev.twitter.com/docs/streaming-apis/messages" (assert (member filter-level '(:NONE :LOW :MEDIUM)) () "FILTER-LEVEL must be one of (:NONE :LOW :MEDIUM).") (when count (assert (< -150000 count 150000) () "COUNT must be NIL or between -150000 and 150000.")) (when language (assert (valid-language-p language) () "~a is not a supported language." language)) (process-stream-inner (signed-stream-request *stream/statuses/firehose* :parameters (prepare* count stall-warnings filter-level language) :method :GET :drakma-params (list :force-binary T)) handler-function))
[ { "context": "isp; Package: cello; -*-\n#|\n\nCopyright (C) 2004 by Kenneth William Tilton\n\nThis library is free software; you can redistrib", "end": 108, "score": 0.9998648166656494, "start": 86, "tag": "NAME", "value": "Kenneth William Tilton" } ]
ix-opengl.lisp
kennytilton/Cello
9
;; -*- mode: Lisp; Syntax: Common-Lisp; Package: cello; -*- #| Copyright (C) 2004 by Kenneth William Tilton This library is free software; you can redistribute it and/or modify it under the terms of the Lisp Lesser GNU Public License (http://opensource.franz.com/preamble.html), known as the LLGPL. This library is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the Lisp Lesser GNU Public License for more details. |# (in-package :cello) (export! .og. .ogc. ogl-shared-resource-tender ogl-node ogl-family dsp-list) (defmethod ogl-dsp-list-prep progn (self) (declare (ignore self)) (assert (not *ogl-listing-p*))) (defvar *ogl-shared-resource-tender*) (defclass ogl-shared-resource-tender () ;; mixin ((display-lists :initform nil :accessor display-lists) (quadrics :initform nil :accessor quadrics) (textures :initform nil :accessor textures))) (defmethod not-to-be :before ((self ogl-shared-resource-tender)) (loop for (nil . dl) in (display-lists self) do (gl-delete-lists dl 1) finally (setf (display-lists self) nil)) (loop for (nil . q) in (quadrics self) do (glu-delete-quadric q))) (defmethod ogl-shared-resource-tender ((self ogl-shared-resource-tender)) self) (defmethod ogl-shared-resource-tender (other) (c-break "ogl-shared-resource-tender undefined for ~a" other)) (defmethod ogl-node-window (other) (c-break "ogl-node-window undefined for ~a" other)) (export! ogl-context ogl-isolate? visible ^visible dsp-list-formula) (defmd ogl-node () (ogl-context nil :cell nil) (ogl-isolate? nil :cell nil) (visible t) (dsp-list nil #+not (disp-lisp-formula)) gl-name) (defun dsp-list-formula () #+bzzt (c-formula (:lazy :until-asked) (assert (not *ogl-listing-p*)) (let ((dl-id (or .cache (gl-gen-lists 1)))) (if (not (^visible)) (progn #+nahh (when .cache ;(trc "zapping invisible cache") (gl-new-list dl-id gl_compile) (gl-end-list))) (progn (ogl-dsp-list-prep self) (glec :post-prep) (if t #+programmerbeware? (without-c-dependency (every 'dsp-list (kids self))) (let ((*ogl-shared-resource-tender* (ogl-shared-resource-tender self))) ;(trc "starting dl" dl-id self) (gl-new-list dl-id gl_compile) (let ((*ogl-listing-p* self) *selecting* *render-clip-l* *render-clip-r* *render-clip-t* *render-clip-b*) (with-metrics (nil nil "ix-paint" self) (ix-paint self))) (glec :post-prep) (trc nil "---------------finished display list" dl-id self) (gl-end-list) (glec :post-prep) (setf (redisplayp .og.) t)) (break "all or nothing on dsp-lists")))) dl-id))) (defun render (self) (let (*selecting* *render-clip-l* *render-clip-r* *render-clip-t* *render-clip-b*) (ogl-echk :render) (with-metrics (nil nil "ix-paint" self) (trc nil "render" self (^height)) (ix-paint self)))) (export! fully-visible) (defgeneric fully-visible (self) (:method ((self ogl-node)) (and (visible self) (or (null .pa) (fully-visible .pa)))) (:method (other) (declare (ignore other)) t)) (defmodel ogl-family () ;; mixin () (:default-initargs :gl-name (c? (incf (gl-name-highest .w.))) :clipped nil)) (defobserver dsp-list () (when old-value (gl-delete-lists old-value 1))) (defmethod not-to-be :after ((self ogl-node)) (bwhen (dl (slot-value self 'dsp-list)) ;; don't trigger lazy cell (gl-delete-lists dl 1)))
66516
;; -*- mode: Lisp; Syntax: Common-Lisp; Package: cello; -*- #| Copyright (C) 2004 by <NAME> This library is free software; you can redistribute it and/or modify it under the terms of the Lisp Lesser GNU Public License (http://opensource.franz.com/preamble.html), known as the LLGPL. This library is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the Lisp Lesser GNU Public License for more details. |# (in-package :cello) (export! .og. .ogc. ogl-shared-resource-tender ogl-node ogl-family dsp-list) (defmethod ogl-dsp-list-prep progn (self) (declare (ignore self)) (assert (not *ogl-listing-p*))) (defvar *ogl-shared-resource-tender*) (defclass ogl-shared-resource-tender () ;; mixin ((display-lists :initform nil :accessor display-lists) (quadrics :initform nil :accessor quadrics) (textures :initform nil :accessor textures))) (defmethod not-to-be :before ((self ogl-shared-resource-tender)) (loop for (nil . dl) in (display-lists self) do (gl-delete-lists dl 1) finally (setf (display-lists self) nil)) (loop for (nil . q) in (quadrics self) do (glu-delete-quadric q))) (defmethod ogl-shared-resource-tender ((self ogl-shared-resource-tender)) self) (defmethod ogl-shared-resource-tender (other) (c-break "ogl-shared-resource-tender undefined for ~a" other)) (defmethod ogl-node-window (other) (c-break "ogl-node-window undefined for ~a" other)) (export! ogl-context ogl-isolate? visible ^visible dsp-list-formula) (defmd ogl-node () (ogl-context nil :cell nil) (ogl-isolate? nil :cell nil) (visible t) (dsp-list nil #+not (disp-lisp-formula)) gl-name) (defun dsp-list-formula () #+bzzt (c-formula (:lazy :until-asked) (assert (not *ogl-listing-p*)) (let ((dl-id (or .cache (gl-gen-lists 1)))) (if (not (^visible)) (progn #+nahh (when .cache ;(trc "zapping invisible cache") (gl-new-list dl-id gl_compile) (gl-end-list))) (progn (ogl-dsp-list-prep self) (glec :post-prep) (if t #+programmerbeware? (without-c-dependency (every 'dsp-list (kids self))) (let ((*ogl-shared-resource-tender* (ogl-shared-resource-tender self))) ;(trc "starting dl" dl-id self) (gl-new-list dl-id gl_compile) (let ((*ogl-listing-p* self) *selecting* *render-clip-l* *render-clip-r* *render-clip-t* *render-clip-b*) (with-metrics (nil nil "ix-paint" self) (ix-paint self))) (glec :post-prep) (trc nil "---------------finished display list" dl-id self) (gl-end-list) (glec :post-prep) (setf (redisplayp .og.) t)) (break "all or nothing on dsp-lists")))) dl-id))) (defun render (self) (let (*selecting* *render-clip-l* *render-clip-r* *render-clip-t* *render-clip-b*) (ogl-echk :render) (with-metrics (nil nil "ix-paint" self) (trc nil "render" self (^height)) (ix-paint self)))) (export! fully-visible) (defgeneric fully-visible (self) (:method ((self ogl-node)) (and (visible self) (or (null .pa) (fully-visible .pa)))) (:method (other) (declare (ignore other)) t)) (defmodel ogl-family () ;; mixin () (:default-initargs :gl-name (c? (incf (gl-name-highest .w.))) :clipped nil)) (defobserver dsp-list () (when old-value (gl-delete-lists old-value 1))) (defmethod not-to-be :after ((self ogl-node)) (bwhen (dl (slot-value self 'dsp-list)) ;; don't trigger lazy cell (gl-delete-lists dl 1)))
true
;; -*- mode: Lisp; Syntax: Common-Lisp; Package: cello; -*- #| Copyright (C) 2004 by PI:NAME:<NAME>END_PI This library is free software; you can redistribute it and/or modify it under the terms of the Lisp Lesser GNU Public License (http://opensource.franz.com/preamble.html), known as the LLGPL. This library is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the Lisp Lesser GNU Public License for more details. |# (in-package :cello) (export! .og. .ogc. ogl-shared-resource-tender ogl-node ogl-family dsp-list) (defmethod ogl-dsp-list-prep progn (self) (declare (ignore self)) (assert (not *ogl-listing-p*))) (defvar *ogl-shared-resource-tender*) (defclass ogl-shared-resource-tender () ;; mixin ((display-lists :initform nil :accessor display-lists) (quadrics :initform nil :accessor quadrics) (textures :initform nil :accessor textures))) (defmethod not-to-be :before ((self ogl-shared-resource-tender)) (loop for (nil . dl) in (display-lists self) do (gl-delete-lists dl 1) finally (setf (display-lists self) nil)) (loop for (nil . q) in (quadrics self) do (glu-delete-quadric q))) (defmethod ogl-shared-resource-tender ((self ogl-shared-resource-tender)) self) (defmethod ogl-shared-resource-tender (other) (c-break "ogl-shared-resource-tender undefined for ~a" other)) (defmethod ogl-node-window (other) (c-break "ogl-node-window undefined for ~a" other)) (export! ogl-context ogl-isolate? visible ^visible dsp-list-formula) (defmd ogl-node () (ogl-context nil :cell nil) (ogl-isolate? nil :cell nil) (visible t) (dsp-list nil #+not (disp-lisp-formula)) gl-name) (defun dsp-list-formula () #+bzzt (c-formula (:lazy :until-asked) (assert (not *ogl-listing-p*)) (let ((dl-id (or .cache (gl-gen-lists 1)))) (if (not (^visible)) (progn #+nahh (when .cache ;(trc "zapping invisible cache") (gl-new-list dl-id gl_compile) (gl-end-list))) (progn (ogl-dsp-list-prep self) (glec :post-prep) (if t #+programmerbeware? (without-c-dependency (every 'dsp-list (kids self))) (let ((*ogl-shared-resource-tender* (ogl-shared-resource-tender self))) ;(trc "starting dl" dl-id self) (gl-new-list dl-id gl_compile) (let ((*ogl-listing-p* self) *selecting* *render-clip-l* *render-clip-r* *render-clip-t* *render-clip-b*) (with-metrics (nil nil "ix-paint" self) (ix-paint self))) (glec :post-prep) (trc nil "---------------finished display list" dl-id self) (gl-end-list) (glec :post-prep) (setf (redisplayp .og.) t)) (break "all or nothing on dsp-lists")))) dl-id))) (defun render (self) (let (*selecting* *render-clip-l* *render-clip-r* *render-clip-t* *render-clip-b*) (ogl-echk :render) (with-metrics (nil nil "ix-paint" self) (trc nil "render" self (^height)) (ix-paint self)))) (export! fully-visible) (defgeneric fully-visible (self) (:method ((self ogl-node)) (and (visible self) (or (null .pa) (fully-visible .pa)))) (:method (other) (declare (ignore other)) t)) (defmodel ogl-family () ;; mixin () (:default-initargs :gl-name (c? (incf (gl-name-highest .w.))) :clipped nil)) (defobserver dsp-list () (when old-value (gl-delete-lists old-value 1))) (defmethod not-to-be :after ((self ogl-node)) (bwhen (dl (slot-value self 'dsp-list)) ;; don't trigger lazy cell (gl-delete-lists dl 1)))
[ { "context": "e for Project Euler Problem 54.\n;;\n;; Code author: Russell A. Edson\n;; Date last modified: 26/08/2021\n\n;; We are give", "end": 73, "score": 0.9998249411582947, "start": 57, "tag": "NAME", "value": "Russell A. Edson" } ]
problem_054.lisp
RussellAndrewEdson/project_euler_solutions
0
;; Code for Project Euler Problem 54. ;; ;; Code author: Russell A. Edson ;; Date last modified: 26/08/2021 ;; We are given a list of two-player poker hands that we first download ;; and parse from the Project Euler problem page. We are given that ;; the hands comprise 10 cards separated by spaces, and the first 5 ;; cards belong to Player 1, and the last 5 cards belong to Player 2. (ql:quickload '(:dexador :str)) (defparameter text-file "https://projecteuler.net/project/resources/p054_poker.txt") (defparameter poker-hands (str:split #\newline (str:trim (dex:get text-file)))) ;; The poker hands look like the following example: (defvar example-hand "5H 5C 6S 7S KD 2C 3S 8S 8D TD") ;; Each card is represented as a string, but actually we want to ;; be able to talk about attributes of the cards like their ;; value and suit and compare cards in a clean way. So we'll define ;; some pesudo-OOP infrastructure here to allow us to deal with ;; the values and suits of these cards explicitly as a data abstraction: (defun value (card) "Return the value of CARD." (str:substring 0 1 card)) (defun suit (card) "Return the suit of CARD." (str:substring 1 2 card)) (value "5H") ;;=> "5" (suit "5H") ;;=> "H" ;; This is a 'good' start, but notice that we cannot easily ;; compare (numerically) the values of different cards, since ;; the value can be a string like "T" or "K" for example. So we'll ;; define a mapping to the natural numbers that lets us compare ;; card values in a straightforward way. (defun comparative-value (card) "Returns a comparable numeric value for CARD, so 2<...<9<T<J<Q<K<A." (let ((values (list "2" "3" "4" "5" "6" "7" "8" "9" "T" "J" "Q" "K" "A"))) (+ 2 (position (value card) values :test #'equalp)))) (comparative-value "TH") ;;=> 10 (comparative-value "KD") ;;=> 13 ;; These functions suffice for us to be able to compare cards and ;; compute differences/duplicates, etc, by leveraging existing ;; functions for string and integer operations. We'll consider a ;; hand to (naturally) just be a list of these card strings, and so ;; we can write a quick function to parse a given 10-card hand and ;; split it into halves for each player's cards: (defun deal-hand (hand) "Return lists for Player 1 and Player 2's cards from the given HAND." (let ((player-1 nil) (player-2 (str:split #\space hand))) (loop repeat 5 do (push (pop player-2) player-1)) (values (reverse player-1) player-2))) (deal-hand example-hand) ;;=> ("5H" "5C" "6S" "7S" "KD") ;;=> ("2C" "3S" "8S" "8D" "TD") ;; We can use the comparative card values to define a simple ;; sort function to get the cards in increasing order: (defun sort-cards (cards) "Return the given CARDS sorted in increasing order of value." (sort (copy-list cards) #'< :key #'comparative-value)) (sort-cards '("5H" "TS" "QS" "2D" "7D" "7C")) ;;=> ("2D" "5H" "7D" "7C" "TS" "QS") ;; We can then easily define a function to pick out the largest value ;; from a given set of cards: (defun largest-value-card (cards) "Return the comparative value for the largest value card in CARDS." (comparative-value (car (last (sort-cards cards))))) (largest-value-card '("5H" "2D" "7C" "QH" "5H")) ;;=> 12 ;; And in particular for the poker rankings, it is useful to know ;; how many of each value/suit are in a given set of cards, so ;; we can code up utility functions for those too. We'll return ;; convenient plist data structures for the counts: (defun card-value-counts (cards) "Return the card value counts for each value in the given CARDS." (let ((unique-values (remove-duplicates (mapcar #'value cards) :test #'equalp))) (loop for value in unique-values append (list value (count value cards :key #'value :test #'equalp))))) (card-value-counts '("2D" "2S" "AS" "7C" "6C" "7H" "KD")) ;;=> ("2" 2 "A" 1 "6" 1 "7" 2 "K" 1) (defun card-suit-counts (cards) "Return the card suit counts for each suit in the given CARDS." (let ((unique-suits (remove-duplicates (mapcar #'suit cards) :test #'equalp))) (loop for suit in unique-suits append (list suit (count suit cards :key #'suit :test #'equalp))))) (card-suit-counts '("2D" "2S" "AS" "7C" "6C" "7H" "KD")) ;;=> ("S" 2 "C" 2 "H" 1 "D" 2) ;; And we in turn use those utility functions to build up further ;; utility functions that will let us distinguish between flushes, ;; straights, pairs, etc. (defun all-same-suit? (cards) "True if all of the CARDS have the same suit." (= 1 (length (loop for (key val) on (card-suit-counts cards) by #'cddr collect key)))) (all-same-suit? '("2D" "3D" "5D")) ;;=> T (all-same-suit? '("2D" "3D" "6S" "5D")) ;;=> NIL (defun all-consecutive-values? (cards) "True if all of the CARDS have consecutive values." (loop for (card . rest-of-cards) on (sort-cards cards) while rest-of-cards always (= 1 (- (comparative-value (car rest-of-cards)) (comparative-value card))))) (all-consecutive-values? '("2D" "3D" "5D")) ;;=> NIL (all-consecutive-values? '("2D" "3D" "5D" "4S")) ;;=> T (defun n-values-match (cards &optional (n 2)) "Return the matching cards when there are N value matches in CARDS." (let ((matches nil)) (loop for (key val) on (card-value-counts cards) by #'cddr when (= val n) do (push (remove-if-not (lambda (card) (equalp (value card) key)) cards) matches)) matches)) (n-values-match '("2D" "2S" "AS" "7C" "6C" "7H" "KD") 2) ;;=> (("7C" "7H") ("2D" "2S")) ;; Finally, we combine everything together in a 'hand ranking' ;; function that returns the type of rank and the cards that make ;; up the rank. (defun hand-ranking (hand) "Return the highest rank for the given HAND and the ranking cards." (setf hand (sort-cards hand)) (let ((quadruples nil) (triples nil) (pairs nil) (leftover-cards hand)) ;; First check for quadruples, triples and pairs in that order (setf quadruples (n-values-match leftover-cards 4)) (setf leftover-cards (set-difference leftover-cards (car quadruples))) (setf triples (n-values-match leftover-cards 3)) (setf leftover-cards (set-difference leftover-cards (car triples))) (setf pairs (n-values-match leftover-cards 2)) (cond ((and (all-same-suit? hand) (equalp (list "T" "J" "Q" "K" "A") (mapcar #'value hand))) (list :royal-flush (largest-value-card hand) hand)) ((and (all-same-suit? hand) (all-consecutive-values? hand)) (list :straight-flush (largest-value-card hand) hand)) ((not (null quadruples)) (list :four-of-a-kind (comparative-value (caar quadruples)) (car quadruples))) ((and (not (null triples)) (not (null pairs))) ;; Note: For a Full House, we consider only the value of ;; the triple, and not the pair. (list :full-house (comparative-value (caar triples)) (append triples pairs))) ((all-same-suit? hand) (list :flush (largest-value-card hand) hand)) ((all-consecutive-values? hand) (list :straight (largest-value-card hand) hand)) ((not (null triples)) (list :three-of-a-kind (comparative-value (caar triples)) (car triples))) ;; For a two-pair, we consider the value of the highest pair. ((= (length pairs) 2) (list :two-pairs (largest-value-card (apply #'append pairs)) pairs)) ((not (null pairs)) (list :one-pair (comparative-value (caar pairs)) (car pairs))) (t (list :high-card (comparative-value (car (last hand))) (last hand)))))) ;; So e.g. we can use this ranking function as follows: (defvar player-1 (nth-value 0 (deal-hand example-hand))) (defvar player-2 (nth-value 1 (deal-hand example-hand))) (hand-ranking player-1) ;;=> (:ONE-PAIR 5 ("5H" "5C")) (hand-ranking player-2) ;;=> (:ONE-PAIR 8 ("8S" "8D")) (hand-ranking '("2H" "2D" "4C" "4D" "4S")) ;;=> (:FULL-HOUSE 4 (("4C" "4D" "4S") ("2D" "2H"))) (hand-ranking '("QC" "4C" "QH" "2S" "4S")) ;;=> (:TWO-PAIRS 12 (("QC" "QH") ("4C" "4S"))) (hand-ranking '("2H" "7H" "QH" "3C" "AS")) ;;=> (:HIGH-CARD 14 ("AS")) ;; We use this ranking function to code a function to determine ;; a winner for a given 10-card hand, recalling that we break ties ;; by checking the values of the ranking cards first. In the event ;; of a tie we compare values for each card individually. (defun ranking-order (ranking) "Return an integer between 0-9 quantifying how good the given RANK is." (let ((ranking-order (list :high-card :one-pair :two-pairs :three-of-a-kind :straight :flush :full-house :four-of-a-kind :straight-flush :royal-flush))) (position ranking ranking-order))) (defun winner (hand) "Return the winner (Player 1 or 2) for the 10-card dealt poker HAND." (let ((winner nil)) (multiple-value-bind (player-1 player-2) (deal-hand hand) ;; Compare hand rankings for each player (let* ((ranking-1 (hand-ranking player-1)) (ranking-order-1 (ranking-order (car ranking-1))) (ranking-value-1 (cadr ranking-1)) (ranking-2 (hand-ranking player-2)) (ranking-order-2 (ranking-order (car ranking-2))) (ranking-value-2 (cadr ranking-2))) ;; When rankings differ, the highest rank wins (if (/= ranking-order-1 ranking-order-2) (setf winner (if (< ranking-order-1 ranking-order-2) 2 1)) ;; Tie-breaker. In this case we look first at the ranking ;; cards' values and pick the highest. (if (/= ranking-value-1 ranking-value-2) (setf winner (if (< ranking-value-1 ranking-value-2) 2 1)) ;; Tie-breaker: now we check the values of each of the ;; cards from highest to lowest to determine the winner. (let ((card-values-1 (mapcar #'comparative-value (reverse (sort-cards player-1)))) (card-values-2 (mapcar #'comparative-value (reverse (sort-cards player-2))))) (block value-compare (loop for i from 0 below (length card-values-1) do (if (/= (nth i card-values-1) (nth i card-values-2)) (if (< (nth i card-values-1) (nth i card-values-2)) (progn (setf winner 2) (return-from value-compare)) (progn (setf winner 1) (return-from value-compare))))))))))) winner)) (winner example-hand) ;;=> 2 (winner "5D 8C 9S JS AC 2C 5C 7D 8S QH") ;;=> 1 (winner "2D 9C AS AH AC 3D 6D 7D TD QD") ;;=> 2 (winner "4D 6S 9H QH QC 3D 6D 7H QD QS") ;;=> 1 (winner "2H 2D 4C 4D 4S 3C 3D 3S 9S 9D") ;;=> 1 ;; We loop through the given poker hands and count how many ;; times Player 1 wins. (loop for hand in poker-hands when (= 1 (winner hand)) count hand) ;;=> 376
70472
;; Code for Project Euler Problem 54. ;; ;; Code author: <NAME> ;; Date last modified: 26/08/2021 ;; We are given a list of two-player poker hands that we first download ;; and parse from the Project Euler problem page. We are given that ;; the hands comprise 10 cards separated by spaces, and the first 5 ;; cards belong to Player 1, and the last 5 cards belong to Player 2. (ql:quickload '(:dexador :str)) (defparameter text-file "https://projecteuler.net/project/resources/p054_poker.txt") (defparameter poker-hands (str:split #\newline (str:trim (dex:get text-file)))) ;; The poker hands look like the following example: (defvar example-hand "5H 5C 6S 7S KD 2C 3S 8S 8D TD") ;; Each card is represented as a string, but actually we want to ;; be able to talk about attributes of the cards like their ;; value and suit and compare cards in a clean way. So we'll define ;; some pesudo-OOP infrastructure here to allow us to deal with ;; the values and suits of these cards explicitly as a data abstraction: (defun value (card) "Return the value of CARD." (str:substring 0 1 card)) (defun suit (card) "Return the suit of CARD." (str:substring 1 2 card)) (value "5H") ;;=> "5" (suit "5H") ;;=> "H" ;; This is a 'good' start, but notice that we cannot easily ;; compare (numerically) the values of different cards, since ;; the value can be a string like "T" or "K" for example. So we'll ;; define a mapping to the natural numbers that lets us compare ;; card values in a straightforward way. (defun comparative-value (card) "Returns a comparable numeric value for CARD, so 2<...<9<T<J<Q<K<A." (let ((values (list "2" "3" "4" "5" "6" "7" "8" "9" "T" "J" "Q" "K" "A"))) (+ 2 (position (value card) values :test #'equalp)))) (comparative-value "TH") ;;=> 10 (comparative-value "KD") ;;=> 13 ;; These functions suffice for us to be able to compare cards and ;; compute differences/duplicates, etc, by leveraging existing ;; functions for string and integer operations. We'll consider a ;; hand to (naturally) just be a list of these card strings, and so ;; we can write a quick function to parse a given 10-card hand and ;; split it into halves for each player's cards: (defun deal-hand (hand) "Return lists for Player 1 and Player 2's cards from the given HAND." (let ((player-1 nil) (player-2 (str:split #\space hand))) (loop repeat 5 do (push (pop player-2) player-1)) (values (reverse player-1) player-2))) (deal-hand example-hand) ;;=> ("5H" "5C" "6S" "7S" "KD") ;;=> ("2C" "3S" "8S" "8D" "TD") ;; We can use the comparative card values to define a simple ;; sort function to get the cards in increasing order: (defun sort-cards (cards) "Return the given CARDS sorted in increasing order of value." (sort (copy-list cards) #'< :key #'comparative-value)) (sort-cards '("5H" "TS" "QS" "2D" "7D" "7C")) ;;=> ("2D" "5H" "7D" "7C" "TS" "QS") ;; We can then easily define a function to pick out the largest value ;; from a given set of cards: (defun largest-value-card (cards) "Return the comparative value for the largest value card in CARDS." (comparative-value (car (last (sort-cards cards))))) (largest-value-card '("5H" "2D" "7C" "QH" "5H")) ;;=> 12 ;; And in particular for the poker rankings, it is useful to know ;; how many of each value/suit are in a given set of cards, so ;; we can code up utility functions for those too. We'll return ;; convenient plist data structures for the counts: (defun card-value-counts (cards) "Return the card value counts for each value in the given CARDS." (let ((unique-values (remove-duplicates (mapcar #'value cards) :test #'equalp))) (loop for value in unique-values append (list value (count value cards :key #'value :test #'equalp))))) (card-value-counts '("2D" "2S" "AS" "7C" "6C" "7H" "KD")) ;;=> ("2" 2 "A" 1 "6" 1 "7" 2 "K" 1) (defun card-suit-counts (cards) "Return the card suit counts for each suit in the given CARDS." (let ((unique-suits (remove-duplicates (mapcar #'suit cards) :test #'equalp))) (loop for suit in unique-suits append (list suit (count suit cards :key #'suit :test #'equalp))))) (card-suit-counts '("2D" "2S" "AS" "7C" "6C" "7H" "KD")) ;;=> ("S" 2 "C" 2 "H" 1 "D" 2) ;; And we in turn use those utility functions to build up further ;; utility functions that will let us distinguish between flushes, ;; straights, pairs, etc. (defun all-same-suit? (cards) "True if all of the CARDS have the same suit." (= 1 (length (loop for (key val) on (card-suit-counts cards) by #'cddr collect key)))) (all-same-suit? '("2D" "3D" "5D")) ;;=> T (all-same-suit? '("2D" "3D" "6S" "5D")) ;;=> NIL (defun all-consecutive-values? (cards) "True if all of the CARDS have consecutive values." (loop for (card . rest-of-cards) on (sort-cards cards) while rest-of-cards always (= 1 (- (comparative-value (car rest-of-cards)) (comparative-value card))))) (all-consecutive-values? '("2D" "3D" "5D")) ;;=> NIL (all-consecutive-values? '("2D" "3D" "5D" "4S")) ;;=> T (defun n-values-match (cards &optional (n 2)) "Return the matching cards when there are N value matches in CARDS." (let ((matches nil)) (loop for (key val) on (card-value-counts cards) by #'cddr when (= val n) do (push (remove-if-not (lambda (card) (equalp (value card) key)) cards) matches)) matches)) (n-values-match '("2D" "2S" "AS" "7C" "6C" "7H" "KD") 2) ;;=> (("7C" "7H") ("2D" "2S")) ;; Finally, we combine everything together in a 'hand ranking' ;; function that returns the type of rank and the cards that make ;; up the rank. (defun hand-ranking (hand) "Return the highest rank for the given HAND and the ranking cards." (setf hand (sort-cards hand)) (let ((quadruples nil) (triples nil) (pairs nil) (leftover-cards hand)) ;; First check for quadruples, triples and pairs in that order (setf quadruples (n-values-match leftover-cards 4)) (setf leftover-cards (set-difference leftover-cards (car quadruples))) (setf triples (n-values-match leftover-cards 3)) (setf leftover-cards (set-difference leftover-cards (car triples))) (setf pairs (n-values-match leftover-cards 2)) (cond ((and (all-same-suit? hand) (equalp (list "T" "J" "Q" "K" "A") (mapcar #'value hand))) (list :royal-flush (largest-value-card hand) hand)) ((and (all-same-suit? hand) (all-consecutive-values? hand)) (list :straight-flush (largest-value-card hand) hand)) ((not (null quadruples)) (list :four-of-a-kind (comparative-value (caar quadruples)) (car quadruples))) ((and (not (null triples)) (not (null pairs))) ;; Note: For a Full House, we consider only the value of ;; the triple, and not the pair. (list :full-house (comparative-value (caar triples)) (append triples pairs))) ((all-same-suit? hand) (list :flush (largest-value-card hand) hand)) ((all-consecutive-values? hand) (list :straight (largest-value-card hand) hand)) ((not (null triples)) (list :three-of-a-kind (comparative-value (caar triples)) (car triples))) ;; For a two-pair, we consider the value of the highest pair. ((= (length pairs) 2) (list :two-pairs (largest-value-card (apply #'append pairs)) pairs)) ((not (null pairs)) (list :one-pair (comparative-value (caar pairs)) (car pairs))) (t (list :high-card (comparative-value (car (last hand))) (last hand)))))) ;; So e.g. we can use this ranking function as follows: (defvar player-1 (nth-value 0 (deal-hand example-hand))) (defvar player-2 (nth-value 1 (deal-hand example-hand))) (hand-ranking player-1) ;;=> (:ONE-PAIR 5 ("5H" "5C")) (hand-ranking player-2) ;;=> (:ONE-PAIR 8 ("8S" "8D")) (hand-ranking '("2H" "2D" "4C" "4D" "4S")) ;;=> (:FULL-HOUSE 4 (("4C" "4D" "4S") ("2D" "2H"))) (hand-ranking '("QC" "4C" "QH" "2S" "4S")) ;;=> (:TWO-PAIRS 12 (("QC" "QH") ("4C" "4S"))) (hand-ranking '("2H" "7H" "QH" "3C" "AS")) ;;=> (:HIGH-CARD 14 ("AS")) ;; We use this ranking function to code a function to determine ;; a winner for a given 10-card hand, recalling that we break ties ;; by checking the values of the ranking cards first. In the event ;; of a tie we compare values for each card individually. (defun ranking-order (ranking) "Return an integer between 0-9 quantifying how good the given RANK is." (let ((ranking-order (list :high-card :one-pair :two-pairs :three-of-a-kind :straight :flush :full-house :four-of-a-kind :straight-flush :royal-flush))) (position ranking ranking-order))) (defun winner (hand) "Return the winner (Player 1 or 2) for the 10-card dealt poker HAND." (let ((winner nil)) (multiple-value-bind (player-1 player-2) (deal-hand hand) ;; Compare hand rankings for each player (let* ((ranking-1 (hand-ranking player-1)) (ranking-order-1 (ranking-order (car ranking-1))) (ranking-value-1 (cadr ranking-1)) (ranking-2 (hand-ranking player-2)) (ranking-order-2 (ranking-order (car ranking-2))) (ranking-value-2 (cadr ranking-2))) ;; When rankings differ, the highest rank wins (if (/= ranking-order-1 ranking-order-2) (setf winner (if (< ranking-order-1 ranking-order-2) 2 1)) ;; Tie-breaker. In this case we look first at the ranking ;; cards' values and pick the highest. (if (/= ranking-value-1 ranking-value-2) (setf winner (if (< ranking-value-1 ranking-value-2) 2 1)) ;; Tie-breaker: now we check the values of each of the ;; cards from highest to lowest to determine the winner. (let ((card-values-1 (mapcar #'comparative-value (reverse (sort-cards player-1)))) (card-values-2 (mapcar #'comparative-value (reverse (sort-cards player-2))))) (block value-compare (loop for i from 0 below (length card-values-1) do (if (/= (nth i card-values-1) (nth i card-values-2)) (if (< (nth i card-values-1) (nth i card-values-2)) (progn (setf winner 2) (return-from value-compare)) (progn (setf winner 1) (return-from value-compare))))))))))) winner)) (winner example-hand) ;;=> 2 (winner "5D 8C 9S JS AC 2C 5C 7D 8S QH") ;;=> 1 (winner "2D 9C AS AH AC 3D 6D 7D TD QD") ;;=> 2 (winner "4D 6S 9H QH QC 3D 6D 7H QD QS") ;;=> 1 (winner "2H 2D 4C 4D 4S 3C 3D 3S 9S 9D") ;;=> 1 ;; We loop through the given poker hands and count how many ;; times Player 1 wins. (loop for hand in poker-hands when (= 1 (winner hand)) count hand) ;;=> 376
true
;; Code for Project Euler Problem 54. ;; ;; Code author: PI:NAME:<NAME>END_PI ;; Date last modified: 26/08/2021 ;; We are given a list of two-player poker hands that we first download ;; and parse from the Project Euler problem page. We are given that ;; the hands comprise 10 cards separated by spaces, and the first 5 ;; cards belong to Player 1, and the last 5 cards belong to Player 2. (ql:quickload '(:dexador :str)) (defparameter text-file "https://projecteuler.net/project/resources/p054_poker.txt") (defparameter poker-hands (str:split #\newline (str:trim (dex:get text-file)))) ;; The poker hands look like the following example: (defvar example-hand "5H 5C 6S 7S KD 2C 3S 8S 8D TD") ;; Each card is represented as a string, but actually we want to ;; be able to talk about attributes of the cards like their ;; value and suit and compare cards in a clean way. So we'll define ;; some pesudo-OOP infrastructure here to allow us to deal with ;; the values and suits of these cards explicitly as a data abstraction: (defun value (card) "Return the value of CARD." (str:substring 0 1 card)) (defun suit (card) "Return the suit of CARD." (str:substring 1 2 card)) (value "5H") ;;=> "5" (suit "5H") ;;=> "H" ;; This is a 'good' start, but notice that we cannot easily ;; compare (numerically) the values of different cards, since ;; the value can be a string like "T" or "K" for example. So we'll ;; define a mapping to the natural numbers that lets us compare ;; card values in a straightforward way. (defun comparative-value (card) "Returns a comparable numeric value for CARD, so 2<...<9<T<J<Q<K<A." (let ((values (list "2" "3" "4" "5" "6" "7" "8" "9" "T" "J" "Q" "K" "A"))) (+ 2 (position (value card) values :test #'equalp)))) (comparative-value "TH") ;;=> 10 (comparative-value "KD") ;;=> 13 ;; These functions suffice for us to be able to compare cards and ;; compute differences/duplicates, etc, by leveraging existing ;; functions for string and integer operations. We'll consider a ;; hand to (naturally) just be a list of these card strings, and so ;; we can write a quick function to parse a given 10-card hand and ;; split it into halves for each player's cards: (defun deal-hand (hand) "Return lists for Player 1 and Player 2's cards from the given HAND." (let ((player-1 nil) (player-2 (str:split #\space hand))) (loop repeat 5 do (push (pop player-2) player-1)) (values (reverse player-1) player-2))) (deal-hand example-hand) ;;=> ("5H" "5C" "6S" "7S" "KD") ;;=> ("2C" "3S" "8S" "8D" "TD") ;; We can use the comparative card values to define a simple ;; sort function to get the cards in increasing order: (defun sort-cards (cards) "Return the given CARDS sorted in increasing order of value." (sort (copy-list cards) #'< :key #'comparative-value)) (sort-cards '("5H" "TS" "QS" "2D" "7D" "7C")) ;;=> ("2D" "5H" "7D" "7C" "TS" "QS") ;; We can then easily define a function to pick out the largest value ;; from a given set of cards: (defun largest-value-card (cards) "Return the comparative value for the largest value card in CARDS." (comparative-value (car (last (sort-cards cards))))) (largest-value-card '("5H" "2D" "7C" "QH" "5H")) ;;=> 12 ;; And in particular for the poker rankings, it is useful to know ;; how many of each value/suit are in a given set of cards, so ;; we can code up utility functions for those too. We'll return ;; convenient plist data structures for the counts: (defun card-value-counts (cards) "Return the card value counts for each value in the given CARDS." (let ((unique-values (remove-duplicates (mapcar #'value cards) :test #'equalp))) (loop for value in unique-values append (list value (count value cards :key #'value :test #'equalp))))) (card-value-counts '("2D" "2S" "AS" "7C" "6C" "7H" "KD")) ;;=> ("2" 2 "A" 1 "6" 1 "7" 2 "K" 1) (defun card-suit-counts (cards) "Return the card suit counts for each suit in the given CARDS." (let ((unique-suits (remove-duplicates (mapcar #'suit cards) :test #'equalp))) (loop for suit in unique-suits append (list suit (count suit cards :key #'suit :test #'equalp))))) (card-suit-counts '("2D" "2S" "AS" "7C" "6C" "7H" "KD")) ;;=> ("S" 2 "C" 2 "H" 1 "D" 2) ;; And we in turn use those utility functions to build up further ;; utility functions that will let us distinguish between flushes, ;; straights, pairs, etc. (defun all-same-suit? (cards) "True if all of the CARDS have the same suit." (= 1 (length (loop for (key val) on (card-suit-counts cards) by #'cddr collect key)))) (all-same-suit? '("2D" "3D" "5D")) ;;=> T (all-same-suit? '("2D" "3D" "6S" "5D")) ;;=> NIL (defun all-consecutive-values? (cards) "True if all of the CARDS have consecutive values." (loop for (card . rest-of-cards) on (sort-cards cards) while rest-of-cards always (= 1 (- (comparative-value (car rest-of-cards)) (comparative-value card))))) (all-consecutive-values? '("2D" "3D" "5D")) ;;=> NIL (all-consecutive-values? '("2D" "3D" "5D" "4S")) ;;=> T (defun n-values-match (cards &optional (n 2)) "Return the matching cards when there are N value matches in CARDS." (let ((matches nil)) (loop for (key val) on (card-value-counts cards) by #'cddr when (= val n) do (push (remove-if-not (lambda (card) (equalp (value card) key)) cards) matches)) matches)) (n-values-match '("2D" "2S" "AS" "7C" "6C" "7H" "KD") 2) ;;=> (("7C" "7H") ("2D" "2S")) ;; Finally, we combine everything together in a 'hand ranking' ;; function that returns the type of rank and the cards that make ;; up the rank. (defun hand-ranking (hand) "Return the highest rank for the given HAND and the ranking cards." (setf hand (sort-cards hand)) (let ((quadruples nil) (triples nil) (pairs nil) (leftover-cards hand)) ;; First check for quadruples, triples and pairs in that order (setf quadruples (n-values-match leftover-cards 4)) (setf leftover-cards (set-difference leftover-cards (car quadruples))) (setf triples (n-values-match leftover-cards 3)) (setf leftover-cards (set-difference leftover-cards (car triples))) (setf pairs (n-values-match leftover-cards 2)) (cond ((and (all-same-suit? hand) (equalp (list "T" "J" "Q" "K" "A") (mapcar #'value hand))) (list :royal-flush (largest-value-card hand) hand)) ((and (all-same-suit? hand) (all-consecutive-values? hand)) (list :straight-flush (largest-value-card hand) hand)) ((not (null quadruples)) (list :four-of-a-kind (comparative-value (caar quadruples)) (car quadruples))) ((and (not (null triples)) (not (null pairs))) ;; Note: For a Full House, we consider only the value of ;; the triple, and not the pair. (list :full-house (comparative-value (caar triples)) (append triples pairs))) ((all-same-suit? hand) (list :flush (largest-value-card hand) hand)) ((all-consecutive-values? hand) (list :straight (largest-value-card hand) hand)) ((not (null triples)) (list :three-of-a-kind (comparative-value (caar triples)) (car triples))) ;; For a two-pair, we consider the value of the highest pair. ((= (length pairs) 2) (list :two-pairs (largest-value-card (apply #'append pairs)) pairs)) ((not (null pairs)) (list :one-pair (comparative-value (caar pairs)) (car pairs))) (t (list :high-card (comparative-value (car (last hand))) (last hand)))))) ;; So e.g. we can use this ranking function as follows: (defvar player-1 (nth-value 0 (deal-hand example-hand))) (defvar player-2 (nth-value 1 (deal-hand example-hand))) (hand-ranking player-1) ;;=> (:ONE-PAIR 5 ("5H" "5C")) (hand-ranking player-2) ;;=> (:ONE-PAIR 8 ("8S" "8D")) (hand-ranking '("2H" "2D" "4C" "4D" "4S")) ;;=> (:FULL-HOUSE 4 (("4C" "4D" "4S") ("2D" "2H"))) (hand-ranking '("QC" "4C" "QH" "2S" "4S")) ;;=> (:TWO-PAIRS 12 (("QC" "QH") ("4C" "4S"))) (hand-ranking '("2H" "7H" "QH" "3C" "AS")) ;;=> (:HIGH-CARD 14 ("AS")) ;; We use this ranking function to code a function to determine ;; a winner for a given 10-card hand, recalling that we break ties ;; by checking the values of the ranking cards first. In the event ;; of a tie we compare values for each card individually. (defun ranking-order (ranking) "Return an integer between 0-9 quantifying how good the given RANK is." (let ((ranking-order (list :high-card :one-pair :two-pairs :three-of-a-kind :straight :flush :full-house :four-of-a-kind :straight-flush :royal-flush))) (position ranking ranking-order))) (defun winner (hand) "Return the winner (Player 1 or 2) for the 10-card dealt poker HAND." (let ((winner nil)) (multiple-value-bind (player-1 player-2) (deal-hand hand) ;; Compare hand rankings for each player (let* ((ranking-1 (hand-ranking player-1)) (ranking-order-1 (ranking-order (car ranking-1))) (ranking-value-1 (cadr ranking-1)) (ranking-2 (hand-ranking player-2)) (ranking-order-2 (ranking-order (car ranking-2))) (ranking-value-2 (cadr ranking-2))) ;; When rankings differ, the highest rank wins (if (/= ranking-order-1 ranking-order-2) (setf winner (if (< ranking-order-1 ranking-order-2) 2 1)) ;; Tie-breaker. In this case we look first at the ranking ;; cards' values and pick the highest. (if (/= ranking-value-1 ranking-value-2) (setf winner (if (< ranking-value-1 ranking-value-2) 2 1)) ;; Tie-breaker: now we check the values of each of the ;; cards from highest to lowest to determine the winner. (let ((card-values-1 (mapcar #'comparative-value (reverse (sort-cards player-1)))) (card-values-2 (mapcar #'comparative-value (reverse (sort-cards player-2))))) (block value-compare (loop for i from 0 below (length card-values-1) do (if (/= (nth i card-values-1) (nth i card-values-2)) (if (< (nth i card-values-1) (nth i card-values-2)) (progn (setf winner 2) (return-from value-compare)) (progn (setf winner 1) (return-from value-compare))))))))))) winner)) (winner example-hand) ;;=> 2 (winner "5D 8C 9S JS AC 2C 5C 7D 8S QH") ;;=> 1 (winner "2D 9C AS AH AC 3D 6D 7D TD QD") ;;=> 2 (winner "4D 6S 9H QH QC 3D 6D 7H QD QS") ;;=> 1 (winner "2H 2D 4C 4D 4S 3C 3D 3S 9S 9D") ;;=> 1 ;; We loop through the given poker hands and count how many ;; times Player 1 wins. (loop for hand in poker-hands when (= 1 (winner hand)) count hand) ;;=> 376
[ { "context": ")\n(defparameter influxdb nil)\n(defparameter user \"root\")\n(defparameter password \"root\")\n\n;; Preform some", "end": 155, "score": 0.9351760745048523, "start": 151, "tag": "USERNAME", "value": "root" }, { "context": "defparameter user \"root\")\n(defparameter password \"root\")\n\n;; Preform some operations to exercise the int", "end": 186, "score": 0.9988670349121094, "start": 182, "tag": "PASSWORD", "value": "root" }, { "context": "lass INFLUXDB to get started the default is\nuser = root, password = root, host = 127.0.0.1, port = 8086.\n", "end": 386, "score": 0.8161174058914185, "start": 382, "tag": "USERNAME", "value": "root" }, { "context": "get started the default is\nuser = root, password = root, host = 127.0.0.1, port = 8086.\n\"\n (setq influ", "end": 403, "score": 0.9991441965103149, "start": 399, "tag": "PASSWORD", "value": "root" }, { "context": "e default is\nuser = root, password = root, host = 127.0.0.1, port = 8086.\n\"\n (setq influxdb (make-instanc", "end": 421, "score": 0.9997608661651611, "start": 412, "tag": "IP_ADDRESS", "value": "127.0.0.1" } ]
examples/examples.lisp
mmaul/cl-influxdb
14
(in-package cl-influxdb.examples) (annot:enable-annot-syntax) (defparameter db "cl_influxdb_example") (defparameter influxdb nil) (defparameter user "root") (defparameter password "root") ;; Preform some operations to exercise the interface @export (defun exercise () (print-run " Usage ===== Lets create a instance of class INFLUXDB to get started the default is user = root, password = root, host = 127.0.0.1, port = 8086. " (setq influxdb (make-instance 'influxdb :database db :user user :password password)) ) (print-run " Create a new database" (handler-case (create-database influxdb db) (command-fail (e) e))) (print-run " If we had tried to create a database and it already existed We get a condition, like this:" (handler-case (create-database influxdb db) (command-fail (e) (print e))) ) (print-run " Load some data Note that all commands" (write-points influxdb (make-influxdb-data :key :response_times :tags '((:host . "server1") (:region . "one")) :columns '(:t1 :v1) :points '((1394761721 1.0) (1394761722 2.0)))) ) (print-run " Now that we inserted some data lets list it. " (query influxdb "select t1,p1 from response_times;") ) t)
94315
(in-package cl-influxdb.examples) (annot:enable-annot-syntax) (defparameter db "cl_influxdb_example") (defparameter influxdb nil) (defparameter user "root") (defparameter password "<PASSWORD>") ;; Preform some operations to exercise the interface @export (defun exercise () (print-run " Usage ===== Lets create a instance of class INFLUXDB to get started the default is user = root, password = <PASSWORD>, host = 127.0.0.1, port = 8086. " (setq influxdb (make-instance 'influxdb :database db :user user :password password)) ) (print-run " Create a new database" (handler-case (create-database influxdb db) (command-fail (e) e))) (print-run " If we had tried to create a database and it already existed We get a condition, like this:" (handler-case (create-database influxdb db) (command-fail (e) (print e))) ) (print-run " Load some data Note that all commands" (write-points influxdb (make-influxdb-data :key :response_times :tags '((:host . "server1") (:region . "one")) :columns '(:t1 :v1) :points '((1394761721 1.0) (1394761722 2.0)))) ) (print-run " Now that we inserted some data lets list it. " (query influxdb "select t1,p1 from response_times;") ) t)
true
(in-package cl-influxdb.examples) (annot:enable-annot-syntax) (defparameter db "cl_influxdb_example") (defparameter influxdb nil) (defparameter user "root") (defparameter password "PI:PASSWORD:<PASSWORD>END_PI") ;; Preform some operations to exercise the interface @export (defun exercise () (print-run " Usage ===== Lets create a instance of class INFLUXDB to get started the default is user = root, password = PI:PASSWORD:<PASSWORD>END_PI, host = 127.0.0.1, port = 8086. " (setq influxdb (make-instance 'influxdb :database db :user user :password password)) ) (print-run " Create a new database" (handler-case (create-database influxdb db) (command-fail (e) e))) (print-run " If we had tried to create a database and it already existed We get a condition, like this:" (handler-case (create-database influxdb db) (command-fail (e) (print e))) ) (print-run " Load some data Note that all commands" (write-points influxdb (make-influxdb-data :key :response_times :tags '((:host . "server1") (:region . "one")) :columns '(:t1 :v1) :points '((1394761721 1.0) (1394761722 2.0)))) ) (print-run " Now that we inserted some data lets list it. " (query influxdb "select t1,p1 from response_times;") ) t)
[ { "context": ";;;;\n;;;\n;; @file use-poly.lisp\n;; @author Mitch Richling <https://www.mitchr.me>\n;; @brief Polynomials", "end": 306, "score": 0.9998792409896851, "start": 292, "tag": "NAME", "value": "Mitch Richling" }, { "context": " (c) 1994,1997,1998,2004,2008,2012,2013,2014,2015, Mitchell Jay Richling <https://www.mitchr.me> All rights reserved.\n;;\n;", "end": 572, "score": 0.9998844861984253, "start": 551, "tag": "NAME", "value": "Mitchell Jay Richling" }, { "context": " derivatives at x.\n\nAlgorithm due to Pankiewicz:\n W. Pankiewicz (1968); Algorithm 337: calculation of a polynomia", "end": 24209, "score": 0.9998282194137573, "start": 24196, "tag": "NAME", "value": "W. Pankiewicz" }, { "context": "also irreducible over $\\mathbb{Q}$.\n\nReferences:\n Carl Friedrich Gauss(1801); Disquisitiones Arithmeticae; Article 42\"\n ", "end": 31019, "score": 0.9998130798339844, "start": 30999, "tag": "NAME", "value": "Carl Friedrich Gauss" }, { "context": " Then\n we have $\\\\rho = v_\\\\delta$\n\nReferences:\n Jacques Charles Francois Sturm(1829); Memoire sur la resolution des equations nu", "end": 37757, "score": 0.9681050181388855, "start": 37727, "tag": "NAME", "value": "Jacques Charles Francois Sturm" }, { "context": "\\\\mathbb{Z}_+$\n \\\\end{enumerate}\n\nReferences:\n Francois D. Budan (1807); Nouvelle methode pour la resolution des e", "end": 38991, "score": 0.9998624324798584, "start": 38974, "tag": "NAME", "value": "Francois D. Budan" }, { "context": "\\\\mathbb{Z}_+$\n \\\\end{enumerate}\n\nReferences:\n Jean Baptiste Joseph Fourier (1820); Sur l'usage du theoreme de Descartes dans", "end": 40298, "score": 0.9998260140419006, "start": 40270, "tag": "NAME", "value": "Jean Baptiste Joseph Fourier" }, { "context": "s, par la Societe Philomatique de Paris: 156-165\n E.J. Barbeau (2003); Polynomials (Problem Books in Mathematics", "end": 40470, "score": 0.9997562170028687, "start": 40458, "tag": "NAME", "value": "E.J. Barbeau" }, { "context": "lynomials (Problem Books in Mathematics); pp 174\n Victor V. Prasolov (2004); Polynomials; ISBN: 3540407146; pp 27\"\n (", "end": 40550, "score": 0.9997111558914185, "start": 40532, "tag": "NAME", "value": "Victor V. Prasolov" }, { "context": " $m$ and $n$ non-negative integers.\n\nReferences:\n Rene Descartes (1637); La Geometrie (an appendix to Discours de ", "end": 42317, "score": 0.9998734593391418, "start": 42303, "tag": "NAME", "value": "Rene Descartes" }, { "context": "o Discours de la methode -- Discourse on Method)\n Michael Mahoney (1979); Geometry (a translation of La Geometrie)\n", "end": 42419, "score": 0.9998786449432373, "start": 42404, "tag": "NAME", "value": "Michael Mahoney" }, { "context": "(1979); Geometry (a translation of La Geometrie)\n Grabiner (1999); Descartes Rule of Signs: Another Construc", "end": 42479, "score": 0.9994043111801147, "start": 42471, "tag": "NAME", "value": "Grabiner" }, { "context": "r Construction; Amer. Math. Monthly 106, 854-855\n Victor V. Prasolov (2004); Polynomials; ISBN: 3540407146; pp 28\"\n (", "end": 42588, "score": 0.9996760487556458, "start": 42570, "tag": "NAME", "value": "Victor V. Prasolov" }, { "context": "es de mathematique. Oeuvres 2 (9)\n Milovanovic, Mitrinovic, Rassias (1994); Topics in polynomials: extre", "end": 47672, "score": 0.7564772963523865, "start": 47667, "tag": "NAME", "value": "itrin" }, { "context": "ematique. Oeuvres 2 (9)\n Milovanovic, Mitrinovic, Rassias (1994); Topics in polynomials: extremal problems,", "end": 47685, "score": 0.7719392776489258, "start": 47678, "tag": "NAME", "value": "Rassias" }, { "context": " problems, inequalities, zeros; ISBN: 981020499X\n Hirst & Macey (1997); Bounding the roots of polynomials", "end": 47781, "score": 0.849269449710846, "start": 47776, "tag": "NAME", "value": "Hirst" }, { "context": "s, inequalities, zeros; ISBN: 981020499X\n Hirst & Macey (1997); Bounding the roots of polynomials; Coll M", "end": 47789, "score": 0.7993224263191223, "start": 47784, "tag": "NAME", "value": "Macey" }, { "context": "e less than the length of the list)\n\nReferences:\n Victor V. Prasolov (2004); Polynomials; ISBN: 3540407146; pp 49-50\"\n", "end": 85447, "score": 0.9998676180839539, "start": 85429, "tag": "NAME", "value": "Victor V. Prasolov" }, { "context": "e large integers with many factors.\n\nReferences:\n Victor V. Prasolov (2004); Polynomials; ISBN: 3540407146; pp 49-50\n ", "end": 88893, "score": 0.9998729825019836, "start": 88875, "tag": "NAME", "value": "Victor V. Prasolov" }, { "context": " (2004); Polynomials; ISBN: 3540407146; pp 49-50\n Joel S. Cohen (2003); Computer Algebra and Symbolic Computation", "end": 88957, "score": 0.9998673796653748, "start": 88944, "tag": "NAME", "value": "Joel S. Cohen" }, { "context": "\\vert p$, and $u^{(j+1)} \\\\nmid p$.\n\nReferences:\n Antonio Machi (2012); Algebra for Symbolic Computation; ISBN: 9", "end": 107978, "score": 0.9997001886367798, "start": 107965, "tag": "NAME", "value": "Antonio Machi" } ]
use-poly.lisp
richmit/mjrcalc
17
;; -*- Mode:Lisp; Syntax:ANSI-Common-LISP; Coding:us-ascii-unix; fill-column:158 -*- ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; ;; @file use-poly.lisp ;; @author Mitch Richling <https://www.mitchr.me> ;; @brief Polynomials over complex, real, rational, and integers.@EOL ;; @std Common Lisp ;; @see tst-poly.lisp ;; @copyright ;; @parblock ;; Copyright (c) 1994,1997,1998,2004,2008,2012,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 ;; @todo mjr_poly_root-solve-search-deflate: Want generic way to specifiy search, refine, and xform methods.@EOL@EOL ;; @todo Make some kind of convention for the type (int, gausian, float, complex, etc...) of polynomials a function works with.@EOL@EOL ;; @todo Better way to find solutions that are in radical extension fields -- i.e. $a,b,c\in\mathbb{Q}$ but $a+b\sqrt{c}\not\in\mathbb{Q}$.@EOL@EOL ;; @todo Better control/seporation/deliniation of Z[x], Q[x], & R[x] across functions. Make this uniform.@EOL@EOL ;; @todo Update unit tests for new functionality.@EOL@EOL ;; @todo mjr_poly_decompose.@EOL@EOL ;; @todo mjr_poly_factor-irreducible.@EOL@EOL ;; @todo mjr_poly_root-solve-jenkins-traub.@EOL@EOL ;; @todo mjr_poly_root-solve-continued-fraction.@EOL@EOL ;; @todo mjr_poly_root-solve-descartes-bisection.@EOL@EOL ;; @todo mjr_poly_root-separate-real.@EOL@EOL ;; @warning Much of this code has become quite experimental! Use the old version if you want to be carefull.@EOL@EOL ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defpackage :MJR_POLY (:USE :COMMON-LISP :MJR_NLEQ :MJR_NUMU :MJR_CMP :MJR_CHK :MJR_PRIME :MJR_VEC :MJR_PRNG :MJR_COMBE :MJR_INTRP :MJR_COMBC :MJR_VVEC :MJR_GPOLY :MJR_EPS) (:DOCUMENTATION "Brief: Univariate Polynomials over R or C.;") (:EXPORT #:mjr_poly_help ;; Autogenerated from #:mjr_gpoly #:mjr_poly_coeff #:mjr_poly_diff #:mjr_poly_- #:mjr_poly_+ #:mjr_poly_* #:mjr_poly_iexpt #:mjr_poly_scale #:mjr_poly_truncate #:mjr_poly_rem #:mjr_poly_mod #:mjr_poly_divides? #:mjr_poly_gcd #:mjr_poly_degree #:mjr_poly_leading-coeff #:mjr_poly_constant-coeff #:mjr_poly_zerop #:mjr_poly_onep #:mjr_poly_constantp #:mjr_poly_simplify #:mjr_poly_eval #:mjr_poly_subst #:mjr_poly_density #:mjr_poly_index ;; Implemented here.. #:mjr_poly_imul #:mjr_poly_count-sign-changes #:mjr_poly_print #:mjr_poly_code #:mjr_poly_intg #:mjr_poly_gcd-primitive ;; Polynomial metrics #:mjr_poly_height #:mjr_poly_length #:mjr_poly_mahler-measure #:mjr_poly_scount-descartes #:mjr_poly_scount-sturm #:mjr_poly_scount-fourier #:mjr_poly_scount-budan #:mjr_poly_root-structure #:mjr_poly_root-structure-print #:mjr_poly_root-count-distinct-real #:mjr_poly_root-count-distinct-interval #:mjr_poly_root-count-distinct-negative-zero-positive #:mjr_poly_root-bound-all #:mjr_poly_root-bound-positive #:mjr_poly_root-bound-all-cauchy #:mjr_poly_eval-poly-and-first-n-derivatives #:mjr_poly_2func #:mjr_poly_seq-eval #:mjr_poly_root-separate-real #:mjr_poly_root-solve-rational #:mjr_poly_root-solve-search-deflate #:mjr_poly_root-solve-low-degree #:mjr_poly_2square-free #:mjr_poly_2primitive #:mjr_poly_2monic #:mjr_poly_root-search-bsect #:mjr_poly_root-search-newton #:mjr_poly_root-search-laguerre #:mjr_poly_root-search-largest-real #:mjr_poly_root-separate-largest-real #:mjr_poly_make-from-roots ;; Make special polynomials #:mjr_poly_make-lagrange #:mjr_poly_make-chebyshev #:mjr_poly_make-legendre #:mjr_poly_make-bernstein #:mjr_poly_make-hermite #:mjr_poly_make-laguerre ;; Make sequences of polynomials #:mjr_poly_seq-make-lagrange #:mjr_poly_seq-make-chebyshev #:mjr_poly_seq-make-legendre #:mjr_poly_seq-make-bernstein #:mjr_poly_seq-make-hermite #:mjr_poly_seq-make-laguerre #:mjr_poly_seq-make-fourier #:mjr_poly_seq-make-sturm-canonical #:mjr_poly_deflate #:mjr_poly_shift #:mjr_poly_reflect #:mjr_poly_zap-zero-roots ;; EXPERIMENTAL!!!! #:mjr_poly_test-property #:mjr_poly_find-integer-factor #:mjr_poly_factor-over-integers ;; MORE EXPERIMENTAL!!!! #:mjr_poly_cubic-depress #:mjr_poly_tschirnhaus-3-2 #:mjr_poly_resultant #:mjr_poly_discriminant-low-degree #:mjr_poly_discriminant-high-degree #:mjr_poly_discriminant #:mjr_poly_factor-square-free #:mjr_poly_factor-irreducible #:mjr_poly_content #:mjr_poly_primitive-part #:mjr_poly_rationalize )) (in-package :MJR_POLY) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_help () "Univariate, Dense Polynomial Library Polynomials are represented as vectors containing the coefficients -- the position in the array implies the power of the monomial in the term to which the coefficient belongs. For example, x^2+4 would be represented as #(1 0 4). The first coefficient should never be zero unless the polynomial is the zero polynomial. No function in this package should ever produce a non-constant polynomial with a zero in the first position; however, all functions will gladly accept such polynomials and silently fix them. Note that while this vector representation is quite adequate for dense polynomials (i.e. polynomials that have mostly non-zero coefficients), this data structure is inefficient in both space and time for sparse polynomials. This library is a work in progress, but it has enough functionality to be useful. Still, some care should be exercised when using it. Tags: (G) means the function is provided by GPOLY and a (!) means the function is not yet implemented. Function names have been abbreviated in this list by replacing 'mjr_poly_' with 'MP_'. * Strings & Printing ** MP_print MP_code * Evaluation ** MP_eval(G) MP_eval-poly-and-first-n-derivatives MP_seq-eval * Arithmetic ** MP_+(G) MP_-(G) MP_*(G) MP_iexpt(G) MP_rem(G) MP_mod(G) MP_truncate(G) MP_gcd(G) MP_gcd-primitive MP_imul MP_divides?(G) * Coefficient access ** MP_coeff(G) MP_leading-coeff(G) MP_constant-coeff(G) * Recognizing special polynomials ** MP_onep(G) MP_constantp(G) MP_zerop(G) * Polynomial factorization ** MP_decompose(!) MP_factor-square-free MP_factor-irreducible(!) * Things we do with roots: ** MP_root-structure ** Solve polynomial (find all roots): *** MP_root-solve-integer MP_root-solve-rational MP_root-solve-low-degree MP_root-solve-search-deflate *** MP_root-solve-jenkins-traub(!) MP_root-solve-continued-fraction(!) MP_root-solve-descartes-bisection(!) ** Finding roots: *** MP_root-search-bsect MP_root-search-laguerre MP_root-search-newton MP_root-search-largest-real *** MP_root-search-max-magnitude ** Bounding roots: *** MP_root-bound-all MP_root-bound-positive ** Separating roots (a root is 'separated' by finding an interval that contains it but no other roots): *** MP_root-separate-largest-real MP_root-separate-real(!) ** Counting distinct roots *** MP_root-count-distinct-real MP_root-count-distinct-interval MP_root-count-distinct-positive * Construct sequences of polynomials ** MP_seq-make-fourier MP_seq-make-sturm-canonical MP_seq-make-chebyshev MP_seq-make-legendre MP_seq-make-lagrange MP_seq-make-bernstein MP_seq-make-hermite MP_seq-make-laguerre * Construct polynomials ** MP_make-chebyshev MP_make-legendre MP_make-lagrange MP_make-bernstein MP_make-hermite MP_make-laguerre * Polynomial metrics ** Sign change based *** MP_scount-descartes MP_scount-sturm MP_scount-fourier MP_scount-budan ** Other *** MP_height MP_length MP_density(G) MP_index(G) MP_degree(G) MP_discriminant-low-degree MP_discriminant-high-degree MP_discriminant MP_content MP_mahler-measure * Other Stuff ** mjr_poly_resultant * Polynomial xforms ** MP_deflate MP_shift MP_reflect MP_diff(G) MP_intg MP_subst(G) MP_zap-zero-roots MP_2square-free MP_2primitive MP_simplify(G) MP_scale(G) MP_rationalize ** MP_cubic-depress mjr_poly_tschirnhaus-3-2" (documentation 'mjr_poly_help 'function)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (mjr_gpoly_make-coeff "") (mjr_gpoly_make-simplify "") (mjr_gpoly_make-scale "") (mjr_gpoly_make-diff "") (mjr_gpoly_make-eval "") (mjr_gpoly_make-+ "") (mjr_gpoly_make-- "") (mjr_gpoly_make-* "") (mjr_gpoly_make-iexpt "") (mjr_gpoly_make-subst "") (mjr_gpoly_make-leading-coeff "") (mjr_gpoly_make-degree "") (mjr_gpoly_make-density "") (mjr_gpoly_make-index "") (mjr_gpoly_make-constant-coeff "") (mjr_gpoly_make-truncate "") (mjr_gpoly_make-rem "") (mjr_gpoly_make-mod "") (mjr_gpoly_make-onep "") (mjr_gpoly_make-zerop "") (mjr_gpoly_make-constantp "") (mjr_gpoly_make-divides? "") (mjr_gpoly_make-gcd "") ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_print (poly &key (var "x") (add-op "+") (add-apad " ") (add-bpad " ") (expt-op "^") (expt-apad "") (expt-bpad "") (mul-op "*") (mul-apad "") (mul-bpad "") (cof-fmt "~s") (cof-bpad "") (cof-apad "") (pow-fmt "~d") (pow-bpad "") (pow-apad "") (ply-apad "") (ply-bpad "") (suppress-zero-terms 't) (suppress-unit-expt 't) (suppress-unit-prod 't) (suppress-zero-powers 't) (return-string nil)) "Print a polynomial. Return POLY. Arguments: - return-string .......... If non-NIL, then do not print but return a string rep of POLY with no following newline. If NIL, then print POLY with a following newline, and return POLY - var .................... variable to use (a string) - add-op ................. string to print for + signs - add-bpad ............... string to print before + signs - add-apad ............... string to print after + signs - cof-fmt ................ format string for coefficients - cof-bpad ............... string to print before coefficients - cof-apad ............... string to print after coefficients - pow-fmt ................ format string powers - pow-bpad ............... string to print before powers - pow-apad ............... string to print after powers - mul-op ................. string to print for * signs - mul-bpad ............... string to print before * signs - mul-apad ............... string to print after * signs - expt-op ................ string to print for ^ signs - expt-bpad .............. string to print before ^ signs - expt-apad .............. string to print after ^ signs - suppress-zero-terms .... do not print 0*x^n - suppress-unit-expt ..... do not print ^1 - suppress-unit-prod ..... do not print 1* - suppress-zero-powers ... do not print x^0" (let ((da-str (with-output-to-string (str-out) (if (vectorp poly) (let ((plen (length poly))) (if (< 0 plen) (loop with not-first-print = nil for power from (1- plen) downto 0 for term across poly initially (format str-out ply-bpad) finally (format str-out ply-apad) do (if (or (not suppress-zero-terms) (mjr_cmp_!=0 term) (and (= power 0) (not not-first-print))) (progn (if not-first-print (format str-out "~a~a~a" add-bpad add-op add-apad)) (if (or (not suppress-unit-prod) (mjr_cmp_!= 1 term) (zerop power)) (format str-out (concatenate 'string cof-bpad cof-fmt cof-apad) term)) (if (and (or (not suppress-unit-prod) (mjr_cmp_!= 1 term)) (or (not suppress-zero-powers) (not (zerop power)))) (format str-out "~a~a~a" mul-bpad mul-op mul-apad)) (if (or (not suppress-zero-powers) (not (zerop power))) (progn (format str-out "~a" var) (if (or (not suppress-unit-expt) (not (= 1 power))) (progn (format str-out "~a~a~a" expt-bpad expt-op expt-apad) (format str-out (concatenate 'string pow-bpad pow-fmt pow-apad) power))))) (setq not-first-print 't)))))))))) (if return-string (if (vectorp poly) da-str) (progn (if (vectorp poly) (format 't "~a~%" da-str)) poly)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_code (poly &key (lang :lang-matlab)) "Return a string using the syntax of the selected programming language or computational environment." (if (not (vectorp poly)) (error "mjr_poly_code: Argument must be a polynomial (a vector)!")) (with-output-to-string (str-out) (flet ((gpp (&key (var "x") (add-op "+") (add-apad "") (add-bpad "") (expt-op "^") (expt-apad "") (expt-bpad "") (mul-op "*") (mul-apad "") (mul-bpad "") (cof-bpad "") (cof-apad "") (pow-bpad "") (pow-apad "") (ply-apad "") (ply-bpad "")) (loop with plen = (length poly) for not-first-print = nil then 't for power from (1- plen) downto 0 for term across poly initially (format str-out ply-bpad) finally (format str-out ply-apad) when not-first-print do (format str-out "~a~a~a" add-bpad add-op add-apad) do (progn (format str-out "~a~a~a~a" cof-bpad (mjr_numu_code term :lang lang) cof-apad cof-bpad) (if (not (zerop power)) (format str-out "~a~a~a~a~a~a~a~a~a~a" mul-bpad mul-op mul-apad var pow-bpad expt-bpad expt-op expt-apad (mjr_numu_code power :lang lang) pow-apad)))))) (case lang ((:lang-povray :lang-matlab :lang-octave :lang-idl :lang-r :lang-hp48 :lang-mathematica :lang-maple :lang-maxima) (gpp)) ((:lang-latex :lang-pdflatex :lang-amstex :lang-tex) (gpp :ply-bpad "$$" :ply-apad "$$" :mul-op " " :pow-bpad "{" :pow-apad "}")) ((:lang-lisp) (progn (format str-out "(+") (loop for power from (1- (length poly)) downto 0 for term across poly do (if (mjr_cmp_!=0 term) (let ((tstr (if (or (mjr_cmp_!= 1 term) (zerop power)) (format nil " ~a" term))) (vstr (if (not (zerop power)) (if (= 1 power) (format nil " x") (format nil " (expt x ~a)" power))))) (if (and tstr vstr) (format str-out " (*~a~a)" tstr vstr) (format str-out "~a" (or tstr vstr)))))) (format str-out ")"))) ('t (error "mjr_poly_code: Language unsupported!")))) str-out)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_intg (poly a b) "Integrate over the interval $[a,b]$." (let* ((poly (mjr_poly_simplify poly)) (plen (length poly)) (ipoly (make-array (1+ plen) :initial-element 0))) (loop for i from 0 upto (1- plen) do (setf (aref ipoly i) (/ (aref poly i) (- plen i)))) (- (mjr_poly_eval ipoly b) (mjr_poly_eval ipoly a)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_zap-zero-roots (poly &optional eps) "Return two values: 1) a new polynomial, $\\text{POLY}/x^n$, where $n$ is the number of times $0$ is a root of POLY, and 2) $n$. EPS is used with mjr_cmp_!=0 to detect non-zero coefficients." (let* ((plen (length poly)) (zcnt (loop for i from (1- plen) downto 0 for ip = (aref poly i) until (mjr_cmp_!=0 ip eps) count 1)) (slim (- plen zcnt))) (values (if (zerop slim) #(1) (subseq poly 0 slim)) zcnt))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_deflate (poly const) "Return the quotient and the remainder from POLY / (X - CONST). Note: The remainder is equal to POLY(CONST). While the result is equivalent to (MJR_POLY_TRUNCATE POLY (VECTOR 1 (- CONST))), this function is faster." (cond ((not (numberp const)) (error "mjr_poly_eval: CONST must be a number!"))) (let* ((poly (mjr_poly_simplify poly)) (plen (length poly)) (polyval 0) (newpoly (mjr_vec_make-const (max 1 (1- plen))))) (loop for i from 0 upto (1- plen) for ht = (+ (* const polyval) (aref poly i)) do (setq polyval ht) when (not (= i (1- plen))) do (setf (aref newpoly i) ht) finally (return (values newpoly polyval))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_shift (b poly) "Shift POLY right B units (or left if B is negative). References: ;; MJR TODO NOTE <2011-11-23 13:07:23 CST> mjr_poly_shift: Add a reference here. The algorithm is the 'fast taylor shift'. The pink book or sure. Perhaps Prasolov too..." (let ((new-poly (mjr_poly_simplify (copy-seq poly))) (b (- b))) (mjr_poly_simplify (dotimes (i (length new-poly) new-poly) (loop for k from i downto 1 do (incf (aref new-poly k) (* b (aref new-poly (1- k))))))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_reflect (poly) "Reflect POLY across the Y-axis (i.e. subst -x)." (let ((new-poly (mjr_poly_simplify (copy-seq poly)))) (loop for cur-coef across poly for odd-pow = (not (oddp (length poly))) then (not odd-pow) for i from 0 when odd-pow do (setf (aref new-poly i) (- cur-coef)) finally (return (mjr_poly_simplify new-poly))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_make-from-roots (&rest the-roots) "Return the the monic polynomial with the given roots. The roots may be given as individual arguments, or a single list may be provided." (let ((the-roots (if (and (car the-roots) (listp (car the-roots))) (car the-roots) the-roots))) (let* ((n (length the-roots)) (a-lst (make-array (1+ n) :initial-element 0)) (a-nxt (make-array (1+ n) :initial-element 0))) (loop initially (setf (aref a-lst n) (- (car the-roots))) for k from 1 upto (1- n) for zk in (cdr the-roots) do (loop initially (setf (aref a-nxt (- n k)) (- (aref a-lst (- n (1- k))) zk)) for j from 1 upto (1- k) do (setf (aref a-nxt (- n j)) (- (aref a-lst (1+ (- n j))) (* zk (aref a-lst (- n j))))) finally (setf (aref a-nxt n) (* (- zk) (aref a-lst n)))) do (rotatef a-lst a-nxt) finally (progn (setf (aref a-lst 0) 1))) a-lst))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_eval-nth-derivative (poly x &optional (order 1)) "Evaluate polynomial derivative." (mjr_poly_eval (mjr_poly_diff poly order) x)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_eval-poly-and-first-n-derivatives (poly x &optional (order 1)) "Return value of poly and the values of the first ORDER derivatives at x. Algorithm due to Pankiewicz: W. Pankiewicz (1968); Algorithm 337: calculation of a polynomial and its derivative values by Horner scheme; Communications of the ACM; Vol 11, Issue 9, pp 633" (let* ((len-1 (1- (length poly))) (odr-1 order) (pd (make-array (1+ order) :initial-element 0))) (loop for i from (1- len-1) downto 0 for nnd = (min odr-1 (- len-1 i)) initially (setf (aref pd 0) (aref poly 0)) do (loop for j from nnd downto 1 do (setf (aref pd j) (+ (* (aref pd j) x) (aref pd (1- j))))) do (setf (aref pd 0) (+ (* (aref pd 0) x) (aref poly (- len-1 i))))) (loop with cnst = 1 for i from 2 upto odr-1 do (setf cnst (* cnst i)) do (setf (aref pd i) (* (aref pd i) cnst))) (values-list (concatenate 'list pd)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_2func (poly &optional num-derivatives) "Return a function that evaluates the POLY and its first NUM-DERIVATIVES." (if (and num-derivatives (> num-derivatives 0)) (eval `(lambda (x) (mjr_poly_eval-poly-and-first-n-derivatives ,poly x ,num-derivatives))) (eval `(lambda (x) (mjr_poly_eval ,poly x))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_seq-eval (seq x &optional result-type) "Evaluate the polynomials in the sequence (list or vector) at $x$, and return the results in a sequence. If result-type is NIL, then the returned type will be the same as the type of seq." (map (or result-type (if (vectorp seq) 'vector 'list)) (lambda (p) (mjr_poly_eval p x)) seq)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_height (poly) "This is the infinity-norm (maximum absolute value of coefficients)" (mjr_vec_norm-infinity poly)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_length (poly) "This is the one-norm (sum of absolute values of coefficients)" (mjr_vec_norm-one poly)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_2square-free (p) "Return a new polynomial with the same roots as poly, but with no multiple roots." (mjr_poly_truncate p (mjr_poly_gcd p (mjr_poly_diff p)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_2monic (poly) "Transform POLY, via multiplication, into a monic polynomial that shares the roots of the original." (mjr_vec_/ poly (aref poly 0))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_rationalize (poly) "Transform POLY so that all coefficients are rational -- imaginary parts of coefficients too." (map 'vector (lambda (x) (if (complexp x) (complex (rationalize (realpart x)) (rationalize (imagpart x))) (rationalize x))) poly)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_content (poly) "Compute the content of an integer or rational polynomial. POLY is rationalized if necessary. If $p\\in\\mathbb{Z}[x]$, then the content is the GCD of the coefficients. If $p\\in\\mathbb{Q}[x], then the content is the GCD of the numerators divided by the LCM of the denominators. i.e. the content is the unique $q\\in\\mathbb{Q}$ such that $p/q$ is a primitive polynomial in $\\mathbb{Z}[x]$ -- all the coefficients are integers have have GCD of $1$." (let* ((poly (mjr_poly_simplify poly))) (cond ((every #'integerp poly) (reduce #'gcd poly)) ((every #'rationalp poly) (/ (apply #'gcd (map 'list #'numerator poly)) (apply #'lcm (map 'list #'denominator poly)))) ((some #'complexp poly) (error "mjr_poly_content: Polynomial must not be complex!")) ((every #'numberp poly) (mjr_poly_content (mjr_poly_rationalize poly))) ('t (error "mjr_poly_content: POLY is not a polynomial!"))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_primitive-part (poly) "Returns the primitive part of the polynomial and the content. Note: poly = cont(poly)*primitive-part(poly)" (let* ((poly (mjr_poly_simplify poly)) (c (mjr_poly_content poly))) (values (mjr_vec_/ poly c) c))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_2primitive (poly) "Transform POLY, via multiplication by a rational number, into an primitive polynomial that shares the roots of the original. The rational number used to transform POLY is the second return value. Results are exact if the polynomial has only integer and/or rational coefficients. A simple generalization of the idea of primitive is used when the polynomial has complex coefficients -- The real and imaginary parts will both be transformed to integers and the entire collection of integers (real parts and imaginary parts together) will not share a common factor other than one. Floating point numbers in the coefficients will be rationalized. The finite precision of floating point arithmetic implies that polynomials made up of floats, doubles, and long doubles are but a simple scalar product away from their integer doppelganger. Unfortunately the vulgarities of floating point arithmetic can destroy this almost-truth. Still, we do the best we can. NOTE: A polynomial $p(x)=\sum_{j=0}^na_jx^j\in\mathbb{Z}[x]$ is primitive if $\mathrm{GCD}(a_0,\cdots,a_n)=1$ -- i.e. the coefficients are relatively prime. Gauss's lemma: If $p$ and $q$ are primitive, then $p\cdot q$ primitive, and if a $p\in\mathbb{Z}[x]$ is irreducible over the $\mathbb{Z}$, then the same polynomial considered in $\mathbb{Q}[x]$ is also irreducible over $\mathbb{Q}$. References: Carl Friedrich Gauss(1801); Disquisitiones Arithmeticae; Article 42" (let* ((poly (mjr_poly_simplify poly)) (p1 (mjr_poly_rationalize poly)) (L (apply #'lcm (mapcar #'denominator (loop for coef across p1 collect (realpart coef) when (complexp coef) collect (imagpart coef))))) (p2 (mjr_vec_* p1 L)) (G (apply #'gcd (loop for coef across p2 collect (realpart coef) when (complexp coef) collect (imagpart coef)))) (p3 (mjr_vec_/ p2 G))) (values p3 (/ L G)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_seq-make-sturm-canonical (p) "Return a list of polynomials representing the 'Canonical Sturm sequence'. The canonical Sturm sequence of a polynomial $p$ is the intermediate results of Euclid's algorithm applied to to $p$ and $p'$: $$ \\begin{array}{lccclcl} p_0(x) & & & = & p(x) & & \\\\ p_1(x) & & & = & p'(x) & & \\\\ p_2(x) & & & = & -\\text{rem}(p_0, p_1) & = & p_1(x) \\cdot q_0(x) - p_0(x) \\\\ p_3(x) & & & = & -\\text{rem}(p_1, p_2) & = & p_2(x) \\cdot q_1(x) - p_1(x) \\\\ \\vdots & & & & & & \\\\ p_m & & & = & -\\text{rem}(p_{m-2}, p{m-1}) & = & p{m-1}(x) \\cdot q_{m-2}(x) - p_{m-2}(x) \\\\ p_{m+1} & = & 0 & = & -\\text{rem}(p_{m-1}, p_m) & & \\\\ \\end{array} $$ where $\\text{rem}(p_i,p_j)$ and $q_i$ are the remainder and the quotient of the polynomial long division of $p_i$ by $p_j$, and where $m\\le\\text{deg}{p}$ is the minimal number of polynomial divisions needed to obtain a zero remainder. Note: The sequence is well defined even when $p$ is not square-free; however, it may not be a Sturm sequence in this case. Confusingly enough, this sequence is always called the canonical Sturm sequence even when it is not really a Sturm sequence." (let ((pd (mjr_poly_diff p))) (nconc (list p pd) (loop for p-2 = p then p-1 for p-1 = pd then p-0 for p-0 = (mjr_poly_- (mjr_poly_rem p-2 p-1)) collect p-0 until (zerop (mjr_poly_degree p-0)))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_seq-make-fourier (p) "Return a list of polynomials representing the 'Fourier sequence'. Let $p$ be a real polynomial of degree $n>0$, then the Fourier sequence of $p$ is: $$F_\\text{seq}(x)=\\big\\{ p(x), p^{(1)}(x),\\ldots,p^{(n)}(x)\\big\\}$$" (loop for i from 0 upto (mjr_poly_degree p) for p-0 = p then (mjr_poly_diff p-0) collect p-0)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_count-sign-changes (seq) "Return the number of sign changes in seq (vector or list) -- zeros are ignored" (if (vectorp seq) (loop for cur-elt across seq for lst-sgn = nil then (if (zerop cur-sgn) lst-sgn cur-sgn) for (cur-sgn cur-amb) = (multiple-value-list (mjr_cmp_signum cur-elt)) count (and lst-sgn (not (zerop cur-sgn)) (not (= cur-sgn lst-sgn))) into count-sgn count cur-amb into count-amb finally (return (values count-sgn (if (not (zerop count-amb)) count-amb)))) (loop for cur-elt in seq for lst-sgn = nil then (if (zerop cur-sgn) lst-sgn cur-sgn) for (cur-sgn cur-amb) = (multiple-value-list (mjr_cmp_signum cur-elt)) count (and lst-sgn (not (zerop cur-sgn)) (not (= cur-sgn lst-sgn))) into count-sgn count cur-amb into count-amb finally (return (values count-sgn (if (not (zerop count-amb)) count-amb)))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_scount-sturm (p l r &optional sturm-sequence) "Compute the difference in the sign changes for $S(x+l)$ and $S(x+h)$ where S is the given Sturm sequence or the canonical one. The return will be the number of distinct real roots the polynomial has in the interval $(l,h]$ when: 1) sturm-sequence is NIL or the canonical Sturm sequence 2) when sturm-sequence is a valid Sturm sequence and $p$ is square-free. A Sturm sequence is a set of polynomials $p_0, p_1, \\dots, p_m\\in\\mathbb{R}[x]$ such that: \\begin{itemize} \\item $p_i$ are all polynomials \\item $m$ is a finite, non-negative integer \\item if $0\\ge i< j\\le m$ then $\\text{deg}(p_i)<\\text{deg}(p_j)$ \\item $p_0$ is square free (no repeated roots) \\item if $p(x_0)=0$, then $\\text{sign}(p_1(x_0))= \\text{sign}(p'(x_0))$ \\item if $p_i(\\xi)=0$ for $0<i<m$ then $\\text{sign}(p_{i-1}(\\xi))= -\\text{sign}(p_{i+1}(\\xi))$ \\item $p_m$ does not change its sign. \\end{itemize} Sturm's theorem\\\\ Let $p$ be a real, square-free polynomial of degree $n>0$ and $l,r\\in \\mathbb{R}$ with $l<r$. Let $S_\\text{seq}(x)=\\big\\{ p_0(x), p_1(x), ..., p_m(x)\\big\\}$ be a Sturm sequence with $p_0=p$. Let $v_l$ and $v_r$ be the sign variations in the sequences $S_\\text{seq}(l)$ and $S_\\text{seq}(r)$. Let $\\rho$ be the number of the real roots of $p$ in $(l,r]$. Let $v_\\delta=v_l - v_r$. Then we have $\\rho = v_\\delta$ Sturm's Canonical Sequence theorem\\\\ Let $p$ be a real polynomial of degree $n>0$ and $l,r\\in \\mathbb{R}$ with $l<r$ and neither $l$ or $r$ is a multiple root of $p$. Let $S_\\text{seq}(x)=\\big\\{ p_0(x), p_1(x), ..., p_m(x)\\big\\}$ be the canonical Sturm sequence of $p$. Let $v_l$ and $v_r$ be the sign variations in the sequences $S_\\text{seq}(l)$ and $S_\\text{seq}(r)$. Let $\\rho$ be the number of distinct real roots of $p$ in $(l,r]$. Let $v_\\delta=v_l - v_r$. Then we have $\\rho = v_\\delta$ References: Jacques Charles Francois Sturm(1829); Memoire sur la resolution des equations numeriques; Bulletin des Sciences de Ferussac 11; 419-425" ;; MJR TODO NOTE <2013-01-01 19:01:18 CST> mjr_poly_scount-sturm: Add refs (pink and blue polynomial books) (let ((ss (or sturm-sequence (mjr_poly_seq-make-sturm-canonical p)))) (- (mjr_poly_count-sign-changes (mjr_poly_seq-eval ss l)) (mjr_poly_count-sign-changes (mjr_poly_seq-eval ss r))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_scount-budan (p l h) "Compute the difference in the sign changes for $p(x+l)$ and $p(x+h)$ Budan's theorem:\\\\ Let $p\\in\\mathbb{R}[x]$ with degree $n>0$ and $l,r\\in \\mathbb{R}$ with $l<r$ and $p(r)\\ne0$. Let $v_l$ and $v_r$ be the sign variations in $p(x+l)$ and $p(x+r)$ respectively. Let $\\rho$ be the number of the real roots of $p$ in $(l,r)$. Let $v_\\delta=v_l - v_r$. \\begin{enumerate} \\item $v_l \\ge v_r$ \\item $\\rho \\le v_\\delta$ \\item if $\\rho < v_\\delta$, then $\\rho = v_\\delta -2\\lambda$ where $\\lambda \\in \\mathbb{Z}_+$ \\end{enumerate} References: Francois D. Budan (1807); Nouvelle methode pour la resolution des equations numeriques; Paris: Courcier" (if (not (mjr_chk_!=0 (mjr_poly_eval p h))) (warn "budan-count: Polynomial should not be zero on h if Budan's theorem is being used!")) (- (mjr_poly_count-sign-changes (mjr_poly_shift (- l) p)) (mjr_poly_count-sign-changes (mjr_poly_shift (- h) p)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_scount-fourier (p l h) "Compute the difference in the sign changes for $F(x+l)$ and $F(x+h)$ where F is the 'Fourier Sequence' for $p$ Fourier's theorem:\\\\ Let $p$ be a real polynomial of degree $n>0$ and $l,r\\in \\mathbb{R}$ with $l<r$ and $p(r)\\ne0$. Let $F_\\text{seq}(x)$ be the Fourier sequence of $p$. Let $v_l$ and $v_r$ be the sign variations in the sequences $F_\\text{seq}(l)$ and $F_\\text{seq}(r)$. Let $\\rho$ be the number of the real roots of $p$ in $(l,r)$. Let $v_\\delta=v_l - v_r$. \\begin{enumerate} \\item $v_l \\ge v_r$ \\item $\\rho \\le v_\\delta$ \\item if $\\rho < v_\\delta$, then $\\rho = v_\\delta -2\\lambda$ where $\\lambda \\in \\mathbb{Z}_+$ \\end{enumerate} References: Jean Baptiste Joseph Fourier (1820); Sur l'usage du theoreme de Descartes dans la recherche des limites des racines; Bulletin des Sciences, par la Societe Philomatique de Paris: 156-165 E.J. Barbeau (2003); Polynomials (Problem Books in Mathematics); pp 174 Victor V. Prasolov (2004); Polynomials; ISBN: 3540407146; pp 27" (if (not (mjr_chk_!=0 (mjr_poly_eval p h))) (warn "fourier-count: Polynomial should not be zero on h if Budan's theorem is being used!")) (let ((d (mjr_poly_degree p))) (- (mjr_poly_count-sign-changes (multiple-value-list (mjr_poly_eval-poly-and-first-n-derivatives p l d))) (mjr_poly_count-sign-changes (multiple-value-list (mjr_poly_eval-poly-and-first-n-derivatives p h d)))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_scount-descartes (poly &optional (c 0)) "Apply Descartes rule of signs to the shifted polynomial. Four values returned: * Max number roots ($P$) to the right of $C$ -- Actual number will be $P-2\\cdot m$ where $m$ is a non-negative integer. * Exact number of roots ($Z$) at $C$ -- Computed from a direct analysis of the polynomial. * Max number of roots ($N$) to the left of $C$ -- Actual number will be $N-2\\cdot n$ where $n$ is a non-negative integer. * Number of ambiguous zeros, or nil -- This occurs when a value is assumed zero because it was small, but not zero Theorem (Descartes): Let $$p(x)=\\sum\\limits_{j=0}^n a_jx^j\\in\\mathbb{R}[x]$$ Let $P=\\sigma(p)$ and $N=\\sigma(p(-x))$ where the $\\sigma$ function is defined as the number of sign changes in the polynomial coefficients ignoring zero coefficients. Let $Z$ be the number of trailing zeros -- i.e. number of zero coefficients at the end of the polynomial. Then the polynomial $p$ has $P-2m$ positive roots, $Z$ zero roots, and $N-2n$ negative roots where $m$ and $n$ non-negative integers. References: Rene Descartes (1637); La Geometrie (an appendix to Discours de la methode -- Discourse on Method) Michael Mahoney (1979); Geometry (a translation of La Geometrie) Grabiner (1999); Descartes Rule of Signs: Another Construction; Amer. Math. Monthly 106, 854-855 Victor V. Prasolov (2004); Polynomials; ISBN: 3540407146; pp 28" (let* ((poly (if (zerop c) (mjr_poly_simplify poly) (mjr_poly_shift c poly))) (plen (length poly))) (cond ((< plen 2) (error "mjr_poly_scount-descartes: Polynomial must be at least degree 1!"))) (loop for cur-coef across poly for odd-pow = (not (oddp plen)) then (not odd-pow) for count=0 = 0 then (if (mjr_cmp_=0 cur-coef) (1+ count=0) 0) for lst-sign = nil then (if (zerop cur-sign) lst-sign cur-sign) for lst-sign-x = nil then (if (zerop cur-sign-x) lst-sign-x cur-sign-x) for (cur-sign cur-ambiguous) = (multiple-value-list (mjr_cmp_signum cur-coef)) for cur-sign-x = (if odd-pow (- cur-sign) cur-sign) count (and lst-sign (not (zerop cur-sign)) (not (= cur-sign lst-sign))) into count+x count (and lst-sign-x (not (zerop cur-sign-x)) (not (= cur-sign-x lst-sign-x))) into count-x count cur-ambiguous into count-ambiguous-zeros finally (return (values count+x count=0 count-x (if (not (zerop count-ambiguous-zeros)) count-ambiguous-zeros)))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_root-bound-positive (poly &key (algorithm :rb-lagrange)) "Return an upper bound (perhaps strict) on the positive real roots of POLY. Returns NIL if anything goes wrong." (let* ((poly (mjr_poly_simplify poly)) ;; MJR TODO NOTE <2013-01-01 18:59:12 CST> mjr_poly_root-bound-positive: Add references, formula, and notes that it is also a global bound... ;; MJR TODO NOTE <2013-01-01 18:59:47 CST> mjr_poly_root-bound-positive: Move into mjr_poly_root-bound-all???? (pdeg (mjr_poly_degree poly)) (pn (aref poly 0))) (if (mjr_chk_!=0 pn) (case algorithm (:rb-lagrange (and (> pdeg 0) (loop with max1 = nil with max2 = nil for j from 0 upto (1- pdeg) for pjr = (/ (aref poly (- pdeg j)) pn) when (< pjr 0) do (let ((pjv (expt (abs pjr) (/ (- pdeg j))))) (if (null max1) (setf max1 pjv) (if (> pjv max1) (rotatef max2 max1 max1 pjv) (if (or (null max2) (> pjv max2)) (setf max2 pjv))))) finally (return (and max1 max2 (+ max1 max2)))))) (otherwise (error "mjr_poly_root-bound-positive: Unknown algorithm!")))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_root-bound-all (poly &key (algorithm :rb-fujiwara)) "Return an upper bound (perhaps strict) on the modulus of the roots of POLY using the given algorithm If the test can not be performed because the polynomial violates a constraint of the algorithm, then NIL is returned. Note: $$P(z)=\\sum\\limits_{i=0}^n a_ix^i$$ The algorithm argument may be one of, or a list of, the following symbols: * :rb-fujiwara - 8.1.11 - Fujiwara (1916) - $$2\\max_{0\\le j\\le n-1}\\left|\\frac{a_j}{a_n}\\right|$$ * :rb-cauchy - 8.1.9 - Cauchy (1829, p122) - $$1+\\max_{0\\le j\\le n-1}\\left|\\frac{a_j}{a_n}\\right|$$ - M,M,R (1994, p224) - $$1+\\frac{1}{\\vert a_n\\vert}\\left(\\max\\limits_{ 0\\leq i\\leq n-1}\\vert a_i\\vert\\right)$$ * :rb-kojima - 8.1.17 - Kojima (1917) - $$\\max\\left\\{ \\left|\\frac{a_0}{a_1}\\right|, 2\\left|\\frac{a_1}{a_2}\\right|, \\cdots, 2\\left|\\frac{a_{n-1}}{a_n}\\right| \\right\\}$$ * :rb-hirst-macey - N/A - Hirst,Macey (1997) - $$ ? $$ * :rb-lagrange - N/A - Lagrange (????) - $$ ? $$ Not yet supported, but will be in a future version * :rb-carmichal - 8.1.12 - Carmichal (1918) - $$\\sum_{j=0}^{n-1}\\left(\\left|\\frac{a_j}{a_n}\\right|^\\frac{1}{n-j}\\right)$$ * :rb-westerfield - N/A - Westerfield (1931) - $$\\hat{M}+\\check{M}$$ where $\\hat{M}$ and $\\check{M}$ are the two largest elements of $$\\left\\{ \\left|\\frac{a_j}{a_n}\\right|^\\frac{1}{n-j} : j=0,...,{n-1}\\right\\}$$ References: Fujiwara (1916); Uber die obere Schranke des absoluten Betrages der Wurzeln einer algebraischen Gleichung; Tohoku Math J 10; p167-171 Kojima (1917); On the limits of the roots of an algebraic equation; Tohoku Math J 11; p119-127 Cauchy (1829); Exercises de mathematique. Oeuvres 2 (9) Milovanovic, Mitrinovic, Rassias (1994); Topics in polynomials: extremal problems, inequalities, zeros; ISBN: 981020499X Hirst & Macey (1997); Bounding the roots of polynomials; Coll Math J 28 (4); pp292" ;; MJR TODO NOTE <2013-01-01 18:57:44 CST> mjr_poly_root-bound-all: IMPLEMENT :rb-carmichal and :rb-westerfield. ;; MJR TODO NOTE <2013-01-01 18:58:19 CST> mjr_poly_root-bound-all: Add refs for Carmichal and Westerfield. ;; MJR TODO NOTE <2013-01-01 18:58:37 CST> mjr_poly_root-bound-all: Add ref for blue polynomial book and/or blue computer algebra book. (let* ((poly (mjr_poly_simplify poly)) (pdeg (mjr_poly_degree poly)) (pn (aref poly 0))) (if (mjr_chk_!=0 pn) (flet ((cmpbnd (alg) (case alg (:rb-fujiwara (* 2 (max (expt (abs (/ (aref poly pdeg) pn)) (/ pdeg)) (loop for j from 1 upto (1- pdeg) maximize (expt (abs (/ (aref poly (- pdeg j)) pn)) (/ (- pdeg j))))))) (:rb-kojima (if (mjr_chk_!=0 (aref poly (1- pdeg))) (* 2 (max (* 1/2 (abs (/ (aref poly pdeg) (aref poly (1- pdeg))))) (loop for j from 1 upto (1- pdeg) for pj+1 = (aref poly (- pdeg (1+ j))) maximize (if (mjr_chk_!=0 pj+1) (abs (/ (aref poly (- pdeg j)) pj+1)) (return-from cmpbnd nil))))))) (:rb-cauchy (1+ (/ (loop for i from 1 upto pdeg maximize (abs (aref poly i))) (abs pn)))) (:rb-lagrange (mjr_poly_root-bound-positive poly :algorithm :rb-lagrange)) (:rb-hirst-macey (max 1 (loop for j from 0 upto (1- pdeg) for pj = (aref poly (- pdeg j)) maximize (if (mjr_chk_!=0 pj) (abs (/ pj pn)) (return-from cmpbnd nil))))) (otherwise (error "mjr_poly_root-bound-all: Unknown algorithm(~a)!" alg))))) (if (listp algorithm) (mapcar #'cmpbnd algorithm) (cmpbnd algorithm)))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_root-bound-all-cauchy (poly &key (xeps 0.0001) (yeps 0.0001) (max-itr 1000)) "Compute an approximation of the cauchy bound on the roots of the polynomial." (loop with soly = (mjr_poly_zap-zero-roots (mjr_poly_simplify poly)) with coly = (apply #'vector (loop for ai across soly for aai = (- (abs ai)) then (abs ai) collect aai)) with ubnd = (or (mjr_poly_root-bound-positive coly :algorithm :rb-lagrange) (mjr_poly_root-bound-all coly :algorithm :rb-fujiwara)) with x0 = 0 with x1 = ubnd with y0 = (mjr_poly_eval coly x0) with y1 = (mjr_poly_eval coly x1) for x-mid = (/ (+ x0 x1) 2) for y-mid = (mjr_poly_eval coly x-mid) for i-cur from 1 upto max-itr until (or (mjr_eps_= 0 y-mid yeps) (mjr_eps_= x0 x1 xeps) (mjr_eps_= x0 x-mid xeps) (mjr_eps_= x1 x-mid xeps) (mjr_eps_= y0 y1 yeps) (mjr_eps_= y0 y-mid yeps) (mjr_eps_= y1 y-mid yeps)) while (cond ((mjr_cmp_< y0 y1) (if (mjr_cmp_< y-mid 0) (setq x0 x-mid y0 y-mid) (setq x1 x-mid y1 y-mid))) ((mjr_cmp_> y0 y1) (if (mjr_cmp_< y-mid 0) (setq x1 x-mid y1 y-mid) (setq x0 x-mid y0 y-mid)))) finally (return x1))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_root-count-distinct-interval (p a b &optional eps) "Use mjr_poly_scount-sturm to compute the total number of distinct, real roots of the polynomial in $(a,b)$ If polynomial is zero at a or b, then those roots will be removed via deflation. If floating point comparisons are required to determine zeros at a and/or b, then eps will be used. Polynomial rationalization via mjr_poly_2primitive is recommended if floating point round-off is a problem." (if (mjr_chk_!=0 (mjr_poly_eval p a) eps) (if (mjr_chk_!=0 (mjr_poly_eval p b) eps) (mjr_poly_scount-sturm p a b) (mjr_poly_root-count-distinct-interval (mjr_poly_deflate p b) a b eps)) (mjr_poly_root-count-distinct-interval (mjr_poly_deflate p a) a b eps))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_root-count-distinct-negative-zero-positive (p &optional eps) "Use mjr_poly_scount-sturm to compute the total number of distinct, real roots of the polynomial in $(a,b)$ mjr_poly_zap-zero-roots and EPS are used to count zero roots (mjr_poly_2primitive is recommended)." (multiple-value-bind (poly nzr) (mjr_poly_zap-zero-roots p eps) (let ((u (ceiling (mjr_poly_root-bound-all poly))) (ss (mjr_poly_seq-make-sturm-canonical poly))) (values (mjr_poly_scount-sturm p (- -1 u) 0 ss) nzr (mjr_poly_scount-sturm p 0 (+ 1 u) ss))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_root-count-distinct-real (p) "Use mjr_poly_scount-sturm and mjr_poly_root-bound-all to compute the total number of distinct, real roots of the polynomial." (let ((u (ceiling (mjr_poly_root-bound-all p)))) (mjr_poly_scount-sturm p (- -1 u) (+ 1 u)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_root-structure (poly &optional use-sturm-sequence) "Return a list of vectors with each vector containing possible counts for negative, zero, positive, and complex roots for POLY." (let* ((poly (mjr_poly_simplify poly)) (num-roots (1- (length poly)))) (multiple-value-bind (max-pos-roots num-zero-roots max-neg-roots) (mjr_poly_scount-descartes poly) (multiple-value-bind (min-neg-roots num-zero-roots-s min-pos-roots) (if use-sturm-sequence (mjr_poly_root-count-distinct-negative-zero-positive poly) (values 0 nil 0)) (if (and num-zero-roots-s (not (= num-zero-roots-s num-zero-roots))) (error "mjr_poly_root-count-distinct-negative-zero-positive: Inconsistent zero root counts!")) ;;(format 't "~10d ~10d ~10d~%" max-pos-roots num-zero-roots max-neg-roots) ;;(format 't "~10d ~10d ~10d~%" min-pos-roots num-zero-roots-s min-neg-roots) (loop for num-not0-roots from (- num-roots num-zero-roots) downto (+ min-pos-roots min-neg-roots) by 2 append (loop for num-neg-roots from max-neg-roots downto min-neg-roots by 2 append (loop for num-pos-roots from max-pos-roots downto min-pos-roots by 2 for num-cmplx-roots = (- num-roots num-not0-roots num-zero-roots) when (and (<= 0 num-cmplx-roots) (= num-not0-roots (+ num-pos-roots num-neg-roots))) collect (vector num-neg-roots num-zero-roots num-pos-roots (- num-roots num-not0-roots num-zero-roots))))))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_root-structure-print (rstruct) "Print out all the list returned from mjr_poly_root-structure in a nice humanly readable table." (format 't " Negative Zero Positive Complex~%") (loop for cnts in rstruct do (format 't "~10d ~10d ~10d ~10d~%" (aref cnts 0) (aref cnts 1) (aref cnts 2) (aref cnts 3)) finally (return rstruct))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_root-solve-rational (poly &key only-integer-roots) "Find rational roots of a polynomial. Morally speaking this only works on a polynomials with integer coefficients; however, this function uses MJR_POLY_2PRIMITIVE to transform POLY into one with integer coefficients if required. Returns: * A list of found roots * The polynomial actually solved (we call this IPOLY) -- the first return of MJR_POLY_2PRIMITIVE on POLY * The logical factor required to transform POLY into IPOLY -- the second return of MJR_POLY_2PRIMITIVE on POLY * the result of deflating IPOLY with each root found" (cond ((not (vectorp poly)) (error "mjr_poly_root-solve-rational: POLY must be a vector")) ((not (every #'realp poly)) (error "mjr_poly_root-solve-rational: POLY must have real coefficients."))) (multiple-value-bind (ipoly ipolyf) (mjr_poly_2primitive poly) (let ((plen (length poly))) (if (zerop (aref ipoly (1- plen))) ;; Here we take care of the case with zero constant coefficient.... (let ((last-zero-idx (loop for i from (1- plen) downto 0 until (not (zerop (aref ipoly i))) minimize i))) (if (zerop last-zero-idx) (error "mjr_poly_root-solve-rational: POLY is zero -- infinitely many roots!!!") (multiple-value-bind (roots ipoly-throw-away ipolyf-throw-away wpoly) (mjr_poly_root-solve-rational (subseq ipoly 0 last-zero-idx)) (declare (ignore ipoly-throw-away ipolyf-throw-away)) ;; Just keep compiler from squawking (values (sort (append (make-list (- plen last-zero-idx) :initial-element 0) roots) #'<) ipoly ;; The original -- not ipoly-throw-away.. ipolyf;; The original -- not ipolyf-throw-away.. wpoly)))) ;; constant coefficient not zero. (let* ((wpoly (copy-seq ipoly)) (first-coef (abs (aref ipoly 0))) (last-coef (abs (aref ipoly (1- plen)))) (first-factors (mjr_prime_all-factors first-coef)) (last-factors (mjr_prime_all-factors last-coef)) (proot-candidates (remove-duplicates (loop for first-factor in first-factors append (loop for last-factor in last-factors for c = (/ last-factor first-factor) when (or (not only-integer-roots) (integerp c)) collect c)))) (root-candidates (sort (append (mapcar #'- proot-candidates) proot-candidates) #'<))) (values (loop for x in root-candidates until (> 2 (length wpoly)) append (loop until (not (multiple-value-bind (dfpoly pval) (mjr_poly_deflate wpoly x) (and (= 0 pval) (setq wpoly dfpoly)))) collect x)) ipoly ipolyf wpoly)))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_root-solve-integer (poly) "Find integer roots of a polynomial. Morally speaking this only works on a polynomials with integer coefficients; however, this function uses MJR_POLY_2PRIMITIVE to transform POLY into one with integer coefficients if required. Returns: * A list of found roots * The polynomial actually solved (we call this IPOLY) -- the first return of MJR_POLY_2PRIMITIVE on POLY * The logical factor required to transform POLY into IPOLY -- the second return of MJR_POLY_2PRIMITIVE on POLY * the result of deflating IPOLY with each root found" (mjr_poly_root-solve-rational poly :only-integer-roots 't)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_root-search-bsect (poly x0 x1 &rest kw-args &key xeps yeps max-itr show-progress) "Use bsect's method to find a root of POLY between X0 and X2. See the documentation for MJR_NLEQ_ROOT-BSECT" (and xeps yeps max-itr show-progress) (flet ((fp (x) (mjr_poly_eval poly x))) (apply #'mjr_nleq_root-bsect #'fp x0 x1 kw-args))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_root-search-newton (poly x0 &rest kw-args &key xeps yeps max-itr show-progress) "Use newton's method to find a root of POLY near (hopefully anyhow) X0. See the documentation for MJR_NLEQ_ROOT-NEWTON" (and xeps yeps max-itr show-progress) ;; Variables not directly used (flet ((fdf (x) (mjr_poly_eval-poly-and-first-n-derivatives poly x 1))) (apply #'mjr_nleq_root-newton #'fdf x0 kw-args))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_root-search-laguerre (poly x0 &rest kw-args &key xeps yeps max-itr show-progress) "Use laguerre's method to find a root of POLY near (hopefully anyhow) X0. See the documentation for MJR_NLEQ_ROOT-LAGUERRE" (and xeps yeps max-itr show-progress) ;; Variables not directly used (flet ((fdfddf (x) (mjr_poly_eval-poly-and-first-n-derivatives poly x 2))) (apply #'mjr_nleq_root-laguerre #'fdfddf (mjr_poly_degree poly) x0 kw-args))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_root-separate-largest-real (poly &key (xeps 1) max-itr yeps show-progress) "Use the canonical sturm-sequence to find an interval containing the largest real root and no other roots. An open interval $(a,b)$ containing the largest real root (and no other roots) is found. This interval will be no wider than :XEPS, and will contain no roots other than the largest real one. The return of this function will two values corresponding to the left and right endpoints of the interval. In the case of a polynomial with no real roots, then (values nil nil) will be returned. If the polynomial is rational, then the interval endpoints will be as well. When removed from the vulgarities of real world computing, this algorithm is guaranteed to work; however, some things can go wrong with real world implementations. When the inputs are rational, and enough memory is available for the necessary precision, the algorithm will always work unless the :MAX-ITR count is violated (the error is 'Maximum iteration count exceeded!'). When using floating point arithmetic various things can go wrong, but when the error 'Could not find a non-root' occurs a lower :YEPS (the only use of this argument is to detect when the polynomial is zero at prospective new interval endpoints) might help." (let ((d (mjr_poly_degree poly))) (cond ((some #'complexp poly) (error "mjr_poly_root-separate-largest-real: POLY must be a non-complex coefficients!")) ((< d 2) (error "mjr_poly_root-separate-largest-real: POLY must be of at least degree two!"))) (let* ((rb (max 1 (ceiling (mjr_poly_root-bound-all poly)))) (ss (mjr_poly_seq-make-sturm-canonical poly)) (b (* 11/10 rb)) (a (- b)) (va (mjr_poly_count-sign-changes (mjr_poly_seq-eval ss a))) (vb (mjr_poly_count-sign-changes (mjr_poly_seq-eval ss b)))) (loop for itr from 1 for n = (- va vb) do (if show-progress (format 't "~5d ~3d ~40a ~40a ~40a ~%" itr n a "" b)) do (if (and max-itr (> itr max-itr)) (error "mjr_poly_root-separate-largest-real: Maximum iteration count exceeded!")) do (if (> n 0) (loop with delta = (/ (- b a) (* 2 (+ d 1))) for i from 0 upto d for c = (/ (+ a b) 2) then (- c delta) when (mjr_cmp_not-zerop (mjr_poly_eval poly c) yeps) do (return (let ((vc (mjr_poly_count-sign-changes (mjr_poly_seq-eval ss c)))) (if (> (- vc vb) 0) (setq a c va vc) (setq b c vb vc)))) do (if show-progress (format 't "~5d ~3a ~40a ~40a ~40a ~%" "" "" "" c "")) ;; Only show after first try finally (error "mjr_poly_root-separate-largest-real: Could not find a non-root!")) (return-from mjr_poly_root-separate-largest-real (values nil nil))) until (and (= n 1) (< (- b a) xeps))) (values a b)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_root-search-largest-real (poly &rest rest) "Return the largest real root or NIL if the polynomial has no real roots. When successful this function returns the center of the interval found by mjr_poly_root-separate-largest-real. All arguments are passed directly to mjr_poly_root-separate-largest-real, so consult that function for usage information." (multiple-value-bind (a b) (apply #'mjr_poly_root-separate-largest-real poly rest) (if (and a b) (/ (+ a b) 2)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_root-solve-low-degree (poly &optional eps) "Return list of root(s) to the small degree (<=3) polynomial. Multiple roots are listed multiple times. The argument EPS is used to avoid division by zero." (if (<= (mjr_poly_degree poly) 3) (let* ((p3 (mjr_poly_coeff poly 3)) (p2 (mjr_poly_coeff poly 2)) (p1 (mjr_poly_coeff poly 1)) (p0 (mjr_poly_coeff poly 0))) (if (mjr_chk_!=0 p3 eps) (if (every #'realp (list p3 p2 p1 p0)) ;; ............................................................... Cubic(deg=3) (let* ((m (+ (* 2 p2 p2 p2) (* -9 p3 p2 p1) (* 27 p3 p3 p0))) ;; ..................................... Real Poly (n (* 4 (expt (- (* p2 p2) (* 3 p3 p1)) 3))) (r (mjr_numu_sqrt (- (* m m) n))) (p (mjr_numu_cubert (/ (+ m r) 2))) (q (mjr_numu_cubert (/ (- m r) 2))) (i1 (/ (+ 1 (complex 0 (sqrt 3))) 2)) (i2 (/ (- 1 (complex 0 (sqrt 3))) 2))) (list (/ (+ p2 p q) (* -3 p3)) (/ (+ (- p2) (* i1 p) (* i2 q)) (* 3 p3)) (/ (+ (- p2) (* i2 p) (* i1 q)) (* 3 p3)))) (let* ((a (/ p2 p3)) ;; ............................................................................... Complex (b (/ p1 p3)) (c (/ p0 p3)) (q (/ (- (* a a) (* 3 b)) 9)) (r (/ (+ (* 2 a a a) (* -9 a b) (* 27 c)) 54)) (r2 (* r r)) (q3 (expt q 3))) (if (and (not (complexp r)) (not (complexp q)) (< r2 q3)) (let* ((an (acos (/ r (mjr_numu_sqrt q3))))) (list (- (* -2 (mjr_numu_sqrt q) (cos (/ an 3))) (/ a 3)) (- (* -2 (mjr_numu_sqrt q) (cos (/ (+ an (* 2 pi)) 3))) (/ a 3)) (- (* -2 (mjr_numu_sqrt q) (cos (/ (- an (* 2 pi)) 3))) (/ a 3)))) (let* ((ca (if (>= (realpart (* (conjugate r) (mjr_numu_sqrt (- r2 q3)))) 0) (mjr_numu_cubert (- (+ r (mjr_numu_sqrt (- r2 q3))))) (mjr_numu_cubert (- (- r (mjr_numu_sqrt (- r2 q3))))))) (cb (if (mjr_chk_!=0 ca) (/ q ca) 0))) (list (- (+ ca cb) (/ a 3)) (+ (- (* -1/2 (+ ca cb)) (/ a 3)) (* #C(0 1) (/ (sqrt 3) 2) (- ca cb))) (- (- (* -1/2 (+ ca cb)) (/ a 3)) (* #C(0 1) (/ (sqrt 3) 2) (- ca cb)))))))) (if (mjr_chk_!=0 p2 eps) (let* ((dsr (mjr_numu_sqrt (- (* p1 p1) (* 4 p2 p0)))) ;; ........................................... Quadratic(deg=2) (tmp (/ (mjr_cmp_abs-max (+ p1 dsr) (- p1 dsr)) -2))) (if (mjr_chk_!=0 tmp eps) (list (/ tmp p2) (/ p0 tmp)) (list 0 0))) (if (mjr_chk_!=0 p1 eps) (list (/ (- p0) p1)) ;; ......................................................................... Linear(deg=1) (if (mjr_chk_!=0 p0 eps) nil (error "mjr_poly_root-solve-low-degree: Infinitely many solutions!")))))) (error "mjr_poly_root-solve-low-degree: Polynomial order is greater than 3!"))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_make-lagrange (points 1point &optional (pval 1)) "Return the unique polynomial that is PVAL (default 1) on the 1point'th element (zero indexed) of POINTS, and zero all the other elements of POINTS" (let ((poly 1) (divs 1) (1p (elt points 1point))) (if (vectorp points) (loop for i from 0 for p across points when (not (= i 1point)) do (setq poly (mjr_poly_* poly (vector 1 (- p))) divs (* divs (- 1p p)))) (loop for i from 0 for p in points when (not (= i 1point)) do (setq poly (mjr_poly_* poly (vector 1 (- p))) divs (* divs (- 1p p))))) (mjr_poly_* poly (/ pval divs)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_seq-make-lagrange (points &optional (pval 1)) "Return a list of polynomials such that the i'th one has value PVAL on the i'th element of POINTS and zero on all other elements" (loop for i from 0 upto (1- (length points)) collect (mjr_poly_make-lagrange points i pval))) ;; MJR TODO NOTE <2012-11-12 22:30:11 CST> mjr_poly_seq-make-lagrange: Optimize this function! ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_seq-make-chebyshev (num &optional (kind 1)) "Compute first NUM Chebyshev Polynomials (as a vector of vectors). kind==1 corresponds to Chebyshev Polynomials of the first kind $T_n$. kind==2 corresponds to Chebyshev Polynomials of the second kind $U_n$." (if (= num 1) (make-array 1 :initial-contents '(#(1))) (loop with p = (make-array num) for i from 2 upto (1- num) initially (setf (aref p 0) #(1) (aref p 1) (if (= kind 1) #(1 0) #(2 0))) finally (return p) do (setf (aref p i) (mjr_poly_- (mjr_poly_* 2 #(1 0) (aref p (- i 1))) (aref p (- i 2))))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_make-chebyshev (power &optional (kind 1)) "Compute Chebyshev Polynomial of the given power. kind==1 corresponds to Chebyshev Polynomials of the first kind $T_n$. kind==2 corresponds to Chebyshev Polynomials of the second kind $U_n$." (let* ((p0 #(1)) (p1 (if (= kind 1) #(1 0) #(2 0)))) (case power (0 p0) (1 p1) (otherwise (loop for i from 2 upto (1+ power) for pa = p0 then pb for pb = p1 then pn for pn = (mjr_poly_- (mjr_poly_* 2 #(1 0) pb) pa) when (= power i) do (return pn)))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_make-legendre (n) "Compute the Nth legendre polynomial using $$\\frac{1}{2^n n!}\\cdot\\frac{d^n}{dx^n}(x^2-1)^n$$" (mjr_poly_* (mjr_poly_diff (mjr_poly_iexpt #(1 0 -1) n) n) (/ (* (expt 2 n) (mjr_combe_! n))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_seq-make-legendre (n) "Return a list of the first n legendre polynomials (starting with the 0'th one)" (loop for i from 0 upto n collect (mjr_poly_make-legendre i))) ;; MJR TODO NOTE <2012-11-12 22:40:48 CST> mjr_poly_seq-make-legendre: Optimize this function! ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_make-bernstein (nu n) "The nu'th Bernstein basis polynomial of degree n." (let ((poly (make-array (1+ n) :initial-element 0)) (tmp (mjr_poly_* (mjr_combe_comb n nu) (mjr_poly_iexpt #(-1 1) (- n nu))))) (dotimes (i (length tmp) poly) (setf (aref poly i) (aref tmp i))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_seq-make-bernstein (n &key show-progress) "The Bernstein basis polynomials of degree n (all n of them in a list)." (reverse (loop with xn = (make-array (1+ n) :initial-element 0) initially (setf (aref xn 0) 1) for nu from n downto 0 for c = (mjr_combe_comb n nu) for p1 = (subseq xn 0 (1+ nu)) for p2 = #(1) then (mjr_poly_* #(-1 1) p2) do (if show-progress (format 't "~4d: ~10d ~4d ~80a ~%" nu c (mjr_poly_degree p1) p2)) collect (mjr_poly_* c p1 p2)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_imul (poly n) "Multiply POLY times the integer N. This function is provided for consistency with other packages that implement arithmetic for various rings -- after all integer multiplication is not terribly interesting for polynomials over Z, Q, R, or C." (mjr_poly_* n poly)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_root-solve-search-deflate (poly &key (xeps 1.0d-5) (yeps 1.0d-5) (xepsr 1.0d-10) (yepsr 1.0d-10) (refine-steps 10) (only-refined nil) (yepsp nil) (retry-factor 4) (float-type 0.0d0) (show-warnings nil) (show-progress nil)) "Find floating point approximations for all of the roots of a polynomial. Three values are returned: list of roots found, list of poly values on roots, and the part of the poly that couldn't be solved. _____THIS FUNCTION SHOULD BE CONSIDERED EXPERIMENTAL_____ This function works most of the time, but the roots are generally only accurate to a few decimal points. Retrying the function after failure can lead to success (different random seeds). Lowering the :XEPS and :YEPS can help in initial root location. If :ONLY-REFINED is used, then increasing :RETRY-FACTOR may be required. On LISPs that support it, setting :FLOAT-TYPE to 0.0L0 may increase accuracy and help with convergence problems due to round off errors. As a last resort, the :YEPSP argument may be set to a value larger than :YEPS in cases where numerical instability leads to deflated polynomials that have roots which are not within :YEPS of being a root of the original polynomial but are within :YEPSP of being a root (i.e. the absolute value of the original polynomial at the proposed root is less than :YEPSP). This last option can lead not-quite-roots that are quite far off, but still useful. The algorithm: 0) Set w<-p 1) Use laguerre to find a root xb of w (:xeps & :yeps) 2) Use laguerre to refine xb (:refine-steps, :xepsr, & :xepsr) 3) If refinement leads to a non-root of w and :only-refined is non-NIL, then NEXT 4) If p is real and xb is complex, check to see if re(xb) is a root of p and w. If so xb<-re(xb) 5) If xb is a root of p and w, then we deflate: a) If p is real and xb is complex, divide out xb and conj(xb) and update w b) otherwise just divide out xb 6) Jump to 1) if w is deg 1 or higher and we haven't gone beyond (retry-factor)*deg(poly) tries" (let ((rpoly (every #'realp poly)) (wpoly (copy-seq poly)) (roots nil) (pvals nil) (yepsp (or yepsp yeps)) (trys (* retry-factor (length poly)))) (loop with refined = nil for guess = (mjr_prng_float-co (float -10 float-type) (float 10 float-type)) for itr from 1 upto trys while (< 1 (length wpoly)) do (multiple-value-bind (x-bst w-bst ex-why) (progn (if show-progress (format 't "Root search: ~f~%" guess)) (mjr_poly_root-search-laguerre wpoly guess :yeps yeps :xeps xeps :show-progress show-progress)) (if show-progress (format 't "Root candidate: ~a~%" x-bst)) ;; Refine the root. (setq refined nil) (if refine-steps (multiple-value-bind (x-bst2 p-bst2 ex-why2) (progn (if show-progress (format 't "Root refine:~%")) (mjr_poly_root-search-laguerre poly x-bst :yeps yepsr :xeps xepsr :max-itr refine-steps :show-progress show-progress)) (if show-progress (format 't "Refinement candidate: ~a~%" x-bst2)) (if (mjr_eps_=0 p-bst2 yepsp) (let ((w-bst2 (mjr_poly_eval wpoly x-bst2))) (if (mjr_eps_=0 w-bst2 yeps) (progn (if show-progress (format 't "Refinement success~%")) (setf x-bst x-bst2 w-bst w-bst2 ex-why ex-why2 refined 't)) (if show-warnings (warn "mjr_poly_root-solve-search-deflate: laguerre refinement failed to find new root: ~a" x-bst)))) (if show-warnings (warn "mjr_poly_root-solve-search-deflate: laguerre refinement failed to converge: ~a" x-bst))))) (if (or refined (null only-refined)) (progn ;; Snip off the complex bit if the real bit is a good root (if (and rpoly (complexp x-bst)) (let* ((x-bst2 (realpart x-bst)) (w-bst2 (mjr_poly_eval wpoly x-bst2))) (if (and (mjr_eps_=0 w-bst2 yeps) (mjr_eps_=0 (mjr_poly_eval poly x-bst2) yepsp)) (progn (if show-progress (format 't "Root real-ifyed~%")) (setf x-bst x-bst2 w-bst w-bst2))))) ;; Snip off the fractional bit if this results in a good root (let* ((x-bst2 (complex (round (realpart x-bst)) (round (imagpart x-bst)))) (w-bst2 (mjr_poly_eval wpoly x-bst2))) (if (and (mjr_eps_=0 w-bst2 yeps) (mjr_eps_=0 (mjr_poly_eval poly x-bst2) yepsp)) (progn (if show-progress (format 't "Root int-ifyed~%")) (setf x-bst x-bst2 w-bst w-bst2)))) ;; Check the "roots", and deflate if things look good (if (mjr_eps_=0 w-bst yeps) (let ((p-bst (mjr_poly_eval poly x-bst))) (if (mjr_eps_=0 p-bst yepsp) (let ((wpoly2 (mjr_poly_deflate wpoly x-bst))) (setf roots (cons x-bst roots) pvals (cons p-bst pvals)) (if (and rpoly (complexp x-bst)) (let* ((x-bst-c (conjugate x-bst))) (if (mjr_eps_=0 (mjr_poly_eval wpoly2 x-bst-c) yeps) (setf roots (cons x-bst-c roots) pvals (cons (mjr_poly_eval poly x-bst-c) pvals) wpoly (mjr_poly_truncate wpoly (vector 1 (* -2 (realpart x-bst)) (mjr_numu_abssqr x-bst)))) (progn (if show-warnings (warn "mjr_poly_root-solve-search-deflate: Numerical instability detected: real poly but conjugate not a root!: ~a" x-bst)) (setf wpoly wpoly2)))) (setf wpoly wpoly2))) (if show-warnings (warn "mjr_poly_root-solve-search-deflate: Numerical instability detected: root of deflated poly not a root of original poly!")))) (if show-warnings (warn "mjr_poly_root-solve-search-deflate: laguerre failed to converge: ~a ~a ~a" x-bst w-bst ex-why)))) (if show-warnings (warn "mjr_poly_root-solve-search-deflate: Ignoring unrefined root: ~a" x-bst)))) do (if (and (= itr (truncate trys 2)) show-warnings) (warn "mjr_poly_root-solve-search-deflate: laguerre having difficulty converging")) do (if show-progress (format 't "ROOT: ~a~%" roots))) (values roots pvals wpoly))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_find-integer-factor (poly degree-or-sample-points &key show-progress) "Return an integer polynomial factor of the integer polynomial specified by POLY of the specified size or NIL if none exist. If a factor was found, then a second return value returned is POLY divided by the factor that was found. If degree-or-sample-points is a vector, then the points will be used in Kronecker's method. As the value of the polynomial on each of these points must be factored, the polynomial must not be zero on any of the points in the vector. The size of the factors may be specified as an integer indicating the degree of the desired factors or a vector of sample points to be used by Kronecker's method (in which case the degree of the factors will be one less than the length of the list) References: Victor V. Prasolov (2004); Polynomials; ISBN: 3540407146; pp 49-50" (let* ((degree (if (vectorp degree-or-sample-points) (1- (length degree-or-sample-points)) degree-or-sample-points)) (x-points (if (vectorp degree-or-sample-points) degree-or-sample-points (make-array (1+ degree)))) (y-points (if (vectorp degree-or-sample-points) (map 'vector (lambda (x) (mjr_poly_eval poly x)) x-points) (apply #'vector (loop with npts = 0 ;; find degree+1 points where the poly is not zero for x = 0 then (if (not (plusp x)) (1+ (abs x)) (- x)) for y = (mjr_poly_eval poly x) do (if show-progress (format 't "testing sample point ~d => ~d~%" x y)) when (not (zerop y)) collect (progn (setf (aref x-points npts) x) (incf npts) y) until (= npts (1+ degree))))))) (if show-progress (format 't "Using x sample points: ~a~%" x-points)) (if show-progress (format 't "Using y sample points: ~a~%" y-points)) (mjr_combc_gen-all-cross-product (loop for i from 0 for x across x-points for y across y-points for pf = (mjr_prime_all-factors (abs y)) do (if show-progress (format 't "factor ~d from ~d into ~d factors~%" y x (length pf))) collect (concatenate 'vector pf (if (not (zerop i)) (mapcar #'- pf)))) :func (lambda (y-vals) (let ((p (mjr_intrp_poly x-points y-vals))) (if (and (= (1+ degree) (length p)) (every #'integerp p)) (let ((quo (mjr_poly_divides? p poly :require-integer-quotient 't))) (if quo (return-from mjr_poly_find-integer-factor (values p quo)))))))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_factor-over-integers (poly &key show-progress) "Return a list of integer polynomial factors of the integer polynomial specified by POLY. Algorithm: 1) The polynomial is transformed into a primitive, integer polynomial if required (see: MJR_POLY_2PRIMITIVE) The multiplicative factor required for this transformation is included in the returned factor list as a constant polynomial NOTE: This will rationalize the polynomial if it contains floating point coefficients (real or complex) 2) All linear factors are found and removed 3) Kronecker's method is applied to the remainder NOTE: Kronecker's method can be quite slow when the polynomial sample values are large integers with many factors. References: Victor V. Prasolov (2004); Polynomials; ISBN: 3540407146; pp 49-50 Joel S. Cohen (2003); Computer Algebra and Symbolic Computation: Mathematical Methods; ISBN: 1568811594; pp362-367" (multiple-value-bind (int-roots ipoly ipolyf pleft) (mjr_poly_root-solve-rational poly) (declare (ignore ipoly)) (setq pleft (mjr_poly_* (/ (reduce #'* (mapcar #'denominator int-roots))) pleft)) (loop with factors = (append (mapcar (lambda (r) (vector (denominator r) (- (numerator r)))) int-roots) (if (not (= 1 ipolyf)) (list (vector (/ ipolyf))))) for degree = 2 then (if gotfac 2 (1+ degree)) for gotfac = nil for sample-points = (mjr_vvec_to-list (list :vvec-type :vvt-aseq :start (floor (- (truncate degree 2))) :step 1 :len (+ degree 1))) for pleftlen = (length pleft) finally (return (append factors (if (or (< 1 pleftlen) (not (= (aref pleft 0) 1))) (list pleft)))) do (if show-progress (format 't "factoring(~d) ~a~%" degree pleft)) do (if show-progress (format 't "factors so far ~a ~%" factors)) while (and (<= degree (floor (/ pleftlen 2))) (< 1 (length pleft)) (or (< 1 pleftlen) (not (= (aref pleft 0) 1)))) do (mjr_combc_gen-all-cross-product (loop for i from 0 for x in sample-points for y = (mjr_poly_eval pleft x) for pf = (mjr_prime_all-factors (abs y)) do (if show-progress (format 't "factor ~d from ~d into ~d factors~%" y x (length pf))) collect (concatenate 'vector pf (if (not (zerop i)) (mapcar #'- pf)))) :func (lambda (y-vals) (mjr_intrp_poly sample-points y-vals)) :exit-if (lambda (p) (if (and (= (1+ degree) (length p)) (every #'integerp p)) (loop for quo = (mjr_poly_divides? p pleft :require-integer-quotient 't) for j from 1 finally (return gotfac) while quo do (progn (push p factors) (setq pleft quo) (setq gotfac 't))))))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_gcd-primitive (poly1 poly2) "Return primitive GCD of poly1 and poly2. See: MJR_POLY_GCD" (mjr_poly_2primitive (mjr_poly_gcd poly1 poly2))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_test-property (poly &rest pp-list) "Return non-nil if the given polynomial has all of the specified polynomial properties. This is not a fast function, but it sure is handy. A few property tests exist as separate functions because of performance. Symbol Description elt_comp :PP-PRIMITIVE Integer, primitive polynomial exact :PP-SQUARE-FREE No double factors fizzy :PP-IRREDUCIBLE No factors exact :PP-MONIC Leading coefficient is 1 fizzy :PP-NUMBER All elements are numbers N/A :PP-REAL All elements are real N/A :PP-INTEGER All elements are integers N/A :PP-RATIONAL All elements are rational N/A :PP-COMPLEX All elements are complex N/A :PP-POSITIVE All elements numeric and positive cmpzy :PP-EVEN The polynomial is an even function cmpzy :PP-ODD The polynomial is an odd function cmpzy :PP-ZERO The zero polynomial cmpzy :PP-IDENTITY The constant 1 polynomial cmpzy :PP-CONSTANT A constant polynomial cmpzy" (let ((poly (mjr_poly_simplify poly)) (deg (mjr_poly_degree poly))) (if (cdr pp-list) (every (lambda (pp) (mjr_poly_test-property poly pp)) pp-list) (case (car pp-list) (:pp-complex (every #'complexp poly)) (:pp-real (every (lambda (x) (and (numberp x) (not (complexp x)))) poly)) (:pp-rational (every #'rationalp poly)) (:pp-integer (every #'integerp poly)) (:pp-number (every #'numberp poly)) (:pp-positive (every #'plusp poly)) (:pp-monic (mjr_cmp_= (mjr_poly_leading-coeff poly) 1)) (:pp-odd (and (oddp deg) (loop for c across poly for i from 0 upto deg finally (return 't) when (and (oddp i) (mjr_cmp_!=0 c)) do (return nil)))) (:pp-even (and (evenp deg) (loop for c across poly for i from 0 upto deg finally (return 't) do (format 't "~a~%" c) when (and (oddp i) (mjr_cmp_!=0 c)) do (return nil)))) (:pp-irreducible (if (< deg 2) 't (if (or (not (mjr_poly_test-property poly :pp-rational)) (mjr_poly_test-property poly :pp-complex)) nil (error "mjr_poly_test-property: Irreducibly tests not implemented for integer or rational polynomials yet!")))) (:pp-primitive (and (mjr_poly_test-property poly :pp-integer) (= 1 (reduce #'gcd poly)))) (:pp-square-free (mjr_poly_test-property (mjr_poly_gcd (mjr_poly_diff poly) poly) :pp-identity)) (:pp-zero (mjr_eps_= #(0) poly)) (:pp-identity (mjr_eps_= #(1) poly)) (:pp-constant (= 0 deg)) (otherwise (error "mjr_poly_test-property: Unknown property")))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_seq-make-hermite (num) "Compute first NUM Hermite Polynomials (as a vector of vectors)." (loop with p = (make-array num) for i from 2 upto (1- num) initially (progn (setf (aref p 0) #(1)) (if (> num 1) (setf (aref p 1) #(1 0)))) finally (return p) do (setf (aref p i) (mjr_poly_- (mjr_poly_* #(1 0) (aref p (- i 1))) (mjr_poly_diff (aref p (- i 1))))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_make-hermite (power) "Compute the Hermite Polynomial of the given power." (let* ((p0 #(1)) (p1 #(1 0))) (case power (0 p0) (1 p1) (otherwise (loop for i from 2 upto (1+ power) for pa = p0 then pb for pb = p1 then pn for pn = (mjr_poly_- (mjr_poly_* #(1 0) pb) (mjr_poly_diff pb)) when (= power i) do (return pn)))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_make-laguerre (power) "Compute the Laguerre Polynomial of the given power." (let* ((p0 #(1)) (p1 #(-1 1))) (case power (0 p0) (1 p1) (otherwise (loop for i from 2 upto (1+ power) for pa = p0 then pb for pb = p1 then pn for pn = (mjr_poly_* (/ i) (mjr_poly_- (mjr_poly_* (mjr_poly_+ (* 2 (1- i)) #(-1 1)) pb) (mjr_poly_* (1- i) pa))) when (= power i) do (return pn)))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_seq-make-laguerre (num) "Compute first NUM Hermite Polynomials (as a vector of vectors)." (loop with p = (make-array num) for i from 2 upto (1- num) initially (progn (setf (aref p 0) #(1)) (if (> num 1) (setf (aref p 1) #(-1 1)))) finally (return p) do (setf (aref p i) (mjr_poly_* (/ i) (mjr_poly_- (mjr_poly_* (mjr_poly_+ (* 2 (1- i)) #(-1 1)) (aref p (1- i))) (mjr_poly_* (1- i) (aref p (- i 2)))))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_cubic-depress (poly) "Return the depressed form of the given cubic polynomial. If $p(x)=ax^3+bx^2+cx+d$, then divide $p$ by $a$ and substitute $t=\frac{b}{-3a}$." (let* ((cpoly (mjr_poly_simplify poly)) (deg (1- (length cpoly)))) (if (= 3 deg) (let* ((a (aref cpoly 0)) (a2 (* a a)) (b (aref cpoly 1)) (b2 (* b b)) (c (aref cpoly 2)) (d (aref cpoly 3))) (vector 1 0 (/ (- (* 3 a c) b2) (* 3 a2)) (/ (+ (* 2 b2 b) (* -9 a b c) (* 27 a2 d)) (* 27 a2 a)))) (error "mjr_poly_cubic-depress: Polynomial must be a cubic!")))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_tschirnhaus-3-2 (poly) "Tschirnhaus transformation (wipe out the power 2 term of a degree 3 polynomial) If $p(x)=ax^3+bx^2+cx+d$, then substitute $t=\frac{b}{3a}$." (mjr_poly_simplify (mjr_poly_subst (vector 1 (/ (mjr_poly_coeff poly 2) (* -3 (mjr_poly_coeff poly 3)))) poly))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_discriminant-low-degree (poly) "Return discriminant of a non-linear, small degree (<=5) polynomial via a direct formula" ;; Maxima Code to compute discriminant ;; degree(f,x) := hipow(f,x)$ ;; discriminant(f,x) := block([n:degree(f,x),fp,d,an], ;; fp : diff(f,x), ;; an : coeff(f,x,n), ;; w : mod(n,4), ;; w : w*(w-1)/2, ;; d : (-1)^w/an, ;; d : d*resultant(f,fp,x) ;; )$ (let* ((cpoly (mjr_poly_simplify poly)) (deg (1- (length poly))) (f (mjr_poly_coeff cpoly 5)) (e (mjr_poly_coeff cpoly 4)) (d (mjr_poly_coeff cpoly 3)) (c (mjr_poly_coeff cpoly 2)) (b (mjr_poly_coeff cpoly 1)) (a (mjr_poly_coeff cpoly 0))) (case deg (5 (let* ((a2 (* a a)) (a3 (* a2 a)) (b2 (* b b)) (b3 (* b2 b)) (b4 (* b3 b)) (c2 (* c c)) (c3 (* c2 c)) (c4 (* c3 c)) (d2 (* d d)) (d3 (* d2 d)) (d4 (* d3 d)) (e2 (* e e)) (e3 (* e2 e)) (e4 (* e3 e)) (f2 (* f f)) (f3 (* f2 f))) ;; 3125*a^4*f^4-2500*a^3*b*e*f^3-3750*a^3*c*d*f^3+2000*a^2*b^2*d*f^3+2250*a^2*b*c^2*f^3-1600*a*b^3*c*f^3+256*b^5* ;; f^3+2000*a^3*c*e^2*f^2-50*a^2*b^2*e^2*f^2+2250*a^3*d^2*e*f^2-2050*a^2*b*c*d*e*f^2+160*a*b^3*d*e*f^2-900*a^2*c^3* ;; e*f^2+1020*a*b^2*c^2*e*f^2-192*b^4*c*e*f^2-900*a^2*b*d^3*f^2+825*a^2*c^2*d^2*f^2+560*a*b^2*c*d^2*f^2-128*b^4*d^2* ;; f^2-630*a*b*c^3*d*f^2+144*b^3*c^2*d*f^2+108*a*c^5*f^2-27*b^2*c^4*f^2-1600*a^3*d*e^3*f+160*a^2*b*c*e^3*f-36*a*b^3* ;; e^3*f+1020*a^2*b*d^2*e^2*f+560*a^2*c^2*d*e^2*f-746*a*b^2*c*d*e^2*f+144*b^4*d*e^2*f+24*a*b*c^3*e^2*f-6*b^3*c^2*e^2* ;; f-630*a^2*c*d^3*e*f+24*a*b^2*d^3*e*f+356*a*b*c^2*d^2*e*f-80*b^3*c*d^2*e*f-72*a*c^4*d*e*f+18*b^2*c^3*d*e*f+108*a^2* ;; d^5*f-72*a*b*c*d^4*f+16*b^3*d^4*f+16*a*c^3*d^3*f-4*b^2*c^2*d^3*f+256*a^3*e^5-192*a^2*b*d*e^4-128*a^2*c^2*e^4+144*a* ;; b^2*c*e^4-27*b^4*e^4+144*a^2*c*d^2*e^3-6*a*b^2*d^2*e^3-80*a*b*c^2*d*e^3+18*b^3*c*d*e^3+16*a*c^4*e^3-4*b^2*c^3*e^3- ;; 27*a^2*d^4*e^2+18*a*b*c*d^3*e^2-4*b^3*d^3*e^2-4*a*c^3*d^2*e^2+b^2*c^2*d^2*e^2 (+ (* -3750 c d a3 f3) (* -2500 b e a3 f3) (* -2050 b c d e a2 f2) (* -1600 a c b3 f3) (* -1600 d f a3 e3) (* -900 b a2 d3 f2) (* -900 e a2 c3 f2) (* -746 a c d f b2 e2) (* -630 a b d c3 f2) (* -630 c e f a2 d3) (* -192 b d a2 e4) (* -192 c e b4 f2) (* -128 a2 c2 e4) (* -128 b4 d2 f2) (* -80 a b d c2 e3) (* -80 c e f b3 d2) (* -72 a b c f d4) (* -72 a d e f c4) (* -50 a2 b2 e2 f2) (* -36 a f b3 e3) (* -27 a2 d4 e2) (* -27 b2 c4 f2) (* -27 b4 e4) (* -6 a b2 d2 e3) (* -6 f b3 c2 e2) (* -4 a c3 d2 e2) (* -4 f b2 c2 d3) (* -4 b2 c3 e3) (* -4 b3 d3 e2) (* 16 a f c3 d3) (* 16 a c4 e3) (* 16 f b3 d4) (* 18 a b c d3 e2) (* 18 c d b3 e3) (* 18 d e f b2 c3) (* 24 a b f c3 e2) (* 24 a e f b2 d3) (* 108 a c4 c f2) (* 108 f a2 d4 d) (* 144 a c b2 e4) (* 144 c a2 d2 e3) (* 144 d f b4 e2) (* 144 d b3 c2 f2) (* 160 a d e b3 f2) (* 160 b c f a2 e3) (* 256 a3 e4 e) (* 256 b4 b f3) (* 356 a b e f c2 d2) (* 560 a c b2 d2 f2) (* 560 d f a2 c2 e2) (* 825 a2 c2 d2 f2) (* 1020 a e b2 c2 f2) (* 1020 b f a2 d2 e2) (* 2000 c a3 e2 f2) (* 2000 d a2 b2 f3) (* 2250 b a2 c2 f3) (* 2250 e a3 d2 f2) (* 3125 a3 a f3 f) (* b2 c2 d2 e2)))) (4 (let* ((a2 (* a a)) (b2 (* b b)) (b3 (* b2 b)) (c2 (* c c)) (c3 (* c2 c)) (d2 (* d d)) (d3 (* d2 d)) (e2 (* e e))) ;; 256*a^3*e^3-192*a^2*b*d*e^2-128*a^2*c^2*e^2+144*a*b^2*c*e^2-27*b^4*e^2+144*a^2*c*d^2*e-6*a*b^2*d^2*e-80*a*b*c^2*d*e+ ;; 18*b^3*c*d*e+16*a*c^4*e-4*b^2*c^3*e-27*a^2*d^4+18*a*b*c*d^3-4*b^3*d^3-4*a*c^3*d^2+b^2*c^2*d^2 (+ (* -192 b d a2 e2) (* -128 a2 c2 e2) (* -80 a b d e c2) (* -27 a2 d3 d) (* -27 b3 b e2) (* -6 a e b2 d2) (* -4 a c3 d2) (* -4 e b2 c3) (* -4 b3 d3) (* 16 a e c3 c) (* 18 a b c d3) (* 18 c d e b3) (* 144 a c b2 e2) (* 144 c e a2 d2) (* 256 a2 a e2 e) (* b2 c2 d2)))) (3 (let* ((b2 (* b b)) (c2 (* c c))) ;; -27*a^2*d^2-(4*b^3-18*a*b*c)*d-4*a*c^3+b^2*c^2 (+ (* -27 a a d d) (* -4 a c2 c) (* 18 a b c d) (* -4 b2 b d) (* b2 c2)))) (2 (let ((b2 (* b b))) ;; b^2-4*a*c (- b2 (* 4 a c)))) (otherwise (error "mjr_poly_discriminant-low-degree: Only polynomials of degree 2, 3, 4, and 5 are supported!"))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_resultant (poly1 poly2) "Return resultant the two polynomials via a recursive GCD-like computation." (labels ((resultant (poly1 poly2) (let ((deg1 (mjr_poly_degree poly1)) (deg2 (mjr_poly_degree poly2))) (if (> deg1 deg2) (mjr_poly_* (if (evenp (* deg1 deg2)) 1 -1) (mjr_poly_resultant poly2 poly1)) (let ((lc (mjr_poly_leading-coeff poly1))) (if (zerop deg1) (vector (expt lc deg2)) (let ((r (mjr_poly_rem poly2 poly1))) (if (mjr_poly_zerop r) (vector 0) (mjr_poly_* (expt lc (- deg2 (mjr_poly_degree r))) (mjr_poly_resultant poly1 r)))))))))) (mjr_poly_leading-coeff (resultant poly1 poly2)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_discriminant-high-degree (poly) "Return discriminant of a non-linear polynomial via a recursive resultant computation." (let ((pdeg (mjr_poly_degree poly))) (* (if (evenp (/ (* pdeg (1- pdeg)) 2)) 1 -1) (/ (mjr_poly_leading-coeff poly)) (mjr_poly_resultant poly (mjr_poly_diff poly))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_discriminant (poly) "Return discriminant of a non-linear polynomial using the most efficient method available." (if (> (mjr_poly_degree poly) 4) (mjr_poly_discriminant-high-degree poly) (mjr_poly_discriminant-low-degree poly))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_factor-square-free (poly) "Return the square-free factorization of POLY as an assoc array with (poly . power). Any factors equal to $1$ are not in the returned list. If the input polynomial is $p\\in\\mathbb{Q}[x]$, then a square-free factorization is $$p=c\\prod_{j=1}^nu_j^j$$ Where $u_j\\in\\mathbb{Q}[x]$, $u^j \\vert p$, and $u^{(j+1)} \\nmid p$. References: Antonio Machi (2012); Algebra for Symbolic Computation; ISBN: 978-88-470-2396-3; pp 108-109" ;; MJR TODO NOTE mjr_poly_factor-square-free: Add reference to Wikipedia and Cohen. ;; MJR TODO NOTE mjr_poly_factor-square-free: Replace with Yun's algorithm, use this for regression tests. See: http://en.wikipedia.org/wiki/Square-free_polynomial#Yun.27s_algorithm ;; MJR TODO NOTE mjr_poly_factor-square-free: Implement finite field version of this for polygfp. (loop with d = (mjr_poly_gcd poly (mjr_poly_diff poly)) with v = (mjr_poly_truncate poly d) with w = (mjr_poly_diff v) with z = (mjr_poly_truncate (mjr_poly_diff poly) d) for j from 1 upto (mjr_poly_degree poly) for uj = (mjr_poly_gcd v (mjr_poly_- z (mjr_poly_* j w))) when (not (mjr_poly_onep uj)) collect (cons uj j))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_factor-irreducible (poly &key show-progress) "Return the irreducible factorization of POLY as an assoc array with (poly . power). VERY SLOW. Uses kronecker's method." ;; MJR TODO NOTE mjr_poly_factor-irreducible: Implement a modern method, and use this for regression tests. (loop with poly-left = poly with d = 1 with pdeg = (mjr_poly_degree poly) for (f pl) = (multiple-value-list (mjr_poly_find-integer-factor poly-left d)) if f collect (let ((daPow (1+ (loop initially (setf poly-left pl) for v = (mjr_poly_divides? f poly-left) while v count (setf poly-left v))))) (if show-progress (format 't "left: ~5d deg: ~5d pow: ~5d factor: ~30a~%" (mjr_poly_degree poly-left) d daPow f )) (cons f daPow)) else do (if show-progress (format 't "left: ~5d deg: ~5d pow: 0 factor: DONE~%" (mjr_poly_degree poly-left) d)) and do (incf d) until (mjr_poly_onep poly-left) until (>= d pdeg))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_mahler-measure (poly &optional (method-class :solve) (method-function #'mjr_poly_root-solve-search-deflate) method-args) "Compute the Mahler measure of the polynomial POLY The optional arguments to determine how the computation is preformed: method-class method-function method-args :solve #'mjr_poly_root-solve-search-deflate nil <= DEFAULT :integrate #'mjr_intg_simple-gauss-kronrod '(:order 21) :integrate #'mjr_intg_simple-gauss-kronrod '(:order 31) :integrate #'mjr_intg_simple-gauss-legendre '(:order 20) :integrate #'mjr_intg_glb-adp-composite-romberg '(:the-err 1.0D-5) :integrate #'mjr_intg_glb-adp-composite-trapezoidal '(:the-err 1.0D-5) Definition Let $p\\in\\mathbb{C}[z]$ with $\\mathrm{deg}(p)=d$. For definiteness, we express $p$ like so: $$p(z)=\\sum_{j=0}^d a_jx^j = a_d\\prod_{j=1}^d (z-\\alpha_j)$$ We then define the Mahler measure to be: $$M(p) = \\vert a_d\\vert\\prod_{\\vert\\alpha_j\\vert\\geq1} \\vert\\alpha_j\\vert = \\exp\\left(\\frac{1}{2\\pi}\\int_0^{2\\pi}\\ln(\\vert p(e^{i\\theta})\\vert)\\,\\mathrm{d}\\theta\\right)$$ Examples: * (mahler-measure #(1 1 0 -1 -1 -1 -1 -1 0 1 1) :integrate #'mjr_intg_simple-gauss-kronrod '(:order 21 )) => 1.4751609391661360d0 * (mahler-measure #(1 1 0 -1 -1 -1 -1 -1 0 1 1) :integrate #'mjr_intg_simple-gauss-kronrod '(:order 31 )) => 0.7012142844290665d0 * (mahler-measure #(1 1 0 -1 -1 -1 -1 -1 0 1 1) :integrate #'mjr_intg_simple-gauss-legendre '(:order 20 )) => 1.0601232234056748d0 * (mahler-measure #(1 1 0 -1 -1 -1 -1 -1 0 1 1) :integrate #'mjr_intg_glb-adp-composite-romberg '(:the-err 1.0D-5)) => 1.1762811031170224d0 * (mahler-measure #(1 1 0 -1 -1 -1 -1 -1 0 1 1) :integrate #'mjr_intg_glb-adp-composite-trapezoidal '(:the-err 1.0D-5)) => 1.1762806954644658d0 * (mahler-measure #(1 1 0 -1 -1 -1 -1 -1 0 1 1) :solve #'mjr_poly_root-solve-search-deflate '( )) => 1.1762808182599178d0" (case method-class (:solve (let* ((roots (mapcar (lambda (x) (max 1 (abs x))) (apply method-function poly method-args))) (numr (length roots))) (if (= numr (mjr_poly_degree poly)) (reduce #'* roots) (error "mahler-measure: Could not find all roots. Found ~d" numr)))) (:integrate (exp (/ (apply method-function (lambda (x) (log (abs (mjr_poly_eval poly (complex (cos x) (sin x)))))) :start 0.0D0 :end (* 2.0d0 pi) method-args) (* 2 pi)))) (otherwise (error "mahler-measure: method-class unsupported"))))
15074
;; -*- Mode:Lisp; Syntax:ANSI-Common-LISP; Coding:us-ascii-unix; fill-column:158 -*- ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; ;; @file use-poly.lisp ;; @author <NAME> <https://www.mitchr.me> ;; @brief Polynomials over complex, real, rational, and integers.@EOL ;; @std Common Lisp ;; @see tst-poly.lisp ;; @copyright ;; @parblock ;; Copyright (c) 1994,1997,1998,2004,2008,2012,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 ;; @todo mjr_poly_root-solve-search-deflate: Want generic way to specifiy search, refine, and xform methods.@EOL@EOL ;; @todo Make some kind of convention for the type (int, gausian, float, complex, etc...) of polynomials a function works with.@EOL@EOL ;; @todo Better way to find solutions that are in radical extension fields -- i.e. $a,b,c\in\mathbb{Q}$ but $a+b\sqrt{c}\not\in\mathbb{Q}$.@EOL@EOL ;; @todo Better control/seporation/deliniation of Z[x], Q[x], & R[x] across functions. Make this uniform.@EOL@EOL ;; @todo Update unit tests for new functionality.@EOL@EOL ;; @todo mjr_poly_decompose.@EOL@EOL ;; @todo mjr_poly_factor-irreducible.@EOL@EOL ;; @todo mjr_poly_root-solve-jenkins-traub.@EOL@EOL ;; @todo mjr_poly_root-solve-continued-fraction.@EOL@EOL ;; @todo mjr_poly_root-solve-descartes-bisection.@EOL@EOL ;; @todo mjr_poly_root-separate-real.@EOL@EOL ;; @warning Much of this code has become quite experimental! Use the old version if you want to be carefull.@EOL@EOL ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defpackage :MJR_POLY (:USE :COMMON-LISP :MJR_NLEQ :MJR_NUMU :MJR_CMP :MJR_CHK :MJR_PRIME :MJR_VEC :MJR_PRNG :MJR_COMBE :MJR_INTRP :MJR_COMBC :MJR_VVEC :MJR_GPOLY :MJR_EPS) (:DOCUMENTATION "Brief: Univariate Polynomials over R or C.;") (:EXPORT #:mjr_poly_help ;; Autogenerated from #:mjr_gpoly #:mjr_poly_coeff #:mjr_poly_diff #:mjr_poly_- #:mjr_poly_+ #:mjr_poly_* #:mjr_poly_iexpt #:mjr_poly_scale #:mjr_poly_truncate #:mjr_poly_rem #:mjr_poly_mod #:mjr_poly_divides? #:mjr_poly_gcd #:mjr_poly_degree #:mjr_poly_leading-coeff #:mjr_poly_constant-coeff #:mjr_poly_zerop #:mjr_poly_onep #:mjr_poly_constantp #:mjr_poly_simplify #:mjr_poly_eval #:mjr_poly_subst #:mjr_poly_density #:mjr_poly_index ;; Implemented here.. #:mjr_poly_imul #:mjr_poly_count-sign-changes #:mjr_poly_print #:mjr_poly_code #:mjr_poly_intg #:mjr_poly_gcd-primitive ;; Polynomial metrics #:mjr_poly_height #:mjr_poly_length #:mjr_poly_mahler-measure #:mjr_poly_scount-descartes #:mjr_poly_scount-sturm #:mjr_poly_scount-fourier #:mjr_poly_scount-budan #:mjr_poly_root-structure #:mjr_poly_root-structure-print #:mjr_poly_root-count-distinct-real #:mjr_poly_root-count-distinct-interval #:mjr_poly_root-count-distinct-negative-zero-positive #:mjr_poly_root-bound-all #:mjr_poly_root-bound-positive #:mjr_poly_root-bound-all-cauchy #:mjr_poly_eval-poly-and-first-n-derivatives #:mjr_poly_2func #:mjr_poly_seq-eval #:mjr_poly_root-separate-real #:mjr_poly_root-solve-rational #:mjr_poly_root-solve-search-deflate #:mjr_poly_root-solve-low-degree #:mjr_poly_2square-free #:mjr_poly_2primitive #:mjr_poly_2monic #:mjr_poly_root-search-bsect #:mjr_poly_root-search-newton #:mjr_poly_root-search-laguerre #:mjr_poly_root-search-largest-real #:mjr_poly_root-separate-largest-real #:mjr_poly_make-from-roots ;; Make special polynomials #:mjr_poly_make-lagrange #:mjr_poly_make-chebyshev #:mjr_poly_make-legendre #:mjr_poly_make-bernstein #:mjr_poly_make-hermite #:mjr_poly_make-laguerre ;; Make sequences of polynomials #:mjr_poly_seq-make-lagrange #:mjr_poly_seq-make-chebyshev #:mjr_poly_seq-make-legendre #:mjr_poly_seq-make-bernstein #:mjr_poly_seq-make-hermite #:mjr_poly_seq-make-laguerre #:mjr_poly_seq-make-fourier #:mjr_poly_seq-make-sturm-canonical #:mjr_poly_deflate #:mjr_poly_shift #:mjr_poly_reflect #:mjr_poly_zap-zero-roots ;; EXPERIMENTAL!!!! #:mjr_poly_test-property #:mjr_poly_find-integer-factor #:mjr_poly_factor-over-integers ;; MORE EXPERIMENTAL!!!! #:mjr_poly_cubic-depress #:mjr_poly_tschirnhaus-3-2 #:mjr_poly_resultant #:mjr_poly_discriminant-low-degree #:mjr_poly_discriminant-high-degree #:mjr_poly_discriminant #:mjr_poly_factor-square-free #:mjr_poly_factor-irreducible #:mjr_poly_content #:mjr_poly_primitive-part #:mjr_poly_rationalize )) (in-package :MJR_POLY) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_help () "Univariate, Dense Polynomial Library Polynomials are represented as vectors containing the coefficients -- the position in the array implies the power of the monomial in the term to which the coefficient belongs. For example, x^2+4 would be represented as #(1 0 4). The first coefficient should never be zero unless the polynomial is the zero polynomial. No function in this package should ever produce a non-constant polynomial with a zero in the first position; however, all functions will gladly accept such polynomials and silently fix them. Note that while this vector representation is quite adequate for dense polynomials (i.e. polynomials that have mostly non-zero coefficients), this data structure is inefficient in both space and time for sparse polynomials. This library is a work in progress, but it has enough functionality to be useful. Still, some care should be exercised when using it. Tags: (G) means the function is provided by GPOLY and a (!) means the function is not yet implemented. Function names have been abbreviated in this list by replacing 'mjr_poly_' with 'MP_'. * Strings & Printing ** MP_print MP_code * Evaluation ** MP_eval(G) MP_eval-poly-and-first-n-derivatives MP_seq-eval * Arithmetic ** MP_+(G) MP_-(G) MP_*(G) MP_iexpt(G) MP_rem(G) MP_mod(G) MP_truncate(G) MP_gcd(G) MP_gcd-primitive MP_imul MP_divides?(G) * Coefficient access ** MP_coeff(G) MP_leading-coeff(G) MP_constant-coeff(G) * Recognizing special polynomials ** MP_onep(G) MP_constantp(G) MP_zerop(G) * Polynomial factorization ** MP_decompose(!) MP_factor-square-free MP_factor-irreducible(!) * Things we do with roots: ** MP_root-structure ** Solve polynomial (find all roots): *** MP_root-solve-integer MP_root-solve-rational MP_root-solve-low-degree MP_root-solve-search-deflate *** MP_root-solve-jenkins-traub(!) MP_root-solve-continued-fraction(!) MP_root-solve-descartes-bisection(!) ** Finding roots: *** MP_root-search-bsect MP_root-search-laguerre MP_root-search-newton MP_root-search-largest-real *** MP_root-search-max-magnitude ** Bounding roots: *** MP_root-bound-all MP_root-bound-positive ** Separating roots (a root is 'separated' by finding an interval that contains it but no other roots): *** MP_root-separate-largest-real MP_root-separate-real(!) ** Counting distinct roots *** MP_root-count-distinct-real MP_root-count-distinct-interval MP_root-count-distinct-positive * Construct sequences of polynomials ** MP_seq-make-fourier MP_seq-make-sturm-canonical MP_seq-make-chebyshev MP_seq-make-legendre MP_seq-make-lagrange MP_seq-make-bernstein MP_seq-make-hermite MP_seq-make-laguerre * Construct polynomials ** MP_make-chebyshev MP_make-legendre MP_make-lagrange MP_make-bernstein MP_make-hermite MP_make-laguerre * Polynomial metrics ** Sign change based *** MP_scount-descartes MP_scount-sturm MP_scount-fourier MP_scount-budan ** Other *** MP_height MP_length MP_density(G) MP_index(G) MP_degree(G) MP_discriminant-low-degree MP_discriminant-high-degree MP_discriminant MP_content MP_mahler-measure * Other Stuff ** mjr_poly_resultant * Polynomial xforms ** MP_deflate MP_shift MP_reflect MP_diff(G) MP_intg MP_subst(G) MP_zap-zero-roots MP_2square-free MP_2primitive MP_simplify(G) MP_scale(G) MP_rationalize ** MP_cubic-depress mjr_poly_tschirnhaus-3-2" (documentation 'mjr_poly_help 'function)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (mjr_gpoly_make-coeff "") (mjr_gpoly_make-simplify "") (mjr_gpoly_make-scale "") (mjr_gpoly_make-diff "") (mjr_gpoly_make-eval "") (mjr_gpoly_make-+ "") (mjr_gpoly_make-- "") (mjr_gpoly_make-* "") (mjr_gpoly_make-iexpt "") (mjr_gpoly_make-subst "") (mjr_gpoly_make-leading-coeff "") (mjr_gpoly_make-degree "") (mjr_gpoly_make-density "") (mjr_gpoly_make-index "") (mjr_gpoly_make-constant-coeff "") (mjr_gpoly_make-truncate "") (mjr_gpoly_make-rem "") (mjr_gpoly_make-mod "") (mjr_gpoly_make-onep "") (mjr_gpoly_make-zerop "") (mjr_gpoly_make-constantp "") (mjr_gpoly_make-divides? "") (mjr_gpoly_make-gcd "") ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_print (poly &key (var "x") (add-op "+") (add-apad " ") (add-bpad " ") (expt-op "^") (expt-apad "") (expt-bpad "") (mul-op "*") (mul-apad "") (mul-bpad "") (cof-fmt "~s") (cof-bpad "") (cof-apad "") (pow-fmt "~d") (pow-bpad "") (pow-apad "") (ply-apad "") (ply-bpad "") (suppress-zero-terms 't) (suppress-unit-expt 't) (suppress-unit-prod 't) (suppress-zero-powers 't) (return-string nil)) "Print a polynomial. Return POLY. Arguments: - return-string .......... If non-NIL, then do not print but return a string rep of POLY with no following newline. If NIL, then print POLY with a following newline, and return POLY - var .................... variable to use (a string) - add-op ................. string to print for + signs - add-bpad ............... string to print before + signs - add-apad ............... string to print after + signs - cof-fmt ................ format string for coefficients - cof-bpad ............... string to print before coefficients - cof-apad ............... string to print after coefficients - pow-fmt ................ format string powers - pow-bpad ............... string to print before powers - pow-apad ............... string to print after powers - mul-op ................. string to print for * signs - mul-bpad ............... string to print before * signs - mul-apad ............... string to print after * signs - expt-op ................ string to print for ^ signs - expt-bpad .............. string to print before ^ signs - expt-apad .............. string to print after ^ signs - suppress-zero-terms .... do not print 0*x^n - suppress-unit-expt ..... do not print ^1 - suppress-unit-prod ..... do not print 1* - suppress-zero-powers ... do not print x^0" (let ((da-str (with-output-to-string (str-out) (if (vectorp poly) (let ((plen (length poly))) (if (< 0 plen) (loop with not-first-print = nil for power from (1- plen) downto 0 for term across poly initially (format str-out ply-bpad) finally (format str-out ply-apad) do (if (or (not suppress-zero-terms) (mjr_cmp_!=0 term) (and (= power 0) (not not-first-print))) (progn (if not-first-print (format str-out "~a~a~a" add-bpad add-op add-apad)) (if (or (not suppress-unit-prod) (mjr_cmp_!= 1 term) (zerop power)) (format str-out (concatenate 'string cof-bpad cof-fmt cof-apad) term)) (if (and (or (not suppress-unit-prod) (mjr_cmp_!= 1 term)) (or (not suppress-zero-powers) (not (zerop power)))) (format str-out "~a~a~a" mul-bpad mul-op mul-apad)) (if (or (not suppress-zero-powers) (not (zerop power))) (progn (format str-out "~a" var) (if (or (not suppress-unit-expt) (not (= 1 power))) (progn (format str-out "~a~a~a" expt-bpad expt-op expt-apad) (format str-out (concatenate 'string pow-bpad pow-fmt pow-apad) power))))) (setq not-first-print 't)))))))))) (if return-string (if (vectorp poly) da-str) (progn (if (vectorp poly) (format 't "~a~%" da-str)) poly)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_code (poly &key (lang :lang-matlab)) "Return a string using the syntax of the selected programming language or computational environment." (if (not (vectorp poly)) (error "mjr_poly_code: Argument must be a polynomial (a vector)!")) (with-output-to-string (str-out) (flet ((gpp (&key (var "x") (add-op "+") (add-apad "") (add-bpad "") (expt-op "^") (expt-apad "") (expt-bpad "") (mul-op "*") (mul-apad "") (mul-bpad "") (cof-bpad "") (cof-apad "") (pow-bpad "") (pow-apad "") (ply-apad "") (ply-bpad "")) (loop with plen = (length poly) for not-first-print = nil then 't for power from (1- plen) downto 0 for term across poly initially (format str-out ply-bpad) finally (format str-out ply-apad) when not-first-print do (format str-out "~a~a~a" add-bpad add-op add-apad) do (progn (format str-out "~a~a~a~a" cof-bpad (mjr_numu_code term :lang lang) cof-apad cof-bpad) (if (not (zerop power)) (format str-out "~a~a~a~a~a~a~a~a~a~a" mul-bpad mul-op mul-apad var pow-bpad expt-bpad expt-op expt-apad (mjr_numu_code power :lang lang) pow-apad)))))) (case lang ((:lang-povray :lang-matlab :lang-octave :lang-idl :lang-r :lang-hp48 :lang-mathematica :lang-maple :lang-maxima) (gpp)) ((:lang-latex :lang-pdflatex :lang-amstex :lang-tex) (gpp :ply-bpad "$$" :ply-apad "$$" :mul-op " " :pow-bpad "{" :pow-apad "}")) ((:lang-lisp) (progn (format str-out "(+") (loop for power from (1- (length poly)) downto 0 for term across poly do (if (mjr_cmp_!=0 term) (let ((tstr (if (or (mjr_cmp_!= 1 term) (zerop power)) (format nil " ~a" term))) (vstr (if (not (zerop power)) (if (= 1 power) (format nil " x") (format nil " (expt x ~a)" power))))) (if (and tstr vstr) (format str-out " (*~a~a)" tstr vstr) (format str-out "~a" (or tstr vstr)))))) (format str-out ")"))) ('t (error "mjr_poly_code: Language unsupported!")))) str-out)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_intg (poly a b) "Integrate over the interval $[a,b]$." (let* ((poly (mjr_poly_simplify poly)) (plen (length poly)) (ipoly (make-array (1+ plen) :initial-element 0))) (loop for i from 0 upto (1- plen) do (setf (aref ipoly i) (/ (aref poly i) (- plen i)))) (- (mjr_poly_eval ipoly b) (mjr_poly_eval ipoly a)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_zap-zero-roots (poly &optional eps) "Return two values: 1) a new polynomial, $\\text{POLY}/x^n$, where $n$ is the number of times $0$ is a root of POLY, and 2) $n$. EPS is used with mjr_cmp_!=0 to detect non-zero coefficients." (let* ((plen (length poly)) (zcnt (loop for i from (1- plen) downto 0 for ip = (aref poly i) until (mjr_cmp_!=0 ip eps) count 1)) (slim (- plen zcnt))) (values (if (zerop slim) #(1) (subseq poly 0 slim)) zcnt))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_deflate (poly const) "Return the quotient and the remainder from POLY / (X - CONST). Note: The remainder is equal to POLY(CONST). While the result is equivalent to (MJR_POLY_TRUNCATE POLY (VECTOR 1 (- CONST))), this function is faster." (cond ((not (numberp const)) (error "mjr_poly_eval: CONST must be a number!"))) (let* ((poly (mjr_poly_simplify poly)) (plen (length poly)) (polyval 0) (newpoly (mjr_vec_make-const (max 1 (1- plen))))) (loop for i from 0 upto (1- plen) for ht = (+ (* const polyval) (aref poly i)) do (setq polyval ht) when (not (= i (1- plen))) do (setf (aref newpoly i) ht) finally (return (values newpoly polyval))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_shift (b poly) "Shift POLY right B units (or left if B is negative). References: ;; MJR TODO NOTE <2011-11-23 13:07:23 CST> mjr_poly_shift: Add a reference here. The algorithm is the 'fast taylor shift'. The pink book or sure. Perhaps Prasolov too..." (let ((new-poly (mjr_poly_simplify (copy-seq poly))) (b (- b))) (mjr_poly_simplify (dotimes (i (length new-poly) new-poly) (loop for k from i downto 1 do (incf (aref new-poly k) (* b (aref new-poly (1- k))))))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_reflect (poly) "Reflect POLY across the Y-axis (i.e. subst -x)." (let ((new-poly (mjr_poly_simplify (copy-seq poly)))) (loop for cur-coef across poly for odd-pow = (not (oddp (length poly))) then (not odd-pow) for i from 0 when odd-pow do (setf (aref new-poly i) (- cur-coef)) finally (return (mjr_poly_simplify new-poly))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_make-from-roots (&rest the-roots) "Return the the monic polynomial with the given roots. The roots may be given as individual arguments, or a single list may be provided." (let ((the-roots (if (and (car the-roots) (listp (car the-roots))) (car the-roots) the-roots))) (let* ((n (length the-roots)) (a-lst (make-array (1+ n) :initial-element 0)) (a-nxt (make-array (1+ n) :initial-element 0))) (loop initially (setf (aref a-lst n) (- (car the-roots))) for k from 1 upto (1- n) for zk in (cdr the-roots) do (loop initially (setf (aref a-nxt (- n k)) (- (aref a-lst (- n (1- k))) zk)) for j from 1 upto (1- k) do (setf (aref a-nxt (- n j)) (- (aref a-lst (1+ (- n j))) (* zk (aref a-lst (- n j))))) finally (setf (aref a-nxt n) (* (- zk) (aref a-lst n)))) do (rotatef a-lst a-nxt) finally (progn (setf (aref a-lst 0) 1))) a-lst))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_eval-nth-derivative (poly x &optional (order 1)) "Evaluate polynomial derivative." (mjr_poly_eval (mjr_poly_diff poly order) x)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_eval-poly-and-first-n-derivatives (poly x &optional (order 1)) "Return value of poly and the values of the first ORDER derivatives at x. Algorithm due to Pankiewicz: <NAME> (1968); Algorithm 337: calculation of a polynomial and its derivative values by Horner scheme; Communications of the ACM; Vol 11, Issue 9, pp 633" (let* ((len-1 (1- (length poly))) (odr-1 order) (pd (make-array (1+ order) :initial-element 0))) (loop for i from (1- len-1) downto 0 for nnd = (min odr-1 (- len-1 i)) initially (setf (aref pd 0) (aref poly 0)) do (loop for j from nnd downto 1 do (setf (aref pd j) (+ (* (aref pd j) x) (aref pd (1- j))))) do (setf (aref pd 0) (+ (* (aref pd 0) x) (aref poly (- len-1 i))))) (loop with cnst = 1 for i from 2 upto odr-1 do (setf cnst (* cnst i)) do (setf (aref pd i) (* (aref pd i) cnst))) (values-list (concatenate 'list pd)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_2func (poly &optional num-derivatives) "Return a function that evaluates the POLY and its first NUM-DERIVATIVES." (if (and num-derivatives (> num-derivatives 0)) (eval `(lambda (x) (mjr_poly_eval-poly-and-first-n-derivatives ,poly x ,num-derivatives))) (eval `(lambda (x) (mjr_poly_eval ,poly x))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_seq-eval (seq x &optional result-type) "Evaluate the polynomials in the sequence (list or vector) at $x$, and return the results in a sequence. If result-type is NIL, then the returned type will be the same as the type of seq." (map (or result-type (if (vectorp seq) 'vector 'list)) (lambda (p) (mjr_poly_eval p x)) seq)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_height (poly) "This is the infinity-norm (maximum absolute value of coefficients)" (mjr_vec_norm-infinity poly)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_length (poly) "This is the one-norm (sum of absolute values of coefficients)" (mjr_vec_norm-one poly)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_2square-free (p) "Return a new polynomial with the same roots as poly, but with no multiple roots." (mjr_poly_truncate p (mjr_poly_gcd p (mjr_poly_diff p)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_2monic (poly) "Transform POLY, via multiplication, into a monic polynomial that shares the roots of the original." (mjr_vec_/ poly (aref poly 0))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_rationalize (poly) "Transform POLY so that all coefficients are rational -- imaginary parts of coefficients too." (map 'vector (lambda (x) (if (complexp x) (complex (rationalize (realpart x)) (rationalize (imagpart x))) (rationalize x))) poly)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_content (poly) "Compute the content of an integer or rational polynomial. POLY is rationalized if necessary. If $p\\in\\mathbb{Z}[x]$, then the content is the GCD of the coefficients. If $p\\in\\mathbb{Q}[x], then the content is the GCD of the numerators divided by the LCM of the denominators. i.e. the content is the unique $q\\in\\mathbb{Q}$ such that $p/q$ is a primitive polynomial in $\\mathbb{Z}[x]$ -- all the coefficients are integers have have GCD of $1$." (let* ((poly (mjr_poly_simplify poly))) (cond ((every #'integerp poly) (reduce #'gcd poly)) ((every #'rationalp poly) (/ (apply #'gcd (map 'list #'numerator poly)) (apply #'lcm (map 'list #'denominator poly)))) ((some #'complexp poly) (error "mjr_poly_content: Polynomial must not be complex!")) ((every #'numberp poly) (mjr_poly_content (mjr_poly_rationalize poly))) ('t (error "mjr_poly_content: POLY is not a polynomial!"))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_primitive-part (poly) "Returns the primitive part of the polynomial and the content. Note: poly = cont(poly)*primitive-part(poly)" (let* ((poly (mjr_poly_simplify poly)) (c (mjr_poly_content poly))) (values (mjr_vec_/ poly c) c))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_2primitive (poly) "Transform POLY, via multiplication by a rational number, into an primitive polynomial that shares the roots of the original. The rational number used to transform POLY is the second return value. Results are exact if the polynomial has only integer and/or rational coefficients. A simple generalization of the idea of primitive is used when the polynomial has complex coefficients -- The real and imaginary parts will both be transformed to integers and the entire collection of integers (real parts and imaginary parts together) will not share a common factor other than one. Floating point numbers in the coefficients will be rationalized. The finite precision of floating point arithmetic implies that polynomials made up of floats, doubles, and long doubles are but a simple scalar product away from their integer doppelganger. Unfortunately the vulgarities of floating point arithmetic can destroy this almost-truth. Still, we do the best we can. NOTE: A polynomial $p(x)=\sum_{j=0}^na_jx^j\in\mathbb{Z}[x]$ is primitive if $\mathrm{GCD}(a_0,\cdots,a_n)=1$ -- i.e. the coefficients are relatively prime. Gauss's lemma: If $p$ and $q$ are primitive, then $p\cdot q$ primitive, and if a $p\in\mathbb{Z}[x]$ is irreducible over the $\mathbb{Z}$, then the same polynomial considered in $\mathbb{Q}[x]$ is also irreducible over $\mathbb{Q}$. References: <NAME>(1801); Disquisitiones Arithmeticae; Article 42" (let* ((poly (mjr_poly_simplify poly)) (p1 (mjr_poly_rationalize poly)) (L (apply #'lcm (mapcar #'denominator (loop for coef across p1 collect (realpart coef) when (complexp coef) collect (imagpart coef))))) (p2 (mjr_vec_* p1 L)) (G (apply #'gcd (loop for coef across p2 collect (realpart coef) when (complexp coef) collect (imagpart coef)))) (p3 (mjr_vec_/ p2 G))) (values p3 (/ L G)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_seq-make-sturm-canonical (p) "Return a list of polynomials representing the 'Canonical Sturm sequence'. The canonical Sturm sequence of a polynomial $p$ is the intermediate results of Euclid's algorithm applied to to $p$ and $p'$: $$ \\begin{array}{lccclcl} p_0(x) & & & = & p(x) & & \\\\ p_1(x) & & & = & p'(x) & & \\\\ p_2(x) & & & = & -\\text{rem}(p_0, p_1) & = & p_1(x) \\cdot q_0(x) - p_0(x) \\\\ p_3(x) & & & = & -\\text{rem}(p_1, p_2) & = & p_2(x) \\cdot q_1(x) - p_1(x) \\\\ \\vdots & & & & & & \\\\ p_m & & & = & -\\text{rem}(p_{m-2}, p{m-1}) & = & p{m-1}(x) \\cdot q_{m-2}(x) - p_{m-2}(x) \\\\ p_{m+1} & = & 0 & = & -\\text{rem}(p_{m-1}, p_m) & & \\\\ \\end{array} $$ where $\\text{rem}(p_i,p_j)$ and $q_i$ are the remainder and the quotient of the polynomial long division of $p_i$ by $p_j$, and where $m\\le\\text{deg}{p}$ is the minimal number of polynomial divisions needed to obtain a zero remainder. Note: The sequence is well defined even when $p$ is not square-free; however, it may not be a Sturm sequence in this case. Confusingly enough, this sequence is always called the canonical Sturm sequence even when it is not really a Sturm sequence." (let ((pd (mjr_poly_diff p))) (nconc (list p pd) (loop for p-2 = p then p-1 for p-1 = pd then p-0 for p-0 = (mjr_poly_- (mjr_poly_rem p-2 p-1)) collect p-0 until (zerop (mjr_poly_degree p-0)))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_seq-make-fourier (p) "Return a list of polynomials representing the 'Fourier sequence'. Let $p$ be a real polynomial of degree $n>0$, then the Fourier sequence of $p$ is: $$F_\\text{seq}(x)=\\big\\{ p(x), p^{(1)}(x),\\ldots,p^{(n)}(x)\\big\\}$$" (loop for i from 0 upto (mjr_poly_degree p) for p-0 = p then (mjr_poly_diff p-0) collect p-0)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_count-sign-changes (seq) "Return the number of sign changes in seq (vector or list) -- zeros are ignored" (if (vectorp seq) (loop for cur-elt across seq for lst-sgn = nil then (if (zerop cur-sgn) lst-sgn cur-sgn) for (cur-sgn cur-amb) = (multiple-value-list (mjr_cmp_signum cur-elt)) count (and lst-sgn (not (zerop cur-sgn)) (not (= cur-sgn lst-sgn))) into count-sgn count cur-amb into count-amb finally (return (values count-sgn (if (not (zerop count-amb)) count-amb)))) (loop for cur-elt in seq for lst-sgn = nil then (if (zerop cur-sgn) lst-sgn cur-sgn) for (cur-sgn cur-amb) = (multiple-value-list (mjr_cmp_signum cur-elt)) count (and lst-sgn (not (zerop cur-sgn)) (not (= cur-sgn lst-sgn))) into count-sgn count cur-amb into count-amb finally (return (values count-sgn (if (not (zerop count-amb)) count-amb)))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_scount-sturm (p l r &optional sturm-sequence) "Compute the difference in the sign changes for $S(x+l)$ and $S(x+h)$ where S is the given Sturm sequence or the canonical one. The return will be the number of distinct real roots the polynomial has in the interval $(l,h]$ when: 1) sturm-sequence is NIL or the canonical Sturm sequence 2) when sturm-sequence is a valid Sturm sequence and $p$ is square-free. A Sturm sequence is a set of polynomials $p_0, p_1, \\dots, p_m\\in\\mathbb{R}[x]$ such that: \\begin{itemize} \\item $p_i$ are all polynomials \\item $m$ is a finite, non-negative integer \\item if $0\\ge i< j\\le m$ then $\\text{deg}(p_i)<\\text{deg}(p_j)$ \\item $p_0$ is square free (no repeated roots) \\item if $p(x_0)=0$, then $\\text{sign}(p_1(x_0))= \\text{sign}(p'(x_0))$ \\item if $p_i(\\xi)=0$ for $0<i<m$ then $\\text{sign}(p_{i-1}(\\xi))= -\\text{sign}(p_{i+1}(\\xi))$ \\item $p_m$ does not change its sign. \\end{itemize} Sturm's theorem\\\\ Let $p$ be a real, square-free polynomial of degree $n>0$ and $l,r\\in \\mathbb{R}$ with $l<r$. Let $S_\\text{seq}(x)=\\big\\{ p_0(x), p_1(x), ..., p_m(x)\\big\\}$ be a Sturm sequence with $p_0=p$. Let $v_l$ and $v_r$ be the sign variations in the sequences $S_\\text{seq}(l)$ and $S_\\text{seq}(r)$. Let $\\rho$ be the number of the real roots of $p$ in $(l,r]$. Let $v_\\delta=v_l - v_r$. Then we have $\\rho = v_\\delta$ Sturm's Canonical Sequence theorem\\\\ Let $p$ be a real polynomial of degree $n>0$ and $l,r\\in \\mathbb{R}$ with $l<r$ and neither $l$ or $r$ is a multiple root of $p$. Let $S_\\text{seq}(x)=\\big\\{ p_0(x), p_1(x), ..., p_m(x)\\big\\}$ be the canonical Sturm sequence of $p$. Let $v_l$ and $v_r$ be the sign variations in the sequences $S_\\text{seq}(l)$ and $S_\\text{seq}(r)$. Let $\\rho$ be the number of distinct real roots of $p$ in $(l,r]$. Let $v_\\delta=v_l - v_r$. Then we have $\\rho = v_\\delta$ References: <NAME>(1829); Memoire sur la resolution des equations numeriques; Bulletin des Sciences de Ferussac 11; 419-425" ;; MJR TODO NOTE <2013-01-01 19:01:18 CST> mjr_poly_scount-sturm: Add refs (pink and blue polynomial books) (let ((ss (or sturm-sequence (mjr_poly_seq-make-sturm-canonical p)))) (- (mjr_poly_count-sign-changes (mjr_poly_seq-eval ss l)) (mjr_poly_count-sign-changes (mjr_poly_seq-eval ss r))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_scount-budan (p l h) "Compute the difference in the sign changes for $p(x+l)$ and $p(x+h)$ Budan's theorem:\\\\ Let $p\\in\\mathbb{R}[x]$ with degree $n>0$ and $l,r\\in \\mathbb{R}$ with $l<r$ and $p(r)\\ne0$. Let $v_l$ and $v_r$ be the sign variations in $p(x+l)$ and $p(x+r)$ respectively. Let $\\rho$ be the number of the real roots of $p$ in $(l,r)$. Let $v_\\delta=v_l - v_r$. \\begin{enumerate} \\item $v_l \\ge v_r$ \\item $\\rho \\le v_\\delta$ \\item if $\\rho < v_\\delta$, then $\\rho = v_\\delta -2\\lambda$ where $\\lambda \\in \\mathbb{Z}_+$ \\end{enumerate} References: <NAME> (1807); Nouvelle methode pour la resolution des equations numeriques; Paris: Courcier" (if (not (mjr_chk_!=0 (mjr_poly_eval p h))) (warn "budan-count: Polynomial should not be zero on h if Budan's theorem is being used!")) (- (mjr_poly_count-sign-changes (mjr_poly_shift (- l) p)) (mjr_poly_count-sign-changes (mjr_poly_shift (- h) p)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_scount-fourier (p l h) "Compute the difference in the sign changes for $F(x+l)$ and $F(x+h)$ where F is the 'Fourier Sequence' for $p$ Fourier's theorem:\\\\ Let $p$ be a real polynomial of degree $n>0$ and $l,r\\in \\mathbb{R}$ with $l<r$ and $p(r)\\ne0$. Let $F_\\text{seq}(x)$ be the Fourier sequence of $p$. Let $v_l$ and $v_r$ be the sign variations in the sequences $F_\\text{seq}(l)$ and $F_\\text{seq}(r)$. Let $\\rho$ be the number of the real roots of $p$ in $(l,r)$. Let $v_\\delta=v_l - v_r$. \\begin{enumerate} \\item $v_l \\ge v_r$ \\item $\\rho \\le v_\\delta$ \\item if $\\rho < v_\\delta$, then $\\rho = v_\\delta -2\\lambda$ where $\\lambda \\in \\mathbb{Z}_+$ \\end{enumerate} References: <NAME> (1820); Sur l'usage du theoreme de Descartes dans la recherche des limites des racines; Bulletin des Sciences, par la Societe Philomatique de Paris: 156-165 <NAME> (2003); Polynomials (Problem Books in Mathematics); pp 174 <NAME> (2004); Polynomials; ISBN: 3540407146; pp 27" (if (not (mjr_chk_!=0 (mjr_poly_eval p h))) (warn "fourier-count: Polynomial should not be zero on h if Budan's theorem is being used!")) (let ((d (mjr_poly_degree p))) (- (mjr_poly_count-sign-changes (multiple-value-list (mjr_poly_eval-poly-and-first-n-derivatives p l d))) (mjr_poly_count-sign-changes (multiple-value-list (mjr_poly_eval-poly-and-first-n-derivatives p h d)))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_scount-descartes (poly &optional (c 0)) "Apply Descartes rule of signs to the shifted polynomial. Four values returned: * Max number roots ($P$) to the right of $C$ -- Actual number will be $P-2\\cdot m$ where $m$ is a non-negative integer. * Exact number of roots ($Z$) at $C$ -- Computed from a direct analysis of the polynomial. * Max number of roots ($N$) to the left of $C$ -- Actual number will be $N-2\\cdot n$ where $n$ is a non-negative integer. * Number of ambiguous zeros, or nil -- This occurs when a value is assumed zero because it was small, but not zero Theorem (Descartes): Let $$p(x)=\\sum\\limits_{j=0}^n a_jx^j\\in\\mathbb{R}[x]$$ Let $P=\\sigma(p)$ and $N=\\sigma(p(-x))$ where the $\\sigma$ function is defined as the number of sign changes in the polynomial coefficients ignoring zero coefficients. Let $Z$ be the number of trailing zeros -- i.e. number of zero coefficients at the end of the polynomial. Then the polynomial $p$ has $P-2m$ positive roots, $Z$ zero roots, and $N-2n$ negative roots where $m$ and $n$ non-negative integers. References: <NAME> (1637); La Geometrie (an appendix to Discours de la methode -- Discourse on Method) <NAME> (1979); Geometry (a translation of La Geometrie) <NAME> (1999); Descartes Rule of Signs: Another Construction; Amer. Math. Monthly 106, 854-855 <NAME> (2004); Polynomials; ISBN: 3540407146; pp 28" (let* ((poly (if (zerop c) (mjr_poly_simplify poly) (mjr_poly_shift c poly))) (plen (length poly))) (cond ((< plen 2) (error "mjr_poly_scount-descartes: Polynomial must be at least degree 1!"))) (loop for cur-coef across poly for odd-pow = (not (oddp plen)) then (not odd-pow) for count=0 = 0 then (if (mjr_cmp_=0 cur-coef) (1+ count=0) 0) for lst-sign = nil then (if (zerop cur-sign) lst-sign cur-sign) for lst-sign-x = nil then (if (zerop cur-sign-x) lst-sign-x cur-sign-x) for (cur-sign cur-ambiguous) = (multiple-value-list (mjr_cmp_signum cur-coef)) for cur-sign-x = (if odd-pow (- cur-sign) cur-sign) count (and lst-sign (not (zerop cur-sign)) (not (= cur-sign lst-sign))) into count+x count (and lst-sign-x (not (zerop cur-sign-x)) (not (= cur-sign-x lst-sign-x))) into count-x count cur-ambiguous into count-ambiguous-zeros finally (return (values count+x count=0 count-x (if (not (zerop count-ambiguous-zeros)) count-ambiguous-zeros)))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_root-bound-positive (poly &key (algorithm :rb-lagrange)) "Return an upper bound (perhaps strict) on the positive real roots of POLY. Returns NIL if anything goes wrong." (let* ((poly (mjr_poly_simplify poly)) ;; MJR TODO NOTE <2013-01-01 18:59:12 CST> mjr_poly_root-bound-positive: Add references, formula, and notes that it is also a global bound... ;; MJR TODO NOTE <2013-01-01 18:59:47 CST> mjr_poly_root-bound-positive: Move into mjr_poly_root-bound-all???? (pdeg (mjr_poly_degree poly)) (pn (aref poly 0))) (if (mjr_chk_!=0 pn) (case algorithm (:rb-lagrange (and (> pdeg 0) (loop with max1 = nil with max2 = nil for j from 0 upto (1- pdeg) for pjr = (/ (aref poly (- pdeg j)) pn) when (< pjr 0) do (let ((pjv (expt (abs pjr) (/ (- pdeg j))))) (if (null max1) (setf max1 pjv) (if (> pjv max1) (rotatef max2 max1 max1 pjv) (if (or (null max2) (> pjv max2)) (setf max2 pjv))))) finally (return (and max1 max2 (+ max1 max2)))))) (otherwise (error "mjr_poly_root-bound-positive: Unknown algorithm!")))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_root-bound-all (poly &key (algorithm :rb-fujiwara)) "Return an upper bound (perhaps strict) on the modulus of the roots of POLY using the given algorithm If the test can not be performed because the polynomial violates a constraint of the algorithm, then NIL is returned. Note: $$P(z)=\\sum\\limits_{i=0}^n a_ix^i$$ The algorithm argument may be one of, or a list of, the following symbols: * :rb-fujiwara - 8.1.11 - Fujiwara (1916) - $$2\\max_{0\\le j\\le n-1}\\left|\\frac{a_j}{a_n}\\right|$$ * :rb-cauchy - 8.1.9 - Cauchy (1829, p122) - $$1+\\max_{0\\le j\\le n-1}\\left|\\frac{a_j}{a_n}\\right|$$ - M,M,R (1994, p224) - $$1+\\frac{1}{\\vert a_n\\vert}\\left(\\max\\limits_{ 0\\leq i\\leq n-1}\\vert a_i\\vert\\right)$$ * :rb-kojima - 8.1.17 - Kojima (1917) - $$\\max\\left\\{ \\left|\\frac{a_0}{a_1}\\right|, 2\\left|\\frac{a_1}{a_2}\\right|, \\cdots, 2\\left|\\frac{a_{n-1}}{a_n}\\right| \\right\\}$$ * :rb-hirst-macey - N/A - Hirst,Macey (1997) - $$ ? $$ * :rb-lagrange - N/A - Lagrange (????) - $$ ? $$ Not yet supported, but will be in a future version * :rb-carmichal - 8.1.12 - Carmichal (1918) - $$\\sum_{j=0}^{n-1}\\left(\\left|\\frac{a_j}{a_n}\\right|^\\frac{1}{n-j}\\right)$$ * :rb-westerfield - N/A - Westerfield (1931) - $$\\hat{M}+\\check{M}$$ where $\\hat{M}$ and $\\check{M}$ are the two largest elements of $$\\left\\{ \\left|\\frac{a_j}{a_n}\\right|^\\frac{1}{n-j} : j=0,...,{n-1}\\right\\}$$ References: Fujiwara (1916); Uber die obere Schranke des absoluten Betrages der Wurzeln einer algebraischen Gleichung; Tohoku Math J 10; p167-171 Kojima (1917); On the limits of the roots of an algebraic equation; Tohoku Math J 11; p119-127 Cauchy (1829); Exercises de mathematique. Oeuvres 2 (9) Milovanovic, M<NAME>ovic, <NAME> (1994); Topics in polynomials: extremal problems, inequalities, zeros; ISBN: 981020499X <NAME> & <NAME> (1997); Bounding the roots of polynomials; Coll Math J 28 (4); pp292" ;; MJR TODO NOTE <2013-01-01 18:57:44 CST> mjr_poly_root-bound-all: IMPLEMENT :rb-carmichal and :rb-westerfield. ;; MJR TODO NOTE <2013-01-01 18:58:19 CST> mjr_poly_root-bound-all: Add refs for Carmichal and Westerfield. ;; MJR TODO NOTE <2013-01-01 18:58:37 CST> mjr_poly_root-bound-all: Add ref for blue polynomial book and/or blue computer algebra book. (let* ((poly (mjr_poly_simplify poly)) (pdeg (mjr_poly_degree poly)) (pn (aref poly 0))) (if (mjr_chk_!=0 pn) (flet ((cmpbnd (alg) (case alg (:rb-fujiwara (* 2 (max (expt (abs (/ (aref poly pdeg) pn)) (/ pdeg)) (loop for j from 1 upto (1- pdeg) maximize (expt (abs (/ (aref poly (- pdeg j)) pn)) (/ (- pdeg j))))))) (:rb-kojima (if (mjr_chk_!=0 (aref poly (1- pdeg))) (* 2 (max (* 1/2 (abs (/ (aref poly pdeg) (aref poly (1- pdeg))))) (loop for j from 1 upto (1- pdeg) for pj+1 = (aref poly (- pdeg (1+ j))) maximize (if (mjr_chk_!=0 pj+1) (abs (/ (aref poly (- pdeg j)) pj+1)) (return-from cmpbnd nil))))))) (:rb-cauchy (1+ (/ (loop for i from 1 upto pdeg maximize (abs (aref poly i))) (abs pn)))) (:rb-lagrange (mjr_poly_root-bound-positive poly :algorithm :rb-lagrange)) (:rb-hirst-macey (max 1 (loop for j from 0 upto (1- pdeg) for pj = (aref poly (- pdeg j)) maximize (if (mjr_chk_!=0 pj) (abs (/ pj pn)) (return-from cmpbnd nil))))) (otherwise (error "mjr_poly_root-bound-all: Unknown algorithm(~a)!" alg))))) (if (listp algorithm) (mapcar #'cmpbnd algorithm) (cmpbnd algorithm)))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_root-bound-all-cauchy (poly &key (xeps 0.0001) (yeps 0.0001) (max-itr 1000)) "Compute an approximation of the cauchy bound on the roots of the polynomial." (loop with soly = (mjr_poly_zap-zero-roots (mjr_poly_simplify poly)) with coly = (apply #'vector (loop for ai across soly for aai = (- (abs ai)) then (abs ai) collect aai)) with ubnd = (or (mjr_poly_root-bound-positive coly :algorithm :rb-lagrange) (mjr_poly_root-bound-all coly :algorithm :rb-fujiwara)) with x0 = 0 with x1 = ubnd with y0 = (mjr_poly_eval coly x0) with y1 = (mjr_poly_eval coly x1) for x-mid = (/ (+ x0 x1) 2) for y-mid = (mjr_poly_eval coly x-mid) for i-cur from 1 upto max-itr until (or (mjr_eps_= 0 y-mid yeps) (mjr_eps_= x0 x1 xeps) (mjr_eps_= x0 x-mid xeps) (mjr_eps_= x1 x-mid xeps) (mjr_eps_= y0 y1 yeps) (mjr_eps_= y0 y-mid yeps) (mjr_eps_= y1 y-mid yeps)) while (cond ((mjr_cmp_< y0 y1) (if (mjr_cmp_< y-mid 0) (setq x0 x-mid y0 y-mid) (setq x1 x-mid y1 y-mid))) ((mjr_cmp_> y0 y1) (if (mjr_cmp_< y-mid 0) (setq x1 x-mid y1 y-mid) (setq x0 x-mid y0 y-mid)))) finally (return x1))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_root-count-distinct-interval (p a b &optional eps) "Use mjr_poly_scount-sturm to compute the total number of distinct, real roots of the polynomial in $(a,b)$ If polynomial is zero at a or b, then those roots will be removed via deflation. If floating point comparisons are required to determine zeros at a and/or b, then eps will be used. Polynomial rationalization via mjr_poly_2primitive is recommended if floating point round-off is a problem." (if (mjr_chk_!=0 (mjr_poly_eval p a) eps) (if (mjr_chk_!=0 (mjr_poly_eval p b) eps) (mjr_poly_scount-sturm p a b) (mjr_poly_root-count-distinct-interval (mjr_poly_deflate p b) a b eps)) (mjr_poly_root-count-distinct-interval (mjr_poly_deflate p a) a b eps))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_root-count-distinct-negative-zero-positive (p &optional eps) "Use mjr_poly_scount-sturm to compute the total number of distinct, real roots of the polynomial in $(a,b)$ mjr_poly_zap-zero-roots and EPS are used to count zero roots (mjr_poly_2primitive is recommended)." (multiple-value-bind (poly nzr) (mjr_poly_zap-zero-roots p eps) (let ((u (ceiling (mjr_poly_root-bound-all poly))) (ss (mjr_poly_seq-make-sturm-canonical poly))) (values (mjr_poly_scount-sturm p (- -1 u) 0 ss) nzr (mjr_poly_scount-sturm p 0 (+ 1 u) ss))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_root-count-distinct-real (p) "Use mjr_poly_scount-sturm and mjr_poly_root-bound-all to compute the total number of distinct, real roots of the polynomial." (let ((u (ceiling (mjr_poly_root-bound-all p)))) (mjr_poly_scount-sturm p (- -1 u) (+ 1 u)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_root-structure (poly &optional use-sturm-sequence) "Return a list of vectors with each vector containing possible counts for negative, zero, positive, and complex roots for POLY." (let* ((poly (mjr_poly_simplify poly)) (num-roots (1- (length poly)))) (multiple-value-bind (max-pos-roots num-zero-roots max-neg-roots) (mjr_poly_scount-descartes poly) (multiple-value-bind (min-neg-roots num-zero-roots-s min-pos-roots) (if use-sturm-sequence (mjr_poly_root-count-distinct-negative-zero-positive poly) (values 0 nil 0)) (if (and num-zero-roots-s (not (= num-zero-roots-s num-zero-roots))) (error "mjr_poly_root-count-distinct-negative-zero-positive: Inconsistent zero root counts!")) ;;(format 't "~10d ~10d ~10d~%" max-pos-roots num-zero-roots max-neg-roots) ;;(format 't "~10d ~10d ~10d~%" min-pos-roots num-zero-roots-s min-neg-roots) (loop for num-not0-roots from (- num-roots num-zero-roots) downto (+ min-pos-roots min-neg-roots) by 2 append (loop for num-neg-roots from max-neg-roots downto min-neg-roots by 2 append (loop for num-pos-roots from max-pos-roots downto min-pos-roots by 2 for num-cmplx-roots = (- num-roots num-not0-roots num-zero-roots) when (and (<= 0 num-cmplx-roots) (= num-not0-roots (+ num-pos-roots num-neg-roots))) collect (vector num-neg-roots num-zero-roots num-pos-roots (- num-roots num-not0-roots num-zero-roots))))))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_root-structure-print (rstruct) "Print out all the list returned from mjr_poly_root-structure in a nice humanly readable table." (format 't " Negative Zero Positive Complex~%") (loop for cnts in rstruct do (format 't "~10d ~10d ~10d ~10d~%" (aref cnts 0) (aref cnts 1) (aref cnts 2) (aref cnts 3)) finally (return rstruct))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_root-solve-rational (poly &key only-integer-roots) "Find rational roots of a polynomial. Morally speaking this only works on a polynomials with integer coefficients; however, this function uses MJR_POLY_2PRIMITIVE to transform POLY into one with integer coefficients if required. Returns: * A list of found roots * The polynomial actually solved (we call this IPOLY) -- the first return of MJR_POLY_2PRIMITIVE on POLY * The logical factor required to transform POLY into IPOLY -- the second return of MJR_POLY_2PRIMITIVE on POLY * the result of deflating IPOLY with each root found" (cond ((not (vectorp poly)) (error "mjr_poly_root-solve-rational: POLY must be a vector")) ((not (every #'realp poly)) (error "mjr_poly_root-solve-rational: POLY must have real coefficients."))) (multiple-value-bind (ipoly ipolyf) (mjr_poly_2primitive poly) (let ((plen (length poly))) (if (zerop (aref ipoly (1- plen))) ;; Here we take care of the case with zero constant coefficient.... (let ((last-zero-idx (loop for i from (1- plen) downto 0 until (not (zerop (aref ipoly i))) minimize i))) (if (zerop last-zero-idx) (error "mjr_poly_root-solve-rational: POLY is zero -- infinitely many roots!!!") (multiple-value-bind (roots ipoly-throw-away ipolyf-throw-away wpoly) (mjr_poly_root-solve-rational (subseq ipoly 0 last-zero-idx)) (declare (ignore ipoly-throw-away ipolyf-throw-away)) ;; Just keep compiler from squawking (values (sort (append (make-list (- plen last-zero-idx) :initial-element 0) roots) #'<) ipoly ;; The original -- not ipoly-throw-away.. ipolyf;; The original -- not ipolyf-throw-away.. wpoly)))) ;; constant coefficient not zero. (let* ((wpoly (copy-seq ipoly)) (first-coef (abs (aref ipoly 0))) (last-coef (abs (aref ipoly (1- plen)))) (first-factors (mjr_prime_all-factors first-coef)) (last-factors (mjr_prime_all-factors last-coef)) (proot-candidates (remove-duplicates (loop for first-factor in first-factors append (loop for last-factor in last-factors for c = (/ last-factor first-factor) when (or (not only-integer-roots) (integerp c)) collect c)))) (root-candidates (sort (append (mapcar #'- proot-candidates) proot-candidates) #'<))) (values (loop for x in root-candidates until (> 2 (length wpoly)) append (loop until (not (multiple-value-bind (dfpoly pval) (mjr_poly_deflate wpoly x) (and (= 0 pval) (setq wpoly dfpoly)))) collect x)) ipoly ipolyf wpoly)))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_root-solve-integer (poly) "Find integer roots of a polynomial. Morally speaking this only works on a polynomials with integer coefficients; however, this function uses MJR_POLY_2PRIMITIVE to transform POLY into one with integer coefficients if required. Returns: * A list of found roots * The polynomial actually solved (we call this IPOLY) -- the first return of MJR_POLY_2PRIMITIVE on POLY * The logical factor required to transform POLY into IPOLY -- the second return of MJR_POLY_2PRIMITIVE on POLY * the result of deflating IPOLY with each root found" (mjr_poly_root-solve-rational poly :only-integer-roots 't)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_root-search-bsect (poly x0 x1 &rest kw-args &key xeps yeps max-itr show-progress) "Use bsect's method to find a root of POLY between X0 and X2. See the documentation for MJR_NLEQ_ROOT-BSECT" (and xeps yeps max-itr show-progress) (flet ((fp (x) (mjr_poly_eval poly x))) (apply #'mjr_nleq_root-bsect #'fp x0 x1 kw-args))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_root-search-newton (poly x0 &rest kw-args &key xeps yeps max-itr show-progress) "Use newton's method to find a root of POLY near (hopefully anyhow) X0. See the documentation for MJR_NLEQ_ROOT-NEWTON" (and xeps yeps max-itr show-progress) ;; Variables not directly used (flet ((fdf (x) (mjr_poly_eval-poly-and-first-n-derivatives poly x 1))) (apply #'mjr_nleq_root-newton #'fdf x0 kw-args))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_root-search-laguerre (poly x0 &rest kw-args &key xeps yeps max-itr show-progress) "Use laguerre's method to find a root of POLY near (hopefully anyhow) X0. See the documentation for MJR_NLEQ_ROOT-LAGUERRE" (and xeps yeps max-itr show-progress) ;; Variables not directly used (flet ((fdfddf (x) (mjr_poly_eval-poly-and-first-n-derivatives poly x 2))) (apply #'mjr_nleq_root-laguerre #'fdfddf (mjr_poly_degree poly) x0 kw-args))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_root-separate-largest-real (poly &key (xeps 1) max-itr yeps show-progress) "Use the canonical sturm-sequence to find an interval containing the largest real root and no other roots. An open interval $(a,b)$ containing the largest real root (and no other roots) is found. This interval will be no wider than :XEPS, and will contain no roots other than the largest real one. The return of this function will two values corresponding to the left and right endpoints of the interval. In the case of a polynomial with no real roots, then (values nil nil) will be returned. If the polynomial is rational, then the interval endpoints will be as well. When removed from the vulgarities of real world computing, this algorithm is guaranteed to work; however, some things can go wrong with real world implementations. When the inputs are rational, and enough memory is available for the necessary precision, the algorithm will always work unless the :MAX-ITR count is violated (the error is 'Maximum iteration count exceeded!'). When using floating point arithmetic various things can go wrong, but when the error 'Could not find a non-root' occurs a lower :YEPS (the only use of this argument is to detect when the polynomial is zero at prospective new interval endpoints) might help." (let ((d (mjr_poly_degree poly))) (cond ((some #'complexp poly) (error "mjr_poly_root-separate-largest-real: POLY must be a non-complex coefficients!")) ((< d 2) (error "mjr_poly_root-separate-largest-real: POLY must be of at least degree two!"))) (let* ((rb (max 1 (ceiling (mjr_poly_root-bound-all poly)))) (ss (mjr_poly_seq-make-sturm-canonical poly)) (b (* 11/10 rb)) (a (- b)) (va (mjr_poly_count-sign-changes (mjr_poly_seq-eval ss a))) (vb (mjr_poly_count-sign-changes (mjr_poly_seq-eval ss b)))) (loop for itr from 1 for n = (- va vb) do (if show-progress (format 't "~5d ~3d ~40a ~40a ~40a ~%" itr n a "" b)) do (if (and max-itr (> itr max-itr)) (error "mjr_poly_root-separate-largest-real: Maximum iteration count exceeded!")) do (if (> n 0) (loop with delta = (/ (- b a) (* 2 (+ d 1))) for i from 0 upto d for c = (/ (+ a b) 2) then (- c delta) when (mjr_cmp_not-zerop (mjr_poly_eval poly c) yeps) do (return (let ((vc (mjr_poly_count-sign-changes (mjr_poly_seq-eval ss c)))) (if (> (- vc vb) 0) (setq a c va vc) (setq b c vb vc)))) do (if show-progress (format 't "~5d ~3a ~40a ~40a ~40a ~%" "" "" "" c "")) ;; Only show after first try finally (error "mjr_poly_root-separate-largest-real: Could not find a non-root!")) (return-from mjr_poly_root-separate-largest-real (values nil nil))) until (and (= n 1) (< (- b a) xeps))) (values a b)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_root-search-largest-real (poly &rest rest) "Return the largest real root or NIL if the polynomial has no real roots. When successful this function returns the center of the interval found by mjr_poly_root-separate-largest-real. All arguments are passed directly to mjr_poly_root-separate-largest-real, so consult that function for usage information." (multiple-value-bind (a b) (apply #'mjr_poly_root-separate-largest-real poly rest) (if (and a b) (/ (+ a b) 2)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_root-solve-low-degree (poly &optional eps) "Return list of root(s) to the small degree (<=3) polynomial. Multiple roots are listed multiple times. The argument EPS is used to avoid division by zero." (if (<= (mjr_poly_degree poly) 3) (let* ((p3 (mjr_poly_coeff poly 3)) (p2 (mjr_poly_coeff poly 2)) (p1 (mjr_poly_coeff poly 1)) (p0 (mjr_poly_coeff poly 0))) (if (mjr_chk_!=0 p3 eps) (if (every #'realp (list p3 p2 p1 p0)) ;; ............................................................... Cubic(deg=3) (let* ((m (+ (* 2 p2 p2 p2) (* -9 p3 p2 p1) (* 27 p3 p3 p0))) ;; ..................................... Real Poly (n (* 4 (expt (- (* p2 p2) (* 3 p3 p1)) 3))) (r (mjr_numu_sqrt (- (* m m) n))) (p (mjr_numu_cubert (/ (+ m r) 2))) (q (mjr_numu_cubert (/ (- m r) 2))) (i1 (/ (+ 1 (complex 0 (sqrt 3))) 2)) (i2 (/ (- 1 (complex 0 (sqrt 3))) 2))) (list (/ (+ p2 p q) (* -3 p3)) (/ (+ (- p2) (* i1 p) (* i2 q)) (* 3 p3)) (/ (+ (- p2) (* i2 p) (* i1 q)) (* 3 p3)))) (let* ((a (/ p2 p3)) ;; ............................................................................... Complex (b (/ p1 p3)) (c (/ p0 p3)) (q (/ (- (* a a) (* 3 b)) 9)) (r (/ (+ (* 2 a a a) (* -9 a b) (* 27 c)) 54)) (r2 (* r r)) (q3 (expt q 3))) (if (and (not (complexp r)) (not (complexp q)) (< r2 q3)) (let* ((an (acos (/ r (mjr_numu_sqrt q3))))) (list (- (* -2 (mjr_numu_sqrt q) (cos (/ an 3))) (/ a 3)) (- (* -2 (mjr_numu_sqrt q) (cos (/ (+ an (* 2 pi)) 3))) (/ a 3)) (- (* -2 (mjr_numu_sqrt q) (cos (/ (- an (* 2 pi)) 3))) (/ a 3)))) (let* ((ca (if (>= (realpart (* (conjugate r) (mjr_numu_sqrt (- r2 q3)))) 0) (mjr_numu_cubert (- (+ r (mjr_numu_sqrt (- r2 q3))))) (mjr_numu_cubert (- (- r (mjr_numu_sqrt (- r2 q3))))))) (cb (if (mjr_chk_!=0 ca) (/ q ca) 0))) (list (- (+ ca cb) (/ a 3)) (+ (- (* -1/2 (+ ca cb)) (/ a 3)) (* #C(0 1) (/ (sqrt 3) 2) (- ca cb))) (- (- (* -1/2 (+ ca cb)) (/ a 3)) (* #C(0 1) (/ (sqrt 3) 2) (- ca cb)))))))) (if (mjr_chk_!=0 p2 eps) (let* ((dsr (mjr_numu_sqrt (- (* p1 p1) (* 4 p2 p0)))) ;; ........................................... Quadratic(deg=2) (tmp (/ (mjr_cmp_abs-max (+ p1 dsr) (- p1 dsr)) -2))) (if (mjr_chk_!=0 tmp eps) (list (/ tmp p2) (/ p0 tmp)) (list 0 0))) (if (mjr_chk_!=0 p1 eps) (list (/ (- p0) p1)) ;; ......................................................................... Linear(deg=1) (if (mjr_chk_!=0 p0 eps) nil (error "mjr_poly_root-solve-low-degree: Infinitely many solutions!")))))) (error "mjr_poly_root-solve-low-degree: Polynomial order is greater than 3!"))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_make-lagrange (points 1point &optional (pval 1)) "Return the unique polynomial that is PVAL (default 1) on the 1point'th element (zero indexed) of POINTS, and zero all the other elements of POINTS" (let ((poly 1) (divs 1) (1p (elt points 1point))) (if (vectorp points) (loop for i from 0 for p across points when (not (= i 1point)) do (setq poly (mjr_poly_* poly (vector 1 (- p))) divs (* divs (- 1p p)))) (loop for i from 0 for p in points when (not (= i 1point)) do (setq poly (mjr_poly_* poly (vector 1 (- p))) divs (* divs (- 1p p))))) (mjr_poly_* poly (/ pval divs)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_seq-make-lagrange (points &optional (pval 1)) "Return a list of polynomials such that the i'th one has value PVAL on the i'th element of POINTS and zero on all other elements" (loop for i from 0 upto (1- (length points)) collect (mjr_poly_make-lagrange points i pval))) ;; MJR TODO NOTE <2012-11-12 22:30:11 CST> mjr_poly_seq-make-lagrange: Optimize this function! ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_seq-make-chebyshev (num &optional (kind 1)) "Compute first NUM Chebyshev Polynomials (as a vector of vectors). kind==1 corresponds to Chebyshev Polynomials of the first kind $T_n$. kind==2 corresponds to Chebyshev Polynomials of the second kind $U_n$." (if (= num 1) (make-array 1 :initial-contents '(#(1))) (loop with p = (make-array num) for i from 2 upto (1- num) initially (setf (aref p 0) #(1) (aref p 1) (if (= kind 1) #(1 0) #(2 0))) finally (return p) do (setf (aref p i) (mjr_poly_- (mjr_poly_* 2 #(1 0) (aref p (- i 1))) (aref p (- i 2))))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_make-chebyshev (power &optional (kind 1)) "Compute Chebyshev Polynomial of the given power. kind==1 corresponds to Chebyshev Polynomials of the first kind $T_n$. kind==2 corresponds to Chebyshev Polynomials of the second kind $U_n$." (let* ((p0 #(1)) (p1 (if (= kind 1) #(1 0) #(2 0)))) (case power (0 p0) (1 p1) (otherwise (loop for i from 2 upto (1+ power) for pa = p0 then pb for pb = p1 then pn for pn = (mjr_poly_- (mjr_poly_* 2 #(1 0) pb) pa) when (= power i) do (return pn)))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_make-legendre (n) "Compute the Nth legendre polynomial using $$\\frac{1}{2^n n!}\\cdot\\frac{d^n}{dx^n}(x^2-1)^n$$" (mjr_poly_* (mjr_poly_diff (mjr_poly_iexpt #(1 0 -1) n) n) (/ (* (expt 2 n) (mjr_combe_! n))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_seq-make-legendre (n) "Return a list of the first n legendre polynomials (starting with the 0'th one)" (loop for i from 0 upto n collect (mjr_poly_make-legendre i))) ;; MJR TODO NOTE <2012-11-12 22:40:48 CST> mjr_poly_seq-make-legendre: Optimize this function! ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_make-bernstein (nu n) "The nu'th Bernstein basis polynomial of degree n." (let ((poly (make-array (1+ n) :initial-element 0)) (tmp (mjr_poly_* (mjr_combe_comb n nu) (mjr_poly_iexpt #(-1 1) (- n nu))))) (dotimes (i (length tmp) poly) (setf (aref poly i) (aref tmp i))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_seq-make-bernstein (n &key show-progress) "The Bernstein basis polynomials of degree n (all n of them in a list)." (reverse (loop with xn = (make-array (1+ n) :initial-element 0) initially (setf (aref xn 0) 1) for nu from n downto 0 for c = (mjr_combe_comb n nu) for p1 = (subseq xn 0 (1+ nu)) for p2 = #(1) then (mjr_poly_* #(-1 1) p2) do (if show-progress (format 't "~4d: ~10d ~4d ~80a ~%" nu c (mjr_poly_degree p1) p2)) collect (mjr_poly_* c p1 p2)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_imul (poly n) "Multiply POLY times the integer N. This function is provided for consistency with other packages that implement arithmetic for various rings -- after all integer multiplication is not terribly interesting for polynomials over Z, Q, R, or C." (mjr_poly_* n poly)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_root-solve-search-deflate (poly &key (xeps 1.0d-5) (yeps 1.0d-5) (xepsr 1.0d-10) (yepsr 1.0d-10) (refine-steps 10) (only-refined nil) (yepsp nil) (retry-factor 4) (float-type 0.0d0) (show-warnings nil) (show-progress nil)) "Find floating point approximations for all of the roots of a polynomial. Three values are returned: list of roots found, list of poly values on roots, and the part of the poly that couldn't be solved. _____THIS FUNCTION SHOULD BE CONSIDERED EXPERIMENTAL_____ This function works most of the time, but the roots are generally only accurate to a few decimal points. Retrying the function after failure can lead to success (different random seeds). Lowering the :XEPS and :YEPS can help in initial root location. If :ONLY-REFINED is used, then increasing :RETRY-FACTOR may be required. On LISPs that support it, setting :FLOAT-TYPE to 0.0L0 may increase accuracy and help with convergence problems due to round off errors. As a last resort, the :YEPSP argument may be set to a value larger than :YEPS in cases where numerical instability leads to deflated polynomials that have roots which are not within :YEPS of being a root of the original polynomial but are within :YEPSP of being a root (i.e. the absolute value of the original polynomial at the proposed root is less than :YEPSP). This last option can lead not-quite-roots that are quite far off, but still useful. The algorithm: 0) Set w<-p 1) Use laguerre to find a root xb of w (:xeps & :yeps) 2) Use laguerre to refine xb (:refine-steps, :xepsr, & :xepsr) 3) If refinement leads to a non-root of w and :only-refined is non-NIL, then NEXT 4) If p is real and xb is complex, check to see if re(xb) is a root of p and w. If so xb<-re(xb) 5) If xb is a root of p and w, then we deflate: a) If p is real and xb is complex, divide out xb and conj(xb) and update w b) otherwise just divide out xb 6) Jump to 1) if w is deg 1 or higher and we haven't gone beyond (retry-factor)*deg(poly) tries" (let ((rpoly (every #'realp poly)) (wpoly (copy-seq poly)) (roots nil) (pvals nil) (yepsp (or yepsp yeps)) (trys (* retry-factor (length poly)))) (loop with refined = nil for guess = (mjr_prng_float-co (float -10 float-type) (float 10 float-type)) for itr from 1 upto trys while (< 1 (length wpoly)) do (multiple-value-bind (x-bst w-bst ex-why) (progn (if show-progress (format 't "Root search: ~f~%" guess)) (mjr_poly_root-search-laguerre wpoly guess :yeps yeps :xeps xeps :show-progress show-progress)) (if show-progress (format 't "Root candidate: ~a~%" x-bst)) ;; Refine the root. (setq refined nil) (if refine-steps (multiple-value-bind (x-bst2 p-bst2 ex-why2) (progn (if show-progress (format 't "Root refine:~%")) (mjr_poly_root-search-laguerre poly x-bst :yeps yepsr :xeps xepsr :max-itr refine-steps :show-progress show-progress)) (if show-progress (format 't "Refinement candidate: ~a~%" x-bst2)) (if (mjr_eps_=0 p-bst2 yepsp) (let ((w-bst2 (mjr_poly_eval wpoly x-bst2))) (if (mjr_eps_=0 w-bst2 yeps) (progn (if show-progress (format 't "Refinement success~%")) (setf x-bst x-bst2 w-bst w-bst2 ex-why ex-why2 refined 't)) (if show-warnings (warn "mjr_poly_root-solve-search-deflate: laguerre refinement failed to find new root: ~a" x-bst)))) (if show-warnings (warn "mjr_poly_root-solve-search-deflate: laguerre refinement failed to converge: ~a" x-bst))))) (if (or refined (null only-refined)) (progn ;; Snip off the complex bit if the real bit is a good root (if (and rpoly (complexp x-bst)) (let* ((x-bst2 (realpart x-bst)) (w-bst2 (mjr_poly_eval wpoly x-bst2))) (if (and (mjr_eps_=0 w-bst2 yeps) (mjr_eps_=0 (mjr_poly_eval poly x-bst2) yepsp)) (progn (if show-progress (format 't "Root real-ifyed~%")) (setf x-bst x-bst2 w-bst w-bst2))))) ;; Snip off the fractional bit if this results in a good root (let* ((x-bst2 (complex (round (realpart x-bst)) (round (imagpart x-bst)))) (w-bst2 (mjr_poly_eval wpoly x-bst2))) (if (and (mjr_eps_=0 w-bst2 yeps) (mjr_eps_=0 (mjr_poly_eval poly x-bst2) yepsp)) (progn (if show-progress (format 't "Root int-ifyed~%")) (setf x-bst x-bst2 w-bst w-bst2)))) ;; Check the "roots", and deflate if things look good (if (mjr_eps_=0 w-bst yeps) (let ((p-bst (mjr_poly_eval poly x-bst))) (if (mjr_eps_=0 p-bst yepsp) (let ((wpoly2 (mjr_poly_deflate wpoly x-bst))) (setf roots (cons x-bst roots) pvals (cons p-bst pvals)) (if (and rpoly (complexp x-bst)) (let* ((x-bst-c (conjugate x-bst))) (if (mjr_eps_=0 (mjr_poly_eval wpoly2 x-bst-c) yeps) (setf roots (cons x-bst-c roots) pvals (cons (mjr_poly_eval poly x-bst-c) pvals) wpoly (mjr_poly_truncate wpoly (vector 1 (* -2 (realpart x-bst)) (mjr_numu_abssqr x-bst)))) (progn (if show-warnings (warn "mjr_poly_root-solve-search-deflate: Numerical instability detected: real poly but conjugate not a root!: ~a" x-bst)) (setf wpoly wpoly2)))) (setf wpoly wpoly2))) (if show-warnings (warn "mjr_poly_root-solve-search-deflate: Numerical instability detected: root of deflated poly not a root of original poly!")))) (if show-warnings (warn "mjr_poly_root-solve-search-deflate: laguerre failed to converge: ~a ~a ~a" x-bst w-bst ex-why)))) (if show-warnings (warn "mjr_poly_root-solve-search-deflate: Ignoring unrefined root: ~a" x-bst)))) do (if (and (= itr (truncate trys 2)) show-warnings) (warn "mjr_poly_root-solve-search-deflate: laguerre having difficulty converging")) do (if show-progress (format 't "ROOT: ~a~%" roots))) (values roots pvals wpoly))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_find-integer-factor (poly degree-or-sample-points &key show-progress) "Return an integer polynomial factor of the integer polynomial specified by POLY of the specified size or NIL if none exist. If a factor was found, then a second return value returned is POLY divided by the factor that was found. If degree-or-sample-points is a vector, then the points will be used in Kronecker's method. As the value of the polynomial on each of these points must be factored, the polynomial must not be zero on any of the points in the vector. The size of the factors may be specified as an integer indicating the degree of the desired factors or a vector of sample points to be used by Kronecker's method (in which case the degree of the factors will be one less than the length of the list) References: <NAME> (2004); Polynomials; ISBN: 3540407146; pp 49-50" (let* ((degree (if (vectorp degree-or-sample-points) (1- (length degree-or-sample-points)) degree-or-sample-points)) (x-points (if (vectorp degree-or-sample-points) degree-or-sample-points (make-array (1+ degree)))) (y-points (if (vectorp degree-or-sample-points) (map 'vector (lambda (x) (mjr_poly_eval poly x)) x-points) (apply #'vector (loop with npts = 0 ;; find degree+1 points where the poly is not zero for x = 0 then (if (not (plusp x)) (1+ (abs x)) (- x)) for y = (mjr_poly_eval poly x) do (if show-progress (format 't "testing sample point ~d => ~d~%" x y)) when (not (zerop y)) collect (progn (setf (aref x-points npts) x) (incf npts) y) until (= npts (1+ degree))))))) (if show-progress (format 't "Using x sample points: ~a~%" x-points)) (if show-progress (format 't "Using y sample points: ~a~%" y-points)) (mjr_combc_gen-all-cross-product (loop for i from 0 for x across x-points for y across y-points for pf = (mjr_prime_all-factors (abs y)) do (if show-progress (format 't "factor ~d from ~d into ~d factors~%" y x (length pf))) collect (concatenate 'vector pf (if (not (zerop i)) (mapcar #'- pf)))) :func (lambda (y-vals) (let ((p (mjr_intrp_poly x-points y-vals))) (if (and (= (1+ degree) (length p)) (every #'integerp p)) (let ((quo (mjr_poly_divides? p poly :require-integer-quotient 't))) (if quo (return-from mjr_poly_find-integer-factor (values p quo)))))))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_factor-over-integers (poly &key show-progress) "Return a list of integer polynomial factors of the integer polynomial specified by POLY. Algorithm: 1) The polynomial is transformed into a primitive, integer polynomial if required (see: MJR_POLY_2PRIMITIVE) The multiplicative factor required for this transformation is included in the returned factor list as a constant polynomial NOTE: This will rationalize the polynomial if it contains floating point coefficients (real or complex) 2) All linear factors are found and removed 3) Kronecker's method is applied to the remainder NOTE: Kronecker's method can be quite slow when the polynomial sample values are large integers with many factors. References: <NAME> (2004); Polynomials; ISBN: 3540407146; pp 49-50 <NAME> (2003); Computer Algebra and Symbolic Computation: Mathematical Methods; ISBN: 1568811594; pp362-367" (multiple-value-bind (int-roots ipoly ipolyf pleft) (mjr_poly_root-solve-rational poly) (declare (ignore ipoly)) (setq pleft (mjr_poly_* (/ (reduce #'* (mapcar #'denominator int-roots))) pleft)) (loop with factors = (append (mapcar (lambda (r) (vector (denominator r) (- (numerator r)))) int-roots) (if (not (= 1 ipolyf)) (list (vector (/ ipolyf))))) for degree = 2 then (if gotfac 2 (1+ degree)) for gotfac = nil for sample-points = (mjr_vvec_to-list (list :vvec-type :vvt-aseq :start (floor (- (truncate degree 2))) :step 1 :len (+ degree 1))) for pleftlen = (length pleft) finally (return (append factors (if (or (< 1 pleftlen) (not (= (aref pleft 0) 1))) (list pleft)))) do (if show-progress (format 't "factoring(~d) ~a~%" degree pleft)) do (if show-progress (format 't "factors so far ~a ~%" factors)) while (and (<= degree (floor (/ pleftlen 2))) (< 1 (length pleft)) (or (< 1 pleftlen) (not (= (aref pleft 0) 1)))) do (mjr_combc_gen-all-cross-product (loop for i from 0 for x in sample-points for y = (mjr_poly_eval pleft x) for pf = (mjr_prime_all-factors (abs y)) do (if show-progress (format 't "factor ~d from ~d into ~d factors~%" y x (length pf))) collect (concatenate 'vector pf (if (not (zerop i)) (mapcar #'- pf)))) :func (lambda (y-vals) (mjr_intrp_poly sample-points y-vals)) :exit-if (lambda (p) (if (and (= (1+ degree) (length p)) (every #'integerp p)) (loop for quo = (mjr_poly_divides? p pleft :require-integer-quotient 't) for j from 1 finally (return gotfac) while quo do (progn (push p factors) (setq pleft quo) (setq gotfac 't))))))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_gcd-primitive (poly1 poly2) "Return primitive GCD of poly1 and poly2. See: MJR_POLY_GCD" (mjr_poly_2primitive (mjr_poly_gcd poly1 poly2))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_test-property (poly &rest pp-list) "Return non-nil if the given polynomial has all of the specified polynomial properties. This is not a fast function, but it sure is handy. A few property tests exist as separate functions because of performance. Symbol Description elt_comp :PP-PRIMITIVE Integer, primitive polynomial exact :PP-SQUARE-FREE No double factors fizzy :PP-IRREDUCIBLE No factors exact :PP-MONIC Leading coefficient is 1 fizzy :PP-NUMBER All elements are numbers N/A :PP-REAL All elements are real N/A :PP-INTEGER All elements are integers N/A :PP-RATIONAL All elements are rational N/A :PP-COMPLEX All elements are complex N/A :PP-POSITIVE All elements numeric and positive cmpzy :PP-EVEN The polynomial is an even function cmpzy :PP-ODD The polynomial is an odd function cmpzy :PP-ZERO The zero polynomial cmpzy :PP-IDENTITY The constant 1 polynomial cmpzy :PP-CONSTANT A constant polynomial cmpzy" (let ((poly (mjr_poly_simplify poly)) (deg (mjr_poly_degree poly))) (if (cdr pp-list) (every (lambda (pp) (mjr_poly_test-property poly pp)) pp-list) (case (car pp-list) (:pp-complex (every #'complexp poly)) (:pp-real (every (lambda (x) (and (numberp x) (not (complexp x)))) poly)) (:pp-rational (every #'rationalp poly)) (:pp-integer (every #'integerp poly)) (:pp-number (every #'numberp poly)) (:pp-positive (every #'plusp poly)) (:pp-monic (mjr_cmp_= (mjr_poly_leading-coeff poly) 1)) (:pp-odd (and (oddp deg) (loop for c across poly for i from 0 upto deg finally (return 't) when (and (oddp i) (mjr_cmp_!=0 c)) do (return nil)))) (:pp-even (and (evenp deg) (loop for c across poly for i from 0 upto deg finally (return 't) do (format 't "~a~%" c) when (and (oddp i) (mjr_cmp_!=0 c)) do (return nil)))) (:pp-irreducible (if (< deg 2) 't (if (or (not (mjr_poly_test-property poly :pp-rational)) (mjr_poly_test-property poly :pp-complex)) nil (error "mjr_poly_test-property: Irreducibly tests not implemented for integer or rational polynomials yet!")))) (:pp-primitive (and (mjr_poly_test-property poly :pp-integer) (= 1 (reduce #'gcd poly)))) (:pp-square-free (mjr_poly_test-property (mjr_poly_gcd (mjr_poly_diff poly) poly) :pp-identity)) (:pp-zero (mjr_eps_= #(0) poly)) (:pp-identity (mjr_eps_= #(1) poly)) (:pp-constant (= 0 deg)) (otherwise (error "mjr_poly_test-property: Unknown property")))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_seq-make-hermite (num) "Compute first NUM Hermite Polynomials (as a vector of vectors)." (loop with p = (make-array num) for i from 2 upto (1- num) initially (progn (setf (aref p 0) #(1)) (if (> num 1) (setf (aref p 1) #(1 0)))) finally (return p) do (setf (aref p i) (mjr_poly_- (mjr_poly_* #(1 0) (aref p (- i 1))) (mjr_poly_diff (aref p (- i 1))))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_make-hermite (power) "Compute the Hermite Polynomial of the given power." (let* ((p0 #(1)) (p1 #(1 0))) (case power (0 p0) (1 p1) (otherwise (loop for i from 2 upto (1+ power) for pa = p0 then pb for pb = p1 then pn for pn = (mjr_poly_- (mjr_poly_* #(1 0) pb) (mjr_poly_diff pb)) when (= power i) do (return pn)))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_make-laguerre (power) "Compute the Laguerre Polynomial of the given power." (let* ((p0 #(1)) (p1 #(-1 1))) (case power (0 p0) (1 p1) (otherwise (loop for i from 2 upto (1+ power) for pa = p0 then pb for pb = p1 then pn for pn = (mjr_poly_* (/ i) (mjr_poly_- (mjr_poly_* (mjr_poly_+ (* 2 (1- i)) #(-1 1)) pb) (mjr_poly_* (1- i) pa))) when (= power i) do (return pn)))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_seq-make-laguerre (num) "Compute first NUM Hermite Polynomials (as a vector of vectors)." (loop with p = (make-array num) for i from 2 upto (1- num) initially (progn (setf (aref p 0) #(1)) (if (> num 1) (setf (aref p 1) #(-1 1)))) finally (return p) do (setf (aref p i) (mjr_poly_* (/ i) (mjr_poly_- (mjr_poly_* (mjr_poly_+ (* 2 (1- i)) #(-1 1)) (aref p (1- i))) (mjr_poly_* (1- i) (aref p (- i 2)))))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_cubic-depress (poly) "Return the depressed form of the given cubic polynomial. If $p(x)=ax^3+bx^2+cx+d$, then divide $p$ by $a$ and substitute $t=\frac{b}{-3a}$." (let* ((cpoly (mjr_poly_simplify poly)) (deg (1- (length cpoly)))) (if (= 3 deg) (let* ((a (aref cpoly 0)) (a2 (* a a)) (b (aref cpoly 1)) (b2 (* b b)) (c (aref cpoly 2)) (d (aref cpoly 3))) (vector 1 0 (/ (- (* 3 a c) b2) (* 3 a2)) (/ (+ (* 2 b2 b) (* -9 a b c) (* 27 a2 d)) (* 27 a2 a)))) (error "mjr_poly_cubic-depress: Polynomial must be a cubic!")))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_tschirnhaus-3-2 (poly) "Tschirnhaus transformation (wipe out the power 2 term of a degree 3 polynomial) If $p(x)=ax^3+bx^2+cx+d$, then substitute $t=\frac{b}{3a}$." (mjr_poly_simplify (mjr_poly_subst (vector 1 (/ (mjr_poly_coeff poly 2) (* -3 (mjr_poly_coeff poly 3)))) poly))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_discriminant-low-degree (poly) "Return discriminant of a non-linear, small degree (<=5) polynomial via a direct formula" ;; Maxima Code to compute discriminant ;; degree(f,x) := hipow(f,x)$ ;; discriminant(f,x) := block([n:degree(f,x),fp,d,an], ;; fp : diff(f,x), ;; an : coeff(f,x,n), ;; w : mod(n,4), ;; w : w*(w-1)/2, ;; d : (-1)^w/an, ;; d : d*resultant(f,fp,x) ;; )$ (let* ((cpoly (mjr_poly_simplify poly)) (deg (1- (length poly))) (f (mjr_poly_coeff cpoly 5)) (e (mjr_poly_coeff cpoly 4)) (d (mjr_poly_coeff cpoly 3)) (c (mjr_poly_coeff cpoly 2)) (b (mjr_poly_coeff cpoly 1)) (a (mjr_poly_coeff cpoly 0))) (case deg (5 (let* ((a2 (* a a)) (a3 (* a2 a)) (b2 (* b b)) (b3 (* b2 b)) (b4 (* b3 b)) (c2 (* c c)) (c3 (* c2 c)) (c4 (* c3 c)) (d2 (* d d)) (d3 (* d2 d)) (d4 (* d3 d)) (e2 (* e e)) (e3 (* e2 e)) (e4 (* e3 e)) (f2 (* f f)) (f3 (* f2 f))) ;; 3125*a^4*f^4-2500*a^3*b*e*f^3-3750*a^3*c*d*f^3+2000*a^2*b^2*d*f^3+2250*a^2*b*c^2*f^3-1600*a*b^3*c*f^3+256*b^5* ;; f^3+2000*a^3*c*e^2*f^2-50*a^2*b^2*e^2*f^2+2250*a^3*d^2*e*f^2-2050*a^2*b*c*d*e*f^2+160*a*b^3*d*e*f^2-900*a^2*c^3* ;; e*f^2+1020*a*b^2*c^2*e*f^2-192*b^4*c*e*f^2-900*a^2*b*d^3*f^2+825*a^2*c^2*d^2*f^2+560*a*b^2*c*d^2*f^2-128*b^4*d^2* ;; f^2-630*a*b*c^3*d*f^2+144*b^3*c^2*d*f^2+108*a*c^5*f^2-27*b^2*c^4*f^2-1600*a^3*d*e^3*f+160*a^2*b*c*e^3*f-36*a*b^3* ;; e^3*f+1020*a^2*b*d^2*e^2*f+560*a^2*c^2*d*e^2*f-746*a*b^2*c*d*e^2*f+144*b^4*d*e^2*f+24*a*b*c^3*e^2*f-6*b^3*c^2*e^2* ;; f-630*a^2*c*d^3*e*f+24*a*b^2*d^3*e*f+356*a*b*c^2*d^2*e*f-80*b^3*c*d^2*e*f-72*a*c^4*d*e*f+18*b^2*c^3*d*e*f+108*a^2* ;; d^5*f-72*a*b*c*d^4*f+16*b^3*d^4*f+16*a*c^3*d^3*f-4*b^2*c^2*d^3*f+256*a^3*e^5-192*a^2*b*d*e^4-128*a^2*c^2*e^4+144*a* ;; b^2*c*e^4-27*b^4*e^4+144*a^2*c*d^2*e^3-6*a*b^2*d^2*e^3-80*a*b*c^2*d*e^3+18*b^3*c*d*e^3+16*a*c^4*e^3-4*b^2*c^3*e^3- ;; 27*a^2*d^4*e^2+18*a*b*c*d^3*e^2-4*b^3*d^3*e^2-4*a*c^3*d^2*e^2+b^2*c^2*d^2*e^2 (+ (* -3750 c d a3 f3) (* -2500 b e a3 f3) (* -2050 b c d e a2 f2) (* -1600 a c b3 f3) (* -1600 d f a3 e3) (* -900 b a2 d3 f2) (* -900 e a2 c3 f2) (* -746 a c d f b2 e2) (* -630 a b d c3 f2) (* -630 c e f a2 d3) (* -192 b d a2 e4) (* -192 c e b4 f2) (* -128 a2 c2 e4) (* -128 b4 d2 f2) (* -80 a b d c2 e3) (* -80 c e f b3 d2) (* -72 a b c f d4) (* -72 a d e f c4) (* -50 a2 b2 e2 f2) (* -36 a f b3 e3) (* -27 a2 d4 e2) (* -27 b2 c4 f2) (* -27 b4 e4) (* -6 a b2 d2 e3) (* -6 f b3 c2 e2) (* -4 a c3 d2 e2) (* -4 f b2 c2 d3) (* -4 b2 c3 e3) (* -4 b3 d3 e2) (* 16 a f c3 d3) (* 16 a c4 e3) (* 16 f b3 d4) (* 18 a b c d3 e2) (* 18 c d b3 e3) (* 18 d e f b2 c3) (* 24 a b f c3 e2) (* 24 a e f b2 d3) (* 108 a c4 c f2) (* 108 f a2 d4 d) (* 144 a c b2 e4) (* 144 c a2 d2 e3) (* 144 d f b4 e2) (* 144 d b3 c2 f2) (* 160 a d e b3 f2) (* 160 b c f a2 e3) (* 256 a3 e4 e) (* 256 b4 b f3) (* 356 a b e f c2 d2) (* 560 a c b2 d2 f2) (* 560 d f a2 c2 e2) (* 825 a2 c2 d2 f2) (* 1020 a e b2 c2 f2) (* 1020 b f a2 d2 e2) (* 2000 c a3 e2 f2) (* 2000 d a2 b2 f3) (* 2250 b a2 c2 f3) (* 2250 e a3 d2 f2) (* 3125 a3 a f3 f) (* b2 c2 d2 e2)))) (4 (let* ((a2 (* a a)) (b2 (* b b)) (b3 (* b2 b)) (c2 (* c c)) (c3 (* c2 c)) (d2 (* d d)) (d3 (* d2 d)) (e2 (* e e))) ;; 256*a^3*e^3-192*a^2*b*d*e^2-128*a^2*c^2*e^2+144*a*b^2*c*e^2-27*b^4*e^2+144*a^2*c*d^2*e-6*a*b^2*d^2*e-80*a*b*c^2*d*e+ ;; 18*b^3*c*d*e+16*a*c^4*e-4*b^2*c^3*e-27*a^2*d^4+18*a*b*c*d^3-4*b^3*d^3-4*a*c^3*d^2+b^2*c^2*d^2 (+ (* -192 b d a2 e2) (* -128 a2 c2 e2) (* -80 a b d e c2) (* -27 a2 d3 d) (* -27 b3 b e2) (* -6 a e b2 d2) (* -4 a c3 d2) (* -4 e b2 c3) (* -4 b3 d3) (* 16 a e c3 c) (* 18 a b c d3) (* 18 c d e b3) (* 144 a c b2 e2) (* 144 c e a2 d2) (* 256 a2 a e2 e) (* b2 c2 d2)))) (3 (let* ((b2 (* b b)) (c2 (* c c))) ;; -27*a^2*d^2-(4*b^3-18*a*b*c)*d-4*a*c^3+b^2*c^2 (+ (* -27 a a d d) (* -4 a c2 c) (* 18 a b c d) (* -4 b2 b d) (* b2 c2)))) (2 (let ((b2 (* b b))) ;; b^2-4*a*c (- b2 (* 4 a c)))) (otherwise (error "mjr_poly_discriminant-low-degree: Only polynomials of degree 2, 3, 4, and 5 are supported!"))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_resultant (poly1 poly2) "Return resultant the two polynomials via a recursive GCD-like computation." (labels ((resultant (poly1 poly2) (let ((deg1 (mjr_poly_degree poly1)) (deg2 (mjr_poly_degree poly2))) (if (> deg1 deg2) (mjr_poly_* (if (evenp (* deg1 deg2)) 1 -1) (mjr_poly_resultant poly2 poly1)) (let ((lc (mjr_poly_leading-coeff poly1))) (if (zerop deg1) (vector (expt lc deg2)) (let ((r (mjr_poly_rem poly2 poly1))) (if (mjr_poly_zerop r) (vector 0) (mjr_poly_* (expt lc (- deg2 (mjr_poly_degree r))) (mjr_poly_resultant poly1 r)))))))))) (mjr_poly_leading-coeff (resultant poly1 poly2)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_discriminant-high-degree (poly) "Return discriminant of a non-linear polynomial via a recursive resultant computation." (let ((pdeg (mjr_poly_degree poly))) (* (if (evenp (/ (* pdeg (1- pdeg)) 2)) 1 -1) (/ (mjr_poly_leading-coeff poly)) (mjr_poly_resultant poly (mjr_poly_diff poly))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_discriminant (poly) "Return discriminant of a non-linear polynomial using the most efficient method available." (if (> (mjr_poly_degree poly) 4) (mjr_poly_discriminant-high-degree poly) (mjr_poly_discriminant-low-degree poly))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_factor-square-free (poly) "Return the square-free factorization of POLY as an assoc array with (poly . power). Any factors equal to $1$ are not in the returned list. If the input polynomial is $p\\in\\mathbb{Q}[x]$, then a square-free factorization is $$p=c\\prod_{j=1}^nu_j^j$$ Where $u_j\\in\\mathbb{Q}[x]$, $u^j \\vert p$, and $u^{(j+1)} \\nmid p$. References: <NAME> (2012); Algebra for Symbolic Computation; ISBN: 978-88-470-2396-3; pp 108-109" ;; MJR TODO NOTE mjr_poly_factor-square-free: Add reference to Wikipedia and Cohen. ;; MJR TODO NOTE mjr_poly_factor-square-free: Replace with Yun's algorithm, use this for regression tests. See: http://en.wikipedia.org/wiki/Square-free_polynomial#Yun.27s_algorithm ;; MJR TODO NOTE mjr_poly_factor-square-free: Implement finite field version of this for polygfp. (loop with d = (mjr_poly_gcd poly (mjr_poly_diff poly)) with v = (mjr_poly_truncate poly d) with w = (mjr_poly_diff v) with z = (mjr_poly_truncate (mjr_poly_diff poly) d) for j from 1 upto (mjr_poly_degree poly) for uj = (mjr_poly_gcd v (mjr_poly_- z (mjr_poly_* j w))) when (not (mjr_poly_onep uj)) collect (cons uj j))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_factor-irreducible (poly &key show-progress) "Return the irreducible factorization of POLY as an assoc array with (poly . power). VERY SLOW. Uses kronecker's method." ;; MJR TODO NOTE mjr_poly_factor-irreducible: Implement a modern method, and use this for regression tests. (loop with poly-left = poly with d = 1 with pdeg = (mjr_poly_degree poly) for (f pl) = (multiple-value-list (mjr_poly_find-integer-factor poly-left d)) if f collect (let ((daPow (1+ (loop initially (setf poly-left pl) for v = (mjr_poly_divides? f poly-left) while v count (setf poly-left v))))) (if show-progress (format 't "left: ~5d deg: ~5d pow: ~5d factor: ~30a~%" (mjr_poly_degree poly-left) d daPow f )) (cons f daPow)) else do (if show-progress (format 't "left: ~5d deg: ~5d pow: 0 factor: DONE~%" (mjr_poly_degree poly-left) d)) and do (incf d) until (mjr_poly_onep poly-left) until (>= d pdeg))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_mahler-measure (poly &optional (method-class :solve) (method-function #'mjr_poly_root-solve-search-deflate) method-args) "Compute the Mahler measure of the polynomial POLY The optional arguments to determine how the computation is preformed: method-class method-function method-args :solve #'mjr_poly_root-solve-search-deflate nil <= DEFAULT :integrate #'mjr_intg_simple-gauss-kronrod '(:order 21) :integrate #'mjr_intg_simple-gauss-kronrod '(:order 31) :integrate #'mjr_intg_simple-gauss-legendre '(:order 20) :integrate #'mjr_intg_glb-adp-composite-romberg '(:the-err 1.0D-5) :integrate #'mjr_intg_glb-adp-composite-trapezoidal '(:the-err 1.0D-5) Definition Let $p\\in\\mathbb{C}[z]$ with $\\mathrm{deg}(p)=d$. For definiteness, we express $p$ like so: $$p(z)=\\sum_{j=0}^d a_jx^j = a_d\\prod_{j=1}^d (z-\\alpha_j)$$ We then define the Mahler measure to be: $$M(p) = \\vert a_d\\vert\\prod_{\\vert\\alpha_j\\vert\\geq1} \\vert\\alpha_j\\vert = \\exp\\left(\\frac{1}{2\\pi}\\int_0^{2\\pi}\\ln(\\vert p(e^{i\\theta})\\vert)\\,\\mathrm{d}\\theta\\right)$$ Examples: * (mahler-measure #(1 1 0 -1 -1 -1 -1 -1 0 1 1) :integrate #'mjr_intg_simple-gauss-kronrod '(:order 21 )) => 1.4751609391661360d0 * (mahler-measure #(1 1 0 -1 -1 -1 -1 -1 0 1 1) :integrate #'mjr_intg_simple-gauss-kronrod '(:order 31 )) => 0.7012142844290665d0 * (mahler-measure #(1 1 0 -1 -1 -1 -1 -1 0 1 1) :integrate #'mjr_intg_simple-gauss-legendre '(:order 20 )) => 1.0601232234056748d0 * (mahler-measure #(1 1 0 -1 -1 -1 -1 -1 0 1 1) :integrate #'mjr_intg_glb-adp-composite-romberg '(:the-err 1.0D-5)) => 1.1762811031170224d0 * (mahler-measure #(1 1 0 -1 -1 -1 -1 -1 0 1 1) :integrate #'mjr_intg_glb-adp-composite-trapezoidal '(:the-err 1.0D-5)) => 1.1762806954644658d0 * (mahler-measure #(1 1 0 -1 -1 -1 -1 -1 0 1 1) :solve #'mjr_poly_root-solve-search-deflate '( )) => 1.1762808182599178d0" (case method-class (:solve (let* ((roots (mapcar (lambda (x) (max 1 (abs x))) (apply method-function poly method-args))) (numr (length roots))) (if (= numr (mjr_poly_degree poly)) (reduce #'* roots) (error "mahler-measure: Could not find all roots. Found ~d" numr)))) (:integrate (exp (/ (apply method-function (lambda (x) (log (abs (mjr_poly_eval poly (complex (cos x) (sin x)))))) :start 0.0D0 :end (* 2.0d0 pi) method-args) (* 2 pi)))) (otherwise (error "mahler-measure: method-class unsupported"))))
true
;; -*- Mode:Lisp; Syntax:ANSI-Common-LISP; Coding:us-ascii-unix; fill-column:158 -*- ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; ;; @file use-poly.lisp ;; @author PI:NAME:<NAME>END_PI <https://www.mitchr.me> ;; @brief Polynomials over complex, real, rational, and integers.@EOL ;; @std Common Lisp ;; @see tst-poly.lisp ;; @copyright ;; @parblock ;; Copyright (c) 1994,1997,1998,2004,2008,2012,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 ;; @todo mjr_poly_root-solve-search-deflate: Want generic way to specifiy search, refine, and xform methods.@EOL@EOL ;; @todo Make some kind of convention for the type (int, gausian, float, complex, etc...) of polynomials a function works with.@EOL@EOL ;; @todo Better way to find solutions that are in radical extension fields -- i.e. $a,b,c\in\mathbb{Q}$ but $a+b\sqrt{c}\not\in\mathbb{Q}$.@EOL@EOL ;; @todo Better control/seporation/deliniation of Z[x], Q[x], & R[x] across functions. Make this uniform.@EOL@EOL ;; @todo Update unit tests for new functionality.@EOL@EOL ;; @todo mjr_poly_decompose.@EOL@EOL ;; @todo mjr_poly_factor-irreducible.@EOL@EOL ;; @todo mjr_poly_root-solve-jenkins-traub.@EOL@EOL ;; @todo mjr_poly_root-solve-continued-fraction.@EOL@EOL ;; @todo mjr_poly_root-solve-descartes-bisection.@EOL@EOL ;; @todo mjr_poly_root-separate-real.@EOL@EOL ;; @warning Much of this code has become quite experimental! Use the old version if you want to be carefull.@EOL@EOL ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defpackage :MJR_POLY (:USE :COMMON-LISP :MJR_NLEQ :MJR_NUMU :MJR_CMP :MJR_CHK :MJR_PRIME :MJR_VEC :MJR_PRNG :MJR_COMBE :MJR_INTRP :MJR_COMBC :MJR_VVEC :MJR_GPOLY :MJR_EPS) (:DOCUMENTATION "Brief: Univariate Polynomials over R or C.;") (:EXPORT #:mjr_poly_help ;; Autogenerated from #:mjr_gpoly #:mjr_poly_coeff #:mjr_poly_diff #:mjr_poly_- #:mjr_poly_+ #:mjr_poly_* #:mjr_poly_iexpt #:mjr_poly_scale #:mjr_poly_truncate #:mjr_poly_rem #:mjr_poly_mod #:mjr_poly_divides? #:mjr_poly_gcd #:mjr_poly_degree #:mjr_poly_leading-coeff #:mjr_poly_constant-coeff #:mjr_poly_zerop #:mjr_poly_onep #:mjr_poly_constantp #:mjr_poly_simplify #:mjr_poly_eval #:mjr_poly_subst #:mjr_poly_density #:mjr_poly_index ;; Implemented here.. #:mjr_poly_imul #:mjr_poly_count-sign-changes #:mjr_poly_print #:mjr_poly_code #:mjr_poly_intg #:mjr_poly_gcd-primitive ;; Polynomial metrics #:mjr_poly_height #:mjr_poly_length #:mjr_poly_mahler-measure #:mjr_poly_scount-descartes #:mjr_poly_scount-sturm #:mjr_poly_scount-fourier #:mjr_poly_scount-budan #:mjr_poly_root-structure #:mjr_poly_root-structure-print #:mjr_poly_root-count-distinct-real #:mjr_poly_root-count-distinct-interval #:mjr_poly_root-count-distinct-negative-zero-positive #:mjr_poly_root-bound-all #:mjr_poly_root-bound-positive #:mjr_poly_root-bound-all-cauchy #:mjr_poly_eval-poly-and-first-n-derivatives #:mjr_poly_2func #:mjr_poly_seq-eval #:mjr_poly_root-separate-real #:mjr_poly_root-solve-rational #:mjr_poly_root-solve-search-deflate #:mjr_poly_root-solve-low-degree #:mjr_poly_2square-free #:mjr_poly_2primitive #:mjr_poly_2monic #:mjr_poly_root-search-bsect #:mjr_poly_root-search-newton #:mjr_poly_root-search-laguerre #:mjr_poly_root-search-largest-real #:mjr_poly_root-separate-largest-real #:mjr_poly_make-from-roots ;; Make special polynomials #:mjr_poly_make-lagrange #:mjr_poly_make-chebyshev #:mjr_poly_make-legendre #:mjr_poly_make-bernstein #:mjr_poly_make-hermite #:mjr_poly_make-laguerre ;; Make sequences of polynomials #:mjr_poly_seq-make-lagrange #:mjr_poly_seq-make-chebyshev #:mjr_poly_seq-make-legendre #:mjr_poly_seq-make-bernstein #:mjr_poly_seq-make-hermite #:mjr_poly_seq-make-laguerre #:mjr_poly_seq-make-fourier #:mjr_poly_seq-make-sturm-canonical #:mjr_poly_deflate #:mjr_poly_shift #:mjr_poly_reflect #:mjr_poly_zap-zero-roots ;; EXPERIMENTAL!!!! #:mjr_poly_test-property #:mjr_poly_find-integer-factor #:mjr_poly_factor-over-integers ;; MORE EXPERIMENTAL!!!! #:mjr_poly_cubic-depress #:mjr_poly_tschirnhaus-3-2 #:mjr_poly_resultant #:mjr_poly_discriminant-low-degree #:mjr_poly_discriminant-high-degree #:mjr_poly_discriminant #:mjr_poly_factor-square-free #:mjr_poly_factor-irreducible #:mjr_poly_content #:mjr_poly_primitive-part #:mjr_poly_rationalize )) (in-package :MJR_POLY) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_help () "Univariate, Dense Polynomial Library Polynomials are represented as vectors containing the coefficients -- the position in the array implies the power of the monomial in the term to which the coefficient belongs. For example, x^2+4 would be represented as #(1 0 4). The first coefficient should never be zero unless the polynomial is the zero polynomial. No function in this package should ever produce a non-constant polynomial with a zero in the first position; however, all functions will gladly accept such polynomials and silently fix them. Note that while this vector representation is quite adequate for dense polynomials (i.e. polynomials that have mostly non-zero coefficients), this data structure is inefficient in both space and time for sparse polynomials. This library is a work in progress, but it has enough functionality to be useful. Still, some care should be exercised when using it. Tags: (G) means the function is provided by GPOLY and a (!) means the function is not yet implemented. Function names have been abbreviated in this list by replacing 'mjr_poly_' with 'MP_'. * Strings & Printing ** MP_print MP_code * Evaluation ** MP_eval(G) MP_eval-poly-and-first-n-derivatives MP_seq-eval * Arithmetic ** MP_+(G) MP_-(G) MP_*(G) MP_iexpt(G) MP_rem(G) MP_mod(G) MP_truncate(G) MP_gcd(G) MP_gcd-primitive MP_imul MP_divides?(G) * Coefficient access ** MP_coeff(G) MP_leading-coeff(G) MP_constant-coeff(G) * Recognizing special polynomials ** MP_onep(G) MP_constantp(G) MP_zerop(G) * Polynomial factorization ** MP_decompose(!) MP_factor-square-free MP_factor-irreducible(!) * Things we do with roots: ** MP_root-structure ** Solve polynomial (find all roots): *** MP_root-solve-integer MP_root-solve-rational MP_root-solve-low-degree MP_root-solve-search-deflate *** MP_root-solve-jenkins-traub(!) MP_root-solve-continued-fraction(!) MP_root-solve-descartes-bisection(!) ** Finding roots: *** MP_root-search-bsect MP_root-search-laguerre MP_root-search-newton MP_root-search-largest-real *** MP_root-search-max-magnitude ** Bounding roots: *** MP_root-bound-all MP_root-bound-positive ** Separating roots (a root is 'separated' by finding an interval that contains it but no other roots): *** MP_root-separate-largest-real MP_root-separate-real(!) ** Counting distinct roots *** MP_root-count-distinct-real MP_root-count-distinct-interval MP_root-count-distinct-positive * Construct sequences of polynomials ** MP_seq-make-fourier MP_seq-make-sturm-canonical MP_seq-make-chebyshev MP_seq-make-legendre MP_seq-make-lagrange MP_seq-make-bernstein MP_seq-make-hermite MP_seq-make-laguerre * Construct polynomials ** MP_make-chebyshev MP_make-legendre MP_make-lagrange MP_make-bernstein MP_make-hermite MP_make-laguerre * Polynomial metrics ** Sign change based *** MP_scount-descartes MP_scount-sturm MP_scount-fourier MP_scount-budan ** Other *** MP_height MP_length MP_density(G) MP_index(G) MP_degree(G) MP_discriminant-low-degree MP_discriminant-high-degree MP_discriminant MP_content MP_mahler-measure * Other Stuff ** mjr_poly_resultant * Polynomial xforms ** MP_deflate MP_shift MP_reflect MP_diff(G) MP_intg MP_subst(G) MP_zap-zero-roots MP_2square-free MP_2primitive MP_simplify(G) MP_scale(G) MP_rationalize ** MP_cubic-depress mjr_poly_tschirnhaus-3-2" (documentation 'mjr_poly_help 'function)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (mjr_gpoly_make-coeff "") (mjr_gpoly_make-simplify "") (mjr_gpoly_make-scale "") (mjr_gpoly_make-diff "") (mjr_gpoly_make-eval "") (mjr_gpoly_make-+ "") (mjr_gpoly_make-- "") (mjr_gpoly_make-* "") (mjr_gpoly_make-iexpt "") (mjr_gpoly_make-subst "") (mjr_gpoly_make-leading-coeff "") (mjr_gpoly_make-degree "") (mjr_gpoly_make-density "") (mjr_gpoly_make-index "") (mjr_gpoly_make-constant-coeff "") (mjr_gpoly_make-truncate "") (mjr_gpoly_make-rem "") (mjr_gpoly_make-mod "") (mjr_gpoly_make-onep "") (mjr_gpoly_make-zerop "") (mjr_gpoly_make-constantp "") (mjr_gpoly_make-divides? "") (mjr_gpoly_make-gcd "") ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_print (poly &key (var "x") (add-op "+") (add-apad " ") (add-bpad " ") (expt-op "^") (expt-apad "") (expt-bpad "") (mul-op "*") (mul-apad "") (mul-bpad "") (cof-fmt "~s") (cof-bpad "") (cof-apad "") (pow-fmt "~d") (pow-bpad "") (pow-apad "") (ply-apad "") (ply-bpad "") (suppress-zero-terms 't) (suppress-unit-expt 't) (suppress-unit-prod 't) (suppress-zero-powers 't) (return-string nil)) "Print a polynomial. Return POLY. Arguments: - return-string .......... If non-NIL, then do not print but return a string rep of POLY with no following newline. If NIL, then print POLY with a following newline, and return POLY - var .................... variable to use (a string) - add-op ................. string to print for + signs - add-bpad ............... string to print before + signs - add-apad ............... string to print after + signs - cof-fmt ................ format string for coefficients - cof-bpad ............... string to print before coefficients - cof-apad ............... string to print after coefficients - pow-fmt ................ format string powers - pow-bpad ............... string to print before powers - pow-apad ............... string to print after powers - mul-op ................. string to print for * signs - mul-bpad ............... string to print before * signs - mul-apad ............... string to print after * signs - expt-op ................ string to print for ^ signs - expt-bpad .............. string to print before ^ signs - expt-apad .............. string to print after ^ signs - suppress-zero-terms .... do not print 0*x^n - suppress-unit-expt ..... do not print ^1 - suppress-unit-prod ..... do not print 1* - suppress-zero-powers ... do not print x^0" (let ((da-str (with-output-to-string (str-out) (if (vectorp poly) (let ((plen (length poly))) (if (< 0 plen) (loop with not-first-print = nil for power from (1- plen) downto 0 for term across poly initially (format str-out ply-bpad) finally (format str-out ply-apad) do (if (or (not suppress-zero-terms) (mjr_cmp_!=0 term) (and (= power 0) (not not-first-print))) (progn (if not-first-print (format str-out "~a~a~a" add-bpad add-op add-apad)) (if (or (not suppress-unit-prod) (mjr_cmp_!= 1 term) (zerop power)) (format str-out (concatenate 'string cof-bpad cof-fmt cof-apad) term)) (if (and (or (not suppress-unit-prod) (mjr_cmp_!= 1 term)) (or (not suppress-zero-powers) (not (zerop power)))) (format str-out "~a~a~a" mul-bpad mul-op mul-apad)) (if (or (not suppress-zero-powers) (not (zerop power))) (progn (format str-out "~a" var) (if (or (not suppress-unit-expt) (not (= 1 power))) (progn (format str-out "~a~a~a" expt-bpad expt-op expt-apad) (format str-out (concatenate 'string pow-bpad pow-fmt pow-apad) power))))) (setq not-first-print 't)))))))))) (if return-string (if (vectorp poly) da-str) (progn (if (vectorp poly) (format 't "~a~%" da-str)) poly)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_code (poly &key (lang :lang-matlab)) "Return a string using the syntax of the selected programming language or computational environment." (if (not (vectorp poly)) (error "mjr_poly_code: Argument must be a polynomial (a vector)!")) (with-output-to-string (str-out) (flet ((gpp (&key (var "x") (add-op "+") (add-apad "") (add-bpad "") (expt-op "^") (expt-apad "") (expt-bpad "") (mul-op "*") (mul-apad "") (mul-bpad "") (cof-bpad "") (cof-apad "") (pow-bpad "") (pow-apad "") (ply-apad "") (ply-bpad "")) (loop with plen = (length poly) for not-first-print = nil then 't for power from (1- plen) downto 0 for term across poly initially (format str-out ply-bpad) finally (format str-out ply-apad) when not-first-print do (format str-out "~a~a~a" add-bpad add-op add-apad) do (progn (format str-out "~a~a~a~a" cof-bpad (mjr_numu_code term :lang lang) cof-apad cof-bpad) (if (not (zerop power)) (format str-out "~a~a~a~a~a~a~a~a~a~a" mul-bpad mul-op mul-apad var pow-bpad expt-bpad expt-op expt-apad (mjr_numu_code power :lang lang) pow-apad)))))) (case lang ((:lang-povray :lang-matlab :lang-octave :lang-idl :lang-r :lang-hp48 :lang-mathematica :lang-maple :lang-maxima) (gpp)) ((:lang-latex :lang-pdflatex :lang-amstex :lang-tex) (gpp :ply-bpad "$$" :ply-apad "$$" :mul-op " " :pow-bpad "{" :pow-apad "}")) ((:lang-lisp) (progn (format str-out "(+") (loop for power from (1- (length poly)) downto 0 for term across poly do (if (mjr_cmp_!=0 term) (let ((tstr (if (or (mjr_cmp_!= 1 term) (zerop power)) (format nil " ~a" term))) (vstr (if (not (zerop power)) (if (= 1 power) (format nil " x") (format nil " (expt x ~a)" power))))) (if (and tstr vstr) (format str-out " (*~a~a)" tstr vstr) (format str-out "~a" (or tstr vstr)))))) (format str-out ")"))) ('t (error "mjr_poly_code: Language unsupported!")))) str-out)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_intg (poly a b) "Integrate over the interval $[a,b]$." (let* ((poly (mjr_poly_simplify poly)) (plen (length poly)) (ipoly (make-array (1+ plen) :initial-element 0))) (loop for i from 0 upto (1- plen) do (setf (aref ipoly i) (/ (aref poly i) (- plen i)))) (- (mjr_poly_eval ipoly b) (mjr_poly_eval ipoly a)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_zap-zero-roots (poly &optional eps) "Return two values: 1) a new polynomial, $\\text{POLY}/x^n$, where $n$ is the number of times $0$ is a root of POLY, and 2) $n$. EPS is used with mjr_cmp_!=0 to detect non-zero coefficients." (let* ((plen (length poly)) (zcnt (loop for i from (1- plen) downto 0 for ip = (aref poly i) until (mjr_cmp_!=0 ip eps) count 1)) (slim (- plen zcnt))) (values (if (zerop slim) #(1) (subseq poly 0 slim)) zcnt))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_deflate (poly const) "Return the quotient and the remainder from POLY / (X - CONST). Note: The remainder is equal to POLY(CONST). While the result is equivalent to (MJR_POLY_TRUNCATE POLY (VECTOR 1 (- CONST))), this function is faster." (cond ((not (numberp const)) (error "mjr_poly_eval: CONST must be a number!"))) (let* ((poly (mjr_poly_simplify poly)) (plen (length poly)) (polyval 0) (newpoly (mjr_vec_make-const (max 1 (1- plen))))) (loop for i from 0 upto (1- plen) for ht = (+ (* const polyval) (aref poly i)) do (setq polyval ht) when (not (= i (1- plen))) do (setf (aref newpoly i) ht) finally (return (values newpoly polyval))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_shift (b poly) "Shift POLY right B units (or left if B is negative). References: ;; MJR TODO NOTE <2011-11-23 13:07:23 CST> mjr_poly_shift: Add a reference here. The algorithm is the 'fast taylor shift'. The pink book or sure. Perhaps Prasolov too..." (let ((new-poly (mjr_poly_simplify (copy-seq poly))) (b (- b))) (mjr_poly_simplify (dotimes (i (length new-poly) new-poly) (loop for k from i downto 1 do (incf (aref new-poly k) (* b (aref new-poly (1- k))))))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_reflect (poly) "Reflect POLY across the Y-axis (i.e. subst -x)." (let ((new-poly (mjr_poly_simplify (copy-seq poly)))) (loop for cur-coef across poly for odd-pow = (not (oddp (length poly))) then (not odd-pow) for i from 0 when odd-pow do (setf (aref new-poly i) (- cur-coef)) finally (return (mjr_poly_simplify new-poly))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_make-from-roots (&rest the-roots) "Return the the monic polynomial with the given roots. The roots may be given as individual arguments, or a single list may be provided." (let ((the-roots (if (and (car the-roots) (listp (car the-roots))) (car the-roots) the-roots))) (let* ((n (length the-roots)) (a-lst (make-array (1+ n) :initial-element 0)) (a-nxt (make-array (1+ n) :initial-element 0))) (loop initially (setf (aref a-lst n) (- (car the-roots))) for k from 1 upto (1- n) for zk in (cdr the-roots) do (loop initially (setf (aref a-nxt (- n k)) (- (aref a-lst (- n (1- k))) zk)) for j from 1 upto (1- k) do (setf (aref a-nxt (- n j)) (- (aref a-lst (1+ (- n j))) (* zk (aref a-lst (- n j))))) finally (setf (aref a-nxt n) (* (- zk) (aref a-lst n)))) do (rotatef a-lst a-nxt) finally (progn (setf (aref a-lst 0) 1))) a-lst))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_eval-nth-derivative (poly x &optional (order 1)) "Evaluate polynomial derivative." (mjr_poly_eval (mjr_poly_diff poly order) x)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_eval-poly-and-first-n-derivatives (poly x &optional (order 1)) "Return value of poly and the values of the first ORDER derivatives at x. Algorithm due to Pankiewicz: PI:NAME:<NAME>END_PI (1968); Algorithm 337: calculation of a polynomial and its derivative values by Horner scheme; Communications of the ACM; Vol 11, Issue 9, pp 633" (let* ((len-1 (1- (length poly))) (odr-1 order) (pd (make-array (1+ order) :initial-element 0))) (loop for i from (1- len-1) downto 0 for nnd = (min odr-1 (- len-1 i)) initially (setf (aref pd 0) (aref poly 0)) do (loop for j from nnd downto 1 do (setf (aref pd j) (+ (* (aref pd j) x) (aref pd (1- j))))) do (setf (aref pd 0) (+ (* (aref pd 0) x) (aref poly (- len-1 i))))) (loop with cnst = 1 for i from 2 upto odr-1 do (setf cnst (* cnst i)) do (setf (aref pd i) (* (aref pd i) cnst))) (values-list (concatenate 'list pd)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_2func (poly &optional num-derivatives) "Return a function that evaluates the POLY and its first NUM-DERIVATIVES." (if (and num-derivatives (> num-derivatives 0)) (eval `(lambda (x) (mjr_poly_eval-poly-and-first-n-derivatives ,poly x ,num-derivatives))) (eval `(lambda (x) (mjr_poly_eval ,poly x))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_seq-eval (seq x &optional result-type) "Evaluate the polynomials in the sequence (list or vector) at $x$, and return the results in a sequence. If result-type is NIL, then the returned type will be the same as the type of seq." (map (or result-type (if (vectorp seq) 'vector 'list)) (lambda (p) (mjr_poly_eval p x)) seq)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_height (poly) "This is the infinity-norm (maximum absolute value of coefficients)" (mjr_vec_norm-infinity poly)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_length (poly) "This is the one-norm (sum of absolute values of coefficients)" (mjr_vec_norm-one poly)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_2square-free (p) "Return a new polynomial with the same roots as poly, but with no multiple roots." (mjr_poly_truncate p (mjr_poly_gcd p (mjr_poly_diff p)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_2monic (poly) "Transform POLY, via multiplication, into a monic polynomial that shares the roots of the original." (mjr_vec_/ poly (aref poly 0))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_rationalize (poly) "Transform POLY so that all coefficients are rational -- imaginary parts of coefficients too." (map 'vector (lambda (x) (if (complexp x) (complex (rationalize (realpart x)) (rationalize (imagpart x))) (rationalize x))) poly)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_content (poly) "Compute the content of an integer or rational polynomial. POLY is rationalized if necessary. If $p\\in\\mathbb{Z}[x]$, then the content is the GCD of the coefficients. If $p\\in\\mathbb{Q}[x], then the content is the GCD of the numerators divided by the LCM of the denominators. i.e. the content is the unique $q\\in\\mathbb{Q}$ such that $p/q$ is a primitive polynomial in $\\mathbb{Z}[x]$ -- all the coefficients are integers have have GCD of $1$." (let* ((poly (mjr_poly_simplify poly))) (cond ((every #'integerp poly) (reduce #'gcd poly)) ((every #'rationalp poly) (/ (apply #'gcd (map 'list #'numerator poly)) (apply #'lcm (map 'list #'denominator poly)))) ((some #'complexp poly) (error "mjr_poly_content: Polynomial must not be complex!")) ((every #'numberp poly) (mjr_poly_content (mjr_poly_rationalize poly))) ('t (error "mjr_poly_content: POLY is not a polynomial!"))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_primitive-part (poly) "Returns the primitive part of the polynomial and the content. Note: poly = cont(poly)*primitive-part(poly)" (let* ((poly (mjr_poly_simplify poly)) (c (mjr_poly_content poly))) (values (mjr_vec_/ poly c) c))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_2primitive (poly) "Transform POLY, via multiplication by a rational number, into an primitive polynomial that shares the roots of the original. The rational number used to transform POLY is the second return value. Results are exact if the polynomial has only integer and/or rational coefficients. A simple generalization of the idea of primitive is used when the polynomial has complex coefficients -- The real and imaginary parts will both be transformed to integers and the entire collection of integers (real parts and imaginary parts together) will not share a common factor other than one. Floating point numbers in the coefficients will be rationalized. The finite precision of floating point arithmetic implies that polynomials made up of floats, doubles, and long doubles are but a simple scalar product away from their integer doppelganger. Unfortunately the vulgarities of floating point arithmetic can destroy this almost-truth. Still, we do the best we can. NOTE: A polynomial $p(x)=\sum_{j=0}^na_jx^j\in\mathbb{Z}[x]$ is primitive if $\mathrm{GCD}(a_0,\cdots,a_n)=1$ -- i.e. the coefficients are relatively prime. Gauss's lemma: If $p$ and $q$ are primitive, then $p\cdot q$ primitive, and if a $p\in\mathbb{Z}[x]$ is irreducible over the $\mathbb{Z}$, then the same polynomial considered in $\mathbb{Q}[x]$ is also irreducible over $\mathbb{Q}$. References: PI:NAME:<NAME>END_PI(1801); Disquisitiones Arithmeticae; Article 42" (let* ((poly (mjr_poly_simplify poly)) (p1 (mjr_poly_rationalize poly)) (L (apply #'lcm (mapcar #'denominator (loop for coef across p1 collect (realpart coef) when (complexp coef) collect (imagpart coef))))) (p2 (mjr_vec_* p1 L)) (G (apply #'gcd (loop for coef across p2 collect (realpart coef) when (complexp coef) collect (imagpart coef)))) (p3 (mjr_vec_/ p2 G))) (values p3 (/ L G)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_seq-make-sturm-canonical (p) "Return a list of polynomials representing the 'Canonical Sturm sequence'. The canonical Sturm sequence of a polynomial $p$ is the intermediate results of Euclid's algorithm applied to to $p$ and $p'$: $$ \\begin{array}{lccclcl} p_0(x) & & & = & p(x) & & \\\\ p_1(x) & & & = & p'(x) & & \\\\ p_2(x) & & & = & -\\text{rem}(p_0, p_1) & = & p_1(x) \\cdot q_0(x) - p_0(x) \\\\ p_3(x) & & & = & -\\text{rem}(p_1, p_2) & = & p_2(x) \\cdot q_1(x) - p_1(x) \\\\ \\vdots & & & & & & \\\\ p_m & & & = & -\\text{rem}(p_{m-2}, p{m-1}) & = & p{m-1}(x) \\cdot q_{m-2}(x) - p_{m-2}(x) \\\\ p_{m+1} & = & 0 & = & -\\text{rem}(p_{m-1}, p_m) & & \\\\ \\end{array} $$ where $\\text{rem}(p_i,p_j)$ and $q_i$ are the remainder and the quotient of the polynomial long division of $p_i$ by $p_j$, and where $m\\le\\text{deg}{p}$ is the minimal number of polynomial divisions needed to obtain a zero remainder. Note: The sequence is well defined even when $p$ is not square-free; however, it may not be a Sturm sequence in this case. Confusingly enough, this sequence is always called the canonical Sturm sequence even when it is not really a Sturm sequence." (let ((pd (mjr_poly_diff p))) (nconc (list p pd) (loop for p-2 = p then p-1 for p-1 = pd then p-0 for p-0 = (mjr_poly_- (mjr_poly_rem p-2 p-1)) collect p-0 until (zerop (mjr_poly_degree p-0)))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_seq-make-fourier (p) "Return a list of polynomials representing the 'Fourier sequence'. Let $p$ be a real polynomial of degree $n>0$, then the Fourier sequence of $p$ is: $$F_\\text{seq}(x)=\\big\\{ p(x), p^{(1)}(x),\\ldots,p^{(n)}(x)\\big\\}$$" (loop for i from 0 upto (mjr_poly_degree p) for p-0 = p then (mjr_poly_diff p-0) collect p-0)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_count-sign-changes (seq) "Return the number of sign changes in seq (vector or list) -- zeros are ignored" (if (vectorp seq) (loop for cur-elt across seq for lst-sgn = nil then (if (zerop cur-sgn) lst-sgn cur-sgn) for (cur-sgn cur-amb) = (multiple-value-list (mjr_cmp_signum cur-elt)) count (and lst-sgn (not (zerop cur-sgn)) (not (= cur-sgn lst-sgn))) into count-sgn count cur-amb into count-amb finally (return (values count-sgn (if (not (zerop count-amb)) count-amb)))) (loop for cur-elt in seq for lst-sgn = nil then (if (zerop cur-sgn) lst-sgn cur-sgn) for (cur-sgn cur-amb) = (multiple-value-list (mjr_cmp_signum cur-elt)) count (and lst-sgn (not (zerop cur-sgn)) (not (= cur-sgn lst-sgn))) into count-sgn count cur-amb into count-amb finally (return (values count-sgn (if (not (zerop count-amb)) count-amb)))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_scount-sturm (p l r &optional sturm-sequence) "Compute the difference in the sign changes for $S(x+l)$ and $S(x+h)$ where S is the given Sturm sequence or the canonical one. The return will be the number of distinct real roots the polynomial has in the interval $(l,h]$ when: 1) sturm-sequence is NIL or the canonical Sturm sequence 2) when sturm-sequence is a valid Sturm sequence and $p$ is square-free. A Sturm sequence is a set of polynomials $p_0, p_1, \\dots, p_m\\in\\mathbb{R}[x]$ such that: \\begin{itemize} \\item $p_i$ are all polynomials \\item $m$ is a finite, non-negative integer \\item if $0\\ge i< j\\le m$ then $\\text{deg}(p_i)<\\text{deg}(p_j)$ \\item $p_0$ is square free (no repeated roots) \\item if $p(x_0)=0$, then $\\text{sign}(p_1(x_0))= \\text{sign}(p'(x_0))$ \\item if $p_i(\\xi)=0$ for $0<i<m$ then $\\text{sign}(p_{i-1}(\\xi))= -\\text{sign}(p_{i+1}(\\xi))$ \\item $p_m$ does not change its sign. \\end{itemize} Sturm's theorem\\\\ Let $p$ be a real, square-free polynomial of degree $n>0$ and $l,r\\in \\mathbb{R}$ with $l<r$. Let $S_\\text{seq}(x)=\\big\\{ p_0(x), p_1(x), ..., p_m(x)\\big\\}$ be a Sturm sequence with $p_0=p$. Let $v_l$ and $v_r$ be the sign variations in the sequences $S_\\text{seq}(l)$ and $S_\\text{seq}(r)$. Let $\\rho$ be the number of the real roots of $p$ in $(l,r]$. Let $v_\\delta=v_l - v_r$. Then we have $\\rho = v_\\delta$ Sturm's Canonical Sequence theorem\\\\ Let $p$ be a real polynomial of degree $n>0$ and $l,r\\in \\mathbb{R}$ with $l<r$ and neither $l$ or $r$ is a multiple root of $p$. Let $S_\\text{seq}(x)=\\big\\{ p_0(x), p_1(x), ..., p_m(x)\\big\\}$ be the canonical Sturm sequence of $p$. Let $v_l$ and $v_r$ be the sign variations in the sequences $S_\\text{seq}(l)$ and $S_\\text{seq}(r)$. Let $\\rho$ be the number of distinct real roots of $p$ in $(l,r]$. Let $v_\\delta=v_l - v_r$. Then we have $\\rho = v_\\delta$ References: PI:NAME:<NAME>END_PI(1829); Memoire sur la resolution des equations numeriques; Bulletin des Sciences de Ferussac 11; 419-425" ;; MJR TODO NOTE <2013-01-01 19:01:18 CST> mjr_poly_scount-sturm: Add refs (pink and blue polynomial books) (let ((ss (or sturm-sequence (mjr_poly_seq-make-sturm-canonical p)))) (- (mjr_poly_count-sign-changes (mjr_poly_seq-eval ss l)) (mjr_poly_count-sign-changes (mjr_poly_seq-eval ss r))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_scount-budan (p l h) "Compute the difference in the sign changes for $p(x+l)$ and $p(x+h)$ Budan's theorem:\\\\ Let $p\\in\\mathbb{R}[x]$ with degree $n>0$ and $l,r\\in \\mathbb{R}$ with $l<r$ and $p(r)\\ne0$. Let $v_l$ and $v_r$ be the sign variations in $p(x+l)$ and $p(x+r)$ respectively. Let $\\rho$ be the number of the real roots of $p$ in $(l,r)$. Let $v_\\delta=v_l - v_r$. \\begin{enumerate} \\item $v_l \\ge v_r$ \\item $\\rho \\le v_\\delta$ \\item if $\\rho < v_\\delta$, then $\\rho = v_\\delta -2\\lambda$ where $\\lambda \\in \\mathbb{Z}_+$ \\end{enumerate} References: PI:NAME:<NAME>END_PI (1807); Nouvelle methode pour la resolution des equations numeriques; Paris: Courcier" (if (not (mjr_chk_!=0 (mjr_poly_eval p h))) (warn "budan-count: Polynomial should not be zero on h if Budan's theorem is being used!")) (- (mjr_poly_count-sign-changes (mjr_poly_shift (- l) p)) (mjr_poly_count-sign-changes (mjr_poly_shift (- h) p)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_scount-fourier (p l h) "Compute the difference in the sign changes for $F(x+l)$ and $F(x+h)$ where F is the 'Fourier Sequence' for $p$ Fourier's theorem:\\\\ Let $p$ be a real polynomial of degree $n>0$ and $l,r\\in \\mathbb{R}$ with $l<r$ and $p(r)\\ne0$. Let $F_\\text{seq}(x)$ be the Fourier sequence of $p$. Let $v_l$ and $v_r$ be the sign variations in the sequences $F_\\text{seq}(l)$ and $F_\\text{seq}(r)$. Let $\\rho$ be the number of the real roots of $p$ in $(l,r)$. Let $v_\\delta=v_l - v_r$. \\begin{enumerate} \\item $v_l \\ge v_r$ \\item $\\rho \\le v_\\delta$ \\item if $\\rho < v_\\delta$, then $\\rho = v_\\delta -2\\lambda$ where $\\lambda \\in \\mathbb{Z}_+$ \\end{enumerate} References: PI:NAME:<NAME>END_PI (1820); Sur l'usage du theoreme de Descartes dans la recherche des limites des racines; Bulletin des Sciences, par la Societe Philomatique de Paris: 156-165 PI:NAME:<NAME>END_PI (2003); Polynomials (Problem Books in Mathematics); pp 174 PI:NAME:<NAME>END_PI (2004); Polynomials; ISBN: 3540407146; pp 27" (if (not (mjr_chk_!=0 (mjr_poly_eval p h))) (warn "fourier-count: Polynomial should not be zero on h if Budan's theorem is being used!")) (let ((d (mjr_poly_degree p))) (- (mjr_poly_count-sign-changes (multiple-value-list (mjr_poly_eval-poly-and-first-n-derivatives p l d))) (mjr_poly_count-sign-changes (multiple-value-list (mjr_poly_eval-poly-and-first-n-derivatives p h d)))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_scount-descartes (poly &optional (c 0)) "Apply Descartes rule of signs to the shifted polynomial. Four values returned: * Max number roots ($P$) to the right of $C$ -- Actual number will be $P-2\\cdot m$ where $m$ is a non-negative integer. * Exact number of roots ($Z$) at $C$ -- Computed from a direct analysis of the polynomial. * Max number of roots ($N$) to the left of $C$ -- Actual number will be $N-2\\cdot n$ where $n$ is a non-negative integer. * Number of ambiguous zeros, or nil -- This occurs when a value is assumed zero because it was small, but not zero Theorem (Descartes): Let $$p(x)=\\sum\\limits_{j=0}^n a_jx^j\\in\\mathbb{R}[x]$$ Let $P=\\sigma(p)$ and $N=\\sigma(p(-x))$ where the $\\sigma$ function is defined as the number of sign changes in the polynomial coefficients ignoring zero coefficients. Let $Z$ be the number of trailing zeros -- i.e. number of zero coefficients at the end of the polynomial. Then the polynomial $p$ has $P-2m$ positive roots, $Z$ zero roots, and $N-2n$ negative roots where $m$ and $n$ non-negative integers. References: PI:NAME:<NAME>END_PI (1637); La Geometrie (an appendix to Discours de la methode -- Discourse on Method) PI:NAME:<NAME>END_PI (1979); Geometry (a translation of La Geometrie) PI:NAME:<NAME>END_PI (1999); Descartes Rule of Signs: Another Construction; Amer. Math. Monthly 106, 854-855 PI:NAME:<NAME>END_PI (2004); Polynomials; ISBN: 3540407146; pp 28" (let* ((poly (if (zerop c) (mjr_poly_simplify poly) (mjr_poly_shift c poly))) (plen (length poly))) (cond ((< plen 2) (error "mjr_poly_scount-descartes: Polynomial must be at least degree 1!"))) (loop for cur-coef across poly for odd-pow = (not (oddp plen)) then (not odd-pow) for count=0 = 0 then (if (mjr_cmp_=0 cur-coef) (1+ count=0) 0) for lst-sign = nil then (if (zerop cur-sign) lst-sign cur-sign) for lst-sign-x = nil then (if (zerop cur-sign-x) lst-sign-x cur-sign-x) for (cur-sign cur-ambiguous) = (multiple-value-list (mjr_cmp_signum cur-coef)) for cur-sign-x = (if odd-pow (- cur-sign) cur-sign) count (and lst-sign (not (zerop cur-sign)) (not (= cur-sign lst-sign))) into count+x count (and lst-sign-x (not (zerop cur-sign-x)) (not (= cur-sign-x lst-sign-x))) into count-x count cur-ambiguous into count-ambiguous-zeros finally (return (values count+x count=0 count-x (if (not (zerop count-ambiguous-zeros)) count-ambiguous-zeros)))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_root-bound-positive (poly &key (algorithm :rb-lagrange)) "Return an upper bound (perhaps strict) on the positive real roots of POLY. Returns NIL if anything goes wrong." (let* ((poly (mjr_poly_simplify poly)) ;; MJR TODO NOTE <2013-01-01 18:59:12 CST> mjr_poly_root-bound-positive: Add references, formula, and notes that it is also a global bound... ;; MJR TODO NOTE <2013-01-01 18:59:47 CST> mjr_poly_root-bound-positive: Move into mjr_poly_root-bound-all???? (pdeg (mjr_poly_degree poly)) (pn (aref poly 0))) (if (mjr_chk_!=0 pn) (case algorithm (:rb-lagrange (and (> pdeg 0) (loop with max1 = nil with max2 = nil for j from 0 upto (1- pdeg) for pjr = (/ (aref poly (- pdeg j)) pn) when (< pjr 0) do (let ((pjv (expt (abs pjr) (/ (- pdeg j))))) (if (null max1) (setf max1 pjv) (if (> pjv max1) (rotatef max2 max1 max1 pjv) (if (or (null max2) (> pjv max2)) (setf max2 pjv))))) finally (return (and max1 max2 (+ max1 max2)))))) (otherwise (error "mjr_poly_root-bound-positive: Unknown algorithm!")))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_root-bound-all (poly &key (algorithm :rb-fujiwara)) "Return an upper bound (perhaps strict) on the modulus of the roots of POLY using the given algorithm If the test can not be performed because the polynomial violates a constraint of the algorithm, then NIL is returned. Note: $$P(z)=\\sum\\limits_{i=0}^n a_ix^i$$ The algorithm argument may be one of, or a list of, the following symbols: * :rb-fujiwara - 8.1.11 - Fujiwara (1916) - $$2\\max_{0\\le j\\le n-1}\\left|\\frac{a_j}{a_n}\\right|$$ * :rb-cauchy - 8.1.9 - Cauchy (1829, p122) - $$1+\\max_{0\\le j\\le n-1}\\left|\\frac{a_j}{a_n}\\right|$$ - M,M,R (1994, p224) - $$1+\\frac{1}{\\vert a_n\\vert}\\left(\\max\\limits_{ 0\\leq i\\leq n-1}\\vert a_i\\vert\\right)$$ * :rb-kojima - 8.1.17 - Kojima (1917) - $$\\max\\left\\{ \\left|\\frac{a_0}{a_1}\\right|, 2\\left|\\frac{a_1}{a_2}\\right|, \\cdots, 2\\left|\\frac{a_{n-1}}{a_n}\\right| \\right\\}$$ * :rb-hirst-macey - N/A - Hirst,Macey (1997) - $$ ? $$ * :rb-lagrange - N/A - Lagrange (????) - $$ ? $$ Not yet supported, but will be in a future version * :rb-carmichal - 8.1.12 - Carmichal (1918) - $$\\sum_{j=0}^{n-1}\\left(\\left|\\frac{a_j}{a_n}\\right|^\\frac{1}{n-j}\\right)$$ * :rb-westerfield - N/A - Westerfield (1931) - $$\\hat{M}+\\check{M}$$ where $\\hat{M}$ and $\\check{M}$ are the two largest elements of $$\\left\\{ \\left|\\frac{a_j}{a_n}\\right|^\\frac{1}{n-j} : j=0,...,{n-1}\\right\\}$$ References: Fujiwara (1916); Uber die obere Schranke des absoluten Betrages der Wurzeln einer algebraischen Gleichung; Tohoku Math J 10; p167-171 Kojima (1917); On the limits of the roots of an algebraic equation; Tohoku Math J 11; p119-127 Cauchy (1829); Exercises de mathematique. Oeuvres 2 (9) Milovanovic, MPI:NAME:<NAME>END_PIovic, PI:NAME:<NAME>END_PI (1994); Topics in polynomials: extremal problems, inequalities, zeros; ISBN: 981020499X PI:NAME:<NAME>END_PI & PI:NAME:<NAME>END_PI (1997); Bounding the roots of polynomials; Coll Math J 28 (4); pp292" ;; MJR TODO NOTE <2013-01-01 18:57:44 CST> mjr_poly_root-bound-all: IMPLEMENT :rb-carmichal and :rb-westerfield. ;; MJR TODO NOTE <2013-01-01 18:58:19 CST> mjr_poly_root-bound-all: Add refs for Carmichal and Westerfield. ;; MJR TODO NOTE <2013-01-01 18:58:37 CST> mjr_poly_root-bound-all: Add ref for blue polynomial book and/or blue computer algebra book. (let* ((poly (mjr_poly_simplify poly)) (pdeg (mjr_poly_degree poly)) (pn (aref poly 0))) (if (mjr_chk_!=0 pn) (flet ((cmpbnd (alg) (case alg (:rb-fujiwara (* 2 (max (expt (abs (/ (aref poly pdeg) pn)) (/ pdeg)) (loop for j from 1 upto (1- pdeg) maximize (expt (abs (/ (aref poly (- pdeg j)) pn)) (/ (- pdeg j))))))) (:rb-kojima (if (mjr_chk_!=0 (aref poly (1- pdeg))) (* 2 (max (* 1/2 (abs (/ (aref poly pdeg) (aref poly (1- pdeg))))) (loop for j from 1 upto (1- pdeg) for pj+1 = (aref poly (- pdeg (1+ j))) maximize (if (mjr_chk_!=0 pj+1) (abs (/ (aref poly (- pdeg j)) pj+1)) (return-from cmpbnd nil))))))) (:rb-cauchy (1+ (/ (loop for i from 1 upto pdeg maximize (abs (aref poly i))) (abs pn)))) (:rb-lagrange (mjr_poly_root-bound-positive poly :algorithm :rb-lagrange)) (:rb-hirst-macey (max 1 (loop for j from 0 upto (1- pdeg) for pj = (aref poly (- pdeg j)) maximize (if (mjr_chk_!=0 pj) (abs (/ pj pn)) (return-from cmpbnd nil))))) (otherwise (error "mjr_poly_root-bound-all: Unknown algorithm(~a)!" alg))))) (if (listp algorithm) (mapcar #'cmpbnd algorithm) (cmpbnd algorithm)))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_root-bound-all-cauchy (poly &key (xeps 0.0001) (yeps 0.0001) (max-itr 1000)) "Compute an approximation of the cauchy bound on the roots of the polynomial." (loop with soly = (mjr_poly_zap-zero-roots (mjr_poly_simplify poly)) with coly = (apply #'vector (loop for ai across soly for aai = (- (abs ai)) then (abs ai) collect aai)) with ubnd = (or (mjr_poly_root-bound-positive coly :algorithm :rb-lagrange) (mjr_poly_root-bound-all coly :algorithm :rb-fujiwara)) with x0 = 0 with x1 = ubnd with y0 = (mjr_poly_eval coly x0) with y1 = (mjr_poly_eval coly x1) for x-mid = (/ (+ x0 x1) 2) for y-mid = (mjr_poly_eval coly x-mid) for i-cur from 1 upto max-itr until (or (mjr_eps_= 0 y-mid yeps) (mjr_eps_= x0 x1 xeps) (mjr_eps_= x0 x-mid xeps) (mjr_eps_= x1 x-mid xeps) (mjr_eps_= y0 y1 yeps) (mjr_eps_= y0 y-mid yeps) (mjr_eps_= y1 y-mid yeps)) while (cond ((mjr_cmp_< y0 y1) (if (mjr_cmp_< y-mid 0) (setq x0 x-mid y0 y-mid) (setq x1 x-mid y1 y-mid))) ((mjr_cmp_> y0 y1) (if (mjr_cmp_< y-mid 0) (setq x1 x-mid y1 y-mid) (setq x0 x-mid y0 y-mid)))) finally (return x1))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_root-count-distinct-interval (p a b &optional eps) "Use mjr_poly_scount-sturm to compute the total number of distinct, real roots of the polynomial in $(a,b)$ If polynomial is zero at a or b, then those roots will be removed via deflation. If floating point comparisons are required to determine zeros at a and/or b, then eps will be used. Polynomial rationalization via mjr_poly_2primitive is recommended if floating point round-off is a problem." (if (mjr_chk_!=0 (mjr_poly_eval p a) eps) (if (mjr_chk_!=0 (mjr_poly_eval p b) eps) (mjr_poly_scount-sturm p a b) (mjr_poly_root-count-distinct-interval (mjr_poly_deflate p b) a b eps)) (mjr_poly_root-count-distinct-interval (mjr_poly_deflate p a) a b eps))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_root-count-distinct-negative-zero-positive (p &optional eps) "Use mjr_poly_scount-sturm to compute the total number of distinct, real roots of the polynomial in $(a,b)$ mjr_poly_zap-zero-roots and EPS are used to count zero roots (mjr_poly_2primitive is recommended)." (multiple-value-bind (poly nzr) (mjr_poly_zap-zero-roots p eps) (let ((u (ceiling (mjr_poly_root-bound-all poly))) (ss (mjr_poly_seq-make-sturm-canonical poly))) (values (mjr_poly_scount-sturm p (- -1 u) 0 ss) nzr (mjr_poly_scount-sturm p 0 (+ 1 u) ss))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_root-count-distinct-real (p) "Use mjr_poly_scount-sturm and mjr_poly_root-bound-all to compute the total number of distinct, real roots of the polynomial." (let ((u (ceiling (mjr_poly_root-bound-all p)))) (mjr_poly_scount-sturm p (- -1 u) (+ 1 u)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_root-structure (poly &optional use-sturm-sequence) "Return a list of vectors with each vector containing possible counts for negative, zero, positive, and complex roots for POLY." (let* ((poly (mjr_poly_simplify poly)) (num-roots (1- (length poly)))) (multiple-value-bind (max-pos-roots num-zero-roots max-neg-roots) (mjr_poly_scount-descartes poly) (multiple-value-bind (min-neg-roots num-zero-roots-s min-pos-roots) (if use-sturm-sequence (mjr_poly_root-count-distinct-negative-zero-positive poly) (values 0 nil 0)) (if (and num-zero-roots-s (not (= num-zero-roots-s num-zero-roots))) (error "mjr_poly_root-count-distinct-negative-zero-positive: Inconsistent zero root counts!")) ;;(format 't "~10d ~10d ~10d~%" max-pos-roots num-zero-roots max-neg-roots) ;;(format 't "~10d ~10d ~10d~%" min-pos-roots num-zero-roots-s min-neg-roots) (loop for num-not0-roots from (- num-roots num-zero-roots) downto (+ min-pos-roots min-neg-roots) by 2 append (loop for num-neg-roots from max-neg-roots downto min-neg-roots by 2 append (loop for num-pos-roots from max-pos-roots downto min-pos-roots by 2 for num-cmplx-roots = (- num-roots num-not0-roots num-zero-roots) when (and (<= 0 num-cmplx-roots) (= num-not0-roots (+ num-pos-roots num-neg-roots))) collect (vector num-neg-roots num-zero-roots num-pos-roots (- num-roots num-not0-roots num-zero-roots))))))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_root-structure-print (rstruct) "Print out all the list returned from mjr_poly_root-structure in a nice humanly readable table." (format 't " Negative Zero Positive Complex~%") (loop for cnts in rstruct do (format 't "~10d ~10d ~10d ~10d~%" (aref cnts 0) (aref cnts 1) (aref cnts 2) (aref cnts 3)) finally (return rstruct))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_root-solve-rational (poly &key only-integer-roots) "Find rational roots of a polynomial. Morally speaking this only works on a polynomials with integer coefficients; however, this function uses MJR_POLY_2PRIMITIVE to transform POLY into one with integer coefficients if required. Returns: * A list of found roots * The polynomial actually solved (we call this IPOLY) -- the first return of MJR_POLY_2PRIMITIVE on POLY * The logical factor required to transform POLY into IPOLY -- the second return of MJR_POLY_2PRIMITIVE on POLY * the result of deflating IPOLY with each root found" (cond ((not (vectorp poly)) (error "mjr_poly_root-solve-rational: POLY must be a vector")) ((not (every #'realp poly)) (error "mjr_poly_root-solve-rational: POLY must have real coefficients."))) (multiple-value-bind (ipoly ipolyf) (mjr_poly_2primitive poly) (let ((plen (length poly))) (if (zerop (aref ipoly (1- plen))) ;; Here we take care of the case with zero constant coefficient.... (let ((last-zero-idx (loop for i from (1- plen) downto 0 until (not (zerop (aref ipoly i))) minimize i))) (if (zerop last-zero-idx) (error "mjr_poly_root-solve-rational: POLY is zero -- infinitely many roots!!!") (multiple-value-bind (roots ipoly-throw-away ipolyf-throw-away wpoly) (mjr_poly_root-solve-rational (subseq ipoly 0 last-zero-idx)) (declare (ignore ipoly-throw-away ipolyf-throw-away)) ;; Just keep compiler from squawking (values (sort (append (make-list (- plen last-zero-idx) :initial-element 0) roots) #'<) ipoly ;; The original -- not ipoly-throw-away.. ipolyf;; The original -- not ipolyf-throw-away.. wpoly)))) ;; constant coefficient not zero. (let* ((wpoly (copy-seq ipoly)) (first-coef (abs (aref ipoly 0))) (last-coef (abs (aref ipoly (1- plen)))) (first-factors (mjr_prime_all-factors first-coef)) (last-factors (mjr_prime_all-factors last-coef)) (proot-candidates (remove-duplicates (loop for first-factor in first-factors append (loop for last-factor in last-factors for c = (/ last-factor first-factor) when (or (not only-integer-roots) (integerp c)) collect c)))) (root-candidates (sort (append (mapcar #'- proot-candidates) proot-candidates) #'<))) (values (loop for x in root-candidates until (> 2 (length wpoly)) append (loop until (not (multiple-value-bind (dfpoly pval) (mjr_poly_deflate wpoly x) (and (= 0 pval) (setq wpoly dfpoly)))) collect x)) ipoly ipolyf wpoly)))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_root-solve-integer (poly) "Find integer roots of a polynomial. Morally speaking this only works on a polynomials with integer coefficients; however, this function uses MJR_POLY_2PRIMITIVE to transform POLY into one with integer coefficients if required. Returns: * A list of found roots * The polynomial actually solved (we call this IPOLY) -- the first return of MJR_POLY_2PRIMITIVE on POLY * The logical factor required to transform POLY into IPOLY -- the second return of MJR_POLY_2PRIMITIVE on POLY * the result of deflating IPOLY with each root found" (mjr_poly_root-solve-rational poly :only-integer-roots 't)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_root-search-bsect (poly x0 x1 &rest kw-args &key xeps yeps max-itr show-progress) "Use bsect's method to find a root of POLY between X0 and X2. See the documentation for MJR_NLEQ_ROOT-BSECT" (and xeps yeps max-itr show-progress) (flet ((fp (x) (mjr_poly_eval poly x))) (apply #'mjr_nleq_root-bsect #'fp x0 x1 kw-args))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_root-search-newton (poly x0 &rest kw-args &key xeps yeps max-itr show-progress) "Use newton's method to find a root of POLY near (hopefully anyhow) X0. See the documentation for MJR_NLEQ_ROOT-NEWTON" (and xeps yeps max-itr show-progress) ;; Variables not directly used (flet ((fdf (x) (mjr_poly_eval-poly-and-first-n-derivatives poly x 1))) (apply #'mjr_nleq_root-newton #'fdf x0 kw-args))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_root-search-laguerre (poly x0 &rest kw-args &key xeps yeps max-itr show-progress) "Use laguerre's method to find a root of POLY near (hopefully anyhow) X0. See the documentation for MJR_NLEQ_ROOT-LAGUERRE" (and xeps yeps max-itr show-progress) ;; Variables not directly used (flet ((fdfddf (x) (mjr_poly_eval-poly-and-first-n-derivatives poly x 2))) (apply #'mjr_nleq_root-laguerre #'fdfddf (mjr_poly_degree poly) x0 kw-args))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_root-separate-largest-real (poly &key (xeps 1) max-itr yeps show-progress) "Use the canonical sturm-sequence to find an interval containing the largest real root and no other roots. An open interval $(a,b)$ containing the largest real root (and no other roots) is found. This interval will be no wider than :XEPS, and will contain no roots other than the largest real one. The return of this function will two values corresponding to the left and right endpoints of the interval. In the case of a polynomial with no real roots, then (values nil nil) will be returned. If the polynomial is rational, then the interval endpoints will be as well. When removed from the vulgarities of real world computing, this algorithm is guaranteed to work; however, some things can go wrong with real world implementations. When the inputs are rational, and enough memory is available for the necessary precision, the algorithm will always work unless the :MAX-ITR count is violated (the error is 'Maximum iteration count exceeded!'). When using floating point arithmetic various things can go wrong, but when the error 'Could not find a non-root' occurs a lower :YEPS (the only use of this argument is to detect when the polynomial is zero at prospective new interval endpoints) might help." (let ((d (mjr_poly_degree poly))) (cond ((some #'complexp poly) (error "mjr_poly_root-separate-largest-real: POLY must be a non-complex coefficients!")) ((< d 2) (error "mjr_poly_root-separate-largest-real: POLY must be of at least degree two!"))) (let* ((rb (max 1 (ceiling (mjr_poly_root-bound-all poly)))) (ss (mjr_poly_seq-make-sturm-canonical poly)) (b (* 11/10 rb)) (a (- b)) (va (mjr_poly_count-sign-changes (mjr_poly_seq-eval ss a))) (vb (mjr_poly_count-sign-changes (mjr_poly_seq-eval ss b)))) (loop for itr from 1 for n = (- va vb) do (if show-progress (format 't "~5d ~3d ~40a ~40a ~40a ~%" itr n a "" b)) do (if (and max-itr (> itr max-itr)) (error "mjr_poly_root-separate-largest-real: Maximum iteration count exceeded!")) do (if (> n 0) (loop with delta = (/ (- b a) (* 2 (+ d 1))) for i from 0 upto d for c = (/ (+ a b) 2) then (- c delta) when (mjr_cmp_not-zerop (mjr_poly_eval poly c) yeps) do (return (let ((vc (mjr_poly_count-sign-changes (mjr_poly_seq-eval ss c)))) (if (> (- vc vb) 0) (setq a c va vc) (setq b c vb vc)))) do (if show-progress (format 't "~5d ~3a ~40a ~40a ~40a ~%" "" "" "" c "")) ;; Only show after first try finally (error "mjr_poly_root-separate-largest-real: Could not find a non-root!")) (return-from mjr_poly_root-separate-largest-real (values nil nil))) until (and (= n 1) (< (- b a) xeps))) (values a b)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_root-search-largest-real (poly &rest rest) "Return the largest real root or NIL if the polynomial has no real roots. When successful this function returns the center of the interval found by mjr_poly_root-separate-largest-real. All arguments are passed directly to mjr_poly_root-separate-largest-real, so consult that function for usage information." (multiple-value-bind (a b) (apply #'mjr_poly_root-separate-largest-real poly rest) (if (and a b) (/ (+ a b) 2)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_root-solve-low-degree (poly &optional eps) "Return list of root(s) to the small degree (<=3) polynomial. Multiple roots are listed multiple times. The argument EPS is used to avoid division by zero." (if (<= (mjr_poly_degree poly) 3) (let* ((p3 (mjr_poly_coeff poly 3)) (p2 (mjr_poly_coeff poly 2)) (p1 (mjr_poly_coeff poly 1)) (p0 (mjr_poly_coeff poly 0))) (if (mjr_chk_!=0 p3 eps) (if (every #'realp (list p3 p2 p1 p0)) ;; ............................................................... Cubic(deg=3) (let* ((m (+ (* 2 p2 p2 p2) (* -9 p3 p2 p1) (* 27 p3 p3 p0))) ;; ..................................... Real Poly (n (* 4 (expt (- (* p2 p2) (* 3 p3 p1)) 3))) (r (mjr_numu_sqrt (- (* m m) n))) (p (mjr_numu_cubert (/ (+ m r) 2))) (q (mjr_numu_cubert (/ (- m r) 2))) (i1 (/ (+ 1 (complex 0 (sqrt 3))) 2)) (i2 (/ (- 1 (complex 0 (sqrt 3))) 2))) (list (/ (+ p2 p q) (* -3 p3)) (/ (+ (- p2) (* i1 p) (* i2 q)) (* 3 p3)) (/ (+ (- p2) (* i2 p) (* i1 q)) (* 3 p3)))) (let* ((a (/ p2 p3)) ;; ............................................................................... Complex (b (/ p1 p3)) (c (/ p0 p3)) (q (/ (- (* a a) (* 3 b)) 9)) (r (/ (+ (* 2 a a a) (* -9 a b) (* 27 c)) 54)) (r2 (* r r)) (q3 (expt q 3))) (if (and (not (complexp r)) (not (complexp q)) (< r2 q3)) (let* ((an (acos (/ r (mjr_numu_sqrt q3))))) (list (- (* -2 (mjr_numu_sqrt q) (cos (/ an 3))) (/ a 3)) (- (* -2 (mjr_numu_sqrt q) (cos (/ (+ an (* 2 pi)) 3))) (/ a 3)) (- (* -2 (mjr_numu_sqrt q) (cos (/ (- an (* 2 pi)) 3))) (/ a 3)))) (let* ((ca (if (>= (realpart (* (conjugate r) (mjr_numu_sqrt (- r2 q3)))) 0) (mjr_numu_cubert (- (+ r (mjr_numu_sqrt (- r2 q3))))) (mjr_numu_cubert (- (- r (mjr_numu_sqrt (- r2 q3))))))) (cb (if (mjr_chk_!=0 ca) (/ q ca) 0))) (list (- (+ ca cb) (/ a 3)) (+ (- (* -1/2 (+ ca cb)) (/ a 3)) (* #C(0 1) (/ (sqrt 3) 2) (- ca cb))) (- (- (* -1/2 (+ ca cb)) (/ a 3)) (* #C(0 1) (/ (sqrt 3) 2) (- ca cb)))))))) (if (mjr_chk_!=0 p2 eps) (let* ((dsr (mjr_numu_sqrt (- (* p1 p1) (* 4 p2 p0)))) ;; ........................................... Quadratic(deg=2) (tmp (/ (mjr_cmp_abs-max (+ p1 dsr) (- p1 dsr)) -2))) (if (mjr_chk_!=0 tmp eps) (list (/ tmp p2) (/ p0 tmp)) (list 0 0))) (if (mjr_chk_!=0 p1 eps) (list (/ (- p0) p1)) ;; ......................................................................... Linear(deg=1) (if (mjr_chk_!=0 p0 eps) nil (error "mjr_poly_root-solve-low-degree: Infinitely many solutions!")))))) (error "mjr_poly_root-solve-low-degree: Polynomial order is greater than 3!"))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_make-lagrange (points 1point &optional (pval 1)) "Return the unique polynomial that is PVAL (default 1) on the 1point'th element (zero indexed) of POINTS, and zero all the other elements of POINTS" (let ((poly 1) (divs 1) (1p (elt points 1point))) (if (vectorp points) (loop for i from 0 for p across points when (not (= i 1point)) do (setq poly (mjr_poly_* poly (vector 1 (- p))) divs (* divs (- 1p p)))) (loop for i from 0 for p in points when (not (= i 1point)) do (setq poly (mjr_poly_* poly (vector 1 (- p))) divs (* divs (- 1p p))))) (mjr_poly_* poly (/ pval divs)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_seq-make-lagrange (points &optional (pval 1)) "Return a list of polynomials such that the i'th one has value PVAL on the i'th element of POINTS and zero on all other elements" (loop for i from 0 upto (1- (length points)) collect (mjr_poly_make-lagrange points i pval))) ;; MJR TODO NOTE <2012-11-12 22:30:11 CST> mjr_poly_seq-make-lagrange: Optimize this function! ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_seq-make-chebyshev (num &optional (kind 1)) "Compute first NUM Chebyshev Polynomials (as a vector of vectors). kind==1 corresponds to Chebyshev Polynomials of the first kind $T_n$. kind==2 corresponds to Chebyshev Polynomials of the second kind $U_n$." (if (= num 1) (make-array 1 :initial-contents '(#(1))) (loop with p = (make-array num) for i from 2 upto (1- num) initially (setf (aref p 0) #(1) (aref p 1) (if (= kind 1) #(1 0) #(2 0))) finally (return p) do (setf (aref p i) (mjr_poly_- (mjr_poly_* 2 #(1 0) (aref p (- i 1))) (aref p (- i 2))))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_make-chebyshev (power &optional (kind 1)) "Compute Chebyshev Polynomial of the given power. kind==1 corresponds to Chebyshev Polynomials of the first kind $T_n$. kind==2 corresponds to Chebyshev Polynomials of the second kind $U_n$." (let* ((p0 #(1)) (p1 (if (= kind 1) #(1 0) #(2 0)))) (case power (0 p0) (1 p1) (otherwise (loop for i from 2 upto (1+ power) for pa = p0 then pb for pb = p1 then pn for pn = (mjr_poly_- (mjr_poly_* 2 #(1 0) pb) pa) when (= power i) do (return pn)))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_make-legendre (n) "Compute the Nth legendre polynomial using $$\\frac{1}{2^n n!}\\cdot\\frac{d^n}{dx^n}(x^2-1)^n$$" (mjr_poly_* (mjr_poly_diff (mjr_poly_iexpt #(1 0 -1) n) n) (/ (* (expt 2 n) (mjr_combe_! n))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_seq-make-legendre (n) "Return a list of the first n legendre polynomials (starting with the 0'th one)" (loop for i from 0 upto n collect (mjr_poly_make-legendre i))) ;; MJR TODO NOTE <2012-11-12 22:40:48 CST> mjr_poly_seq-make-legendre: Optimize this function! ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_make-bernstein (nu n) "The nu'th Bernstein basis polynomial of degree n." (let ((poly (make-array (1+ n) :initial-element 0)) (tmp (mjr_poly_* (mjr_combe_comb n nu) (mjr_poly_iexpt #(-1 1) (- n nu))))) (dotimes (i (length tmp) poly) (setf (aref poly i) (aref tmp i))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_seq-make-bernstein (n &key show-progress) "The Bernstein basis polynomials of degree n (all n of them in a list)." (reverse (loop with xn = (make-array (1+ n) :initial-element 0) initially (setf (aref xn 0) 1) for nu from n downto 0 for c = (mjr_combe_comb n nu) for p1 = (subseq xn 0 (1+ nu)) for p2 = #(1) then (mjr_poly_* #(-1 1) p2) do (if show-progress (format 't "~4d: ~10d ~4d ~80a ~%" nu c (mjr_poly_degree p1) p2)) collect (mjr_poly_* c p1 p2)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_imul (poly n) "Multiply POLY times the integer N. This function is provided for consistency with other packages that implement arithmetic for various rings -- after all integer multiplication is not terribly interesting for polynomials over Z, Q, R, or C." (mjr_poly_* n poly)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_root-solve-search-deflate (poly &key (xeps 1.0d-5) (yeps 1.0d-5) (xepsr 1.0d-10) (yepsr 1.0d-10) (refine-steps 10) (only-refined nil) (yepsp nil) (retry-factor 4) (float-type 0.0d0) (show-warnings nil) (show-progress nil)) "Find floating point approximations for all of the roots of a polynomial. Three values are returned: list of roots found, list of poly values on roots, and the part of the poly that couldn't be solved. _____THIS FUNCTION SHOULD BE CONSIDERED EXPERIMENTAL_____ This function works most of the time, but the roots are generally only accurate to a few decimal points. Retrying the function after failure can lead to success (different random seeds). Lowering the :XEPS and :YEPS can help in initial root location. If :ONLY-REFINED is used, then increasing :RETRY-FACTOR may be required. On LISPs that support it, setting :FLOAT-TYPE to 0.0L0 may increase accuracy and help with convergence problems due to round off errors. As a last resort, the :YEPSP argument may be set to a value larger than :YEPS in cases where numerical instability leads to deflated polynomials that have roots which are not within :YEPS of being a root of the original polynomial but are within :YEPSP of being a root (i.e. the absolute value of the original polynomial at the proposed root is less than :YEPSP). This last option can lead not-quite-roots that are quite far off, but still useful. The algorithm: 0) Set w<-p 1) Use laguerre to find a root xb of w (:xeps & :yeps) 2) Use laguerre to refine xb (:refine-steps, :xepsr, & :xepsr) 3) If refinement leads to a non-root of w and :only-refined is non-NIL, then NEXT 4) If p is real and xb is complex, check to see if re(xb) is a root of p and w. If so xb<-re(xb) 5) If xb is a root of p and w, then we deflate: a) If p is real and xb is complex, divide out xb and conj(xb) and update w b) otherwise just divide out xb 6) Jump to 1) if w is deg 1 or higher and we haven't gone beyond (retry-factor)*deg(poly) tries" (let ((rpoly (every #'realp poly)) (wpoly (copy-seq poly)) (roots nil) (pvals nil) (yepsp (or yepsp yeps)) (trys (* retry-factor (length poly)))) (loop with refined = nil for guess = (mjr_prng_float-co (float -10 float-type) (float 10 float-type)) for itr from 1 upto trys while (< 1 (length wpoly)) do (multiple-value-bind (x-bst w-bst ex-why) (progn (if show-progress (format 't "Root search: ~f~%" guess)) (mjr_poly_root-search-laguerre wpoly guess :yeps yeps :xeps xeps :show-progress show-progress)) (if show-progress (format 't "Root candidate: ~a~%" x-bst)) ;; Refine the root. (setq refined nil) (if refine-steps (multiple-value-bind (x-bst2 p-bst2 ex-why2) (progn (if show-progress (format 't "Root refine:~%")) (mjr_poly_root-search-laguerre poly x-bst :yeps yepsr :xeps xepsr :max-itr refine-steps :show-progress show-progress)) (if show-progress (format 't "Refinement candidate: ~a~%" x-bst2)) (if (mjr_eps_=0 p-bst2 yepsp) (let ((w-bst2 (mjr_poly_eval wpoly x-bst2))) (if (mjr_eps_=0 w-bst2 yeps) (progn (if show-progress (format 't "Refinement success~%")) (setf x-bst x-bst2 w-bst w-bst2 ex-why ex-why2 refined 't)) (if show-warnings (warn "mjr_poly_root-solve-search-deflate: laguerre refinement failed to find new root: ~a" x-bst)))) (if show-warnings (warn "mjr_poly_root-solve-search-deflate: laguerre refinement failed to converge: ~a" x-bst))))) (if (or refined (null only-refined)) (progn ;; Snip off the complex bit if the real bit is a good root (if (and rpoly (complexp x-bst)) (let* ((x-bst2 (realpart x-bst)) (w-bst2 (mjr_poly_eval wpoly x-bst2))) (if (and (mjr_eps_=0 w-bst2 yeps) (mjr_eps_=0 (mjr_poly_eval poly x-bst2) yepsp)) (progn (if show-progress (format 't "Root real-ifyed~%")) (setf x-bst x-bst2 w-bst w-bst2))))) ;; Snip off the fractional bit if this results in a good root (let* ((x-bst2 (complex (round (realpart x-bst)) (round (imagpart x-bst)))) (w-bst2 (mjr_poly_eval wpoly x-bst2))) (if (and (mjr_eps_=0 w-bst2 yeps) (mjr_eps_=0 (mjr_poly_eval poly x-bst2) yepsp)) (progn (if show-progress (format 't "Root int-ifyed~%")) (setf x-bst x-bst2 w-bst w-bst2)))) ;; Check the "roots", and deflate if things look good (if (mjr_eps_=0 w-bst yeps) (let ((p-bst (mjr_poly_eval poly x-bst))) (if (mjr_eps_=0 p-bst yepsp) (let ((wpoly2 (mjr_poly_deflate wpoly x-bst))) (setf roots (cons x-bst roots) pvals (cons p-bst pvals)) (if (and rpoly (complexp x-bst)) (let* ((x-bst-c (conjugate x-bst))) (if (mjr_eps_=0 (mjr_poly_eval wpoly2 x-bst-c) yeps) (setf roots (cons x-bst-c roots) pvals (cons (mjr_poly_eval poly x-bst-c) pvals) wpoly (mjr_poly_truncate wpoly (vector 1 (* -2 (realpart x-bst)) (mjr_numu_abssqr x-bst)))) (progn (if show-warnings (warn "mjr_poly_root-solve-search-deflate: Numerical instability detected: real poly but conjugate not a root!: ~a" x-bst)) (setf wpoly wpoly2)))) (setf wpoly wpoly2))) (if show-warnings (warn "mjr_poly_root-solve-search-deflate: Numerical instability detected: root of deflated poly not a root of original poly!")))) (if show-warnings (warn "mjr_poly_root-solve-search-deflate: laguerre failed to converge: ~a ~a ~a" x-bst w-bst ex-why)))) (if show-warnings (warn "mjr_poly_root-solve-search-deflate: Ignoring unrefined root: ~a" x-bst)))) do (if (and (= itr (truncate trys 2)) show-warnings) (warn "mjr_poly_root-solve-search-deflate: laguerre having difficulty converging")) do (if show-progress (format 't "ROOT: ~a~%" roots))) (values roots pvals wpoly))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_find-integer-factor (poly degree-or-sample-points &key show-progress) "Return an integer polynomial factor of the integer polynomial specified by POLY of the specified size or NIL if none exist. If a factor was found, then a second return value returned is POLY divided by the factor that was found. If degree-or-sample-points is a vector, then the points will be used in Kronecker's method. As the value of the polynomial on each of these points must be factored, the polynomial must not be zero on any of the points in the vector. The size of the factors may be specified as an integer indicating the degree of the desired factors or a vector of sample points to be used by Kronecker's method (in which case the degree of the factors will be one less than the length of the list) References: PI:NAME:<NAME>END_PI (2004); Polynomials; ISBN: 3540407146; pp 49-50" (let* ((degree (if (vectorp degree-or-sample-points) (1- (length degree-or-sample-points)) degree-or-sample-points)) (x-points (if (vectorp degree-or-sample-points) degree-or-sample-points (make-array (1+ degree)))) (y-points (if (vectorp degree-or-sample-points) (map 'vector (lambda (x) (mjr_poly_eval poly x)) x-points) (apply #'vector (loop with npts = 0 ;; find degree+1 points where the poly is not zero for x = 0 then (if (not (plusp x)) (1+ (abs x)) (- x)) for y = (mjr_poly_eval poly x) do (if show-progress (format 't "testing sample point ~d => ~d~%" x y)) when (not (zerop y)) collect (progn (setf (aref x-points npts) x) (incf npts) y) until (= npts (1+ degree))))))) (if show-progress (format 't "Using x sample points: ~a~%" x-points)) (if show-progress (format 't "Using y sample points: ~a~%" y-points)) (mjr_combc_gen-all-cross-product (loop for i from 0 for x across x-points for y across y-points for pf = (mjr_prime_all-factors (abs y)) do (if show-progress (format 't "factor ~d from ~d into ~d factors~%" y x (length pf))) collect (concatenate 'vector pf (if (not (zerop i)) (mapcar #'- pf)))) :func (lambda (y-vals) (let ((p (mjr_intrp_poly x-points y-vals))) (if (and (= (1+ degree) (length p)) (every #'integerp p)) (let ((quo (mjr_poly_divides? p poly :require-integer-quotient 't))) (if quo (return-from mjr_poly_find-integer-factor (values p quo)))))))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_factor-over-integers (poly &key show-progress) "Return a list of integer polynomial factors of the integer polynomial specified by POLY. Algorithm: 1) The polynomial is transformed into a primitive, integer polynomial if required (see: MJR_POLY_2PRIMITIVE) The multiplicative factor required for this transformation is included in the returned factor list as a constant polynomial NOTE: This will rationalize the polynomial if it contains floating point coefficients (real or complex) 2) All linear factors are found and removed 3) Kronecker's method is applied to the remainder NOTE: Kronecker's method can be quite slow when the polynomial sample values are large integers with many factors. References: PI:NAME:<NAME>END_PI (2004); Polynomials; ISBN: 3540407146; pp 49-50 PI:NAME:<NAME>END_PI (2003); Computer Algebra and Symbolic Computation: Mathematical Methods; ISBN: 1568811594; pp362-367" (multiple-value-bind (int-roots ipoly ipolyf pleft) (mjr_poly_root-solve-rational poly) (declare (ignore ipoly)) (setq pleft (mjr_poly_* (/ (reduce #'* (mapcar #'denominator int-roots))) pleft)) (loop with factors = (append (mapcar (lambda (r) (vector (denominator r) (- (numerator r)))) int-roots) (if (not (= 1 ipolyf)) (list (vector (/ ipolyf))))) for degree = 2 then (if gotfac 2 (1+ degree)) for gotfac = nil for sample-points = (mjr_vvec_to-list (list :vvec-type :vvt-aseq :start (floor (- (truncate degree 2))) :step 1 :len (+ degree 1))) for pleftlen = (length pleft) finally (return (append factors (if (or (< 1 pleftlen) (not (= (aref pleft 0) 1))) (list pleft)))) do (if show-progress (format 't "factoring(~d) ~a~%" degree pleft)) do (if show-progress (format 't "factors so far ~a ~%" factors)) while (and (<= degree (floor (/ pleftlen 2))) (< 1 (length pleft)) (or (< 1 pleftlen) (not (= (aref pleft 0) 1)))) do (mjr_combc_gen-all-cross-product (loop for i from 0 for x in sample-points for y = (mjr_poly_eval pleft x) for pf = (mjr_prime_all-factors (abs y)) do (if show-progress (format 't "factor ~d from ~d into ~d factors~%" y x (length pf))) collect (concatenate 'vector pf (if (not (zerop i)) (mapcar #'- pf)))) :func (lambda (y-vals) (mjr_intrp_poly sample-points y-vals)) :exit-if (lambda (p) (if (and (= (1+ degree) (length p)) (every #'integerp p)) (loop for quo = (mjr_poly_divides? p pleft :require-integer-quotient 't) for j from 1 finally (return gotfac) while quo do (progn (push p factors) (setq pleft quo) (setq gotfac 't))))))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_gcd-primitive (poly1 poly2) "Return primitive GCD of poly1 and poly2. See: MJR_POLY_GCD" (mjr_poly_2primitive (mjr_poly_gcd poly1 poly2))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_test-property (poly &rest pp-list) "Return non-nil if the given polynomial has all of the specified polynomial properties. This is not a fast function, but it sure is handy. A few property tests exist as separate functions because of performance. Symbol Description elt_comp :PP-PRIMITIVE Integer, primitive polynomial exact :PP-SQUARE-FREE No double factors fizzy :PP-IRREDUCIBLE No factors exact :PP-MONIC Leading coefficient is 1 fizzy :PP-NUMBER All elements are numbers N/A :PP-REAL All elements are real N/A :PP-INTEGER All elements are integers N/A :PP-RATIONAL All elements are rational N/A :PP-COMPLEX All elements are complex N/A :PP-POSITIVE All elements numeric and positive cmpzy :PP-EVEN The polynomial is an even function cmpzy :PP-ODD The polynomial is an odd function cmpzy :PP-ZERO The zero polynomial cmpzy :PP-IDENTITY The constant 1 polynomial cmpzy :PP-CONSTANT A constant polynomial cmpzy" (let ((poly (mjr_poly_simplify poly)) (deg (mjr_poly_degree poly))) (if (cdr pp-list) (every (lambda (pp) (mjr_poly_test-property poly pp)) pp-list) (case (car pp-list) (:pp-complex (every #'complexp poly)) (:pp-real (every (lambda (x) (and (numberp x) (not (complexp x)))) poly)) (:pp-rational (every #'rationalp poly)) (:pp-integer (every #'integerp poly)) (:pp-number (every #'numberp poly)) (:pp-positive (every #'plusp poly)) (:pp-monic (mjr_cmp_= (mjr_poly_leading-coeff poly) 1)) (:pp-odd (and (oddp deg) (loop for c across poly for i from 0 upto deg finally (return 't) when (and (oddp i) (mjr_cmp_!=0 c)) do (return nil)))) (:pp-even (and (evenp deg) (loop for c across poly for i from 0 upto deg finally (return 't) do (format 't "~a~%" c) when (and (oddp i) (mjr_cmp_!=0 c)) do (return nil)))) (:pp-irreducible (if (< deg 2) 't (if (or (not (mjr_poly_test-property poly :pp-rational)) (mjr_poly_test-property poly :pp-complex)) nil (error "mjr_poly_test-property: Irreducibly tests not implemented for integer or rational polynomials yet!")))) (:pp-primitive (and (mjr_poly_test-property poly :pp-integer) (= 1 (reduce #'gcd poly)))) (:pp-square-free (mjr_poly_test-property (mjr_poly_gcd (mjr_poly_diff poly) poly) :pp-identity)) (:pp-zero (mjr_eps_= #(0) poly)) (:pp-identity (mjr_eps_= #(1) poly)) (:pp-constant (= 0 deg)) (otherwise (error "mjr_poly_test-property: Unknown property")))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_seq-make-hermite (num) "Compute first NUM Hermite Polynomials (as a vector of vectors)." (loop with p = (make-array num) for i from 2 upto (1- num) initially (progn (setf (aref p 0) #(1)) (if (> num 1) (setf (aref p 1) #(1 0)))) finally (return p) do (setf (aref p i) (mjr_poly_- (mjr_poly_* #(1 0) (aref p (- i 1))) (mjr_poly_diff (aref p (- i 1))))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_make-hermite (power) "Compute the Hermite Polynomial of the given power." (let* ((p0 #(1)) (p1 #(1 0))) (case power (0 p0) (1 p1) (otherwise (loop for i from 2 upto (1+ power) for pa = p0 then pb for pb = p1 then pn for pn = (mjr_poly_- (mjr_poly_* #(1 0) pb) (mjr_poly_diff pb)) when (= power i) do (return pn)))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_make-laguerre (power) "Compute the Laguerre Polynomial of the given power." (let* ((p0 #(1)) (p1 #(-1 1))) (case power (0 p0) (1 p1) (otherwise (loop for i from 2 upto (1+ power) for pa = p0 then pb for pb = p1 then pn for pn = (mjr_poly_* (/ i) (mjr_poly_- (mjr_poly_* (mjr_poly_+ (* 2 (1- i)) #(-1 1)) pb) (mjr_poly_* (1- i) pa))) when (= power i) do (return pn)))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_seq-make-laguerre (num) "Compute first NUM Hermite Polynomials (as a vector of vectors)." (loop with p = (make-array num) for i from 2 upto (1- num) initially (progn (setf (aref p 0) #(1)) (if (> num 1) (setf (aref p 1) #(-1 1)))) finally (return p) do (setf (aref p i) (mjr_poly_* (/ i) (mjr_poly_- (mjr_poly_* (mjr_poly_+ (* 2 (1- i)) #(-1 1)) (aref p (1- i))) (mjr_poly_* (1- i) (aref p (- i 2)))))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_cubic-depress (poly) "Return the depressed form of the given cubic polynomial. If $p(x)=ax^3+bx^2+cx+d$, then divide $p$ by $a$ and substitute $t=\frac{b}{-3a}$." (let* ((cpoly (mjr_poly_simplify poly)) (deg (1- (length cpoly)))) (if (= 3 deg) (let* ((a (aref cpoly 0)) (a2 (* a a)) (b (aref cpoly 1)) (b2 (* b b)) (c (aref cpoly 2)) (d (aref cpoly 3))) (vector 1 0 (/ (- (* 3 a c) b2) (* 3 a2)) (/ (+ (* 2 b2 b) (* -9 a b c) (* 27 a2 d)) (* 27 a2 a)))) (error "mjr_poly_cubic-depress: Polynomial must be a cubic!")))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_tschirnhaus-3-2 (poly) "Tschirnhaus transformation (wipe out the power 2 term of a degree 3 polynomial) If $p(x)=ax^3+bx^2+cx+d$, then substitute $t=\frac{b}{3a}$." (mjr_poly_simplify (mjr_poly_subst (vector 1 (/ (mjr_poly_coeff poly 2) (* -3 (mjr_poly_coeff poly 3)))) poly))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_discriminant-low-degree (poly) "Return discriminant of a non-linear, small degree (<=5) polynomial via a direct formula" ;; Maxima Code to compute discriminant ;; degree(f,x) := hipow(f,x)$ ;; discriminant(f,x) := block([n:degree(f,x),fp,d,an], ;; fp : diff(f,x), ;; an : coeff(f,x,n), ;; w : mod(n,4), ;; w : w*(w-1)/2, ;; d : (-1)^w/an, ;; d : d*resultant(f,fp,x) ;; )$ (let* ((cpoly (mjr_poly_simplify poly)) (deg (1- (length poly))) (f (mjr_poly_coeff cpoly 5)) (e (mjr_poly_coeff cpoly 4)) (d (mjr_poly_coeff cpoly 3)) (c (mjr_poly_coeff cpoly 2)) (b (mjr_poly_coeff cpoly 1)) (a (mjr_poly_coeff cpoly 0))) (case deg (5 (let* ((a2 (* a a)) (a3 (* a2 a)) (b2 (* b b)) (b3 (* b2 b)) (b4 (* b3 b)) (c2 (* c c)) (c3 (* c2 c)) (c4 (* c3 c)) (d2 (* d d)) (d3 (* d2 d)) (d4 (* d3 d)) (e2 (* e e)) (e3 (* e2 e)) (e4 (* e3 e)) (f2 (* f f)) (f3 (* f2 f))) ;; 3125*a^4*f^4-2500*a^3*b*e*f^3-3750*a^3*c*d*f^3+2000*a^2*b^2*d*f^3+2250*a^2*b*c^2*f^3-1600*a*b^3*c*f^3+256*b^5* ;; f^3+2000*a^3*c*e^2*f^2-50*a^2*b^2*e^2*f^2+2250*a^3*d^2*e*f^2-2050*a^2*b*c*d*e*f^2+160*a*b^3*d*e*f^2-900*a^2*c^3* ;; e*f^2+1020*a*b^2*c^2*e*f^2-192*b^4*c*e*f^2-900*a^2*b*d^3*f^2+825*a^2*c^2*d^2*f^2+560*a*b^2*c*d^2*f^2-128*b^4*d^2* ;; f^2-630*a*b*c^3*d*f^2+144*b^3*c^2*d*f^2+108*a*c^5*f^2-27*b^2*c^4*f^2-1600*a^3*d*e^3*f+160*a^2*b*c*e^3*f-36*a*b^3* ;; e^3*f+1020*a^2*b*d^2*e^2*f+560*a^2*c^2*d*e^2*f-746*a*b^2*c*d*e^2*f+144*b^4*d*e^2*f+24*a*b*c^3*e^2*f-6*b^3*c^2*e^2* ;; f-630*a^2*c*d^3*e*f+24*a*b^2*d^3*e*f+356*a*b*c^2*d^2*e*f-80*b^3*c*d^2*e*f-72*a*c^4*d*e*f+18*b^2*c^3*d*e*f+108*a^2* ;; d^5*f-72*a*b*c*d^4*f+16*b^3*d^4*f+16*a*c^3*d^3*f-4*b^2*c^2*d^3*f+256*a^3*e^5-192*a^2*b*d*e^4-128*a^2*c^2*e^4+144*a* ;; b^2*c*e^4-27*b^4*e^4+144*a^2*c*d^2*e^3-6*a*b^2*d^2*e^3-80*a*b*c^2*d*e^3+18*b^3*c*d*e^3+16*a*c^4*e^3-4*b^2*c^3*e^3- ;; 27*a^2*d^4*e^2+18*a*b*c*d^3*e^2-4*b^3*d^3*e^2-4*a*c^3*d^2*e^2+b^2*c^2*d^2*e^2 (+ (* -3750 c d a3 f3) (* -2500 b e a3 f3) (* -2050 b c d e a2 f2) (* -1600 a c b3 f3) (* -1600 d f a3 e3) (* -900 b a2 d3 f2) (* -900 e a2 c3 f2) (* -746 a c d f b2 e2) (* -630 a b d c3 f2) (* -630 c e f a2 d3) (* -192 b d a2 e4) (* -192 c e b4 f2) (* -128 a2 c2 e4) (* -128 b4 d2 f2) (* -80 a b d c2 e3) (* -80 c e f b3 d2) (* -72 a b c f d4) (* -72 a d e f c4) (* -50 a2 b2 e2 f2) (* -36 a f b3 e3) (* -27 a2 d4 e2) (* -27 b2 c4 f2) (* -27 b4 e4) (* -6 a b2 d2 e3) (* -6 f b3 c2 e2) (* -4 a c3 d2 e2) (* -4 f b2 c2 d3) (* -4 b2 c3 e3) (* -4 b3 d3 e2) (* 16 a f c3 d3) (* 16 a c4 e3) (* 16 f b3 d4) (* 18 a b c d3 e2) (* 18 c d b3 e3) (* 18 d e f b2 c3) (* 24 a b f c3 e2) (* 24 a e f b2 d3) (* 108 a c4 c f2) (* 108 f a2 d4 d) (* 144 a c b2 e4) (* 144 c a2 d2 e3) (* 144 d f b4 e2) (* 144 d b3 c2 f2) (* 160 a d e b3 f2) (* 160 b c f a2 e3) (* 256 a3 e4 e) (* 256 b4 b f3) (* 356 a b e f c2 d2) (* 560 a c b2 d2 f2) (* 560 d f a2 c2 e2) (* 825 a2 c2 d2 f2) (* 1020 a e b2 c2 f2) (* 1020 b f a2 d2 e2) (* 2000 c a3 e2 f2) (* 2000 d a2 b2 f3) (* 2250 b a2 c2 f3) (* 2250 e a3 d2 f2) (* 3125 a3 a f3 f) (* b2 c2 d2 e2)))) (4 (let* ((a2 (* a a)) (b2 (* b b)) (b3 (* b2 b)) (c2 (* c c)) (c3 (* c2 c)) (d2 (* d d)) (d3 (* d2 d)) (e2 (* e e))) ;; 256*a^3*e^3-192*a^2*b*d*e^2-128*a^2*c^2*e^2+144*a*b^2*c*e^2-27*b^4*e^2+144*a^2*c*d^2*e-6*a*b^2*d^2*e-80*a*b*c^2*d*e+ ;; 18*b^3*c*d*e+16*a*c^4*e-4*b^2*c^3*e-27*a^2*d^4+18*a*b*c*d^3-4*b^3*d^3-4*a*c^3*d^2+b^2*c^2*d^2 (+ (* -192 b d a2 e2) (* -128 a2 c2 e2) (* -80 a b d e c2) (* -27 a2 d3 d) (* -27 b3 b e2) (* -6 a e b2 d2) (* -4 a c3 d2) (* -4 e b2 c3) (* -4 b3 d3) (* 16 a e c3 c) (* 18 a b c d3) (* 18 c d e b3) (* 144 a c b2 e2) (* 144 c e a2 d2) (* 256 a2 a e2 e) (* b2 c2 d2)))) (3 (let* ((b2 (* b b)) (c2 (* c c))) ;; -27*a^2*d^2-(4*b^3-18*a*b*c)*d-4*a*c^3+b^2*c^2 (+ (* -27 a a d d) (* -4 a c2 c) (* 18 a b c d) (* -4 b2 b d) (* b2 c2)))) (2 (let ((b2 (* b b))) ;; b^2-4*a*c (- b2 (* 4 a c)))) (otherwise (error "mjr_poly_discriminant-low-degree: Only polynomials of degree 2, 3, 4, and 5 are supported!"))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_resultant (poly1 poly2) "Return resultant the two polynomials via a recursive GCD-like computation." (labels ((resultant (poly1 poly2) (let ((deg1 (mjr_poly_degree poly1)) (deg2 (mjr_poly_degree poly2))) (if (> deg1 deg2) (mjr_poly_* (if (evenp (* deg1 deg2)) 1 -1) (mjr_poly_resultant poly2 poly1)) (let ((lc (mjr_poly_leading-coeff poly1))) (if (zerop deg1) (vector (expt lc deg2)) (let ((r (mjr_poly_rem poly2 poly1))) (if (mjr_poly_zerop r) (vector 0) (mjr_poly_* (expt lc (- deg2 (mjr_poly_degree r))) (mjr_poly_resultant poly1 r)))))))))) (mjr_poly_leading-coeff (resultant poly1 poly2)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_discriminant-high-degree (poly) "Return discriminant of a non-linear polynomial via a recursive resultant computation." (let ((pdeg (mjr_poly_degree poly))) (* (if (evenp (/ (* pdeg (1- pdeg)) 2)) 1 -1) (/ (mjr_poly_leading-coeff poly)) (mjr_poly_resultant poly (mjr_poly_diff poly))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_discriminant (poly) "Return discriminant of a non-linear polynomial using the most efficient method available." (if (> (mjr_poly_degree poly) 4) (mjr_poly_discriminant-high-degree poly) (mjr_poly_discriminant-low-degree poly))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_factor-square-free (poly) "Return the square-free factorization of POLY as an assoc array with (poly . power). Any factors equal to $1$ are not in the returned list. If the input polynomial is $p\\in\\mathbb{Q}[x]$, then a square-free factorization is $$p=c\\prod_{j=1}^nu_j^j$$ Where $u_j\\in\\mathbb{Q}[x]$, $u^j \\vert p$, and $u^{(j+1)} \\nmid p$. References: PI:NAME:<NAME>END_PI (2012); Algebra for Symbolic Computation; ISBN: 978-88-470-2396-3; pp 108-109" ;; MJR TODO NOTE mjr_poly_factor-square-free: Add reference to Wikipedia and Cohen. ;; MJR TODO NOTE mjr_poly_factor-square-free: Replace with Yun's algorithm, use this for regression tests. See: http://en.wikipedia.org/wiki/Square-free_polynomial#Yun.27s_algorithm ;; MJR TODO NOTE mjr_poly_factor-square-free: Implement finite field version of this for polygfp. (loop with d = (mjr_poly_gcd poly (mjr_poly_diff poly)) with v = (mjr_poly_truncate poly d) with w = (mjr_poly_diff v) with z = (mjr_poly_truncate (mjr_poly_diff poly) d) for j from 1 upto (mjr_poly_degree poly) for uj = (mjr_poly_gcd v (mjr_poly_- z (mjr_poly_* j w))) when (not (mjr_poly_onep uj)) collect (cons uj j))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_factor-irreducible (poly &key show-progress) "Return the irreducible factorization of POLY as an assoc array with (poly . power). VERY SLOW. Uses kronecker's method." ;; MJR TODO NOTE mjr_poly_factor-irreducible: Implement a modern method, and use this for regression tests. (loop with poly-left = poly with d = 1 with pdeg = (mjr_poly_degree poly) for (f pl) = (multiple-value-list (mjr_poly_find-integer-factor poly-left d)) if f collect (let ((daPow (1+ (loop initially (setf poly-left pl) for v = (mjr_poly_divides? f poly-left) while v count (setf poly-left v))))) (if show-progress (format 't "left: ~5d deg: ~5d pow: ~5d factor: ~30a~%" (mjr_poly_degree poly-left) d daPow f )) (cons f daPow)) else do (if show-progress (format 't "left: ~5d deg: ~5d pow: 0 factor: DONE~%" (mjr_poly_degree poly-left) d)) and do (incf d) until (mjr_poly_onep poly-left) until (>= d pdeg))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun mjr_poly_mahler-measure (poly &optional (method-class :solve) (method-function #'mjr_poly_root-solve-search-deflate) method-args) "Compute the Mahler measure of the polynomial POLY The optional arguments to determine how the computation is preformed: method-class method-function method-args :solve #'mjr_poly_root-solve-search-deflate nil <= DEFAULT :integrate #'mjr_intg_simple-gauss-kronrod '(:order 21) :integrate #'mjr_intg_simple-gauss-kronrod '(:order 31) :integrate #'mjr_intg_simple-gauss-legendre '(:order 20) :integrate #'mjr_intg_glb-adp-composite-romberg '(:the-err 1.0D-5) :integrate #'mjr_intg_glb-adp-composite-trapezoidal '(:the-err 1.0D-5) Definition Let $p\\in\\mathbb{C}[z]$ with $\\mathrm{deg}(p)=d$. For definiteness, we express $p$ like so: $$p(z)=\\sum_{j=0}^d a_jx^j = a_d\\prod_{j=1}^d (z-\\alpha_j)$$ We then define the Mahler measure to be: $$M(p) = \\vert a_d\\vert\\prod_{\\vert\\alpha_j\\vert\\geq1} \\vert\\alpha_j\\vert = \\exp\\left(\\frac{1}{2\\pi}\\int_0^{2\\pi}\\ln(\\vert p(e^{i\\theta})\\vert)\\,\\mathrm{d}\\theta\\right)$$ Examples: * (mahler-measure #(1 1 0 -1 -1 -1 -1 -1 0 1 1) :integrate #'mjr_intg_simple-gauss-kronrod '(:order 21 )) => 1.4751609391661360d0 * (mahler-measure #(1 1 0 -1 -1 -1 -1 -1 0 1 1) :integrate #'mjr_intg_simple-gauss-kronrod '(:order 31 )) => 0.7012142844290665d0 * (mahler-measure #(1 1 0 -1 -1 -1 -1 -1 0 1 1) :integrate #'mjr_intg_simple-gauss-legendre '(:order 20 )) => 1.0601232234056748d0 * (mahler-measure #(1 1 0 -1 -1 -1 -1 -1 0 1 1) :integrate #'mjr_intg_glb-adp-composite-romberg '(:the-err 1.0D-5)) => 1.1762811031170224d0 * (mahler-measure #(1 1 0 -1 -1 -1 -1 -1 0 1 1) :integrate #'mjr_intg_glb-adp-composite-trapezoidal '(:the-err 1.0D-5)) => 1.1762806954644658d0 * (mahler-measure #(1 1 0 -1 -1 -1 -1 -1 0 1 1) :solve #'mjr_poly_root-solve-search-deflate '( )) => 1.1762808182599178d0" (case method-class (:solve (let* ((roots (mapcar (lambda (x) (max 1 (abs x))) (apply method-function poly method-args))) (numr (length roots))) (if (= numr (mjr_poly_degree poly)) (reduce #'* roots) (error "mahler-measure: Could not find all roots. Found ~d" numr)))) (:integrate (exp (/ (apply method-function (lambda (x) (log (abs (mjr_poly_eval poly (complex (cos x) (sin x)))))) :start 0.0D0 :end (* 2.0d0 pi) method-args) (* 2 pi)))) (otherwise (error "mahler-measure: method-class unsupported"))))
[ { "context": "orking with vectors.\n\n;; Copyright (C) Nov. 2008 Volker van Nek\n\n;; modified 08-12-03: vector_factor factors list", "end": 162, "score": 0.999847412109375, "start": 148, "tag": "NAME", "value": "Volker van Nek" } ]
maxima/src/maxima/share/vector/vector_rebuild.lisp
nilqed/spadlib
1
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Some utilities for working with vectors. ;; Copyright (C) Nov. 2008 Volker van Nek ;; modified 08-12-03: vector_factor factors lists and matrices ;; 08-12-05: vector_eval: $ratprint set to false ;; 08-12-10: rename stardisp to stardisp1, assign property of $stardisp ;; 08-12-14: vector_eval: cut out sratsimp, rename it to vector_simp ;; $vector_rebuild: evaluate mnctimes, bugfix case mdefine ;; 20-02-27: TeX-support added ;; 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., 51 Franklin Street, Fifth Floor, Boston, ;; MA 02110-1301, USA. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Functions at Maxima level: ;; vector_rebuild(x), vector_rebuild(x,[param_list]) ;; vector_simp(x), has evfun property ;; vector_factor(x), has evfun property ;; extract_equations(x) ;; Operators at Maxima level: ;; |x| vector length ;; x~y cross product (lbp=134, rbp=133) ;; Option variable at Maxima level: ;; vector_factor_minus ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; mtimesq ;; In combination with setting listarith & friends to false ;; mtimesq allows to suppress automatic arithmetrics ;; and to bypass the displa function dim-mquotient: ;; 1 1 [ 2 ] ;; 1/r*[2,3]; --> - [2, 3] or 1/r*matrix([2],[3]);--> - [ ] ;; r r [ 3 ] ;; mtimesq display symbol is "*" and is settable by stardisp. ;; One evaluation steps from mtimesq to mtimes and vice versa. (meval `(($infix) mtimesq 120 119)) (defprop mtimesq simp-mtimesq operators) (defun simp-mtimesq (a tmp z) (declare (ignore tmp)) `((mtimesq simp) ,(simplifya (cadr a) z) ,(simplifya (caddr a) z))) (defmfun mtimesq (a b) `((mtimes simp) ,a ,b)) (putprop 'mtimesq (get 'mtimes 'dissym) 'dissym) ;; extend stardisp in displa.lisp : (defun stardisp1 (symbol val) (declare (ignore symbol)) (putprop 'mtimes (if val '(#\*) '(#\space)) 'dissym) (putprop 'mtimesq (get 'mtimes 'dissym) 'dissym) ) ;; (defprop $stardisp stardisp1 assign) (defun mtimesqp (expr) (and (not (atom expr)) (eq 'mtimesq (caar expr))) ) ;; TeX-support: (putprop 'mtimesq 'tex-mtimesq 'tex) ;; (defun tex-mtimesq (x l r) (append l (tex (cadr x) nil nil 'mparen 'mparen) `("\\,") ; `("\\cdot") ; if preferred (tex (caddr x) nil nil 'mparen 'mparen) r )) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; $vector_simp (defun $vector_simp (expre$$ion) (let (($listarith t) ($doallmxops t)) ($expand (meval `(($ev) ,expre$$ion $infeval))) )) ;; mtimesq needs an extra evaluation here (putprop '$vector_simp t 'evfun) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; $vector_rebuild (defun $vector_rebuild (expr &optional (params '((mlist))) ) (when (or (not ($listp params)) (some #'(lambda (p) (or ($constantp p) (not (or ($symbolp p) ($subvarp p))))) (cdr params))) (merror (format nil "The optional second argument to `vector_rebuild'~%~ must be a list of symbols or subscripted variables."))) (if (or (atom expr) ($scalarp expr)) expr (let ((op (mop expr)) (args (margs expr)) ) (if (not (car args)) (return-from $vector_rebuild expr)) ;; noarg-op (cond ((eq op 'mequal) (cons `(mequal simp) (mapcar #'(lambda (arg) ($vector_rebuild arg params)) args) )) ((eq op 'mdefine) (meval `((mdefine simp) ,(cadr expr) ,($vector_rebuild (caddr expr) params)) )) (t (vector-rebuild expr (cdr params)) ))))) (defun vector-rebuild (expr params) (let (coef-matrix col-flag tmp-vec col (res '((mplus) 0)) (n 0) (vec ($vector_simp expr)) ) (when (not (vector-p vec)) (return-from vector-rebuild expr)) (when (zero-vector-p vec) (return-from vector-rebuild vec)) (when (column-vector-p vec) (setq col-flag t)) (dolist (a (cdr vec)) (when col-flag (setq a (cadr a))) (setq coef-matrix (append coef-matrix (list (coef-list a params)))) ) (setq params (append params '(1))) (dolist (p params) (setq col (mapcar #'(lambda (row) (nth n row)) coef-matrix)) (incf n) (when (some #'(lambda (e) (not (zerop1 e))) col) (progn (setq tmp-vec `((mlist simp) ,@col) ) (when col-flag (setq tmp-vec (row-to-column tmp-vec))) (setq res (append res `(((mtimes) ,p ,tmp-vec)) ))) )) (meval res) )) ;; e.g. expr=4-2*t+3*s, params=(s t) --> (3 -2 4) (defun coef-list (expr params) (let (res c) (dolist (p params) (setq c (meval `(($coeff) ,expr ,p))) (push c res) (setq expr (meval `((mplus) ,expr ((mtimes) ((mminus) ,c) ,p))) )) (reverse (cons expr res)) )) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; $extract_equations (defun $extract_equations (equation) (let ((err-msg "Argument to `extract_equations' is not a vector equation.") args left right) (and (not (atom equation)) (not (eq (mop equation) 'mequal)) (merror err-msg)) (setq args (cdr equation)) (setq left ($vector_simp (car args))) (setq right ($vector_simp (cadr args))) (cond ((and (vector-p left) (vector-p right))) ;; OK ;; due to a bug in Maxima allow left or right to be zero: ((and (eql 0 left) (vector-p right)) (setq left (cons '(mlist simp) (make-list (vector-dim right) :initial-element 0))) ) ((and (eql 0 right) (vector-p left)) (setq right (cons '(mlist simp) (make-list (vector-dim left) :initial-element 0))) ) (t (merror err-msg) )) (when (not ($listp left)) (setq left (column-to-row left))) (when (not ($listp right)) (setq right (column-to-row right))) (meval `(($map) "=" ,left ,right)) )) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; $vector_factor (defun $vector_factor (expr) (if (atom expr) expr (let ((op (mop expr))) (cond ((eq op 'mequal) `((mequal simp) ,@(mapcar #'$vector_factor (cdr expr))) ) ((eq op 'mdefine) (meval `((mdefine simp) ,(cadr expr) ,($vector_factor (caddr expr))) )) ((member op '(mplus mnctimes crossq) :test #'eq) `((,op simp) ,@(mapcar #'$vector_factor (cdr expr))) ) (t (vector-extract-gcd expr) ))))) ;; incl. op=mtimes,mminus (putprop '$vector_factor t 'evfun) ;; if you whish to factor out a minus sign, set this to true (defmvar $vector_factor_minus nil) (defun vector-extract-gcd (expr) (let (fac vec args minus-flag $ratprint) (setq vec ($vector_simp expr)) (cond ((or (zero-vector-p vec) (zero-$matrix-p vec)) vec) ((or ($listp vec) ($matrixp vec)) (setq args (if ($listp vec) (cdr vec) (apply #'append (mapcar #'cdr (cdr vec))) )) (setq fac (reduce #'(lambda (a b) ($gcd a b)) (cons (car args) args))) (setq vec (meval `(($fullmapl) ((lambda) ((mlist) e) (($ratsimp) ((mquotient) e ,fac))) ,vec ))) (and $vector_factor_minus (every #'(lambda (a) (eq t (meval `(($is) ((mlessp) ,a 0))))) args) (setq minus-flag t) (setq vec (meval `(($fullmapl) ((lambda) ((mlist) e) ((mminus) e)) ,vec) ))) (if minus-flag (if (eql 1 fac) `((mminus) ,vec) `((mminus) ((mtimesq) ,fac ,vec)) ) (if (eql 1 fac) vec `((mtimesq) ,fac ,vec) ))) (t expr )))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; vector length (meval `(($matchfix) $\| $\|)) (defprop $\| simp-vector-length operators) (defun simp-vector-length (a tmp z) (declare (ignore tmp) (ignore z)) (oneargcheck a) (setq a ($vector_simp (cadr a))) (cond (($scalarp a) (meval `((mabs simp) ,a)) ) ((vector-p a) (let (args) (setq args (if ($listp a) (cdr a) (mapcar #'cadr (cdr a)) )) (setq args (mapcar #'(lambda (a) (meval `((mexpt) ,a 2))) args)) (meval `(($sqrt simp) ((mplus simp) ,@args))) )) (t `(($\|) ,a) ))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; cross product (meval `(($infix) $\~ 134 133)) ;; lbp and rbp copied from vect.mac (defprop $\~ simp-vector-cross operators) ;; if it seems fit we can suppress automatic simplification ;; by using an alias: ;; ;; (meval `(($infix) crossq 134 133)) ;; (putprop 'crossq '(#\~) 'dissym) ;; ;; (defun simp-vector-cross (a tmp z) ;; (declare (ignore tmp) (ignore z)) ;; (twoargcheck a) ;; `((crossq simp) ,(cadr a) ,(caddr a)) ) ;; ;; again, here is one more step of evaluation needed ;; (defmfun crossq (a b) ;; (let ((v ($vector_simp a)) ;; (w ($vector_simp b)) ;; cross col-flag dim-v dim-w) ;;)) (defun simp-vector-cross (a tmp z) (declare (ignore tmp) (ignore z)) (twoargcheck a) (let ((v ($vector_simp (cadr a))) (w ($vector_simp (caddr a))) cross col-flag dim-v dim-w) (if (and (vector-p v) (vector-p w)) (progn (when (column-vector-p v) (setq v (column-to-row v) col-flag t)) (when (column-vector-p w) (setq w (column-to-row w) col-flag t)) (setq dim-v (1- (length v)) dim-w (1- (length w))) (cond ((and (= 2 dim-v) (= 2 dim-w)) ;; v[1]*w[2]-v[2]*w[1] (meval `((mplus simp) ((mtimes simp) ,(cadr v) ,(caddr w)) ((mminus) ((mtimes simp) ,(caddr v) ,(cadr w))) ))) ((and (= 3 dim-v) (= 3 dim-w)) ;; [ v[2]*w[3]-v[3]*w[2], ;; v[3]*w[1]-v[1]*w[3], ;; v[1]*w[2]-v[2]*w[1] ] (setq cross `((mlist simp) ,(meval `((mplus simp) ((mtimes simp) ,(caddr v) ,(cadddr w)) ((mminus) ((mtimes simp) ,(cadddr v) ,(caddr w))) )) ,(meval `((mplus simp) ((mtimes simp) ,(cadddr v) ,(cadr w)) ((mminus) ((mtimes simp) ,(cadr v) ,(cadddr w))) )) ,(meval `((mplus simp) ((mtimes simp) ,(cadr v) ,(caddr w)) ((mminus) ((mtimes simp) ,(caddr v) ,(cadr w))) )) )) (if col-flag (row-to-column cross) cross )) (t `(($\~) ,v ,w) ) )) `(($\~) ,v ,w) ))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; some small helpers (defun column-to-row (col) ;; assume col to be a column vector (a $matrix) (cons '(mlist simp) (mapcar #'cadr (cdr col)) )) (defun row-to-column (row) ;; assume row to be a row vector (a mlist) (cons '($matrix simp) (mapcar #'(lambda (e) (list '(mlist simp) e)) (cdr row) ))) (defun vector-dim (vec) ;; assume vec to be a row or column vector (length (cdr vec)) ) (defun column-vector-p (obj) (and ($matrixp obj) (= 2 (length (cadr obj))) )) (defun vector-p (obj) (or ($listp obj) (column-vector-p obj))) (defun zero-vector-p (obj) (or (zero-mlist-p obj) (and (zero-$matrix-p obj) (= 2 (length (cadr obj)))) )) (defun zero-mlist-p (obj) (and ($listp obj) (every #'zerop1 (cdr obj)) )) (defun zero-$matrix-p (obj) (and ($matrixp obj) (every #'zero-mlist-p (cdr obj)) )) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
56297
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Some utilities for working with vectors. ;; Copyright (C) Nov. 2008 <NAME> ;; modified 08-12-03: vector_factor factors lists and matrices ;; 08-12-05: vector_eval: $ratprint set to false ;; 08-12-10: rename stardisp to stardisp1, assign property of $stardisp ;; 08-12-14: vector_eval: cut out sratsimp, rename it to vector_simp ;; $vector_rebuild: evaluate mnctimes, bugfix case mdefine ;; 20-02-27: TeX-support added ;; 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., 51 Franklin Street, Fifth Floor, Boston, ;; MA 02110-1301, USA. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Functions at Maxima level: ;; vector_rebuild(x), vector_rebuild(x,[param_list]) ;; vector_simp(x), has evfun property ;; vector_factor(x), has evfun property ;; extract_equations(x) ;; Operators at Maxima level: ;; |x| vector length ;; x~y cross product (lbp=134, rbp=133) ;; Option variable at Maxima level: ;; vector_factor_minus ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; mtimesq ;; In combination with setting listarith & friends to false ;; mtimesq allows to suppress automatic arithmetrics ;; and to bypass the displa function dim-mquotient: ;; 1 1 [ 2 ] ;; 1/r*[2,3]; --> - [2, 3] or 1/r*matrix([2],[3]);--> - [ ] ;; r r [ 3 ] ;; mtimesq display symbol is "*" and is settable by stardisp. ;; One evaluation steps from mtimesq to mtimes and vice versa. (meval `(($infix) mtimesq 120 119)) (defprop mtimesq simp-mtimesq operators) (defun simp-mtimesq (a tmp z) (declare (ignore tmp)) `((mtimesq simp) ,(simplifya (cadr a) z) ,(simplifya (caddr a) z))) (defmfun mtimesq (a b) `((mtimes simp) ,a ,b)) (putprop 'mtimesq (get 'mtimes 'dissym) 'dissym) ;; extend stardisp in displa.lisp : (defun stardisp1 (symbol val) (declare (ignore symbol)) (putprop 'mtimes (if val '(#\*) '(#\space)) 'dissym) (putprop 'mtimesq (get 'mtimes 'dissym) 'dissym) ) ;; (defprop $stardisp stardisp1 assign) (defun mtimesqp (expr) (and (not (atom expr)) (eq 'mtimesq (caar expr))) ) ;; TeX-support: (putprop 'mtimesq 'tex-mtimesq 'tex) ;; (defun tex-mtimesq (x l r) (append l (tex (cadr x) nil nil 'mparen 'mparen) `("\\,") ; `("\\cdot") ; if preferred (tex (caddr x) nil nil 'mparen 'mparen) r )) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; $vector_simp (defun $vector_simp (expre$$ion) (let (($listarith t) ($doallmxops t)) ($expand (meval `(($ev) ,expre$$ion $infeval))) )) ;; mtimesq needs an extra evaluation here (putprop '$vector_simp t 'evfun) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; $vector_rebuild (defun $vector_rebuild (expr &optional (params '((mlist))) ) (when (or (not ($listp params)) (some #'(lambda (p) (or ($constantp p) (not (or ($symbolp p) ($subvarp p))))) (cdr params))) (merror (format nil "The optional second argument to `vector_rebuild'~%~ must be a list of symbols or subscripted variables."))) (if (or (atom expr) ($scalarp expr)) expr (let ((op (mop expr)) (args (margs expr)) ) (if (not (car args)) (return-from $vector_rebuild expr)) ;; noarg-op (cond ((eq op 'mequal) (cons `(mequal simp) (mapcar #'(lambda (arg) ($vector_rebuild arg params)) args) )) ((eq op 'mdefine) (meval `((mdefine simp) ,(cadr expr) ,($vector_rebuild (caddr expr) params)) )) (t (vector-rebuild expr (cdr params)) ))))) (defun vector-rebuild (expr params) (let (coef-matrix col-flag tmp-vec col (res '((mplus) 0)) (n 0) (vec ($vector_simp expr)) ) (when (not (vector-p vec)) (return-from vector-rebuild expr)) (when (zero-vector-p vec) (return-from vector-rebuild vec)) (when (column-vector-p vec) (setq col-flag t)) (dolist (a (cdr vec)) (when col-flag (setq a (cadr a))) (setq coef-matrix (append coef-matrix (list (coef-list a params)))) ) (setq params (append params '(1))) (dolist (p params) (setq col (mapcar #'(lambda (row) (nth n row)) coef-matrix)) (incf n) (when (some #'(lambda (e) (not (zerop1 e))) col) (progn (setq tmp-vec `((mlist simp) ,@col) ) (when col-flag (setq tmp-vec (row-to-column tmp-vec))) (setq res (append res `(((mtimes) ,p ,tmp-vec)) ))) )) (meval res) )) ;; e.g. expr=4-2*t+3*s, params=(s t) --> (3 -2 4) (defun coef-list (expr params) (let (res c) (dolist (p params) (setq c (meval `(($coeff) ,expr ,p))) (push c res) (setq expr (meval `((mplus) ,expr ((mtimes) ((mminus) ,c) ,p))) )) (reverse (cons expr res)) )) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; $extract_equations (defun $extract_equations (equation) (let ((err-msg "Argument to `extract_equations' is not a vector equation.") args left right) (and (not (atom equation)) (not (eq (mop equation) 'mequal)) (merror err-msg)) (setq args (cdr equation)) (setq left ($vector_simp (car args))) (setq right ($vector_simp (cadr args))) (cond ((and (vector-p left) (vector-p right))) ;; OK ;; due to a bug in Maxima allow left or right to be zero: ((and (eql 0 left) (vector-p right)) (setq left (cons '(mlist simp) (make-list (vector-dim right) :initial-element 0))) ) ((and (eql 0 right) (vector-p left)) (setq right (cons '(mlist simp) (make-list (vector-dim left) :initial-element 0))) ) (t (merror err-msg) )) (when (not ($listp left)) (setq left (column-to-row left))) (when (not ($listp right)) (setq right (column-to-row right))) (meval `(($map) "=" ,left ,right)) )) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; $vector_factor (defun $vector_factor (expr) (if (atom expr) expr (let ((op (mop expr))) (cond ((eq op 'mequal) `((mequal simp) ,@(mapcar #'$vector_factor (cdr expr))) ) ((eq op 'mdefine) (meval `((mdefine simp) ,(cadr expr) ,($vector_factor (caddr expr))) )) ((member op '(mplus mnctimes crossq) :test #'eq) `((,op simp) ,@(mapcar #'$vector_factor (cdr expr))) ) (t (vector-extract-gcd expr) ))))) ;; incl. op=mtimes,mminus (putprop '$vector_factor t 'evfun) ;; if you whish to factor out a minus sign, set this to true (defmvar $vector_factor_minus nil) (defun vector-extract-gcd (expr) (let (fac vec args minus-flag $ratprint) (setq vec ($vector_simp expr)) (cond ((or (zero-vector-p vec) (zero-$matrix-p vec)) vec) ((or ($listp vec) ($matrixp vec)) (setq args (if ($listp vec) (cdr vec) (apply #'append (mapcar #'cdr (cdr vec))) )) (setq fac (reduce #'(lambda (a b) ($gcd a b)) (cons (car args) args))) (setq vec (meval `(($fullmapl) ((lambda) ((mlist) e) (($ratsimp) ((mquotient) e ,fac))) ,vec ))) (and $vector_factor_minus (every #'(lambda (a) (eq t (meval `(($is) ((mlessp) ,a 0))))) args) (setq minus-flag t) (setq vec (meval `(($fullmapl) ((lambda) ((mlist) e) ((mminus) e)) ,vec) ))) (if minus-flag (if (eql 1 fac) `((mminus) ,vec) `((mminus) ((mtimesq) ,fac ,vec)) ) (if (eql 1 fac) vec `((mtimesq) ,fac ,vec) ))) (t expr )))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; vector length (meval `(($matchfix) $\| $\|)) (defprop $\| simp-vector-length operators) (defun simp-vector-length (a tmp z) (declare (ignore tmp) (ignore z)) (oneargcheck a) (setq a ($vector_simp (cadr a))) (cond (($scalarp a) (meval `((mabs simp) ,a)) ) ((vector-p a) (let (args) (setq args (if ($listp a) (cdr a) (mapcar #'cadr (cdr a)) )) (setq args (mapcar #'(lambda (a) (meval `((mexpt) ,a 2))) args)) (meval `(($sqrt simp) ((mplus simp) ,@args))) )) (t `(($\|) ,a) ))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; cross product (meval `(($infix) $\~ 134 133)) ;; lbp and rbp copied from vect.mac (defprop $\~ simp-vector-cross operators) ;; if it seems fit we can suppress automatic simplification ;; by using an alias: ;; ;; (meval `(($infix) crossq 134 133)) ;; (putprop 'crossq '(#\~) 'dissym) ;; ;; (defun simp-vector-cross (a tmp z) ;; (declare (ignore tmp) (ignore z)) ;; (twoargcheck a) ;; `((crossq simp) ,(cadr a) ,(caddr a)) ) ;; ;; again, here is one more step of evaluation needed ;; (defmfun crossq (a b) ;; (let ((v ($vector_simp a)) ;; (w ($vector_simp b)) ;; cross col-flag dim-v dim-w) ;;)) (defun simp-vector-cross (a tmp z) (declare (ignore tmp) (ignore z)) (twoargcheck a) (let ((v ($vector_simp (cadr a))) (w ($vector_simp (caddr a))) cross col-flag dim-v dim-w) (if (and (vector-p v) (vector-p w)) (progn (when (column-vector-p v) (setq v (column-to-row v) col-flag t)) (when (column-vector-p w) (setq w (column-to-row w) col-flag t)) (setq dim-v (1- (length v)) dim-w (1- (length w))) (cond ((and (= 2 dim-v) (= 2 dim-w)) ;; v[1]*w[2]-v[2]*w[1] (meval `((mplus simp) ((mtimes simp) ,(cadr v) ,(caddr w)) ((mminus) ((mtimes simp) ,(caddr v) ,(cadr w))) ))) ((and (= 3 dim-v) (= 3 dim-w)) ;; [ v[2]*w[3]-v[3]*w[2], ;; v[3]*w[1]-v[1]*w[3], ;; v[1]*w[2]-v[2]*w[1] ] (setq cross `((mlist simp) ,(meval `((mplus simp) ((mtimes simp) ,(caddr v) ,(cadddr w)) ((mminus) ((mtimes simp) ,(cadddr v) ,(caddr w))) )) ,(meval `((mplus simp) ((mtimes simp) ,(cadddr v) ,(cadr w)) ((mminus) ((mtimes simp) ,(cadr v) ,(cadddr w))) )) ,(meval `((mplus simp) ((mtimes simp) ,(cadr v) ,(caddr w)) ((mminus) ((mtimes simp) ,(caddr v) ,(cadr w))) )) )) (if col-flag (row-to-column cross) cross )) (t `(($\~) ,v ,w) ) )) `(($\~) ,v ,w) ))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; some small helpers (defun column-to-row (col) ;; assume col to be a column vector (a $matrix) (cons '(mlist simp) (mapcar #'cadr (cdr col)) )) (defun row-to-column (row) ;; assume row to be a row vector (a mlist) (cons '($matrix simp) (mapcar #'(lambda (e) (list '(mlist simp) e)) (cdr row) ))) (defun vector-dim (vec) ;; assume vec to be a row or column vector (length (cdr vec)) ) (defun column-vector-p (obj) (and ($matrixp obj) (= 2 (length (cadr obj))) )) (defun vector-p (obj) (or ($listp obj) (column-vector-p obj))) (defun zero-vector-p (obj) (or (zero-mlist-p obj) (and (zero-$matrix-p obj) (= 2 (length (cadr obj)))) )) (defun zero-mlist-p (obj) (and ($listp obj) (every #'zerop1 (cdr obj)) )) (defun zero-$matrix-p (obj) (and ($matrixp obj) (every #'zero-mlist-p (cdr obj)) )) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
true
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Some utilities for working with vectors. ;; Copyright (C) Nov. 2008 PI:NAME:<NAME>END_PI ;; modified 08-12-03: vector_factor factors lists and matrices ;; 08-12-05: vector_eval: $ratprint set to false ;; 08-12-10: rename stardisp to stardisp1, assign property of $stardisp ;; 08-12-14: vector_eval: cut out sratsimp, rename it to vector_simp ;; $vector_rebuild: evaluate mnctimes, bugfix case mdefine ;; 20-02-27: TeX-support added ;; 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., 51 Franklin Street, Fifth Floor, Boston, ;; MA 02110-1301, USA. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Functions at Maxima level: ;; vector_rebuild(x), vector_rebuild(x,[param_list]) ;; vector_simp(x), has evfun property ;; vector_factor(x), has evfun property ;; extract_equations(x) ;; Operators at Maxima level: ;; |x| vector length ;; x~y cross product (lbp=134, rbp=133) ;; Option variable at Maxima level: ;; vector_factor_minus ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; mtimesq ;; In combination with setting listarith & friends to false ;; mtimesq allows to suppress automatic arithmetrics ;; and to bypass the displa function dim-mquotient: ;; 1 1 [ 2 ] ;; 1/r*[2,3]; --> - [2, 3] or 1/r*matrix([2],[3]);--> - [ ] ;; r r [ 3 ] ;; mtimesq display symbol is "*" and is settable by stardisp. ;; One evaluation steps from mtimesq to mtimes and vice versa. (meval `(($infix) mtimesq 120 119)) (defprop mtimesq simp-mtimesq operators) (defun simp-mtimesq (a tmp z) (declare (ignore tmp)) `((mtimesq simp) ,(simplifya (cadr a) z) ,(simplifya (caddr a) z))) (defmfun mtimesq (a b) `((mtimes simp) ,a ,b)) (putprop 'mtimesq (get 'mtimes 'dissym) 'dissym) ;; extend stardisp in displa.lisp : (defun stardisp1 (symbol val) (declare (ignore symbol)) (putprop 'mtimes (if val '(#\*) '(#\space)) 'dissym) (putprop 'mtimesq (get 'mtimes 'dissym) 'dissym) ) ;; (defprop $stardisp stardisp1 assign) (defun mtimesqp (expr) (and (not (atom expr)) (eq 'mtimesq (caar expr))) ) ;; TeX-support: (putprop 'mtimesq 'tex-mtimesq 'tex) ;; (defun tex-mtimesq (x l r) (append l (tex (cadr x) nil nil 'mparen 'mparen) `("\\,") ; `("\\cdot") ; if preferred (tex (caddr x) nil nil 'mparen 'mparen) r )) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; $vector_simp (defun $vector_simp (expre$$ion) (let (($listarith t) ($doallmxops t)) ($expand (meval `(($ev) ,expre$$ion $infeval))) )) ;; mtimesq needs an extra evaluation here (putprop '$vector_simp t 'evfun) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; $vector_rebuild (defun $vector_rebuild (expr &optional (params '((mlist))) ) (when (or (not ($listp params)) (some #'(lambda (p) (or ($constantp p) (not (or ($symbolp p) ($subvarp p))))) (cdr params))) (merror (format nil "The optional second argument to `vector_rebuild'~%~ must be a list of symbols or subscripted variables."))) (if (or (atom expr) ($scalarp expr)) expr (let ((op (mop expr)) (args (margs expr)) ) (if (not (car args)) (return-from $vector_rebuild expr)) ;; noarg-op (cond ((eq op 'mequal) (cons `(mequal simp) (mapcar #'(lambda (arg) ($vector_rebuild arg params)) args) )) ((eq op 'mdefine) (meval `((mdefine simp) ,(cadr expr) ,($vector_rebuild (caddr expr) params)) )) (t (vector-rebuild expr (cdr params)) ))))) (defun vector-rebuild (expr params) (let (coef-matrix col-flag tmp-vec col (res '((mplus) 0)) (n 0) (vec ($vector_simp expr)) ) (when (not (vector-p vec)) (return-from vector-rebuild expr)) (when (zero-vector-p vec) (return-from vector-rebuild vec)) (when (column-vector-p vec) (setq col-flag t)) (dolist (a (cdr vec)) (when col-flag (setq a (cadr a))) (setq coef-matrix (append coef-matrix (list (coef-list a params)))) ) (setq params (append params '(1))) (dolist (p params) (setq col (mapcar #'(lambda (row) (nth n row)) coef-matrix)) (incf n) (when (some #'(lambda (e) (not (zerop1 e))) col) (progn (setq tmp-vec `((mlist simp) ,@col) ) (when col-flag (setq tmp-vec (row-to-column tmp-vec))) (setq res (append res `(((mtimes) ,p ,tmp-vec)) ))) )) (meval res) )) ;; e.g. expr=4-2*t+3*s, params=(s t) --> (3 -2 4) (defun coef-list (expr params) (let (res c) (dolist (p params) (setq c (meval `(($coeff) ,expr ,p))) (push c res) (setq expr (meval `((mplus) ,expr ((mtimes) ((mminus) ,c) ,p))) )) (reverse (cons expr res)) )) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; $extract_equations (defun $extract_equations (equation) (let ((err-msg "Argument to `extract_equations' is not a vector equation.") args left right) (and (not (atom equation)) (not (eq (mop equation) 'mequal)) (merror err-msg)) (setq args (cdr equation)) (setq left ($vector_simp (car args))) (setq right ($vector_simp (cadr args))) (cond ((and (vector-p left) (vector-p right))) ;; OK ;; due to a bug in Maxima allow left or right to be zero: ((and (eql 0 left) (vector-p right)) (setq left (cons '(mlist simp) (make-list (vector-dim right) :initial-element 0))) ) ((and (eql 0 right) (vector-p left)) (setq right (cons '(mlist simp) (make-list (vector-dim left) :initial-element 0))) ) (t (merror err-msg) )) (when (not ($listp left)) (setq left (column-to-row left))) (when (not ($listp right)) (setq right (column-to-row right))) (meval `(($map) "=" ,left ,right)) )) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; $vector_factor (defun $vector_factor (expr) (if (atom expr) expr (let ((op (mop expr))) (cond ((eq op 'mequal) `((mequal simp) ,@(mapcar #'$vector_factor (cdr expr))) ) ((eq op 'mdefine) (meval `((mdefine simp) ,(cadr expr) ,($vector_factor (caddr expr))) )) ((member op '(mplus mnctimes crossq) :test #'eq) `((,op simp) ,@(mapcar #'$vector_factor (cdr expr))) ) (t (vector-extract-gcd expr) ))))) ;; incl. op=mtimes,mminus (putprop '$vector_factor t 'evfun) ;; if you whish to factor out a minus sign, set this to true (defmvar $vector_factor_minus nil) (defun vector-extract-gcd (expr) (let (fac vec args minus-flag $ratprint) (setq vec ($vector_simp expr)) (cond ((or (zero-vector-p vec) (zero-$matrix-p vec)) vec) ((or ($listp vec) ($matrixp vec)) (setq args (if ($listp vec) (cdr vec) (apply #'append (mapcar #'cdr (cdr vec))) )) (setq fac (reduce #'(lambda (a b) ($gcd a b)) (cons (car args) args))) (setq vec (meval `(($fullmapl) ((lambda) ((mlist) e) (($ratsimp) ((mquotient) e ,fac))) ,vec ))) (and $vector_factor_minus (every #'(lambda (a) (eq t (meval `(($is) ((mlessp) ,a 0))))) args) (setq minus-flag t) (setq vec (meval `(($fullmapl) ((lambda) ((mlist) e) ((mminus) e)) ,vec) ))) (if minus-flag (if (eql 1 fac) `((mminus) ,vec) `((mminus) ((mtimesq) ,fac ,vec)) ) (if (eql 1 fac) vec `((mtimesq) ,fac ,vec) ))) (t expr )))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; vector length (meval `(($matchfix) $\| $\|)) (defprop $\| simp-vector-length operators) (defun simp-vector-length (a tmp z) (declare (ignore tmp) (ignore z)) (oneargcheck a) (setq a ($vector_simp (cadr a))) (cond (($scalarp a) (meval `((mabs simp) ,a)) ) ((vector-p a) (let (args) (setq args (if ($listp a) (cdr a) (mapcar #'cadr (cdr a)) )) (setq args (mapcar #'(lambda (a) (meval `((mexpt) ,a 2))) args)) (meval `(($sqrt simp) ((mplus simp) ,@args))) )) (t `(($\|) ,a) ))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; cross product (meval `(($infix) $\~ 134 133)) ;; lbp and rbp copied from vect.mac (defprop $\~ simp-vector-cross operators) ;; if it seems fit we can suppress automatic simplification ;; by using an alias: ;; ;; (meval `(($infix) crossq 134 133)) ;; (putprop 'crossq '(#\~) 'dissym) ;; ;; (defun simp-vector-cross (a tmp z) ;; (declare (ignore tmp) (ignore z)) ;; (twoargcheck a) ;; `((crossq simp) ,(cadr a) ,(caddr a)) ) ;; ;; again, here is one more step of evaluation needed ;; (defmfun crossq (a b) ;; (let ((v ($vector_simp a)) ;; (w ($vector_simp b)) ;; cross col-flag dim-v dim-w) ;;)) (defun simp-vector-cross (a tmp z) (declare (ignore tmp) (ignore z)) (twoargcheck a) (let ((v ($vector_simp (cadr a))) (w ($vector_simp (caddr a))) cross col-flag dim-v dim-w) (if (and (vector-p v) (vector-p w)) (progn (when (column-vector-p v) (setq v (column-to-row v) col-flag t)) (when (column-vector-p w) (setq w (column-to-row w) col-flag t)) (setq dim-v (1- (length v)) dim-w (1- (length w))) (cond ((and (= 2 dim-v) (= 2 dim-w)) ;; v[1]*w[2]-v[2]*w[1] (meval `((mplus simp) ((mtimes simp) ,(cadr v) ,(caddr w)) ((mminus) ((mtimes simp) ,(caddr v) ,(cadr w))) ))) ((and (= 3 dim-v) (= 3 dim-w)) ;; [ v[2]*w[3]-v[3]*w[2], ;; v[3]*w[1]-v[1]*w[3], ;; v[1]*w[2]-v[2]*w[1] ] (setq cross `((mlist simp) ,(meval `((mplus simp) ((mtimes simp) ,(caddr v) ,(cadddr w)) ((mminus) ((mtimes simp) ,(cadddr v) ,(caddr w))) )) ,(meval `((mplus simp) ((mtimes simp) ,(cadddr v) ,(cadr w)) ((mminus) ((mtimes simp) ,(cadr v) ,(cadddr w))) )) ,(meval `((mplus simp) ((mtimes simp) ,(cadr v) ,(caddr w)) ((mminus) ((mtimes simp) ,(caddr v) ,(cadr w))) )) )) (if col-flag (row-to-column cross) cross )) (t `(($\~) ,v ,w) ) )) `(($\~) ,v ,w) ))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; some small helpers (defun column-to-row (col) ;; assume col to be a column vector (a $matrix) (cons '(mlist simp) (mapcar #'cadr (cdr col)) )) (defun row-to-column (row) ;; assume row to be a row vector (a mlist) (cons '($matrix simp) (mapcar #'(lambda (e) (list '(mlist simp) e)) (cdr row) ))) (defun vector-dim (vec) ;; assume vec to be a row or column vector (length (cdr vec)) ) (defun column-vector-p (obj) (and ($matrixp obj) (= 2 (length (cadr obj))) )) (defun vector-p (obj) (or ($listp obj) (column-vector-p obj))) (defun zero-vector-p (obj) (or (zero-mlist-p obj) (and (zero-$matrix-p obj) (= 2 (length (cadr obj)))) )) (defun zero-mlist-p (obj) (and ($listp obj) (every #'zerop1 (cdr obj)) )) (defun zero-$matrix-p (obj) (and ($matrixp obj) (every #'zero-mlist-p (cdr obj)) )) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
[ { "context": "or Common Lisp\"\n :version \"1.0.0\"\n :author \"Andrew Berkley <[email protected]>\"\n :licence \"BSD 3 Clause", "end": 107, "score": 0.9998973608016968, "start": 93, "tag": "NAME", "value": "Andrew Berkley" }, { "context": " :version \"1.0.0\"\n :author \"Andrew Berkley <[email protected]>\"\n :licence \"BSD 3 Clause\"\n :depends-on (\"f", "end": 128, "score": 0.9999287128448486, "start": 109, "tag": "EMAIL", "value": "[email protected]" } ]
vxi11.asd
ajberkley/cl-vxi11
0
(defsystem :vxi11 :description "VXI11 for Common Lisp" :version "1.0.0" :author "Andrew Berkley <[email protected]>" :licence "BSD 3 Clause" :depends-on ("frpc2" "drx" "fsocket" "pounds" "babel" "trivial-garbage") :components ((:file "vxi11")))
93470
(defsystem :vxi11 :description "VXI11 for Common Lisp" :version "1.0.0" :author "<NAME> <<EMAIL>>" :licence "BSD 3 Clause" :depends-on ("frpc2" "drx" "fsocket" "pounds" "babel" "trivial-garbage") :components ((:file "vxi11")))
true
(defsystem :vxi11 :description "VXI11 for Common Lisp" :version "1.0.0" :author "PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>" :licence "BSD 3 Clause" :depends-on ("frpc2" "drx" "fsocket" "pounds" "babel" "trivial-garbage") :components ((:file "vxi11")))
[ { "context": " DEALINGS IN THE SOFTWARE.\n;\n; Original authors: Sol Swords <[email protected]>\n\n\n(in-package \"SV\")\n\n(incl", "end": 1447, "score": 0.9998688697814941, "start": 1437, "tag": "NAME", "value": "Sol Swords" }, { "context": "N THE SOFTWARE.\n;\n; Original authors: Sol Swords <[email protected]>\n\n\n(in-package \"SV\")\n\n(include-book \"svtv-stobj\")", "end": 1469, "score": 0.9999280571937561, "start": 1449, "tag": "EMAIL", "value": "[email protected]" } ]
books/centaur/sv/svtv/svtv-stobj-pipeline-thm.lisp
mayankmanj/acl2
0
; Centaur SV Hardware Verification Tutorial ; Copyright (C) 2016 Centaur Technology ; Copyright (C) 2022 Intel Corporation ; ; Contact: ; Centaur Technology Formal Verification Group ; 7600-C N. Capital of Texas Highway, Suite 300, Austin, TX 78731, USA. ; http://www.centtech.com/ ; ; License: (An MIT/X11-style license) ; ; Permission is hereby granted, free of charge, to any person obtaining a ; copy of this software and associated documentation files (the "Software"), ; to deal in the Software without restriction, including without limitation ; the rights to use, copy, modify, merge, publish, distribute, sublicense, ; and/or sell copies of the Software, and to permit persons to whom the ; Software is furnished to do so, subject to the following conditions: ; ; The above copyright notice and this permission notice shall be included in ; all copies or substantial portions of the Software. ; ; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR ; IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, ; FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE ; AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER ; LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING ; FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER ; DEALINGS IN THE SOFTWARE. ; ; Original authors: Sol Swords <[email protected]> (in-package "SV") (include-book "svtv-stobj") (include-book "svtv-stobj-cycle") (include-book "clause-processors/meta-extract-user" :dir :System) (include-book "clause-processors/pseudo-term-fty" :dir :System) (include-book "centaur/meta/replace" :dir :System) (include-book "centaur/meta/unify-strict" :dir :system) (include-book "centaur/meta/lambda-measure" :dir :system) ;; Uses the contents of a svtv-stobj to prove that a pipeline expresses the ;; correct formula of the cycle. #|| (include-book "svtv-stobj-defsvtv") (local (defconst *my-design* (make-design :top "my-mod" :modalist (list (cons "my-mod" (make-module :wires (list (make-wire :name "in" :width 5 :low-idx 0) (make-wire :name "out" :width 5 :low-idx 0)) :assigns (list (cons (list (make-lhrange :w 5 :atom (make-lhatom-var :name "out" :rsh 0))) (make-driver :value (svcall bitnot (svcall zerox 5 "in"))))))))))) (defsvtv$-phasewise my-svtv :design *my-design* :phases ((:label the-phase :inputs (("in" in)) :outputs (("out" out))) (:label the-next-phase :inputs (("in" in2)) :outputs (("out" out2))))) (def-pipeline-thm my-svtv) (def-cycle-thm my-svtv) ;; (make-event ;; `(defund my-cycle () ;; (declare (xargs :guard t)) ;; ',(svtv-data->cycle-fsm svtv-data))) ;; (make-event ;; `(defund my-namemap () ;; (declare (xargs :guard t)) ;; ',(svtv-data->namemap svtv-data))) ;; (make-event ;; `(defund my-pipeline-setup () ;; (declare (xargs :guard t)) ;; ',(svtv-data->pipeline-setup svtv-data))) ;; (local (in-theory (disable (my-cycle) ;; (my-namemap) ;; (my-pipeline-setup)))) ;; (defthm my-svtv-pipeline-correct ;; (b* ((fsm (my-cycle)) ;; (rename-fsm (make-svtv-fsm :base-fsm fsm ;; :namemap (my-namemap))) ;; (renamed-fsm (svtv-fsm->renamed-fsm rename-fsm)) ;; ((pipeline-setup pipe) (my-pipeline-setup)) ;; (outvars (svtv-probealist-outvars pipe.probes)) ;; (run (base-fsm-run ;; (svex-alistlist-eval ;; (svtv-fsm-run-input-substs ;; (take (len outvars) pipe.inputs) ;; pipe.overrides ;; rename-fsm) ;; env) ;; (svex-alist-eval pipe.initst env) ;; renamed-fsm outvars))) ;; (svex-envs-equivalent ;; (svex-alist-eval (svtv->outexprs (my-svtv)) env) ;; (svtv-probealist-extract pipe.probes run))) ;; :hints (("goal" :clause-processor (svtv-pipeline-clause-proc ;; clause ;; '((my-cycle) ;; (my-namemap) ;; (my-pipeline-setup) ;; (svtv->outexprs$inline (my-svtv)) ;; env) ;; svtv-data state) ;; :in-theory (enable svtv-pipeline-correct)))) ||# (define svtv-pipeline-correct ((cycle-fsm base-fsm-p) (namemap svtv-name-lhs-map-p) (pipeline-setup pipeline-setup-p) (pipeline-result svex-alist-p) (env svex-env-p)) :verify-guards nil :enabled t (b* ((fsm cycle-fsm) (rename-fsm (make-svtv-fsm :base-fsm fsm :namemap namemap)) (renamed-fsm (svtv-fsm->renamed-fsm rename-fsm)) ((pipeline-setup pipe) pipeline-setup) (outvars (svtv-probealist-outvars pipe.probes)) (run (base-fsm-run (svex-alistlist-eval (svtv-fsm-run-input-substs (take (len outvars) pipe.inputs) pipe.overrides rename-fsm) env) (svex-alist-eval pipe.initst env) renamed-fsm outvars))) (svex-envs-equivalent (svex-alist-eval pipeline-result env) (svtv-probealist-extract pipe.probes run))) /// (local (defthm take-of-svex-alistlist-eval (equal (take n (svex-alistlist-eval x env)) (svex-alistlist-eval (take n x) env)) :hints(("Goal" :in-theory (e/d (svex-alistlist-eval take) (acl2::take-when-atom acl2::take-of-too-many)) :induct t :expand ((svex-alist-eval nil env)))))) (defthm svtv-pipeline-correct-when-svtv-data$ap (implies (and (svtv-datap svtv-data) (svtv-data->pipeline-validp svtv-data)) (svtv-pipeline-correct (svtv-data$c->cycle-fsm svtv-data) (svtv-data$c->namemap svtv-data) (svtv-data$c->pipeline-setup svtv-data) (svtv-data$c->pipeline svtv-data) env)) :hints(("Goal" :in-theory (enable svtv-data$ap svtv-fsm-run-is-base-fsm-run))))) (define svtv-cycle-correct ((phase-fsm base-fsm-p) (cycle-phases svtv-cyclephaselist-p) (cycle-fsm base-fsm-p)) :guard (not (hons-dups-p (svex-alist-keys (base-fsm->nextstate phase-fsm)))) :enabled t (b* (((base-fsm phase-fsm)) ((mv values nextstate) (svtv-cycle-compile (svex-identity-subst (svex-alist-keys phase-fsm.nextstate)) cycle-phases phase-fsm nil))) ;; simp is irrelevant under base-fsm-eval-equiv (base-fsm-eval-equiv (make-base-fsm :values values :nextstate nextstate) cycle-fsm)) /// (defthm svtv-cycle-correct-when-svtv-data$ap (implies (and (svtv-datap svtv-data) (svtv-data->cycle-fsm-validp svtv-data)) (svtv-cycle-correct (svtv-data$c->phase-fsm svtv-data) (svtv-data$c->cycle-phases svtv-data) (svtv-data$c->cycle-fsm svtv-data))) :hints(("Goal" :in-theory (enable svtv-data$ap cycle-fsm-okp-implies-cycle-compile-values-equiv))))) (local (in-theory (disable svtv-pipeline-correct svtv-cycle-correct))) (defevaluator svtvpipe-ev svtvpipe-ev-lst ((typespec-check ts x) (if a b c) (equal a b) (not a) (iff a b) (implies a b) ;; (svtv-data$c-pipeline-okp svtvdat results) ;; (svtv-data$c->cycle-fsm$inline svtvdat) ;; (svtv-data$c->pipeline-setup$inline svtvdat) ;; (svtv-data$c->namemap$inline svtvdat) (svtv-pipeline-correct cycle namemap setup pipeline env) (svtv-cycle-correct phase-fsm cycle-phases cycle-fsm) ) :namedp t) (local (acl2::def-ev-pseudo-term-fty-support svtvpipe-ev svtvpipe-ev-lst)) (acl2::def-meta-extract svtvpipe-ev svtvpipe-ev-lst) (local (in-theory (disable w))) (local (acl2::def-functional-instance svtvpipe-ev-when-agree-on-term-vars cmr::base-ev-when-agree-on-term-vars ((cmr::base-ev svtvpipe-ev) (cmr::base-ev-list svtvpipe-ev-lst)))) (local (in-theory (disable svtvpipe-ev-when-agree-on-term-vars))) (local (defthmd svtvpipe-ev-when-no-term-vars (implies (and (syntaxp (not (equal a ''nil))) (not (cmr::term-vars x))) (equal (svtvpipe-ev x a) (svtvpipe-ev x nil))) :hints (("goal" :use ((:instance svtvpipe-ev-when-agree-on-term-vars (a a) (b nil))) :in-theory (enable acl2::eval-alists-agree))))) (define meta-extract-const-value ((term pseudo-termp) state) :returns (mv err val) (b* ((term (acl2::pseudo-term-fix term)) ((unless (eq (cmr::term-vars term) nil)) (mv "term has variables" nil)) ((unless (logic-fnsp term (w state))) (mv "term has non-logic functions" nil))) (acl2::magic-ev term nil state t nil)) ;; (acl2::pseudo-term-case term ;; :const (mv nil term.val) ;; :fncall (b* (((unless (eq term.args nil)) ;; (mv "fncall has arguments" nil)) ;; ((mv ok formals body) (acl2::fn-get-def-w term.fn wrld)) ;; ((unless (and ok ;; (not formals) ;; (pseudo-termp body) ;; (acl2::pseudo-term-case body :const))) ;; (mv (msg "function ~x0 not recognized as a constant" term.fn) nil))) ;; (mv nil (acl2::pseudo-term-const->val body))) ;; :otherwise (mv (msg "bad form for constant term: ~x0" term) nil)) /// (defret <fn>-correct (implies (and (not err) (svtvpipe-ev-meta-extract-global-facts)) (equal (svtvpipe-ev term a) val)) :hints(("Goal" :in-theory (enable svtvpipe-ev-when-no-term-vars))))) ;; (local ;; #!cmr ;; (defthm term-unify-strict-reversible-hyp ;; (implies (acl2::rewriting-negative-literal ;; `(mv-nth '0 (term-unify-strict ,pat ,x ,alist))) ;; (iff (mv-nth 0 (term-unify-strict pat x alist)) ;; (equal (term-subst-strict pat (mv-nth 1 (term-unify-strict pat x alist))) ;; (pseudo-term-fix x)))))) ;; (local (in-theory (disable cmr::term-unify-strict-reversible-iff))) ;; (define pipeline-okp-implicant-term ((wrld plist-worldp)) ;; :returns (mv err (impl-term pseudo-termp)) ;; ;; :verify-guards nil ;; (b* ((form (acl2::meta-extract-formula-w 'svtv-data$c-pipeline-okp wrld)) ;; ((unless (pseudo-termp form)) ;; (mv "pipeline-okp formula was not pseudo-termp" nil)) ;; ;; Form is the conjunction of formulas for the defun-sk, namely ;; ;; definition of pipeline-okp ;; ;; pipeline-okp-necc theorem ;; ;; The second is the one we want. ;; ((mv ok alist) ;; (cmr::term-unify-strict ;; '(if pipe-ok-def (implies (svtv-data$c-pipeline-okp svtv-data$c results) ;; impl-term) ;; 'nil) ;; form ;; '((svtv-data$c . svtv-data$c) ;; (results . results)))) ;; ((unless ok) ;; (mv "pipeline-okp formula had unexpected form" nil))) ;; (mv nil (cdr (hons-assoc-equal 'impl-term alist)))) ;; /// ;; (set-ignore-ok t) ;; (local ;; (make-event ;; (let ((form ;; `(progn ;; (defthm expand-term-subst-strict ;; (implies (syntaxp (quotep x)) ;; (equal (cmr::term-subst-strict x acl2::a) ;; ,(acl2::body 'cmr::term-subst-strict nil (w state)))) ;; :hints(("Goal" :in-theory (enable cmr::term-subst-strict)))) ;; (defthm expand-termlist-subst-strict ;; (implies (syntaxp (quotep x)) ;; (equal (cmr::termlist-subst-strict x acl2::a) ;; ,(acl2::body 'cmr::termlist-subst-strict nil (w state)))) ;; :hints(("Goal" :in-theory (enable cmr::termlist-subst-strict))))))) ;; (value form)))) ;; (local (defthmd equal-cons-strong ;; (implies (syntaxp (not (or (quotep x) ;; (and (quotep a) (quotep b))))) ;; (equal (Equal x (cons a b)) ;; (and (consp x) ;; (equal (car x) a) ;; (equal (cdr x) b)))))) ;; (local (defthm assoc-is-hons-assoc-equal-when-key ;; (implies k ;; (equal (assoc-equal k x) ;; (hons-assoc-equal k x))))) ;; (defret <fn>-correct ;; (implies (and (not err) ;; (svtvpipe-ev-meta-extract-global-facts) ;; (equal wrld (w state)) ;; (svtv-data$c-pipeline-okp ;; (cdr (hons-assoc-equal 'svtv-data$c alist)) ;; (cdr (hons-assoc-equal 'results alist)))) ;; (svtvpipe-ev impl-term alist)) ;; :hints(("Goal" ;; :use ((:instance SVTVPIPE-EV-META-EXTRACT-FORMULA ;; (st state) (name 'svtv-data$c-pipeline-okp) (a alist))) ;; :in-theory (e/d (cmr::equal-of-pseudo-term-fncall ;; equal-cons-strong) ;; (SVTVPIPE-EV-META-EXTRACT-FORMULA)) ;; :do-not-induct t)))) ;; (acl2::def-functional-instance svtvpipe-ev-of-lazy-beta-reduce ;; cmr::base-ev-of-lazy-beta-reduce ;; ((cmr::base-ev svtvpipe-ev) ;; (cmr::base-ev-list svtvpipe-ev-lst))) (local (defthm pseudo-termp-nth-when-pseudo-term-listp (implies (pseudo-term-listp x) (pseudo-termp (nth n x))))) ;; (define svtvpipe-ev-pseudo-term-mapping-correct-p ((map cmr::pseudo-term-mapping-p) (env alistp)) ;; (b* (((when (atom map)) t) ;; ((unless (mbt (and (consp (car map)) ;; (pseudo-termp (caar map))))) ;; (svtvpipe-ev-pseudo-term-mapping-correct-p (cdr map) env))) ;; (and (equal (svtvpipe-ev (caar map) env) ;; (svtvpipe-ev (cdar map) env)) ;; (svtvpipe-ev-pseudo-term-mapping-correct-p (cdr map) env)))) ;; (acl2::def-functional-instance svtvpipe-ev-term-replace-correct ;; cmr::term-replace-correct ;; ((cmr::base-ev svtvpipe-ev) ;; (cmr::base-ev-list svtvpipe-ev-lst) ;; (cmr::base-ev-pseudo-term-mapping-correct-p ;; svtvpipe-ev-pseudo-term-mapping-correct-p)) ;; :hints(("Goal" :in-theory (enable svtvpipe-ev-pseudo-term-mapping-correct-p)))) (define pipeline-okp-hint-subst ((hints pseudo-term-listp) svtv-data state) :returns (mv err (subst cmr::pseudo-term-mapping-p)) :prepwork ((local (in-theory (disable nth)))) (b* (((acl2::nths cycle-term namemap-term pipeline-setup-term pipeline-term) hints) ((mv cycle-term-err cycle-val) (meta-extract-const-value cycle-term state)) ((when (or cycle-term-err (not (equal cycle-val (svtv-data->cycle-fsm svtv-data))))) (mv (msg "The cycle term given, ~x0, ~@1" cycle-term (if cycle-term-err "failed to evaluate." "does not equal the cycle FSM currently stored in the given svtv-data stobj.")) nil)) ((mv namemap-term-err namemap-val) (meta-extract-const-value namemap-term state)) ((when (or namemap-term-err (not (equal namemap-val (svtv-data->namemap svtv-data))))) (mv (msg "The namemap term given, ~x0, ~@1" (if namemap-term-err "failed to evaluate." "does not equal the namemap currently stored in the given svtv-data stobj.")) nil)) ((mv pipeline-setup-term-err pipeline-setup-val) (meta-extract-const-value pipeline-setup-term state)) ((when (or pipeline-setup-term-err (not (equal pipeline-setup-val (svtv-data->pipeline-setup svtv-data))))) (mv (msg "The pipeline-setup term given, ~x0, ~@1" (if pipeline-setup-term-err "failed to evaluate." "does not equal the pipeline-setup currently stored in the given svtv-data stobj.")) nil)) ((mv pipeline-term-err pipeline-val) (meta-extract-const-value pipeline-term state)) ((when (or pipeline-term-err (not (equal pipeline-val (svtv-data->pipeline svtv-data))))) (mv (msg "The pipeline term given, ~x0, ~@1" (if pipeline-term-err "failed to evaluate." "does not equal the pipeline currently stored in the given svtv-data stobj.")) nil))) (mv nil `(((svtv-data$c->cycle-fsm$inline svtv-data$c) . ,(acl2::pseudo-term-fix cycle-term)) ((svtv-data$c->namemap$inline svtv-data$c) . ,(acl2::pseudo-term-fix namemap-term)) ((svtv-data$c->pipeline-setup$inline svtv-data$c) . ,(acl2::pseudo-term-fix pipeline-setup-term)) (results . ,(acl2::pseudo-term-fix pipeline-term))))) /// ;; (defret <fn>-correct ;; (implies (and (not err) ;; (svtvpipe-ev-meta-extract-global-facts) ;; (equal (cdr (assoc-equal 'svtv-data$c env)) svtv-data) ;; (equal (cdr (assoc-equal 'results env)) (svtv-data->pipeline svtv-data))) ;; (svtvpipe-ev-pseudo-term-mapping-correct-p subst env)) ;; :hints(("Goal" :in-theory (enable svtvpipe-ev-pseudo-term-mapping-correct-p)))) ) (local (acl2::def-functional-instance svtvpipe-ev-when-agree-on-term-vars cmr::base-ev-when-agree-on-term-vars ((cmr::base-ev svtvpipe-ev) (cmr::base-ev-list svtvpipe-ev-lst)))) (local (in-theory (disable svtvpipe-ev-when-agree-on-term-vars))) (local (defthm eval-alists-agree-of-cons-non-member (implies (not (member v lst)) (acl2::eval-alists-agree lst (cons (cons v val) a) a)) :hints(("Goal" :in-theory (enable acl2::eval-alists-agree))))) (defthm svtvpipe-ev-remove-unused-var (implies (not (member v (cmr::term-vars x))) (equal (svtvpipe-ev x (cons (cons v val) a)) (svtvpipe-ev x a))) :hints (("goal" :use ((:instance svtvpipe-ev-when-agree-on-term-vars (b a) (a (cons (cons v val) a))))))) (define svtv-pipeline-clause-proc (clause hints svtv-data state) ;; hints are: (cycle-term namemap-term pipeline-setup-term pipeline-term env-term) (b* (((unless (mbt (svtv-datap svtv-data))) (mv "impossible" nil)) ((unless (svtv-data->pipeline-validp svtv-data)) (mv "svtv-data pipeline not valid" nil)) ((unless (and (pseudo-term-listp hints) (eql (len hints) 5))) (mv "bad hints" nil)) ((mv hints-err ?subst) (pipeline-okp-hint-subst hints svtv-data state)) ((when hints-err) (mv hints-err nil)) ((acl2::nths cycle-term namemap-term pipeline-setup-term pipeline-term env) hints) ;; ((mv impl-err impl-term) (pipeline-okp-implicant-term (w state))) ;; ((when impl-err) ;; (mv impl-err nil)) ;; (impl-term-beta (cmr::lazy-beta-reduce impl-term)) ;; (impl-term-subst (cmr::term-replace impl-term-beta subst)) ;; ((when (cmr::member-term-vars 'results impl-term-subst)) ;; (mv "programming error: result was in added term" nil)) ;; ((when (cmr::member-term-vars 'svtv-data$c impl-term-subst)) ;; (mv "svtv-data$c was still free in term, check def of svtv-data$c-pipeline-okp" nil)) ) ;; (mv nil (list (cons `(not ,impl-term-subst) clause))) (mv nil (list (cons `(not (svtv-pipeline-correct ,cycle-term ,namemap-term ,pipeline-setup-term ,pipeline-term ,env)) clause)))) /// (defthm svtv-pipeline-clause-proc-correct (implies (and (pseudo-term-listp clause) (alistp a) (svtvpipe-ev-meta-extract-global-facts) (svtvpipe-ev (acl2::conjoin-clauses (acl2::clauses-result (svtv-pipeline-clause-proc clause hints svtv-data state))) ;; `((svtv-data$c . ,svtv-data) ;; (results . ,(svtv-data->pipeline svtv-data))) a)) (svtvpipe-ev (disjoin clause) a)) :hints (("goal" :do-not-induct t :in-theory (e/d (pipeline-okp-hint-subst) (nth)) ;; :use ((:instance svtvpipe-ev-term-replace-correct ;; (x (CMR::LAZY-BETA-REDUCE (MV-NTH 1 ;; (PIPELINE-OKP-IMPLICANT-TERM (W STATE))))) ;; (map (MV-NTH 1 ;; (PIPELINE-OKP-HINT-SUBST HINTS SVTV-DATA state))) ;; (env ;; `((svtv-data$c . ,svtv-data) ;; (results . ,(svtv-data->pipeline svtv-data)) ;; . ,a)))) )) :rule-classes :clause-processor)) (defun def-pipeline-thm-fn (svtv-name cycle-name define-cycle stobj-name) (declare (xargs :mode :program)) (b* ((define-cycle (or (not cycle-name) define-cycle)) (cycle-name (or cycle-name (intern-in-package-of-symbol (concatenate 'string (symbol-name svtv-name) "-CYCLE") svtv-name))) (cycle-events (and define-cycle `((make-event `(define ,',cycle-name () :no-function t :returns (fsm base-fsm-p) ',(svtv-data->cycle-fsm ,stobj-name)))))) (namemap-name (intern-in-package-of-symbol (concatenate 'string (symbol-name svtv-name) "-NAMEMAP") svtv-name)) (pipeline-setup-name (intern-in-package-of-symbol (concatenate 'string (symbol-name svtv-name) "-PIPELINE-SETUP") svtv-name)) (thmname (intern-in-package-of-symbol (concatenate 'string (symbol-name svtv-name) "-PIPELINE-CORRECT") svtv-name))) `(progn ,@cycle-events (make-event `(define ,',namemap-name () :no-function t :returns (namemap svtv-name-lhs-map-p) ',(svtv-data->namemap ,stobj-name))) (make-event `(define ,',pipeline-setup-name () :no-function t :returns (setup pipeline-setup-p) ',(svtv-data->pipeline-setup ,stobj-name))) (in-theory (disable ,@(and define-cycle `((,cycle-name))))) (defthmd ,thmname (b* ((fsm (,cycle-name)) (rename-fsm (make-svtv-fsm :base-fsm fsm :namemap (,namemap-name))) (renamed-fsm (svtv-fsm->renamed-fsm rename-fsm)) ((pipeline-setup pipe) (,pipeline-setup-name)) (outvars (svtv-probealist-outvars pipe.probes)) (run (base-fsm-run (svex-alistlist-eval (svtv-fsm-run-input-substs (take (len outvars) pipe.inputs) pipe.overrides rename-fsm) env) (svex-alist-eval pipe.initst env) renamed-fsm outvars))) (svex-envs-equivalent (svex-alist-eval (svtv->outexprs (,svtv-name)) env) (svtv-probealist-extract pipe.probes run))) :hints (("goal" :clause-processor (svtv-pipeline-clause-proc clause '((,cycle-name) (,namemap-name) (,pipeline-setup-name) (svtv->outexprs$inline (,svtv-name)) env) ,stobj-name state) :in-theory (enable svtv-pipeline-correct)))) (add-to-ruleset! svtv-pipeline-thms ,thmname) (add-to-ruleset! svtv-pipeline-thm-constants '((:executable-counterpart ,namemap-name) (:executable-counterpart ,pipeline-setup-name)))))) (defmacro def-pipeline-thm (svtv-name &key cycle-name define-cycle (stobj-name 'svtv-data)) (def-pipeline-thm-fn svtv-name cycle-name define-cycle stobj-name)) (defxdoc def-pipeline-thm :parents (svex-stvs svtv-data) :short "Prove that an SVTV pipeline is an unrolling of the FSM that it's based on" :long "<p>When computing an SVTV pipeline using @(see defsvtv$) or @(see defsvtv$-phasewise), a FSM is first created and the pipeline is then a composition (unrolling) of FSM phases. This is an invariant of the @(see svtv-data) stobj; if the @('pipeline-valid') bit of the @('svtv-data') stobj is set, then it is known that the @('pipeline') field is an unrolling of the @('cycle-fsm') field, with unrolling parameters specified in the @('pipeline-setup') field.</p> <p>The @('def-pipeline-thm') event uses this invariant of the @('svtv-data') stobj to prove that property, given an SVTV that was created using @('defsvtv$'). This event requires that the @('svtv-data') stobj was not changed since the creation of the @('defsvtv$'). It proves a theorem of the following form:</p> @({ (b* ((fsm (svtv-cycle)) (rename-fsm (make-svtv-fsm :base-fsm fsm :namemap (svtv-namemap))) (renamed-fsm (svtv-fsm->renamed-fsm rename-fsm)) ((pipeline-setup pipe) (svtv-pipeline-setup)) (outvars (svtv-probealist-outvars pipe.probes)) (run (base-fsm-run (svex-alistlist-eval (svtv-fsm-run-input-substs (take (len outvars) pipe.inputs) pipe.overrides rename-fsm) env) (svex-alist-eval pipe.initst env) renamed-fsm outvars))) (svex-envs-equivalent (svex-alist-eval (svtv->outexprs (svtv)) env) (svtv-probealist-extract pipe.probes run))) }) <p>Here @('(svtv)') is the SVTV created by @('defsvtv$'). The other constant functions @('(svtv-cycle)'), @('(svtv-namemap)'), and @('(svtv-pipeline-setup)') are introduced by the @('def-pipeline-thm') event. (The cycle function doesn't need to be created if a previous @('def-pipeline-thm') event already introduced it.)</p> <p>The options for @('def-pipeline-thm') are as follows:</p> @({ (def-pipeline-thm svtv-name ;; optional, in case cycle was introduced previously :cycle-name cycle-name) }) ") (define cycle-okp-hint-subst ((hints pseudo-term-listp) svtv-data state) :returns (mv err (subst cmr::pseudo-term-mapping-p)) :prepwork ((local (in-theory (disable nth)))) (b* (((acl2::nths phase-term cycle-phases-term cycle-term) hints) ((mv cycle-term-err cycle-val) (meta-extract-const-value cycle-term state)) ((when (or cycle-term-err (not (equal cycle-val (svtv-data->cycle-fsm svtv-data))))) (mv "bad cycle value" nil)) ((mv phase-term-err phase-val) (meta-extract-const-value phase-term state)) ((when (or phase-term-err (not (equal phase-val (svtv-data->phase-fsm svtv-data))))) (mv "bad phase-fsm value" nil)) ((mv cycle-phases-term-err cycle-phases-val) (meta-extract-const-value cycle-phases-term state)) ((when (or cycle-phases-term-err (not (equal cycle-phases-val (svtv-data->cycle-phases svtv-data))))) (mv "bad cycle-phases value" nil))) (mv nil `(((svtv-data$c->cycle-fsm$inline svtv-data$c) . ,(acl2::pseudo-term-fix cycle-term)) ((svtv-data$c->phase-fsm$inline svtv-data$c) . ,(acl2::pseudo-term-fix phase-term)) ((svtv-data$c->cycle-phases$inline svtv-data$c) . ,(acl2::pseudo-term-fix cycle-phases-term))))) /// ;; (defret <fn>-correct ;; (implies (and (not err) ;; (svtvpipe-ev-meta-extract-global-facts) ;; (equal (cdr (assoc-equal 'svtv-data$c env)) svtv-data) ;; (equal (cdr (assoc-equal 'results env)) (svtv-data->pipeline svtv-data))) ;; (svtvpipe-ev-pseudo-term-mapping-correct-p subst env)) ;; :hints(("Goal" :in-theory (enable svtvpipe-ev-pseudo-term-mapping-correct-p)))) ) (define svtv-cycle-clause-proc (clause hints svtv-data state) ;; hints are: (phase-term cycle-phases-term cycle-term) (b* (((unless (mbt (svtv-datap svtv-data))) (mv "impossible" nil)) ((unless (svtv-data->cycle-fsm-validp svtv-data)) (mv "svtv-data cycle not valid" nil)) ((unless (and (pseudo-term-listp hints) (eql (len hints) 3))) (mv "bad hints" nil)) ((mv hints-err ?subst) (cycle-okp-hint-subst hints svtv-data state)) ((when hints-err) (mv hints-err nil)) ((acl2::nths phase-term cycle-phases-term cycle-term) hints) ;; ((mv impl-err impl-term) (pipeline-okp-implicant-term (w state))) ;; ((when impl-err) ;; (mv impl-err nil)) ;; (impl-term-beta (cmr::lazy-beta-reduce impl-term)) ;; (impl-term-subst (cmr::term-replace impl-term-beta subst)) ;; ((when (cmr::member-term-vars 'results impl-term-subst)) ;; (mv "programming error: result was in added term" nil)) ;; ((when (cmr::member-term-vars 'svtv-data$c impl-term-subst)) ;; (mv "svtv-data$c was still free in term, check def of svtv-data$c-pipeline-okp" nil)) ) ;; (mv nil (list (cons `(not ,impl-term-subst) clause))) (mv nil (list (cons `(not (svtv-cycle-correct ,phase-term ,cycle-phases-term ,cycle-term)) clause)))) /// (defthm svtv-cycle-clause-proc-correct (implies (and (pseudo-term-listp clause) (alistp a) (svtvpipe-ev-meta-extract-global-facts) (svtvpipe-ev (acl2::conjoin-clauses (acl2::clauses-result (svtv-cycle-clause-proc clause hints svtv-data state))) ;; `((svtv-data$c . ,svtv-data) ;; (results . ,(svtv-data->cycle svtv-data))) a)) (svtvpipe-ev (disjoin clause) a)) :hints (("goal" :do-not-induct t :in-theory (e/d (cycle-okp-hint-subst) (nth)) ;; :use ((:instance svtvpipe-ev-term-replace-correct ;; (x (CMR::LAZY-BETA-REDUCE (MV-NTH 1 ;; (CYCLE-OKP-IMPLICANT-TERM (W STATE))))) ;; (map (MV-NTH 1 ;; (CYCLE-OKP-HINT-SUBST HINTS SVTV-DATA state))) ;; (env ;; `((svtv-data$c . ,svtv-data) ;; (results . ,(svtv-data->cycle svtv-data)) ;; . ,a)))) )) :rule-classes :clause-processor)) (defun def-cycle-thm-fn (svtv-name cycle-name phase-name define-cycle define-phase stobj-name) (declare (xargs :mode :program)) (b* ((define-cycle (or (not cycle-name) define-cycle)) (cycle-name (or cycle-name (intern-in-package-of-symbol (concatenate 'string (symbol-name svtv-name) "-CYCLE") svtv-name))) (cycle-events (and define-cycle `((make-event `(define ,',cycle-name () :no-function t :returns (fsm base-fsm-p) ',(svtv-data->cycle-fsm ,stobj-name)))))) (define-phase (or (not phase-name) define-phase)) (phase-name (or phase-name (intern-in-package-of-symbol (concatenate 'string (symbol-name svtv-name) "-PHASE") svtv-name))) (phase-events (and define-phase `((make-event `(define ,',phase-name () :no-function t :returns (fsm base-fsm-p) ',(svtv-data->phase-fsm ,stobj-name)))))) (cycle-phases-name (intern-in-package-of-symbol (concatenate 'string (symbol-name svtv-name) "-CYCLE-PHASES") svtv-name)) (thmname (intern-in-package-of-symbol (concatenate 'string (symbol-name svtv-name) "-CYCLE-CORRECT") svtv-name))) `(progn ,@cycle-events ,@phase-events (make-event `(define ,',cycle-phases-name () :no-function t :returns (cycle-phases svtv-cyclephaselist-p) ',(svtv-data->cycle-phases ,stobj-name))) (in-theory (disable ,@(and define-cycle `((,cycle-name))) ,@(and define-phase `((,phase-name))))) (defthmd ,thmname (b* (((base-fsm phase-fsm) (,phase-name)) ((mv values nextstate) (svtv-cycle-compile (svex-identity-subst (svex-alist-keys phase-fsm.nextstate)) (,cycle-phases-name) phase-fsm nil))) (base-fsm-eval-equiv (,cycle-name) (make-base-fsm :values values :nextstate nextstate))) :hints (("goal" :clause-processor (svtv-cycle-clause-proc clause '((,phase-name) (,cycle-phases-name) (,cycle-name)) ,stobj-name state) :in-theory (enable svtv-cycle-correct)))) (add-to-ruleset! svtv-cycle-thms ,thmname) (add-to-ruleset! svtv-cycle-thm-constants '((:executable-counterpart ,cycle-phases-name)))))) (defmacro def-cycle-thm (svtv-name &key cycle-name phase-name define-cycle define-phase (stobj-name 'svtv-data)) (def-cycle-thm-fn svtv-name cycle-name phase-name define-cycle define-phase stobj-name)) (defxdoc def-cycle-thm :parents (svex-stvs svtv-data) :short "Prove that an SVTV cycle FSM an unrolling of the phase FSM that it's based on" :long " <p>The @('def-cycle-thm') event uses this invariant of the @('svtv-data') stobj to prove that the cycle FSM is equivalent to the unrolling according to the cycle phases of the phase FSM. This event requires that the @('svtv-data') stobj was not disrupted in such a way as to make its cycle FSM invalid since creating the cycle using @('defcycle') or @('defsvtv$'). It proves a theorem of the following form:</p> @({ (b* (((base-fsm phase-fsm) (phase-fsm)) ((mv values nextstate) (svtv-cycle-compile (svex-identity-subst (svex-alist-keys phase-fsm.nextstate)) (cycle-phases) phase-fsm nil))) (base-fsm-eval-equiv (cycle-fsm) (make-base-fsm :values values :nextstate nextstate))) }) <p>The options for @('def-cycle-thm') are as follows:</p> @({ (def-cycle-thm svtv-name ;; used for default names ;; optional, in case cycle was introduced previously :cycle-name cycle-name :phase-name phase-name :define-cycle t :define-phase t :stobj-name svtv-data) }) ")
53514
; Centaur SV Hardware Verification Tutorial ; Copyright (C) 2016 Centaur Technology ; Copyright (C) 2022 Intel Corporation ; ; Contact: ; Centaur Technology Formal Verification Group ; 7600-C N. Capital of Texas Highway, Suite 300, Austin, TX 78731, USA. ; http://www.centtech.com/ ; ; License: (An MIT/X11-style license) ; ; Permission is hereby granted, free of charge, to any person obtaining a ; copy of this software and associated documentation files (the "Software"), ; to deal in the Software without restriction, including without limitation ; the rights to use, copy, modify, merge, publish, distribute, sublicense, ; and/or sell copies of the Software, and to permit persons to whom the ; Software is furnished to do so, subject to the following conditions: ; ; The above copyright notice and this permission notice shall be included in ; all copies or substantial portions of the Software. ; ; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR ; IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, ; FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE ; AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER ; LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING ; FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER ; DEALINGS IN THE SOFTWARE. ; ; Original authors: <NAME> <<EMAIL>> (in-package "SV") (include-book "svtv-stobj") (include-book "svtv-stobj-cycle") (include-book "clause-processors/meta-extract-user" :dir :System) (include-book "clause-processors/pseudo-term-fty" :dir :System) (include-book "centaur/meta/replace" :dir :System) (include-book "centaur/meta/unify-strict" :dir :system) (include-book "centaur/meta/lambda-measure" :dir :system) ;; Uses the contents of a svtv-stobj to prove that a pipeline expresses the ;; correct formula of the cycle. #|| (include-book "svtv-stobj-defsvtv") (local (defconst *my-design* (make-design :top "my-mod" :modalist (list (cons "my-mod" (make-module :wires (list (make-wire :name "in" :width 5 :low-idx 0) (make-wire :name "out" :width 5 :low-idx 0)) :assigns (list (cons (list (make-lhrange :w 5 :atom (make-lhatom-var :name "out" :rsh 0))) (make-driver :value (svcall bitnot (svcall zerox 5 "in"))))))))))) (defsvtv$-phasewise my-svtv :design *my-design* :phases ((:label the-phase :inputs (("in" in)) :outputs (("out" out))) (:label the-next-phase :inputs (("in" in2)) :outputs (("out" out2))))) (def-pipeline-thm my-svtv) (def-cycle-thm my-svtv) ;; (make-event ;; `(defund my-cycle () ;; (declare (xargs :guard t)) ;; ',(svtv-data->cycle-fsm svtv-data))) ;; (make-event ;; `(defund my-namemap () ;; (declare (xargs :guard t)) ;; ',(svtv-data->namemap svtv-data))) ;; (make-event ;; `(defund my-pipeline-setup () ;; (declare (xargs :guard t)) ;; ',(svtv-data->pipeline-setup svtv-data))) ;; (local (in-theory (disable (my-cycle) ;; (my-namemap) ;; (my-pipeline-setup)))) ;; (defthm my-svtv-pipeline-correct ;; (b* ((fsm (my-cycle)) ;; (rename-fsm (make-svtv-fsm :base-fsm fsm ;; :namemap (my-namemap))) ;; (renamed-fsm (svtv-fsm->renamed-fsm rename-fsm)) ;; ((pipeline-setup pipe) (my-pipeline-setup)) ;; (outvars (svtv-probealist-outvars pipe.probes)) ;; (run (base-fsm-run ;; (svex-alistlist-eval ;; (svtv-fsm-run-input-substs ;; (take (len outvars) pipe.inputs) ;; pipe.overrides ;; rename-fsm) ;; env) ;; (svex-alist-eval pipe.initst env) ;; renamed-fsm outvars))) ;; (svex-envs-equivalent ;; (svex-alist-eval (svtv->outexprs (my-svtv)) env) ;; (svtv-probealist-extract pipe.probes run))) ;; :hints (("goal" :clause-processor (svtv-pipeline-clause-proc ;; clause ;; '((my-cycle) ;; (my-namemap) ;; (my-pipeline-setup) ;; (svtv->outexprs$inline (my-svtv)) ;; env) ;; svtv-data state) ;; :in-theory (enable svtv-pipeline-correct)))) ||# (define svtv-pipeline-correct ((cycle-fsm base-fsm-p) (namemap svtv-name-lhs-map-p) (pipeline-setup pipeline-setup-p) (pipeline-result svex-alist-p) (env svex-env-p)) :verify-guards nil :enabled t (b* ((fsm cycle-fsm) (rename-fsm (make-svtv-fsm :base-fsm fsm :namemap namemap)) (renamed-fsm (svtv-fsm->renamed-fsm rename-fsm)) ((pipeline-setup pipe) pipeline-setup) (outvars (svtv-probealist-outvars pipe.probes)) (run (base-fsm-run (svex-alistlist-eval (svtv-fsm-run-input-substs (take (len outvars) pipe.inputs) pipe.overrides rename-fsm) env) (svex-alist-eval pipe.initst env) renamed-fsm outvars))) (svex-envs-equivalent (svex-alist-eval pipeline-result env) (svtv-probealist-extract pipe.probes run))) /// (local (defthm take-of-svex-alistlist-eval (equal (take n (svex-alistlist-eval x env)) (svex-alistlist-eval (take n x) env)) :hints(("Goal" :in-theory (e/d (svex-alistlist-eval take) (acl2::take-when-atom acl2::take-of-too-many)) :induct t :expand ((svex-alist-eval nil env)))))) (defthm svtv-pipeline-correct-when-svtv-data$ap (implies (and (svtv-datap svtv-data) (svtv-data->pipeline-validp svtv-data)) (svtv-pipeline-correct (svtv-data$c->cycle-fsm svtv-data) (svtv-data$c->namemap svtv-data) (svtv-data$c->pipeline-setup svtv-data) (svtv-data$c->pipeline svtv-data) env)) :hints(("Goal" :in-theory (enable svtv-data$ap svtv-fsm-run-is-base-fsm-run))))) (define svtv-cycle-correct ((phase-fsm base-fsm-p) (cycle-phases svtv-cyclephaselist-p) (cycle-fsm base-fsm-p)) :guard (not (hons-dups-p (svex-alist-keys (base-fsm->nextstate phase-fsm)))) :enabled t (b* (((base-fsm phase-fsm)) ((mv values nextstate) (svtv-cycle-compile (svex-identity-subst (svex-alist-keys phase-fsm.nextstate)) cycle-phases phase-fsm nil))) ;; simp is irrelevant under base-fsm-eval-equiv (base-fsm-eval-equiv (make-base-fsm :values values :nextstate nextstate) cycle-fsm)) /// (defthm svtv-cycle-correct-when-svtv-data$ap (implies (and (svtv-datap svtv-data) (svtv-data->cycle-fsm-validp svtv-data)) (svtv-cycle-correct (svtv-data$c->phase-fsm svtv-data) (svtv-data$c->cycle-phases svtv-data) (svtv-data$c->cycle-fsm svtv-data))) :hints(("Goal" :in-theory (enable svtv-data$ap cycle-fsm-okp-implies-cycle-compile-values-equiv))))) (local (in-theory (disable svtv-pipeline-correct svtv-cycle-correct))) (defevaluator svtvpipe-ev svtvpipe-ev-lst ((typespec-check ts x) (if a b c) (equal a b) (not a) (iff a b) (implies a b) ;; (svtv-data$c-pipeline-okp svtvdat results) ;; (svtv-data$c->cycle-fsm$inline svtvdat) ;; (svtv-data$c->pipeline-setup$inline svtvdat) ;; (svtv-data$c->namemap$inline svtvdat) (svtv-pipeline-correct cycle namemap setup pipeline env) (svtv-cycle-correct phase-fsm cycle-phases cycle-fsm) ) :namedp t) (local (acl2::def-ev-pseudo-term-fty-support svtvpipe-ev svtvpipe-ev-lst)) (acl2::def-meta-extract svtvpipe-ev svtvpipe-ev-lst) (local (in-theory (disable w))) (local (acl2::def-functional-instance svtvpipe-ev-when-agree-on-term-vars cmr::base-ev-when-agree-on-term-vars ((cmr::base-ev svtvpipe-ev) (cmr::base-ev-list svtvpipe-ev-lst)))) (local (in-theory (disable svtvpipe-ev-when-agree-on-term-vars))) (local (defthmd svtvpipe-ev-when-no-term-vars (implies (and (syntaxp (not (equal a ''nil))) (not (cmr::term-vars x))) (equal (svtvpipe-ev x a) (svtvpipe-ev x nil))) :hints (("goal" :use ((:instance svtvpipe-ev-when-agree-on-term-vars (a a) (b nil))) :in-theory (enable acl2::eval-alists-agree))))) (define meta-extract-const-value ((term pseudo-termp) state) :returns (mv err val) (b* ((term (acl2::pseudo-term-fix term)) ((unless (eq (cmr::term-vars term) nil)) (mv "term has variables" nil)) ((unless (logic-fnsp term (w state))) (mv "term has non-logic functions" nil))) (acl2::magic-ev term nil state t nil)) ;; (acl2::pseudo-term-case term ;; :const (mv nil term.val) ;; :fncall (b* (((unless (eq term.args nil)) ;; (mv "fncall has arguments" nil)) ;; ((mv ok formals body) (acl2::fn-get-def-w term.fn wrld)) ;; ((unless (and ok ;; (not formals) ;; (pseudo-termp body) ;; (acl2::pseudo-term-case body :const))) ;; (mv (msg "function ~x0 not recognized as a constant" term.fn) nil))) ;; (mv nil (acl2::pseudo-term-const->val body))) ;; :otherwise (mv (msg "bad form for constant term: ~x0" term) nil)) /// (defret <fn>-correct (implies (and (not err) (svtvpipe-ev-meta-extract-global-facts)) (equal (svtvpipe-ev term a) val)) :hints(("Goal" :in-theory (enable svtvpipe-ev-when-no-term-vars))))) ;; (local ;; #!cmr ;; (defthm term-unify-strict-reversible-hyp ;; (implies (acl2::rewriting-negative-literal ;; `(mv-nth '0 (term-unify-strict ,pat ,x ,alist))) ;; (iff (mv-nth 0 (term-unify-strict pat x alist)) ;; (equal (term-subst-strict pat (mv-nth 1 (term-unify-strict pat x alist))) ;; (pseudo-term-fix x)))))) ;; (local (in-theory (disable cmr::term-unify-strict-reversible-iff))) ;; (define pipeline-okp-implicant-term ((wrld plist-worldp)) ;; :returns (mv err (impl-term pseudo-termp)) ;; ;; :verify-guards nil ;; (b* ((form (acl2::meta-extract-formula-w 'svtv-data$c-pipeline-okp wrld)) ;; ((unless (pseudo-termp form)) ;; (mv "pipeline-okp formula was not pseudo-termp" nil)) ;; ;; Form is the conjunction of formulas for the defun-sk, namely ;; ;; definition of pipeline-okp ;; ;; pipeline-okp-necc theorem ;; ;; The second is the one we want. ;; ((mv ok alist) ;; (cmr::term-unify-strict ;; '(if pipe-ok-def (implies (svtv-data$c-pipeline-okp svtv-data$c results) ;; impl-term) ;; 'nil) ;; form ;; '((svtv-data$c . svtv-data$c) ;; (results . results)))) ;; ((unless ok) ;; (mv "pipeline-okp formula had unexpected form" nil))) ;; (mv nil (cdr (hons-assoc-equal 'impl-term alist)))) ;; /// ;; (set-ignore-ok t) ;; (local ;; (make-event ;; (let ((form ;; `(progn ;; (defthm expand-term-subst-strict ;; (implies (syntaxp (quotep x)) ;; (equal (cmr::term-subst-strict x acl2::a) ;; ,(acl2::body 'cmr::term-subst-strict nil (w state)))) ;; :hints(("Goal" :in-theory (enable cmr::term-subst-strict)))) ;; (defthm expand-termlist-subst-strict ;; (implies (syntaxp (quotep x)) ;; (equal (cmr::termlist-subst-strict x acl2::a) ;; ,(acl2::body 'cmr::termlist-subst-strict nil (w state)))) ;; :hints(("Goal" :in-theory (enable cmr::termlist-subst-strict))))))) ;; (value form)))) ;; (local (defthmd equal-cons-strong ;; (implies (syntaxp (not (or (quotep x) ;; (and (quotep a) (quotep b))))) ;; (equal (Equal x (cons a b)) ;; (and (consp x) ;; (equal (car x) a) ;; (equal (cdr x) b)))))) ;; (local (defthm assoc-is-hons-assoc-equal-when-key ;; (implies k ;; (equal (assoc-equal k x) ;; (hons-assoc-equal k x))))) ;; (defret <fn>-correct ;; (implies (and (not err) ;; (svtvpipe-ev-meta-extract-global-facts) ;; (equal wrld (w state)) ;; (svtv-data$c-pipeline-okp ;; (cdr (hons-assoc-equal 'svtv-data$c alist)) ;; (cdr (hons-assoc-equal 'results alist)))) ;; (svtvpipe-ev impl-term alist)) ;; :hints(("Goal" ;; :use ((:instance SVTVPIPE-EV-META-EXTRACT-FORMULA ;; (st state) (name 'svtv-data$c-pipeline-okp) (a alist))) ;; :in-theory (e/d (cmr::equal-of-pseudo-term-fncall ;; equal-cons-strong) ;; (SVTVPIPE-EV-META-EXTRACT-FORMULA)) ;; :do-not-induct t)))) ;; (acl2::def-functional-instance svtvpipe-ev-of-lazy-beta-reduce ;; cmr::base-ev-of-lazy-beta-reduce ;; ((cmr::base-ev svtvpipe-ev) ;; (cmr::base-ev-list svtvpipe-ev-lst))) (local (defthm pseudo-termp-nth-when-pseudo-term-listp (implies (pseudo-term-listp x) (pseudo-termp (nth n x))))) ;; (define svtvpipe-ev-pseudo-term-mapping-correct-p ((map cmr::pseudo-term-mapping-p) (env alistp)) ;; (b* (((when (atom map)) t) ;; ((unless (mbt (and (consp (car map)) ;; (pseudo-termp (caar map))))) ;; (svtvpipe-ev-pseudo-term-mapping-correct-p (cdr map) env))) ;; (and (equal (svtvpipe-ev (caar map) env) ;; (svtvpipe-ev (cdar map) env)) ;; (svtvpipe-ev-pseudo-term-mapping-correct-p (cdr map) env)))) ;; (acl2::def-functional-instance svtvpipe-ev-term-replace-correct ;; cmr::term-replace-correct ;; ((cmr::base-ev svtvpipe-ev) ;; (cmr::base-ev-list svtvpipe-ev-lst) ;; (cmr::base-ev-pseudo-term-mapping-correct-p ;; svtvpipe-ev-pseudo-term-mapping-correct-p)) ;; :hints(("Goal" :in-theory (enable svtvpipe-ev-pseudo-term-mapping-correct-p)))) (define pipeline-okp-hint-subst ((hints pseudo-term-listp) svtv-data state) :returns (mv err (subst cmr::pseudo-term-mapping-p)) :prepwork ((local (in-theory (disable nth)))) (b* (((acl2::nths cycle-term namemap-term pipeline-setup-term pipeline-term) hints) ((mv cycle-term-err cycle-val) (meta-extract-const-value cycle-term state)) ((when (or cycle-term-err (not (equal cycle-val (svtv-data->cycle-fsm svtv-data))))) (mv (msg "The cycle term given, ~x0, ~@1" cycle-term (if cycle-term-err "failed to evaluate." "does not equal the cycle FSM currently stored in the given svtv-data stobj.")) nil)) ((mv namemap-term-err namemap-val) (meta-extract-const-value namemap-term state)) ((when (or namemap-term-err (not (equal namemap-val (svtv-data->namemap svtv-data))))) (mv (msg "The namemap term given, ~x0, ~@1" (if namemap-term-err "failed to evaluate." "does not equal the namemap currently stored in the given svtv-data stobj.")) nil)) ((mv pipeline-setup-term-err pipeline-setup-val) (meta-extract-const-value pipeline-setup-term state)) ((when (or pipeline-setup-term-err (not (equal pipeline-setup-val (svtv-data->pipeline-setup svtv-data))))) (mv (msg "The pipeline-setup term given, ~x0, ~@1" (if pipeline-setup-term-err "failed to evaluate." "does not equal the pipeline-setup currently stored in the given svtv-data stobj.")) nil)) ((mv pipeline-term-err pipeline-val) (meta-extract-const-value pipeline-term state)) ((when (or pipeline-term-err (not (equal pipeline-val (svtv-data->pipeline svtv-data))))) (mv (msg "The pipeline term given, ~x0, ~@1" (if pipeline-term-err "failed to evaluate." "does not equal the pipeline currently stored in the given svtv-data stobj.")) nil))) (mv nil `(((svtv-data$c->cycle-fsm$inline svtv-data$c) . ,(acl2::pseudo-term-fix cycle-term)) ((svtv-data$c->namemap$inline svtv-data$c) . ,(acl2::pseudo-term-fix namemap-term)) ((svtv-data$c->pipeline-setup$inline svtv-data$c) . ,(acl2::pseudo-term-fix pipeline-setup-term)) (results . ,(acl2::pseudo-term-fix pipeline-term))))) /// ;; (defret <fn>-correct ;; (implies (and (not err) ;; (svtvpipe-ev-meta-extract-global-facts) ;; (equal (cdr (assoc-equal 'svtv-data$c env)) svtv-data) ;; (equal (cdr (assoc-equal 'results env)) (svtv-data->pipeline svtv-data))) ;; (svtvpipe-ev-pseudo-term-mapping-correct-p subst env)) ;; :hints(("Goal" :in-theory (enable svtvpipe-ev-pseudo-term-mapping-correct-p)))) ) (local (acl2::def-functional-instance svtvpipe-ev-when-agree-on-term-vars cmr::base-ev-when-agree-on-term-vars ((cmr::base-ev svtvpipe-ev) (cmr::base-ev-list svtvpipe-ev-lst)))) (local (in-theory (disable svtvpipe-ev-when-agree-on-term-vars))) (local (defthm eval-alists-agree-of-cons-non-member (implies (not (member v lst)) (acl2::eval-alists-agree lst (cons (cons v val) a) a)) :hints(("Goal" :in-theory (enable acl2::eval-alists-agree))))) (defthm svtvpipe-ev-remove-unused-var (implies (not (member v (cmr::term-vars x))) (equal (svtvpipe-ev x (cons (cons v val) a)) (svtvpipe-ev x a))) :hints (("goal" :use ((:instance svtvpipe-ev-when-agree-on-term-vars (b a) (a (cons (cons v val) a))))))) (define svtv-pipeline-clause-proc (clause hints svtv-data state) ;; hints are: (cycle-term namemap-term pipeline-setup-term pipeline-term env-term) (b* (((unless (mbt (svtv-datap svtv-data))) (mv "impossible" nil)) ((unless (svtv-data->pipeline-validp svtv-data)) (mv "svtv-data pipeline not valid" nil)) ((unless (and (pseudo-term-listp hints) (eql (len hints) 5))) (mv "bad hints" nil)) ((mv hints-err ?subst) (pipeline-okp-hint-subst hints svtv-data state)) ((when hints-err) (mv hints-err nil)) ((acl2::nths cycle-term namemap-term pipeline-setup-term pipeline-term env) hints) ;; ((mv impl-err impl-term) (pipeline-okp-implicant-term (w state))) ;; ((when impl-err) ;; (mv impl-err nil)) ;; (impl-term-beta (cmr::lazy-beta-reduce impl-term)) ;; (impl-term-subst (cmr::term-replace impl-term-beta subst)) ;; ((when (cmr::member-term-vars 'results impl-term-subst)) ;; (mv "programming error: result was in added term" nil)) ;; ((when (cmr::member-term-vars 'svtv-data$c impl-term-subst)) ;; (mv "svtv-data$c was still free in term, check def of svtv-data$c-pipeline-okp" nil)) ) ;; (mv nil (list (cons `(not ,impl-term-subst) clause))) (mv nil (list (cons `(not (svtv-pipeline-correct ,cycle-term ,namemap-term ,pipeline-setup-term ,pipeline-term ,env)) clause)))) /// (defthm svtv-pipeline-clause-proc-correct (implies (and (pseudo-term-listp clause) (alistp a) (svtvpipe-ev-meta-extract-global-facts) (svtvpipe-ev (acl2::conjoin-clauses (acl2::clauses-result (svtv-pipeline-clause-proc clause hints svtv-data state))) ;; `((svtv-data$c . ,svtv-data) ;; (results . ,(svtv-data->pipeline svtv-data))) a)) (svtvpipe-ev (disjoin clause) a)) :hints (("goal" :do-not-induct t :in-theory (e/d (pipeline-okp-hint-subst) (nth)) ;; :use ((:instance svtvpipe-ev-term-replace-correct ;; (x (CMR::LAZY-BETA-REDUCE (MV-NTH 1 ;; (PIPELINE-OKP-IMPLICANT-TERM (W STATE))))) ;; (map (MV-NTH 1 ;; (PIPELINE-OKP-HINT-SUBST HINTS SVTV-DATA state))) ;; (env ;; `((svtv-data$c . ,svtv-data) ;; (results . ,(svtv-data->pipeline svtv-data)) ;; . ,a)))) )) :rule-classes :clause-processor)) (defun def-pipeline-thm-fn (svtv-name cycle-name define-cycle stobj-name) (declare (xargs :mode :program)) (b* ((define-cycle (or (not cycle-name) define-cycle)) (cycle-name (or cycle-name (intern-in-package-of-symbol (concatenate 'string (symbol-name svtv-name) "-CYCLE") svtv-name))) (cycle-events (and define-cycle `((make-event `(define ,',cycle-name () :no-function t :returns (fsm base-fsm-p) ',(svtv-data->cycle-fsm ,stobj-name)))))) (namemap-name (intern-in-package-of-symbol (concatenate 'string (symbol-name svtv-name) "-NAMEMAP") svtv-name)) (pipeline-setup-name (intern-in-package-of-symbol (concatenate 'string (symbol-name svtv-name) "-PIPELINE-SETUP") svtv-name)) (thmname (intern-in-package-of-symbol (concatenate 'string (symbol-name svtv-name) "-PIPELINE-CORRECT") svtv-name))) `(progn ,@cycle-events (make-event `(define ,',namemap-name () :no-function t :returns (namemap svtv-name-lhs-map-p) ',(svtv-data->namemap ,stobj-name))) (make-event `(define ,',pipeline-setup-name () :no-function t :returns (setup pipeline-setup-p) ',(svtv-data->pipeline-setup ,stobj-name))) (in-theory (disable ,@(and define-cycle `((,cycle-name))))) (defthmd ,thmname (b* ((fsm (,cycle-name)) (rename-fsm (make-svtv-fsm :base-fsm fsm :namemap (,namemap-name))) (renamed-fsm (svtv-fsm->renamed-fsm rename-fsm)) ((pipeline-setup pipe) (,pipeline-setup-name)) (outvars (svtv-probealist-outvars pipe.probes)) (run (base-fsm-run (svex-alistlist-eval (svtv-fsm-run-input-substs (take (len outvars) pipe.inputs) pipe.overrides rename-fsm) env) (svex-alist-eval pipe.initst env) renamed-fsm outvars))) (svex-envs-equivalent (svex-alist-eval (svtv->outexprs (,svtv-name)) env) (svtv-probealist-extract pipe.probes run))) :hints (("goal" :clause-processor (svtv-pipeline-clause-proc clause '((,cycle-name) (,namemap-name) (,pipeline-setup-name) (svtv->outexprs$inline (,svtv-name)) env) ,stobj-name state) :in-theory (enable svtv-pipeline-correct)))) (add-to-ruleset! svtv-pipeline-thms ,thmname) (add-to-ruleset! svtv-pipeline-thm-constants '((:executable-counterpart ,namemap-name) (:executable-counterpart ,pipeline-setup-name)))))) (defmacro def-pipeline-thm (svtv-name &key cycle-name define-cycle (stobj-name 'svtv-data)) (def-pipeline-thm-fn svtv-name cycle-name define-cycle stobj-name)) (defxdoc def-pipeline-thm :parents (svex-stvs svtv-data) :short "Prove that an SVTV pipeline is an unrolling of the FSM that it's based on" :long "<p>When computing an SVTV pipeline using @(see defsvtv$) or @(see defsvtv$-phasewise), a FSM is first created and the pipeline is then a composition (unrolling) of FSM phases. This is an invariant of the @(see svtv-data) stobj; if the @('pipeline-valid') bit of the @('svtv-data') stobj is set, then it is known that the @('pipeline') field is an unrolling of the @('cycle-fsm') field, with unrolling parameters specified in the @('pipeline-setup') field.</p> <p>The @('def-pipeline-thm') event uses this invariant of the @('svtv-data') stobj to prove that property, given an SVTV that was created using @('defsvtv$'). This event requires that the @('svtv-data') stobj was not changed since the creation of the @('defsvtv$'). It proves a theorem of the following form:</p> @({ (b* ((fsm (svtv-cycle)) (rename-fsm (make-svtv-fsm :base-fsm fsm :namemap (svtv-namemap))) (renamed-fsm (svtv-fsm->renamed-fsm rename-fsm)) ((pipeline-setup pipe) (svtv-pipeline-setup)) (outvars (svtv-probealist-outvars pipe.probes)) (run (base-fsm-run (svex-alistlist-eval (svtv-fsm-run-input-substs (take (len outvars) pipe.inputs) pipe.overrides rename-fsm) env) (svex-alist-eval pipe.initst env) renamed-fsm outvars))) (svex-envs-equivalent (svex-alist-eval (svtv->outexprs (svtv)) env) (svtv-probealist-extract pipe.probes run))) }) <p>Here @('(svtv)') is the SVTV created by @('defsvtv$'). The other constant functions @('(svtv-cycle)'), @('(svtv-namemap)'), and @('(svtv-pipeline-setup)') are introduced by the @('def-pipeline-thm') event. (The cycle function doesn't need to be created if a previous @('def-pipeline-thm') event already introduced it.)</p> <p>The options for @('def-pipeline-thm') are as follows:</p> @({ (def-pipeline-thm svtv-name ;; optional, in case cycle was introduced previously :cycle-name cycle-name) }) ") (define cycle-okp-hint-subst ((hints pseudo-term-listp) svtv-data state) :returns (mv err (subst cmr::pseudo-term-mapping-p)) :prepwork ((local (in-theory (disable nth)))) (b* (((acl2::nths phase-term cycle-phases-term cycle-term) hints) ((mv cycle-term-err cycle-val) (meta-extract-const-value cycle-term state)) ((when (or cycle-term-err (not (equal cycle-val (svtv-data->cycle-fsm svtv-data))))) (mv "bad cycle value" nil)) ((mv phase-term-err phase-val) (meta-extract-const-value phase-term state)) ((when (or phase-term-err (not (equal phase-val (svtv-data->phase-fsm svtv-data))))) (mv "bad phase-fsm value" nil)) ((mv cycle-phases-term-err cycle-phases-val) (meta-extract-const-value cycle-phases-term state)) ((when (or cycle-phases-term-err (not (equal cycle-phases-val (svtv-data->cycle-phases svtv-data))))) (mv "bad cycle-phases value" nil))) (mv nil `(((svtv-data$c->cycle-fsm$inline svtv-data$c) . ,(acl2::pseudo-term-fix cycle-term)) ((svtv-data$c->phase-fsm$inline svtv-data$c) . ,(acl2::pseudo-term-fix phase-term)) ((svtv-data$c->cycle-phases$inline svtv-data$c) . ,(acl2::pseudo-term-fix cycle-phases-term))))) /// ;; (defret <fn>-correct ;; (implies (and (not err) ;; (svtvpipe-ev-meta-extract-global-facts) ;; (equal (cdr (assoc-equal 'svtv-data$c env)) svtv-data) ;; (equal (cdr (assoc-equal 'results env)) (svtv-data->pipeline svtv-data))) ;; (svtvpipe-ev-pseudo-term-mapping-correct-p subst env)) ;; :hints(("Goal" :in-theory (enable svtvpipe-ev-pseudo-term-mapping-correct-p)))) ) (define svtv-cycle-clause-proc (clause hints svtv-data state) ;; hints are: (phase-term cycle-phases-term cycle-term) (b* (((unless (mbt (svtv-datap svtv-data))) (mv "impossible" nil)) ((unless (svtv-data->cycle-fsm-validp svtv-data)) (mv "svtv-data cycle not valid" nil)) ((unless (and (pseudo-term-listp hints) (eql (len hints) 3))) (mv "bad hints" nil)) ((mv hints-err ?subst) (cycle-okp-hint-subst hints svtv-data state)) ((when hints-err) (mv hints-err nil)) ((acl2::nths phase-term cycle-phases-term cycle-term) hints) ;; ((mv impl-err impl-term) (pipeline-okp-implicant-term (w state))) ;; ((when impl-err) ;; (mv impl-err nil)) ;; (impl-term-beta (cmr::lazy-beta-reduce impl-term)) ;; (impl-term-subst (cmr::term-replace impl-term-beta subst)) ;; ((when (cmr::member-term-vars 'results impl-term-subst)) ;; (mv "programming error: result was in added term" nil)) ;; ((when (cmr::member-term-vars 'svtv-data$c impl-term-subst)) ;; (mv "svtv-data$c was still free in term, check def of svtv-data$c-pipeline-okp" nil)) ) ;; (mv nil (list (cons `(not ,impl-term-subst) clause))) (mv nil (list (cons `(not (svtv-cycle-correct ,phase-term ,cycle-phases-term ,cycle-term)) clause)))) /// (defthm svtv-cycle-clause-proc-correct (implies (and (pseudo-term-listp clause) (alistp a) (svtvpipe-ev-meta-extract-global-facts) (svtvpipe-ev (acl2::conjoin-clauses (acl2::clauses-result (svtv-cycle-clause-proc clause hints svtv-data state))) ;; `((svtv-data$c . ,svtv-data) ;; (results . ,(svtv-data->cycle svtv-data))) a)) (svtvpipe-ev (disjoin clause) a)) :hints (("goal" :do-not-induct t :in-theory (e/d (cycle-okp-hint-subst) (nth)) ;; :use ((:instance svtvpipe-ev-term-replace-correct ;; (x (CMR::LAZY-BETA-REDUCE (MV-NTH 1 ;; (CYCLE-OKP-IMPLICANT-TERM (W STATE))))) ;; (map (MV-NTH 1 ;; (CYCLE-OKP-HINT-SUBST HINTS SVTV-DATA state))) ;; (env ;; `((svtv-data$c . ,svtv-data) ;; (results . ,(svtv-data->cycle svtv-data)) ;; . ,a)))) )) :rule-classes :clause-processor)) (defun def-cycle-thm-fn (svtv-name cycle-name phase-name define-cycle define-phase stobj-name) (declare (xargs :mode :program)) (b* ((define-cycle (or (not cycle-name) define-cycle)) (cycle-name (or cycle-name (intern-in-package-of-symbol (concatenate 'string (symbol-name svtv-name) "-CYCLE") svtv-name))) (cycle-events (and define-cycle `((make-event `(define ,',cycle-name () :no-function t :returns (fsm base-fsm-p) ',(svtv-data->cycle-fsm ,stobj-name)))))) (define-phase (or (not phase-name) define-phase)) (phase-name (or phase-name (intern-in-package-of-symbol (concatenate 'string (symbol-name svtv-name) "-PHASE") svtv-name))) (phase-events (and define-phase `((make-event `(define ,',phase-name () :no-function t :returns (fsm base-fsm-p) ',(svtv-data->phase-fsm ,stobj-name)))))) (cycle-phases-name (intern-in-package-of-symbol (concatenate 'string (symbol-name svtv-name) "-CYCLE-PHASES") svtv-name)) (thmname (intern-in-package-of-symbol (concatenate 'string (symbol-name svtv-name) "-CYCLE-CORRECT") svtv-name))) `(progn ,@cycle-events ,@phase-events (make-event `(define ,',cycle-phases-name () :no-function t :returns (cycle-phases svtv-cyclephaselist-p) ',(svtv-data->cycle-phases ,stobj-name))) (in-theory (disable ,@(and define-cycle `((,cycle-name))) ,@(and define-phase `((,phase-name))))) (defthmd ,thmname (b* (((base-fsm phase-fsm) (,phase-name)) ((mv values nextstate) (svtv-cycle-compile (svex-identity-subst (svex-alist-keys phase-fsm.nextstate)) (,cycle-phases-name) phase-fsm nil))) (base-fsm-eval-equiv (,cycle-name) (make-base-fsm :values values :nextstate nextstate))) :hints (("goal" :clause-processor (svtv-cycle-clause-proc clause '((,phase-name) (,cycle-phases-name) (,cycle-name)) ,stobj-name state) :in-theory (enable svtv-cycle-correct)))) (add-to-ruleset! svtv-cycle-thms ,thmname) (add-to-ruleset! svtv-cycle-thm-constants '((:executable-counterpart ,cycle-phases-name)))))) (defmacro def-cycle-thm (svtv-name &key cycle-name phase-name define-cycle define-phase (stobj-name 'svtv-data)) (def-cycle-thm-fn svtv-name cycle-name phase-name define-cycle define-phase stobj-name)) (defxdoc def-cycle-thm :parents (svex-stvs svtv-data) :short "Prove that an SVTV cycle FSM an unrolling of the phase FSM that it's based on" :long " <p>The @('def-cycle-thm') event uses this invariant of the @('svtv-data') stobj to prove that the cycle FSM is equivalent to the unrolling according to the cycle phases of the phase FSM. This event requires that the @('svtv-data') stobj was not disrupted in such a way as to make its cycle FSM invalid since creating the cycle using @('defcycle') or @('defsvtv$'). It proves a theorem of the following form:</p> @({ (b* (((base-fsm phase-fsm) (phase-fsm)) ((mv values nextstate) (svtv-cycle-compile (svex-identity-subst (svex-alist-keys phase-fsm.nextstate)) (cycle-phases) phase-fsm nil))) (base-fsm-eval-equiv (cycle-fsm) (make-base-fsm :values values :nextstate nextstate))) }) <p>The options for @('def-cycle-thm') are as follows:</p> @({ (def-cycle-thm svtv-name ;; used for default names ;; optional, in case cycle was introduced previously :cycle-name cycle-name :phase-name phase-name :define-cycle t :define-phase t :stobj-name svtv-data) }) ")
true
; Centaur SV Hardware Verification Tutorial ; Copyright (C) 2016 Centaur Technology ; Copyright (C) 2022 Intel Corporation ; ; Contact: ; Centaur Technology Formal Verification Group ; 7600-C N. Capital of Texas Highway, Suite 300, Austin, TX 78731, USA. ; http://www.centtech.com/ ; ; License: (An MIT/X11-style license) ; ; Permission is hereby granted, free of charge, to any person obtaining a ; copy of this software and associated documentation files (the "Software"), ; to deal in the Software without restriction, including without limitation ; the rights to use, copy, modify, merge, publish, distribute, sublicense, ; and/or sell copies of the Software, and to permit persons to whom the ; Software is furnished to do so, subject to the following conditions: ; ; The above copyright notice and this permission notice shall be included in ; all copies or substantial portions of the Software. ; ; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR ; IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, ; FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE ; AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER ; LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING ; FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER ; DEALINGS IN THE SOFTWARE. ; ; Original authors: PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> (in-package "SV") (include-book "svtv-stobj") (include-book "svtv-stobj-cycle") (include-book "clause-processors/meta-extract-user" :dir :System) (include-book "clause-processors/pseudo-term-fty" :dir :System) (include-book "centaur/meta/replace" :dir :System) (include-book "centaur/meta/unify-strict" :dir :system) (include-book "centaur/meta/lambda-measure" :dir :system) ;; Uses the contents of a svtv-stobj to prove that a pipeline expresses the ;; correct formula of the cycle. #|| (include-book "svtv-stobj-defsvtv") (local (defconst *my-design* (make-design :top "my-mod" :modalist (list (cons "my-mod" (make-module :wires (list (make-wire :name "in" :width 5 :low-idx 0) (make-wire :name "out" :width 5 :low-idx 0)) :assigns (list (cons (list (make-lhrange :w 5 :atom (make-lhatom-var :name "out" :rsh 0))) (make-driver :value (svcall bitnot (svcall zerox 5 "in"))))))))))) (defsvtv$-phasewise my-svtv :design *my-design* :phases ((:label the-phase :inputs (("in" in)) :outputs (("out" out))) (:label the-next-phase :inputs (("in" in2)) :outputs (("out" out2))))) (def-pipeline-thm my-svtv) (def-cycle-thm my-svtv) ;; (make-event ;; `(defund my-cycle () ;; (declare (xargs :guard t)) ;; ',(svtv-data->cycle-fsm svtv-data))) ;; (make-event ;; `(defund my-namemap () ;; (declare (xargs :guard t)) ;; ',(svtv-data->namemap svtv-data))) ;; (make-event ;; `(defund my-pipeline-setup () ;; (declare (xargs :guard t)) ;; ',(svtv-data->pipeline-setup svtv-data))) ;; (local (in-theory (disable (my-cycle) ;; (my-namemap) ;; (my-pipeline-setup)))) ;; (defthm my-svtv-pipeline-correct ;; (b* ((fsm (my-cycle)) ;; (rename-fsm (make-svtv-fsm :base-fsm fsm ;; :namemap (my-namemap))) ;; (renamed-fsm (svtv-fsm->renamed-fsm rename-fsm)) ;; ((pipeline-setup pipe) (my-pipeline-setup)) ;; (outvars (svtv-probealist-outvars pipe.probes)) ;; (run (base-fsm-run ;; (svex-alistlist-eval ;; (svtv-fsm-run-input-substs ;; (take (len outvars) pipe.inputs) ;; pipe.overrides ;; rename-fsm) ;; env) ;; (svex-alist-eval pipe.initst env) ;; renamed-fsm outvars))) ;; (svex-envs-equivalent ;; (svex-alist-eval (svtv->outexprs (my-svtv)) env) ;; (svtv-probealist-extract pipe.probes run))) ;; :hints (("goal" :clause-processor (svtv-pipeline-clause-proc ;; clause ;; '((my-cycle) ;; (my-namemap) ;; (my-pipeline-setup) ;; (svtv->outexprs$inline (my-svtv)) ;; env) ;; svtv-data state) ;; :in-theory (enable svtv-pipeline-correct)))) ||# (define svtv-pipeline-correct ((cycle-fsm base-fsm-p) (namemap svtv-name-lhs-map-p) (pipeline-setup pipeline-setup-p) (pipeline-result svex-alist-p) (env svex-env-p)) :verify-guards nil :enabled t (b* ((fsm cycle-fsm) (rename-fsm (make-svtv-fsm :base-fsm fsm :namemap namemap)) (renamed-fsm (svtv-fsm->renamed-fsm rename-fsm)) ((pipeline-setup pipe) pipeline-setup) (outvars (svtv-probealist-outvars pipe.probes)) (run (base-fsm-run (svex-alistlist-eval (svtv-fsm-run-input-substs (take (len outvars) pipe.inputs) pipe.overrides rename-fsm) env) (svex-alist-eval pipe.initst env) renamed-fsm outvars))) (svex-envs-equivalent (svex-alist-eval pipeline-result env) (svtv-probealist-extract pipe.probes run))) /// (local (defthm take-of-svex-alistlist-eval (equal (take n (svex-alistlist-eval x env)) (svex-alistlist-eval (take n x) env)) :hints(("Goal" :in-theory (e/d (svex-alistlist-eval take) (acl2::take-when-atom acl2::take-of-too-many)) :induct t :expand ((svex-alist-eval nil env)))))) (defthm svtv-pipeline-correct-when-svtv-data$ap (implies (and (svtv-datap svtv-data) (svtv-data->pipeline-validp svtv-data)) (svtv-pipeline-correct (svtv-data$c->cycle-fsm svtv-data) (svtv-data$c->namemap svtv-data) (svtv-data$c->pipeline-setup svtv-data) (svtv-data$c->pipeline svtv-data) env)) :hints(("Goal" :in-theory (enable svtv-data$ap svtv-fsm-run-is-base-fsm-run))))) (define svtv-cycle-correct ((phase-fsm base-fsm-p) (cycle-phases svtv-cyclephaselist-p) (cycle-fsm base-fsm-p)) :guard (not (hons-dups-p (svex-alist-keys (base-fsm->nextstate phase-fsm)))) :enabled t (b* (((base-fsm phase-fsm)) ((mv values nextstate) (svtv-cycle-compile (svex-identity-subst (svex-alist-keys phase-fsm.nextstate)) cycle-phases phase-fsm nil))) ;; simp is irrelevant under base-fsm-eval-equiv (base-fsm-eval-equiv (make-base-fsm :values values :nextstate nextstate) cycle-fsm)) /// (defthm svtv-cycle-correct-when-svtv-data$ap (implies (and (svtv-datap svtv-data) (svtv-data->cycle-fsm-validp svtv-data)) (svtv-cycle-correct (svtv-data$c->phase-fsm svtv-data) (svtv-data$c->cycle-phases svtv-data) (svtv-data$c->cycle-fsm svtv-data))) :hints(("Goal" :in-theory (enable svtv-data$ap cycle-fsm-okp-implies-cycle-compile-values-equiv))))) (local (in-theory (disable svtv-pipeline-correct svtv-cycle-correct))) (defevaluator svtvpipe-ev svtvpipe-ev-lst ((typespec-check ts x) (if a b c) (equal a b) (not a) (iff a b) (implies a b) ;; (svtv-data$c-pipeline-okp svtvdat results) ;; (svtv-data$c->cycle-fsm$inline svtvdat) ;; (svtv-data$c->pipeline-setup$inline svtvdat) ;; (svtv-data$c->namemap$inline svtvdat) (svtv-pipeline-correct cycle namemap setup pipeline env) (svtv-cycle-correct phase-fsm cycle-phases cycle-fsm) ) :namedp t) (local (acl2::def-ev-pseudo-term-fty-support svtvpipe-ev svtvpipe-ev-lst)) (acl2::def-meta-extract svtvpipe-ev svtvpipe-ev-lst) (local (in-theory (disable w))) (local (acl2::def-functional-instance svtvpipe-ev-when-agree-on-term-vars cmr::base-ev-when-agree-on-term-vars ((cmr::base-ev svtvpipe-ev) (cmr::base-ev-list svtvpipe-ev-lst)))) (local (in-theory (disable svtvpipe-ev-when-agree-on-term-vars))) (local (defthmd svtvpipe-ev-when-no-term-vars (implies (and (syntaxp (not (equal a ''nil))) (not (cmr::term-vars x))) (equal (svtvpipe-ev x a) (svtvpipe-ev x nil))) :hints (("goal" :use ((:instance svtvpipe-ev-when-agree-on-term-vars (a a) (b nil))) :in-theory (enable acl2::eval-alists-agree))))) (define meta-extract-const-value ((term pseudo-termp) state) :returns (mv err val) (b* ((term (acl2::pseudo-term-fix term)) ((unless (eq (cmr::term-vars term) nil)) (mv "term has variables" nil)) ((unless (logic-fnsp term (w state))) (mv "term has non-logic functions" nil))) (acl2::magic-ev term nil state t nil)) ;; (acl2::pseudo-term-case term ;; :const (mv nil term.val) ;; :fncall (b* (((unless (eq term.args nil)) ;; (mv "fncall has arguments" nil)) ;; ((mv ok formals body) (acl2::fn-get-def-w term.fn wrld)) ;; ((unless (and ok ;; (not formals) ;; (pseudo-termp body) ;; (acl2::pseudo-term-case body :const))) ;; (mv (msg "function ~x0 not recognized as a constant" term.fn) nil))) ;; (mv nil (acl2::pseudo-term-const->val body))) ;; :otherwise (mv (msg "bad form for constant term: ~x0" term) nil)) /// (defret <fn>-correct (implies (and (not err) (svtvpipe-ev-meta-extract-global-facts)) (equal (svtvpipe-ev term a) val)) :hints(("Goal" :in-theory (enable svtvpipe-ev-when-no-term-vars))))) ;; (local ;; #!cmr ;; (defthm term-unify-strict-reversible-hyp ;; (implies (acl2::rewriting-negative-literal ;; `(mv-nth '0 (term-unify-strict ,pat ,x ,alist))) ;; (iff (mv-nth 0 (term-unify-strict pat x alist)) ;; (equal (term-subst-strict pat (mv-nth 1 (term-unify-strict pat x alist))) ;; (pseudo-term-fix x)))))) ;; (local (in-theory (disable cmr::term-unify-strict-reversible-iff))) ;; (define pipeline-okp-implicant-term ((wrld plist-worldp)) ;; :returns (mv err (impl-term pseudo-termp)) ;; ;; :verify-guards nil ;; (b* ((form (acl2::meta-extract-formula-w 'svtv-data$c-pipeline-okp wrld)) ;; ((unless (pseudo-termp form)) ;; (mv "pipeline-okp formula was not pseudo-termp" nil)) ;; ;; Form is the conjunction of formulas for the defun-sk, namely ;; ;; definition of pipeline-okp ;; ;; pipeline-okp-necc theorem ;; ;; The second is the one we want. ;; ((mv ok alist) ;; (cmr::term-unify-strict ;; '(if pipe-ok-def (implies (svtv-data$c-pipeline-okp svtv-data$c results) ;; impl-term) ;; 'nil) ;; form ;; '((svtv-data$c . svtv-data$c) ;; (results . results)))) ;; ((unless ok) ;; (mv "pipeline-okp formula had unexpected form" nil))) ;; (mv nil (cdr (hons-assoc-equal 'impl-term alist)))) ;; /// ;; (set-ignore-ok t) ;; (local ;; (make-event ;; (let ((form ;; `(progn ;; (defthm expand-term-subst-strict ;; (implies (syntaxp (quotep x)) ;; (equal (cmr::term-subst-strict x acl2::a) ;; ,(acl2::body 'cmr::term-subst-strict nil (w state)))) ;; :hints(("Goal" :in-theory (enable cmr::term-subst-strict)))) ;; (defthm expand-termlist-subst-strict ;; (implies (syntaxp (quotep x)) ;; (equal (cmr::termlist-subst-strict x acl2::a) ;; ,(acl2::body 'cmr::termlist-subst-strict nil (w state)))) ;; :hints(("Goal" :in-theory (enable cmr::termlist-subst-strict))))))) ;; (value form)))) ;; (local (defthmd equal-cons-strong ;; (implies (syntaxp (not (or (quotep x) ;; (and (quotep a) (quotep b))))) ;; (equal (Equal x (cons a b)) ;; (and (consp x) ;; (equal (car x) a) ;; (equal (cdr x) b)))))) ;; (local (defthm assoc-is-hons-assoc-equal-when-key ;; (implies k ;; (equal (assoc-equal k x) ;; (hons-assoc-equal k x))))) ;; (defret <fn>-correct ;; (implies (and (not err) ;; (svtvpipe-ev-meta-extract-global-facts) ;; (equal wrld (w state)) ;; (svtv-data$c-pipeline-okp ;; (cdr (hons-assoc-equal 'svtv-data$c alist)) ;; (cdr (hons-assoc-equal 'results alist)))) ;; (svtvpipe-ev impl-term alist)) ;; :hints(("Goal" ;; :use ((:instance SVTVPIPE-EV-META-EXTRACT-FORMULA ;; (st state) (name 'svtv-data$c-pipeline-okp) (a alist))) ;; :in-theory (e/d (cmr::equal-of-pseudo-term-fncall ;; equal-cons-strong) ;; (SVTVPIPE-EV-META-EXTRACT-FORMULA)) ;; :do-not-induct t)))) ;; (acl2::def-functional-instance svtvpipe-ev-of-lazy-beta-reduce ;; cmr::base-ev-of-lazy-beta-reduce ;; ((cmr::base-ev svtvpipe-ev) ;; (cmr::base-ev-list svtvpipe-ev-lst))) (local (defthm pseudo-termp-nth-when-pseudo-term-listp (implies (pseudo-term-listp x) (pseudo-termp (nth n x))))) ;; (define svtvpipe-ev-pseudo-term-mapping-correct-p ((map cmr::pseudo-term-mapping-p) (env alistp)) ;; (b* (((when (atom map)) t) ;; ((unless (mbt (and (consp (car map)) ;; (pseudo-termp (caar map))))) ;; (svtvpipe-ev-pseudo-term-mapping-correct-p (cdr map) env))) ;; (and (equal (svtvpipe-ev (caar map) env) ;; (svtvpipe-ev (cdar map) env)) ;; (svtvpipe-ev-pseudo-term-mapping-correct-p (cdr map) env)))) ;; (acl2::def-functional-instance svtvpipe-ev-term-replace-correct ;; cmr::term-replace-correct ;; ((cmr::base-ev svtvpipe-ev) ;; (cmr::base-ev-list svtvpipe-ev-lst) ;; (cmr::base-ev-pseudo-term-mapping-correct-p ;; svtvpipe-ev-pseudo-term-mapping-correct-p)) ;; :hints(("Goal" :in-theory (enable svtvpipe-ev-pseudo-term-mapping-correct-p)))) (define pipeline-okp-hint-subst ((hints pseudo-term-listp) svtv-data state) :returns (mv err (subst cmr::pseudo-term-mapping-p)) :prepwork ((local (in-theory (disable nth)))) (b* (((acl2::nths cycle-term namemap-term pipeline-setup-term pipeline-term) hints) ((mv cycle-term-err cycle-val) (meta-extract-const-value cycle-term state)) ((when (or cycle-term-err (not (equal cycle-val (svtv-data->cycle-fsm svtv-data))))) (mv (msg "The cycle term given, ~x0, ~@1" cycle-term (if cycle-term-err "failed to evaluate." "does not equal the cycle FSM currently stored in the given svtv-data stobj.")) nil)) ((mv namemap-term-err namemap-val) (meta-extract-const-value namemap-term state)) ((when (or namemap-term-err (not (equal namemap-val (svtv-data->namemap svtv-data))))) (mv (msg "The namemap term given, ~x0, ~@1" (if namemap-term-err "failed to evaluate." "does not equal the namemap currently stored in the given svtv-data stobj.")) nil)) ((mv pipeline-setup-term-err pipeline-setup-val) (meta-extract-const-value pipeline-setup-term state)) ((when (or pipeline-setup-term-err (not (equal pipeline-setup-val (svtv-data->pipeline-setup svtv-data))))) (mv (msg "The pipeline-setup term given, ~x0, ~@1" (if pipeline-setup-term-err "failed to evaluate." "does not equal the pipeline-setup currently stored in the given svtv-data stobj.")) nil)) ((mv pipeline-term-err pipeline-val) (meta-extract-const-value pipeline-term state)) ((when (or pipeline-term-err (not (equal pipeline-val (svtv-data->pipeline svtv-data))))) (mv (msg "The pipeline term given, ~x0, ~@1" (if pipeline-term-err "failed to evaluate." "does not equal the pipeline currently stored in the given svtv-data stobj.")) nil))) (mv nil `(((svtv-data$c->cycle-fsm$inline svtv-data$c) . ,(acl2::pseudo-term-fix cycle-term)) ((svtv-data$c->namemap$inline svtv-data$c) . ,(acl2::pseudo-term-fix namemap-term)) ((svtv-data$c->pipeline-setup$inline svtv-data$c) . ,(acl2::pseudo-term-fix pipeline-setup-term)) (results . ,(acl2::pseudo-term-fix pipeline-term))))) /// ;; (defret <fn>-correct ;; (implies (and (not err) ;; (svtvpipe-ev-meta-extract-global-facts) ;; (equal (cdr (assoc-equal 'svtv-data$c env)) svtv-data) ;; (equal (cdr (assoc-equal 'results env)) (svtv-data->pipeline svtv-data))) ;; (svtvpipe-ev-pseudo-term-mapping-correct-p subst env)) ;; :hints(("Goal" :in-theory (enable svtvpipe-ev-pseudo-term-mapping-correct-p)))) ) (local (acl2::def-functional-instance svtvpipe-ev-when-agree-on-term-vars cmr::base-ev-when-agree-on-term-vars ((cmr::base-ev svtvpipe-ev) (cmr::base-ev-list svtvpipe-ev-lst)))) (local (in-theory (disable svtvpipe-ev-when-agree-on-term-vars))) (local (defthm eval-alists-agree-of-cons-non-member (implies (not (member v lst)) (acl2::eval-alists-agree lst (cons (cons v val) a) a)) :hints(("Goal" :in-theory (enable acl2::eval-alists-agree))))) (defthm svtvpipe-ev-remove-unused-var (implies (not (member v (cmr::term-vars x))) (equal (svtvpipe-ev x (cons (cons v val) a)) (svtvpipe-ev x a))) :hints (("goal" :use ((:instance svtvpipe-ev-when-agree-on-term-vars (b a) (a (cons (cons v val) a))))))) (define svtv-pipeline-clause-proc (clause hints svtv-data state) ;; hints are: (cycle-term namemap-term pipeline-setup-term pipeline-term env-term) (b* (((unless (mbt (svtv-datap svtv-data))) (mv "impossible" nil)) ((unless (svtv-data->pipeline-validp svtv-data)) (mv "svtv-data pipeline not valid" nil)) ((unless (and (pseudo-term-listp hints) (eql (len hints) 5))) (mv "bad hints" nil)) ((mv hints-err ?subst) (pipeline-okp-hint-subst hints svtv-data state)) ((when hints-err) (mv hints-err nil)) ((acl2::nths cycle-term namemap-term pipeline-setup-term pipeline-term env) hints) ;; ((mv impl-err impl-term) (pipeline-okp-implicant-term (w state))) ;; ((when impl-err) ;; (mv impl-err nil)) ;; (impl-term-beta (cmr::lazy-beta-reduce impl-term)) ;; (impl-term-subst (cmr::term-replace impl-term-beta subst)) ;; ((when (cmr::member-term-vars 'results impl-term-subst)) ;; (mv "programming error: result was in added term" nil)) ;; ((when (cmr::member-term-vars 'svtv-data$c impl-term-subst)) ;; (mv "svtv-data$c was still free in term, check def of svtv-data$c-pipeline-okp" nil)) ) ;; (mv nil (list (cons `(not ,impl-term-subst) clause))) (mv nil (list (cons `(not (svtv-pipeline-correct ,cycle-term ,namemap-term ,pipeline-setup-term ,pipeline-term ,env)) clause)))) /// (defthm svtv-pipeline-clause-proc-correct (implies (and (pseudo-term-listp clause) (alistp a) (svtvpipe-ev-meta-extract-global-facts) (svtvpipe-ev (acl2::conjoin-clauses (acl2::clauses-result (svtv-pipeline-clause-proc clause hints svtv-data state))) ;; `((svtv-data$c . ,svtv-data) ;; (results . ,(svtv-data->pipeline svtv-data))) a)) (svtvpipe-ev (disjoin clause) a)) :hints (("goal" :do-not-induct t :in-theory (e/d (pipeline-okp-hint-subst) (nth)) ;; :use ((:instance svtvpipe-ev-term-replace-correct ;; (x (CMR::LAZY-BETA-REDUCE (MV-NTH 1 ;; (PIPELINE-OKP-IMPLICANT-TERM (W STATE))))) ;; (map (MV-NTH 1 ;; (PIPELINE-OKP-HINT-SUBST HINTS SVTV-DATA state))) ;; (env ;; `((svtv-data$c . ,svtv-data) ;; (results . ,(svtv-data->pipeline svtv-data)) ;; . ,a)))) )) :rule-classes :clause-processor)) (defun def-pipeline-thm-fn (svtv-name cycle-name define-cycle stobj-name) (declare (xargs :mode :program)) (b* ((define-cycle (or (not cycle-name) define-cycle)) (cycle-name (or cycle-name (intern-in-package-of-symbol (concatenate 'string (symbol-name svtv-name) "-CYCLE") svtv-name))) (cycle-events (and define-cycle `((make-event `(define ,',cycle-name () :no-function t :returns (fsm base-fsm-p) ',(svtv-data->cycle-fsm ,stobj-name)))))) (namemap-name (intern-in-package-of-symbol (concatenate 'string (symbol-name svtv-name) "-NAMEMAP") svtv-name)) (pipeline-setup-name (intern-in-package-of-symbol (concatenate 'string (symbol-name svtv-name) "-PIPELINE-SETUP") svtv-name)) (thmname (intern-in-package-of-symbol (concatenate 'string (symbol-name svtv-name) "-PIPELINE-CORRECT") svtv-name))) `(progn ,@cycle-events (make-event `(define ,',namemap-name () :no-function t :returns (namemap svtv-name-lhs-map-p) ',(svtv-data->namemap ,stobj-name))) (make-event `(define ,',pipeline-setup-name () :no-function t :returns (setup pipeline-setup-p) ',(svtv-data->pipeline-setup ,stobj-name))) (in-theory (disable ,@(and define-cycle `((,cycle-name))))) (defthmd ,thmname (b* ((fsm (,cycle-name)) (rename-fsm (make-svtv-fsm :base-fsm fsm :namemap (,namemap-name))) (renamed-fsm (svtv-fsm->renamed-fsm rename-fsm)) ((pipeline-setup pipe) (,pipeline-setup-name)) (outvars (svtv-probealist-outvars pipe.probes)) (run (base-fsm-run (svex-alistlist-eval (svtv-fsm-run-input-substs (take (len outvars) pipe.inputs) pipe.overrides rename-fsm) env) (svex-alist-eval pipe.initst env) renamed-fsm outvars))) (svex-envs-equivalent (svex-alist-eval (svtv->outexprs (,svtv-name)) env) (svtv-probealist-extract pipe.probes run))) :hints (("goal" :clause-processor (svtv-pipeline-clause-proc clause '((,cycle-name) (,namemap-name) (,pipeline-setup-name) (svtv->outexprs$inline (,svtv-name)) env) ,stobj-name state) :in-theory (enable svtv-pipeline-correct)))) (add-to-ruleset! svtv-pipeline-thms ,thmname) (add-to-ruleset! svtv-pipeline-thm-constants '((:executable-counterpart ,namemap-name) (:executable-counterpart ,pipeline-setup-name)))))) (defmacro def-pipeline-thm (svtv-name &key cycle-name define-cycle (stobj-name 'svtv-data)) (def-pipeline-thm-fn svtv-name cycle-name define-cycle stobj-name)) (defxdoc def-pipeline-thm :parents (svex-stvs svtv-data) :short "Prove that an SVTV pipeline is an unrolling of the FSM that it's based on" :long "<p>When computing an SVTV pipeline using @(see defsvtv$) or @(see defsvtv$-phasewise), a FSM is first created and the pipeline is then a composition (unrolling) of FSM phases. This is an invariant of the @(see svtv-data) stobj; if the @('pipeline-valid') bit of the @('svtv-data') stobj is set, then it is known that the @('pipeline') field is an unrolling of the @('cycle-fsm') field, with unrolling parameters specified in the @('pipeline-setup') field.</p> <p>The @('def-pipeline-thm') event uses this invariant of the @('svtv-data') stobj to prove that property, given an SVTV that was created using @('defsvtv$'). This event requires that the @('svtv-data') stobj was not changed since the creation of the @('defsvtv$'). It proves a theorem of the following form:</p> @({ (b* ((fsm (svtv-cycle)) (rename-fsm (make-svtv-fsm :base-fsm fsm :namemap (svtv-namemap))) (renamed-fsm (svtv-fsm->renamed-fsm rename-fsm)) ((pipeline-setup pipe) (svtv-pipeline-setup)) (outvars (svtv-probealist-outvars pipe.probes)) (run (base-fsm-run (svex-alistlist-eval (svtv-fsm-run-input-substs (take (len outvars) pipe.inputs) pipe.overrides rename-fsm) env) (svex-alist-eval pipe.initst env) renamed-fsm outvars))) (svex-envs-equivalent (svex-alist-eval (svtv->outexprs (svtv)) env) (svtv-probealist-extract pipe.probes run))) }) <p>Here @('(svtv)') is the SVTV created by @('defsvtv$'). The other constant functions @('(svtv-cycle)'), @('(svtv-namemap)'), and @('(svtv-pipeline-setup)') are introduced by the @('def-pipeline-thm') event. (The cycle function doesn't need to be created if a previous @('def-pipeline-thm') event already introduced it.)</p> <p>The options for @('def-pipeline-thm') are as follows:</p> @({ (def-pipeline-thm svtv-name ;; optional, in case cycle was introduced previously :cycle-name cycle-name) }) ") (define cycle-okp-hint-subst ((hints pseudo-term-listp) svtv-data state) :returns (mv err (subst cmr::pseudo-term-mapping-p)) :prepwork ((local (in-theory (disable nth)))) (b* (((acl2::nths phase-term cycle-phases-term cycle-term) hints) ((mv cycle-term-err cycle-val) (meta-extract-const-value cycle-term state)) ((when (or cycle-term-err (not (equal cycle-val (svtv-data->cycle-fsm svtv-data))))) (mv "bad cycle value" nil)) ((mv phase-term-err phase-val) (meta-extract-const-value phase-term state)) ((when (or phase-term-err (not (equal phase-val (svtv-data->phase-fsm svtv-data))))) (mv "bad phase-fsm value" nil)) ((mv cycle-phases-term-err cycle-phases-val) (meta-extract-const-value cycle-phases-term state)) ((when (or cycle-phases-term-err (not (equal cycle-phases-val (svtv-data->cycle-phases svtv-data))))) (mv "bad cycle-phases value" nil))) (mv nil `(((svtv-data$c->cycle-fsm$inline svtv-data$c) . ,(acl2::pseudo-term-fix cycle-term)) ((svtv-data$c->phase-fsm$inline svtv-data$c) . ,(acl2::pseudo-term-fix phase-term)) ((svtv-data$c->cycle-phases$inline svtv-data$c) . ,(acl2::pseudo-term-fix cycle-phases-term))))) /// ;; (defret <fn>-correct ;; (implies (and (not err) ;; (svtvpipe-ev-meta-extract-global-facts) ;; (equal (cdr (assoc-equal 'svtv-data$c env)) svtv-data) ;; (equal (cdr (assoc-equal 'results env)) (svtv-data->pipeline svtv-data))) ;; (svtvpipe-ev-pseudo-term-mapping-correct-p subst env)) ;; :hints(("Goal" :in-theory (enable svtvpipe-ev-pseudo-term-mapping-correct-p)))) ) (define svtv-cycle-clause-proc (clause hints svtv-data state) ;; hints are: (phase-term cycle-phases-term cycle-term) (b* (((unless (mbt (svtv-datap svtv-data))) (mv "impossible" nil)) ((unless (svtv-data->cycle-fsm-validp svtv-data)) (mv "svtv-data cycle not valid" nil)) ((unless (and (pseudo-term-listp hints) (eql (len hints) 3))) (mv "bad hints" nil)) ((mv hints-err ?subst) (cycle-okp-hint-subst hints svtv-data state)) ((when hints-err) (mv hints-err nil)) ((acl2::nths phase-term cycle-phases-term cycle-term) hints) ;; ((mv impl-err impl-term) (pipeline-okp-implicant-term (w state))) ;; ((when impl-err) ;; (mv impl-err nil)) ;; (impl-term-beta (cmr::lazy-beta-reduce impl-term)) ;; (impl-term-subst (cmr::term-replace impl-term-beta subst)) ;; ((when (cmr::member-term-vars 'results impl-term-subst)) ;; (mv "programming error: result was in added term" nil)) ;; ((when (cmr::member-term-vars 'svtv-data$c impl-term-subst)) ;; (mv "svtv-data$c was still free in term, check def of svtv-data$c-pipeline-okp" nil)) ) ;; (mv nil (list (cons `(not ,impl-term-subst) clause))) (mv nil (list (cons `(not (svtv-cycle-correct ,phase-term ,cycle-phases-term ,cycle-term)) clause)))) /// (defthm svtv-cycle-clause-proc-correct (implies (and (pseudo-term-listp clause) (alistp a) (svtvpipe-ev-meta-extract-global-facts) (svtvpipe-ev (acl2::conjoin-clauses (acl2::clauses-result (svtv-cycle-clause-proc clause hints svtv-data state))) ;; `((svtv-data$c . ,svtv-data) ;; (results . ,(svtv-data->cycle svtv-data))) a)) (svtvpipe-ev (disjoin clause) a)) :hints (("goal" :do-not-induct t :in-theory (e/d (cycle-okp-hint-subst) (nth)) ;; :use ((:instance svtvpipe-ev-term-replace-correct ;; (x (CMR::LAZY-BETA-REDUCE (MV-NTH 1 ;; (CYCLE-OKP-IMPLICANT-TERM (W STATE))))) ;; (map (MV-NTH 1 ;; (CYCLE-OKP-HINT-SUBST HINTS SVTV-DATA state))) ;; (env ;; `((svtv-data$c . ,svtv-data) ;; (results . ,(svtv-data->cycle svtv-data)) ;; . ,a)))) )) :rule-classes :clause-processor)) (defun def-cycle-thm-fn (svtv-name cycle-name phase-name define-cycle define-phase stobj-name) (declare (xargs :mode :program)) (b* ((define-cycle (or (not cycle-name) define-cycle)) (cycle-name (or cycle-name (intern-in-package-of-symbol (concatenate 'string (symbol-name svtv-name) "-CYCLE") svtv-name))) (cycle-events (and define-cycle `((make-event `(define ,',cycle-name () :no-function t :returns (fsm base-fsm-p) ',(svtv-data->cycle-fsm ,stobj-name)))))) (define-phase (or (not phase-name) define-phase)) (phase-name (or phase-name (intern-in-package-of-symbol (concatenate 'string (symbol-name svtv-name) "-PHASE") svtv-name))) (phase-events (and define-phase `((make-event `(define ,',phase-name () :no-function t :returns (fsm base-fsm-p) ',(svtv-data->phase-fsm ,stobj-name)))))) (cycle-phases-name (intern-in-package-of-symbol (concatenate 'string (symbol-name svtv-name) "-CYCLE-PHASES") svtv-name)) (thmname (intern-in-package-of-symbol (concatenate 'string (symbol-name svtv-name) "-CYCLE-CORRECT") svtv-name))) `(progn ,@cycle-events ,@phase-events (make-event `(define ,',cycle-phases-name () :no-function t :returns (cycle-phases svtv-cyclephaselist-p) ',(svtv-data->cycle-phases ,stobj-name))) (in-theory (disable ,@(and define-cycle `((,cycle-name))) ,@(and define-phase `((,phase-name))))) (defthmd ,thmname (b* (((base-fsm phase-fsm) (,phase-name)) ((mv values nextstate) (svtv-cycle-compile (svex-identity-subst (svex-alist-keys phase-fsm.nextstate)) (,cycle-phases-name) phase-fsm nil))) (base-fsm-eval-equiv (,cycle-name) (make-base-fsm :values values :nextstate nextstate))) :hints (("goal" :clause-processor (svtv-cycle-clause-proc clause '((,phase-name) (,cycle-phases-name) (,cycle-name)) ,stobj-name state) :in-theory (enable svtv-cycle-correct)))) (add-to-ruleset! svtv-cycle-thms ,thmname) (add-to-ruleset! svtv-cycle-thm-constants '((:executable-counterpart ,cycle-phases-name)))))) (defmacro def-cycle-thm (svtv-name &key cycle-name phase-name define-cycle define-phase (stobj-name 'svtv-data)) (def-cycle-thm-fn svtv-name cycle-name phase-name define-cycle define-phase stobj-name)) (defxdoc def-cycle-thm :parents (svex-stvs svtv-data) :short "Prove that an SVTV cycle FSM an unrolling of the phase FSM that it's based on" :long " <p>The @('def-cycle-thm') event uses this invariant of the @('svtv-data') stobj to prove that the cycle FSM is equivalent to the unrolling according to the cycle phases of the phase FSM. This event requires that the @('svtv-data') stobj was not disrupted in such a way as to make its cycle FSM invalid since creating the cycle using @('defcycle') or @('defsvtv$'). It proves a theorem of the following form:</p> @({ (b* (((base-fsm phase-fsm) (phase-fsm)) ((mv values nextstate) (svtv-cycle-compile (svex-identity-subst (svex-alist-keys phase-fsm.nextstate)) (cycle-phases) phase-fsm nil))) (base-fsm-eval-equiv (cycle-fsm) (make-base-fsm :values values :nextstate nextstate))) }) <p>The options for @('def-cycle-thm') are as follows:</p> @({ (def-cycle-thm svtv-name ;; used for default names ;; optional, in case cycle was introduced previously :cycle-name cycle-name :phase-name phase-name :define-cycle t :define-phase t :stobj-name svtv-data) }) ")
[ { "context": "Package:CHAOS -*-\n;;;\n;;; Copyright (c) 2000-2015, Toshimi Sawada. All rights reserved.\n;;;\n;;; Redistribution and ", "end": 103, "score": 0.9998227953910828, "start": 89, "tag": "NAME", "value": "Toshimi Sawada" }, { "context": ";;; **************\n;;; FROM OBJ3 implementation by Tim.Winkler of SRI.\n;;; I don't know how this could be effici", "end": 4786, "score": 0.9996858835220337, "start": 4775, "tag": "NAME", "value": "Tim.Winkler" } ]
comlib/macros.lisp
debian-janitor/cafeobj
25
;;;-*- Mode:Lisp; Syntax:Common-Lisp; Package:CHAOS -*- ;;; ;;; Copyright (c) 2000-2015, Toshimi Sawada. 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 :CHAOS) #|============================================================================== System: Chaos Module: comlib File: macros.lisp ==============================================================================|# #-:chaos-debug (declaim (optimize (speed 3) (safety 0) #-GCL (debug 0))) #+:chaos-debug (declaim (optimize (speed 1) (safety 3) #-GCL (debug 3))) ;;;== DESCTIPTION ============================================================== ;;; A collection of misc utility macros. ;;; ******* ;;; DECLAIM_____________________________________________________________________ ;;; ******* ;;;#-(or cltl2 GCL) ;;;(defmacro declaim (arg) `(proclaim ',arg)) ;;; **************** ;;; FAMOUS ONCE-ONLY____________________________________________________________ ;;; **************** (defmacro once-only (vars &body body) (let ((gensym-var (gensym)) (run-time-vars (gensym)) (run-time-vals (gensym)) (expand-time-val-forms ())) (dolist (var vars) (push `(if (or (symbolp ,var) (numberp ,var) (and (listp ,var) (member (car ,var) '(quote function)))) ,var (let ((,gensym-var (gensym))) (push ,gensym-var ,run-time-vars) (push ,var ,run-time-vals) ,gensym-var)) expand-time-val-forms)) `(let* (,run-time-vars ,run-time-vals (wrapped-body (let ,(mapcar #'list vars (reverse expand-time-val-forms)) ,@body))) `(let ,(mapcar #'list (reverse ,run-time-vars) (reverse ,run-time-vals)) ,wrapped-body)))) ;;; ********************************* ;;; Specialized MEMBER/ASSOC/POSITION___________________________________________ ;;; ********************************* #-:ccl (defmacro memq (item list) `(member ,item ,list :test #'eq)) #-:ccl (defmacro assq (item list) `(assoc ,item ,list :test #'eq)) (defmacro posq (item list) `(position ,item ,list :test #'eq)) (defmacro memeq (item list) `(member ,item ,list :test #'equal)) (defmacro asseq (item list) `(assoc ,item ,list :test #'equal)) (defmacro poseq (item list) `(position ,item ,list :test #'equal)) ;;; ********** ;;; CASE-EQUAL__________________________________________________________________ ;;; ********** ;;; same as normal `case' test by equal instead of eql. (defmacro case-equal (keyform &rest clauses &aux (form nil) (key (gensym))) (dolist (clause (reverse clauses) `(let ((,key ,keyform)) ,form)) #+GCL (declare (object clause)) (cond ((or (eq (car clause) 't) (eq (car clause) 'otherwise)) (setq form `(progn ,@(cdr clause)))) ((consp (car clause)) (setq form `(if (member ,key ',(car clause) :test #'equal) (progn ,@(cdr clause)) ,form))) ((car clause) (setq form `(if (equal ,key ',(car clause)) (progn ,@(cdr clause)) ,form))))) ) ;;; ************** ;;; DOTIMES-FIXNUM______________________________________________________________ ;;; ************** ;;; FROM OBJ3 implementation by Tim.Winkler of SRI. ;;; I don't know how this could be efficient in general, but for GCL(KCL..) this ;;; works well. ;;; (defmacro dotimes-fixnum (&rest body) (let ((var (car (car body))) (lim (cadr (car body))) (res (cddr (car body))) (acts (cdr body)) (limvar (gensym)) (lab (gensym))) ` (block () (let* ((,limvar ,lim) (,var 0)) (declare (type fixnum ,var ,limvar)) (tagbody ,lab (if (>= ,var ,limvar) (return (progn ,@res))) (tagbody ,@acts) (setf (the fixnum ,var) (the fixnum (1+ (the fixnum ,var)))) (go ,lab))))) ) ;;; **************** ;;; Syntactic Sugars____________________________________________________________ ;;; **************** (defmacro msetq (vars value) `(multiple-value-setq ,vars ,value)) (defmacro mlet (vars value &body body) `(multiple-value-bind ,vars ,value ,@body)) ;;; let-if ;;; Binds let arguments only if condition is non-nil, and evaluates body ;;; in any case. (defmacro let-if (condition bindings &body body) `(if ,condition (let ,bindings ,@body) (progn ,@(if (eq (caar body) 'declare) (cdr body) body)))) ;;; when-bind ;;; Binds the symbol to predicate and executes body only if predicate ;;; is non-nil." (defmacro when-bind ((symbol predicate) &body body) `(let ((,symbol ,predicate)) (when ,symbol ,@body))) ;;; while ;;; Keeps invoking the body while the test is true; test is tested before each ;;; loop. ;;;; #-(or :allegro-v6.0 :allegro-v6.1 :allegro-v6.2 :allegro-v7.0 :allegro-v8.0) #-(or :allegro) (defmacro while (test &body body) (let ((end-test (gensym)) (loop (gensym))) `(block nil (tagbody (go ,end-test) ,loop ,@body ,end-test (when ,test (go ,loop)) (return))))) ;;; while-not ;;; Keeps invoking the body while the test is not true; test is tested before ;;; each loop. (defmacro while-not (test &body body) (let ((end-test (gensym)) (loop (gensym))) `(block nil (tagbody (go ,end-test) ,loop ,@body ,end-test (unless ,test (go ,loop)) (return))))) ;;; def-synonym sym1 sym2 ;;; (defmacro def-synonym (sym1 sym2) `(setf (symbol-function ',sym1) (symbol-function ',sym2))) ;;; ;;; #-:excl #-(or :excl ccl) (defmacro fixnump (num) `(typep ,num 'fixnum)) ;;; EOF
70803
;;;-*- Mode:Lisp; Syntax:Common-Lisp; Package:CHAOS -*- ;;; ;;; Copyright (c) 2000-2015, <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 :CHAOS) #|============================================================================== System: Chaos Module: comlib File: macros.lisp ==============================================================================|# #-:chaos-debug (declaim (optimize (speed 3) (safety 0) #-GCL (debug 0))) #+:chaos-debug (declaim (optimize (speed 1) (safety 3) #-GCL (debug 3))) ;;;== DESCTIPTION ============================================================== ;;; A collection of misc utility macros. ;;; ******* ;;; DECLAIM_____________________________________________________________________ ;;; ******* ;;;#-(or cltl2 GCL) ;;;(defmacro declaim (arg) `(proclaim ',arg)) ;;; **************** ;;; FAMOUS ONCE-ONLY____________________________________________________________ ;;; **************** (defmacro once-only (vars &body body) (let ((gensym-var (gensym)) (run-time-vars (gensym)) (run-time-vals (gensym)) (expand-time-val-forms ())) (dolist (var vars) (push `(if (or (symbolp ,var) (numberp ,var) (and (listp ,var) (member (car ,var) '(quote function)))) ,var (let ((,gensym-var (gensym))) (push ,gensym-var ,run-time-vars) (push ,var ,run-time-vals) ,gensym-var)) expand-time-val-forms)) `(let* (,run-time-vars ,run-time-vals (wrapped-body (let ,(mapcar #'list vars (reverse expand-time-val-forms)) ,@body))) `(let ,(mapcar #'list (reverse ,run-time-vars) (reverse ,run-time-vals)) ,wrapped-body)))) ;;; ********************************* ;;; Specialized MEMBER/ASSOC/POSITION___________________________________________ ;;; ********************************* #-:ccl (defmacro memq (item list) `(member ,item ,list :test #'eq)) #-:ccl (defmacro assq (item list) `(assoc ,item ,list :test #'eq)) (defmacro posq (item list) `(position ,item ,list :test #'eq)) (defmacro memeq (item list) `(member ,item ,list :test #'equal)) (defmacro asseq (item list) `(assoc ,item ,list :test #'equal)) (defmacro poseq (item list) `(position ,item ,list :test #'equal)) ;;; ********** ;;; CASE-EQUAL__________________________________________________________________ ;;; ********** ;;; same as normal `case' test by equal instead of eql. (defmacro case-equal (keyform &rest clauses &aux (form nil) (key (gensym))) (dolist (clause (reverse clauses) `(let ((,key ,keyform)) ,form)) #+GCL (declare (object clause)) (cond ((or (eq (car clause) 't) (eq (car clause) 'otherwise)) (setq form `(progn ,@(cdr clause)))) ((consp (car clause)) (setq form `(if (member ,key ',(car clause) :test #'equal) (progn ,@(cdr clause)) ,form))) ((car clause) (setq form `(if (equal ,key ',(car clause)) (progn ,@(cdr clause)) ,form))))) ) ;;; ************** ;;; DOTIMES-FIXNUM______________________________________________________________ ;;; ************** ;;; FROM OBJ3 implementation by <NAME> of SRI. ;;; I don't know how this could be efficient in general, but for GCL(KCL..) this ;;; works well. ;;; (defmacro dotimes-fixnum (&rest body) (let ((var (car (car body))) (lim (cadr (car body))) (res (cddr (car body))) (acts (cdr body)) (limvar (gensym)) (lab (gensym))) ` (block () (let* ((,limvar ,lim) (,var 0)) (declare (type fixnum ,var ,limvar)) (tagbody ,lab (if (>= ,var ,limvar) (return (progn ,@res))) (tagbody ,@acts) (setf (the fixnum ,var) (the fixnum (1+ (the fixnum ,var)))) (go ,lab))))) ) ;;; **************** ;;; Syntactic Sugars____________________________________________________________ ;;; **************** (defmacro msetq (vars value) `(multiple-value-setq ,vars ,value)) (defmacro mlet (vars value &body body) `(multiple-value-bind ,vars ,value ,@body)) ;;; let-if ;;; Binds let arguments only if condition is non-nil, and evaluates body ;;; in any case. (defmacro let-if (condition bindings &body body) `(if ,condition (let ,bindings ,@body) (progn ,@(if (eq (caar body) 'declare) (cdr body) body)))) ;;; when-bind ;;; Binds the symbol to predicate and executes body only if predicate ;;; is non-nil." (defmacro when-bind ((symbol predicate) &body body) `(let ((,symbol ,predicate)) (when ,symbol ,@body))) ;;; while ;;; Keeps invoking the body while the test is true; test is tested before each ;;; loop. ;;;; #-(or :allegro-v6.0 :allegro-v6.1 :allegro-v6.2 :allegro-v7.0 :allegro-v8.0) #-(or :allegro) (defmacro while (test &body body) (let ((end-test (gensym)) (loop (gensym))) `(block nil (tagbody (go ,end-test) ,loop ,@body ,end-test (when ,test (go ,loop)) (return))))) ;;; while-not ;;; Keeps invoking the body while the test is not true; test is tested before ;;; each loop. (defmacro while-not (test &body body) (let ((end-test (gensym)) (loop (gensym))) `(block nil (tagbody (go ,end-test) ,loop ,@body ,end-test (unless ,test (go ,loop)) (return))))) ;;; def-synonym sym1 sym2 ;;; (defmacro def-synonym (sym1 sym2) `(setf (symbol-function ',sym1) (symbol-function ',sym2))) ;;; ;;; #-:excl #-(or :excl ccl) (defmacro fixnump (num) `(typep ,num 'fixnum)) ;;; EOF
true
;;;-*- Mode:Lisp; Syntax:Common-Lisp; Package:CHAOS -*- ;;; ;;; Copyright (c) 2000-2015, 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 :CHAOS) #|============================================================================== System: Chaos Module: comlib File: macros.lisp ==============================================================================|# #-:chaos-debug (declaim (optimize (speed 3) (safety 0) #-GCL (debug 0))) #+:chaos-debug (declaim (optimize (speed 1) (safety 3) #-GCL (debug 3))) ;;;== DESCTIPTION ============================================================== ;;; A collection of misc utility macros. ;;; ******* ;;; DECLAIM_____________________________________________________________________ ;;; ******* ;;;#-(or cltl2 GCL) ;;;(defmacro declaim (arg) `(proclaim ',arg)) ;;; **************** ;;; FAMOUS ONCE-ONLY____________________________________________________________ ;;; **************** (defmacro once-only (vars &body body) (let ((gensym-var (gensym)) (run-time-vars (gensym)) (run-time-vals (gensym)) (expand-time-val-forms ())) (dolist (var vars) (push `(if (or (symbolp ,var) (numberp ,var) (and (listp ,var) (member (car ,var) '(quote function)))) ,var (let ((,gensym-var (gensym))) (push ,gensym-var ,run-time-vars) (push ,var ,run-time-vals) ,gensym-var)) expand-time-val-forms)) `(let* (,run-time-vars ,run-time-vals (wrapped-body (let ,(mapcar #'list vars (reverse expand-time-val-forms)) ,@body))) `(let ,(mapcar #'list (reverse ,run-time-vars) (reverse ,run-time-vals)) ,wrapped-body)))) ;;; ********************************* ;;; Specialized MEMBER/ASSOC/POSITION___________________________________________ ;;; ********************************* #-:ccl (defmacro memq (item list) `(member ,item ,list :test #'eq)) #-:ccl (defmacro assq (item list) `(assoc ,item ,list :test #'eq)) (defmacro posq (item list) `(position ,item ,list :test #'eq)) (defmacro memeq (item list) `(member ,item ,list :test #'equal)) (defmacro asseq (item list) `(assoc ,item ,list :test #'equal)) (defmacro poseq (item list) `(position ,item ,list :test #'equal)) ;;; ********** ;;; CASE-EQUAL__________________________________________________________________ ;;; ********** ;;; same as normal `case' test by equal instead of eql. (defmacro case-equal (keyform &rest clauses &aux (form nil) (key (gensym))) (dolist (clause (reverse clauses) `(let ((,key ,keyform)) ,form)) #+GCL (declare (object clause)) (cond ((or (eq (car clause) 't) (eq (car clause) 'otherwise)) (setq form `(progn ,@(cdr clause)))) ((consp (car clause)) (setq form `(if (member ,key ',(car clause) :test #'equal) (progn ,@(cdr clause)) ,form))) ((car clause) (setq form `(if (equal ,key ',(car clause)) (progn ,@(cdr clause)) ,form))))) ) ;;; ************** ;;; DOTIMES-FIXNUM______________________________________________________________ ;;; ************** ;;; FROM OBJ3 implementation by PI:NAME:<NAME>END_PI of SRI. ;;; I don't know how this could be efficient in general, but for GCL(KCL..) this ;;; works well. ;;; (defmacro dotimes-fixnum (&rest body) (let ((var (car (car body))) (lim (cadr (car body))) (res (cddr (car body))) (acts (cdr body)) (limvar (gensym)) (lab (gensym))) ` (block () (let* ((,limvar ,lim) (,var 0)) (declare (type fixnum ,var ,limvar)) (tagbody ,lab (if (>= ,var ,limvar) (return (progn ,@res))) (tagbody ,@acts) (setf (the fixnum ,var) (the fixnum (1+ (the fixnum ,var)))) (go ,lab))))) ) ;;; **************** ;;; Syntactic Sugars____________________________________________________________ ;;; **************** (defmacro msetq (vars value) `(multiple-value-setq ,vars ,value)) (defmacro mlet (vars value &body body) `(multiple-value-bind ,vars ,value ,@body)) ;;; let-if ;;; Binds let arguments only if condition is non-nil, and evaluates body ;;; in any case. (defmacro let-if (condition bindings &body body) `(if ,condition (let ,bindings ,@body) (progn ,@(if (eq (caar body) 'declare) (cdr body) body)))) ;;; when-bind ;;; Binds the symbol to predicate and executes body only if predicate ;;; is non-nil." (defmacro when-bind ((symbol predicate) &body body) `(let ((,symbol ,predicate)) (when ,symbol ,@body))) ;;; while ;;; Keeps invoking the body while the test is true; test is tested before each ;;; loop. ;;;; #-(or :allegro-v6.0 :allegro-v6.1 :allegro-v6.2 :allegro-v7.0 :allegro-v8.0) #-(or :allegro) (defmacro while (test &body body) (let ((end-test (gensym)) (loop (gensym))) `(block nil (tagbody (go ,end-test) ,loop ,@body ,end-test (when ,test (go ,loop)) (return))))) ;;; while-not ;;; Keeps invoking the body while the test is not true; test is tested before ;;; each loop. (defmacro while-not (test &body body) (let ((end-test (gensym)) (loop (gensym))) `(block nil (tagbody (go ,end-test) ,loop ,@body ,end-test (unless ,test (go ,loop)) (return))))) ;;; def-synonym sym1 sym2 ;;; (defmacro def-synonym (sym1 sym2) `(setf (symbol-function ',sym1) (symbol-function ',sym2))) ;;; ;;; #-:excl #-(or :excl ccl) (defmacro fixnump (num) `(typep ,num 'fixnum)) ;;; EOF
[ { "context": "ion\n;;;; All rights reserved.\n;;;;\n;;;; Author(s): Neil T. Dantam <[email protected]>\n;;;; Georgia Tech Humanoid Robot", "end": 148, "score": 0.9998907446861267, "start": 134, "tag": "NAME", "value": "Neil T. Dantam" }, { "context": "ts reserved.\n;;;;\n;;;; Author(s): Neil T. Dantam <[email protected]>\n;;;; Georgia Tech Humanoid Robotics Lab\n;;;; Und", "end": 164, "score": 0.9999341368675232, "start": 150, "tag": "EMAIL", "value": "[email protected]" }, { "context": "THE\n;;;; POSSIBILITY OF SUCH DAMAGE.\n\n;; Author: Neil T. Dantam\n\n\n(in-package :ach)\n\n;;(declaim (optimize (speed ", "end": 1771, "score": 0.9998917579650879, "start": 1757, "tag": "NAME", "value": "Neil T. Dantam" } ]
lisp/pipe.lisp
munzir/39-ach
0
;;;; -*- Lisp -*- ;;;; ;;;; Copyright (c) 2009-2011, Georgia Tech Research Corporation ;;;; All rights reserved. ;;;; ;;;; Author(s): Neil T. Dantam <[email protected]> ;;;; Georgia Tech Humanoid Robotics Lab ;;;; Under Direction of Prof. Mike Stilman ;;;; ;;;; ;;;; This file is provided under the following "BSD-style" License: ;;;; ;;;; ;;;; Redistribution and use in source and binary forms, with or ;;;; without modification, are permitted provided that the following ;;;; conditions are met: ;;;; ;;;; * Redistributions of source code must retain the above copyright ;;;; notice, this list of conditions and the following disclaimer. ;;;; ;;;; * Redistributions in binary form must reproduce the above ;;;; copyright notice, this list of conditions and the following ;;;; disclaimer in the documentation and/or other materials provided ;;;; with the distribution. ;;;; ;;;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND ;;;; CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, ;;;; INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF ;;;; MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE ;;;; DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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. ;; Author: Neil T. Dantam (in-package :ach) ;;(declaim (optimize (speed 3) (safety 0))) ;;;;;;;;;;;;;;;;; ;;; CONSTANTS ;;; ;;;;;;;;;;;;;;;;; ;; let's make the delimiters int32s. That'll be faster to compare, right? (declaim (type (unsigned-byte 32) *size-delim* *data-delim*)) (defparameter *size-delim* (decode-uint (map-into (make-octet-vector 4) #'char-code "size") :little)) (defparameter *data-delim* (decode-uint (map-into (make-octet-vector 4) #'char-code "data") :little)) (defparameter +next-cmd+ (map-into (make-octet-vector 4) #'char-code "next")) (defparameter +last-cmd+ (map-into (make-octet-vector 4) #'char-code "last")) (defparameter +poll-cmd+ (map-into (make-octet-vector 4) #'char-code "poll")) ;(defparameter +next-cmd+ "next") ;(defparameter +last-cmd+ "last") ;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; GENERAL INTERACTION ;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;; (defstruct channel mode synchronous transport name host reuse-buffer buffer) (defun channel-input (channel) (socket-stream (channel-transport channel))) (defun channel-output (channel) (socket-stream (channel-transport channel))) (declaim (inline make-size-buf)) (defun make-size-buf () (make-octet-vector 12)) (defun ach-stream-read (stream &optional buffer) "read a frame from the stream or return nil if closed. If buffer is specified, it may, but does not have to, be used." (declare (type (or null octet-vector) buffer)) (let* ((size-buf (make-size-buf)) (n-read (read-sequence size-buf stream))) (declare (dynamic-extent size-buf)) (unless (zerop n-read) (assert (= *size-delim* (the (unsigned-byte 32) (decode-uint size-buf :little 0))) () "Invalid size delimiter: ~A, ~&buffer: ~A~&msg: ~A" (subseq size-buf 0 4) size-buf (concatenate 'string (map 'string #'code-char size-buf) (loop for i below 80 for c = (code-char (read-byte stream)) collect c until (char-equal c #\Newline)))) (assert (= *data-delim* (the (unsigned-byte 32) (decode-uint size-buf :little 8))) () "Invalid data delimiter: ~A, ~&buffer: ~A~&msg: ~A" (subseq size-buf 8) size-buf (map 'string #'code-char size-buf)) (let* ((size (decode-uint size-buf :big 4)) (buffer (if (and buffer (= size (length buffer))) buffer (make-octet-vector size)))) (declare (fixnum size)) (read-sequence buffer stream) buffer)))) (defun ach-stream-write (stream buffer) "write a frame to the stream" (declare (stream stream) (octet-vector buffer)) (let ((size-buf (make-size-buf))) (encode-int *size-delim* :little size-buf 0) (encode-int (length buffer) :big size-buf 4) (encode-int *data-delim* :little size-buf 8) (write-sequence size-buf stream) (write-sequence buffer stream))) (defun ach-stream-write-string (stream string) (declare (simple-string string)) (write-sequence (map-into (make-octet-vector (length string)) #'char-code string) stream)) ;;;;;;;;;;;;;;; ;;; SOCKETS ;;; ;;;;;;;;;;;;;;; (defun ach-connect (channel-name &key (host "localhost") (port 8075) (mode :subscribe) (synchronous t) reuse-buffer) (declare (string channel-name host) (fixnum port) (symbol mode)) (assert (or (eq mode :subscribe) (eq mode :publish)) () "Invalid mode: ~A" mode) (assert (if synchronous (eq mode :subscribe) t) () "Can only SUBSCRIBE when SYNCHRONOUS.") (let* ((sock (socket-connect host port :element-type '(unsigned-byte 8))) (s (socket-stream sock))) (flet ((write-header (label value) (ach-stream-write-string s (format nil "~&~A: ~A~%" label value)))) (write-header "channel" channel-name) (write-header "mode" (cond ((eq mode :subscribe) "subscribe") ((eq mode :publish) "publish") (t (error "Invalid mode, again...: ~A" mode)))) (when synchronous (write-header "synchronous" "perry"))) (write-byte (char-code #\Newline) s) (force-output s) (make-channel :mode mode :synchronous synchronous :transport sock :name channel-name :host host :reuse-buffer reuse-buffer))) (defun ach-disconnect (channel) (socket-close (channel-transport channel))) (defun ach-sock-sync-cmd (stream command) (declare (stream stream) (type (octet-vector 4) command)) (write-sequence command stream) (finish-output stream)) (defun which-buffer (channel buffer-arg) (or buffer-arg (and (channel-reuse-buffer channel) (channel-buffer channel)))) (defmacro def-ach-getter (name cmd) `(defun ,name (channel &optional buffer) (assert (and (eq (channel-mode channel) :subscribe) (channel-synchronous channel)) () "Invalid channel for synchronous command: ~A" channel) (ach-sock-sync-cmd (channel-input channel) ,cmd) (let ((buffer (ach-stream-read (channel-output channel) (or buffer (and (channel-reuse-buffer channel) (channel-buffer channel)))))) (when (channel-reuse-buffer channel) (setf (channel-buffer channel) buffer)) buffer))) (def-ach-getter ach-next +next-cmd+) (def-ach-getter ach-last +last-cmd+) (def-ach-getter ach-poll +poll-cmd+) (defun ach-send (channel buffer) (assert (eq (channel-mode channel) :publish) () "Invalid channel mode for put") (ach-stream-write (channel-input channel) buffer) (force-output (channel-output channel))) ;;;;;;;;;;;;; ;;; UTILS ;;; ;;;;;;;;;;;;; (defmacro ach-closef (&rest places) `(progn ,@(loop for place in places collect `(when (and (boundp ',place) ,place) (ach:ach-close ,place) (setq ,place nil))))) (defgeneric ach-map (result-type function thing)) (defmethod ach-map ((result-type (eql nil)) (function function) (thing stream)) (loop for frame = (ach-stream-read thing) while frame do (funcall function frame))) (defmethod ach-map ((result-type (eql 'list)) (function function) (thing stream)) (loop for frame = (ach-stream-read thing) while frame collect (funcall function frame))) (defmethod ach-map (result-type (function function) (thing pathname)) (with-open-file (file thing :direction :input :element-type '(unsigned-byte 8)) (ach-map result-type function file))) (defmethod ach-map (result-type (function function) (thing string)) (ach-map result-type function (pathname thing))) (defun ach-log-start (directory &rest channels) (sb-ext:run-program "achlog" (concatenate 'list (list "-v" "-d" directory) channels) :output t :search t :wait nil)) (defun ach-log-stop (process) (sb-ext:process-kill process 15) ;(sb-ext:process-close process) nil) (defmacro with-ach-log ((directory &rest channels) &body body) (let ((var (gensym))) `(let ((,var (ach-log-start ,directory ,@channels))) (unwind-protect (progn ,@body) (ach-log-stop ,var))))) ;; (defun wait-next (channel &key count buffer) ;; (assert (and (ach-handle-opened channel) ;; (ach-handle-pointer channel)) () ;; "Invalid channel: ~A" channel) ;; (cond ;; ((and (null count) (null buffer)) ;; (wait-next channel ;; :count ;; (cffi:with-foreign-object (p-frame-size :uint) ;; (let ((r (ach-wait-next (ach-handle-pointer channel) ;; (cffi:null-pointer) 0 p-frame-size))) ;; (assert (= (cffi:foreign-enum-value 'ach-status :overflow) ;; r) () "Invalid status getting size: ~A" ;; (status-keyword r))) ;; (cffi:mem-ref p-frame-size :uint)))) ;; ((and count (null buffer)) ;; (get-last channel :buffer (make-octet-vector count))) ;; (buffer ;; (let ((frame-size) (r)) ;; (cffi:with-foreign-object (p-frame-size :uint) ;; (cffi-sys:with-pointer-to-vector-data (pbuf buffer) ;; (setq r (ach-get-last (ach-handle-pointer channel) ;; pbuf (length buffer) p-frame-size))) ;; (setq frame-size (cffi:mem-ref p-frame-size :uint))) ;; (unless (eq :ok (status-keyword r)) ;; (ach-status (status-keyword r) "Reading frame")) ;; ;;FIXME: handle this ;; (assert (= frame-size (length buffer)) () "Mismatched frame size") ;; (values buffer frame-size (cffi:foreign-enum-keyword 'ach-status r)))))) ;; ;;;;;;;;;;;;;;;;;;;;; ;; ;;; CHILD PROCESS ;;; ;; ;;;;;;;;;;;;;;;;;;;;; ;; (defun ach-open (channel-name &key (direction :input) last) ;; "Open an ach channel" ;; (let ((proc-input (when (or (eq direction :output) ;; (eq direction :input-sync)) ;; :stream)) ;; (proc-output (when (or (eq direction :input) ;; (eq direction :input-sync)) ;; :stream))) ;; (make-channel ;; :direction direction ;; :process (sb-ext:run-program "achpipe" ;; `( ;; ,(case direction ;; (:input "-s") ;; (:input-sync "-S") ;; (:output "-p") ;; (otherwise (error "Invalid direction: ~A" ;; direction))) ;; ,channel-name ;; ,@(when last (list "--last"))) ;; :search t ;; :wait nil ;; :input proc-input ;; ;;:input-element-type '(unsigned-byte 8) ;; :output proc-output ;; ;;:output-element-type '(unsigned-byte 8) ;; :error *standard-output*)))) ;; ;;:error "/tmp/achlisperr")))) ;; ;;(defun read-bytes-dammit (buffer stream) ;; ;; (declare (octet-vector buffer)) ;; ;; (if (eq (stream-element-type stream) 'unsigned-byte) ;; ;; (read-sequence buffer stream) ;; ;; (dotimes (i (length buffer)) ;; ;; (setf (aref buffer i) ;; ;; (read-byte stream))))) ;; (defun write-bytes-dammit (buffer stream) ;; (declare (octet-vector buffer)) ;; (if (eq (stream-element-type stream) 'unsigned-byte) ;; (write-sequence buffer stream) ;; (dotimes (i (length buffer)) ;; (write-byte (aref buffer i) stream )))) ;; (defun ach-read (channel &optional buffer) ;; "read a frame from the channel" ;; (declare (type (or null octet-vector) buffer)) ;; (assert (or (eq :input (channel-direction channel)) ;; (eq :input-sync (channel-direction channel))) ;; () "Channel direction must be :INPUT, not ~S" ;; (channel-direction channel)) ;; (let ((s (channel-output channel)) ;; ;;(size-buf (make-array 12 :element-type 'unsigned-byte))) ;; (size-buf (make-size-buf))) ;; (read-sequence size-buf s) ;; (assert (= *size-delim* ;; (decode-uint size-buf :little 0)) () ;; "Invalid size delimiter: ~A" (subseq size-buf 0 4)) ;; (assert (= *data-delim* ;; (decode-uint size-buf :little 8)) () ;; "Invalid size delimiter: ~A" (subseq size-buf 8)) ;; (let* ((size (decode-uint size-buf :big 4)) ;; ;;(buffer (make-array size :element-type '(unsigned-byte 8)))) ;; (buffer (if (= size (length buffer)) buffer ;; (make-octet-vector size)))) ;; ;(read-bytes-dammit buffer s) ;; (read-sequence buffer s) ;; buffer))) ;; (defun ach-write (channel buffer) ;; "write a frame to the channel" ;; (declare (octet-vector buffer)) ;; (assert (eq :output (channel-direction channel)) () ;; "Channel direction must be :OUTPUT, not ~S" ;; (channel-direction channel)) ;; (let ((s (channel-input channel)) ;; ;;(size-buf (make-array 12 :element-type 'unsigned-byte))) ;; (size-buf (make-size-buf))) ;; (encode-int *size-delim* :little 0) ;; (encode-int (length buffer) :big 4) ;; (encode-int *data-delim* :little 8) ;; (write-sequence size-buf s) ;; (write-sequence buffer s))) ;; ;;(write-bytes-dammit size-buf s) ;; ;;(write-bytes-dammit buffer s))) ;; (defun ach-status (channel) ;; (sb-ext:process-status (channel-process channel))) ;; (defun ach-close (channel) ;; "Close ach channel" ;; (sb-ext:process-kill (channel-process channel) sb-posix:sigterm) ;; (sb-ext:process-wait (channel-process channel) t) ;; (sb-ext:process-close (channel-process channel)) ;; (setf (channel-direction channel) nil) ;; channel) ;; ;;;;;;;;;;;;;;;;;;;;;;;;;; ;; ;;; CONTINUOUS READING ;;; ;; ;;;;;;;;;;;;;;;;;;;;;;;;;; ;; ;;; maintain a background thread that will continuously read the ;; ;;; channel ;; (defun make-listener (channel-name &key last) ;; ;;(declare (optimize (speed 3) (safety 0))) ;; (let ((lock (sb-thread:make-mutex)) ;; (buffer (make-octet-vector 0)) ;; (continue t)) ;; (declare (octet-vector buffer)) ;; (let ((thread ; start the listening thread ;; (sb-thread:make-thread ;; (lambda () (let ((channel (ach-open channel-name ;; :direction :input :last last))) ;; (unwind-protect (loop ;; while continue ;; for tmp-buffer = (ach-read channel) ;; do (sb-thread:with-mutex (lock) ;; (setq buffer tmp-buffer))) ;; (ach-close channel)))) ;; :name (concatenate 'string "ach-listener-" channel-name)))) ;; ;; return a closure to get the next buffer or terminate the listener ;; (lambda (&key terminate) ;; (if terminate ;; ;; stop the listener ;; (progn ;; ;; FIXME: be more robust ;; (setq continue nil) ;; (sb-thread:join-thread thread)) ;; ;; get the buffer ;; (progn ;; (sb-thread:with-mutex (lock) ;; (copy-seq buffer)))))))) ;;; Synchronous communication ;; (defun send-sync-cmd (channel last) ;; (write-sequence (if last +last-cmd+ +next-cmd+) ;; (channel-input channel)) ;; (finish-output (channel-input channel))) ;; (defun make-ach-sync (channel-name) ;; (let ((channel (ach-open channel-name :direction :input-sync))) ;; (let ((fun (lambda (&key (last t) terminate channel-hook) ;; (cond ;; (terminate ;; ;; close channel ;; (ach-close channel)) ;; (channel-hook ;; (funcall channel-hook channel)) ;; (t ;; ;; read channel ;; (progn ;; ;; send cmd ;; (send-sync-cmd channel last) ;; ;; get data ;; (ach-read channel))))))) ;; (sb-ext:finalize fun (lambda () (ach-close channel))) ;; fun)))
6644
;;;; -*- Lisp -*- ;;;; ;;;; Copyright (c) 2009-2011, Georgia Tech Research Corporation ;;;; All rights reserved. ;;;; ;;;; Author(s): <NAME> <<EMAIL>> ;;;; Georgia Tech Humanoid Robotics Lab ;;;; Under Direction of Prof. Mike Stilman ;;;; ;;;; ;;;; This file is provided under the following "BSD-style" License: ;;;; ;;;; ;;;; Redistribution and use in source and binary forms, with or ;;;; without modification, are permitted provided that the following ;;;; conditions are met: ;;;; ;;;; * Redistributions of source code must retain the above copyright ;;;; notice, this list of conditions and the following disclaimer. ;;;; ;;;; * Redistributions in binary form must reproduce the above ;;;; copyright notice, this list of conditions and the following ;;;; disclaimer in the documentation and/or other materials provided ;;;; with the distribution. ;;;; ;;;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND ;;;; CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, ;;;; INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF ;;;; MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE ;;;; DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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. ;; Author: <NAME> (in-package :ach) ;;(declaim (optimize (speed 3) (safety 0))) ;;;;;;;;;;;;;;;;; ;;; CONSTANTS ;;; ;;;;;;;;;;;;;;;;; ;; let's make the delimiters int32s. That'll be faster to compare, right? (declaim (type (unsigned-byte 32) *size-delim* *data-delim*)) (defparameter *size-delim* (decode-uint (map-into (make-octet-vector 4) #'char-code "size") :little)) (defparameter *data-delim* (decode-uint (map-into (make-octet-vector 4) #'char-code "data") :little)) (defparameter +next-cmd+ (map-into (make-octet-vector 4) #'char-code "next")) (defparameter +last-cmd+ (map-into (make-octet-vector 4) #'char-code "last")) (defparameter +poll-cmd+ (map-into (make-octet-vector 4) #'char-code "poll")) ;(defparameter +next-cmd+ "next") ;(defparameter +last-cmd+ "last") ;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; GENERAL INTERACTION ;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;; (defstruct channel mode synchronous transport name host reuse-buffer buffer) (defun channel-input (channel) (socket-stream (channel-transport channel))) (defun channel-output (channel) (socket-stream (channel-transport channel))) (declaim (inline make-size-buf)) (defun make-size-buf () (make-octet-vector 12)) (defun ach-stream-read (stream &optional buffer) "read a frame from the stream or return nil if closed. If buffer is specified, it may, but does not have to, be used." (declare (type (or null octet-vector) buffer)) (let* ((size-buf (make-size-buf)) (n-read (read-sequence size-buf stream))) (declare (dynamic-extent size-buf)) (unless (zerop n-read) (assert (= *size-delim* (the (unsigned-byte 32) (decode-uint size-buf :little 0))) () "Invalid size delimiter: ~A, ~&buffer: ~A~&msg: ~A" (subseq size-buf 0 4) size-buf (concatenate 'string (map 'string #'code-char size-buf) (loop for i below 80 for c = (code-char (read-byte stream)) collect c until (char-equal c #\Newline)))) (assert (= *data-delim* (the (unsigned-byte 32) (decode-uint size-buf :little 8))) () "Invalid data delimiter: ~A, ~&buffer: ~A~&msg: ~A" (subseq size-buf 8) size-buf (map 'string #'code-char size-buf)) (let* ((size (decode-uint size-buf :big 4)) (buffer (if (and buffer (= size (length buffer))) buffer (make-octet-vector size)))) (declare (fixnum size)) (read-sequence buffer stream) buffer)))) (defun ach-stream-write (stream buffer) "write a frame to the stream" (declare (stream stream) (octet-vector buffer)) (let ((size-buf (make-size-buf))) (encode-int *size-delim* :little size-buf 0) (encode-int (length buffer) :big size-buf 4) (encode-int *data-delim* :little size-buf 8) (write-sequence size-buf stream) (write-sequence buffer stream))) (defun ach-stream-write-string (stream string) (declare (simple-string string)) (write-sequence (map-into (make-octet-vector (length string)) #'char-code string) stream)) ;;;;;;;;;;;;;;; ;;; SOCKETS ;;; ;;;;;;;;;;;;;;; (defun ach-connect (channel-name &key (host "localhost") (port 8075) (mode :subscribe) (synchronous t) reuse-buffer) (declare (string channel-name host) (fixnum port) (symbol mode)) (assert (or (eq mode :subscribe) (eq mode :publish)) () "Invalid mode: ~A" mode) (assert (if synchronous (eq mode :subscribe) t) () "Can only SUBSCRIBE when SYNCHRONOUS.") (let* ((sock (socket-connect host port :element-type '(unsigned-byte 8))) (s (socket-stream sock))) (flet ((write-header (label value) (ach-stream-write-string s (format nil "~&~A: ~A~%" label value)))) (write-header "channel" channel-name) (write-header "mode" (cond ((eq mode :subscribe) "subscribe") ((eq mode :publish) "publish") (t (error "Invalid mode, again...: ~A" mode)))) (when synchronous (write-header "synchronous" "perry"))) (write-byte (char-code #\Newline) s) (force-output s) (make-channel :mode mode :synchronous synchronous :transport sock :name channel-name :host host :reuse-buffer reuse-buffer))) (defun ach-disconnect (channel) (socket-close (channel-transport channel))) (defun ach-sock-sync-cmd (stream command) (declare (stream stream) (type (octet-vector 4) command)) (write-sequence command stream) (finish-output stream)) (defun which-buffer (channel buffer-arg) (or buffer-arg (and (channel-reuse-buffer channel) (channel-buffer channel)))) (defmacro def-ach-getter (name cmd) `(defun ,name (channel &optional buffer) (assert (and (eq (channel-mode channel) :subscribe) (channel-synchronous channel)) () "Invalid channel for synchronous command: ~A" channel) (ach-sock-sync-cmd (channel-input channel) ,cmd) (let ((buffer (ach-stream-read (channel-output channel) (or buffer (and (channel-reuse-buffer channel) (channel-buffer channel)))))) (when (channel-reuse-buffer channel) (setf (channel-buffer channel) buffer)) buffer))) (def-ach-getter ach-next +next-cmd+) (def-ach-getter ach-last +last-cmd+) (def-ach-getter ach-poll +poll-cmd+) (defun ach-send (channel buffer) (assert (eq (channel-mode channel) :publish) () "Invalid channel mode for put") (ach-stream-write (channel-input channel) buffer) (force-output (channel-output channel))) ;;;;;;;;;;;;; ;;; UTILS ;;; ;;;;;;;;;;;;; (defmacro ach-closef (&rest places) `(progn ,@(loop for place in places collect `(when (and (boundp ',place) ,place) (ach:ach-close ,place) (setq ,place nil))))) (defgeneric ach-map (result-type function thing)) (defmethod ach-map ((result-type (eql nil)) (function function) (thing stream)) (loop for frame = (ach-stream-read thing) while frame do (funcall function frame))) (defmethod ach-map ((result-type (eql 'list)) (function function) (thing stream)) (loop for frame = (ach-stream-read thing) while frame collect (funcall function frame))) (defmethod ach-map (result-type (function function) (thing pathname)) (with-open-file (file thing :direction :input :element-type '(unsigned-byte 8)) (ach-map result-type function file))) (defmethod ach-map (result-type (function function) (thing string)) (ach-map result-type function (pathname thing))) (defun ach-log-start (directory &rest channels) (sb-ext:run-program "achlog" (concatenate 'list (list "-v" "-d" directory) channels) :output t :search t :wait nil)) (defun ach-log-stop (process) (sb-ext:process-kill process 15) ;(sb-ext:process-close process) nil) (defmacro with-ach-log ((directory &rest channels) &body body) (let ((var (gensym))) `(let ((,var (ach-log-start ,directory ,@channels))) (unwind-protect (progn ,@body) (ach-log-stop ,var))))) ;; (defun wait-next (channel &key count buffer) ;; (assert (and (ach-handle-opened channel) ;; (ach-handle-pointer channel)) () ;; "Invalid channel: ~A" channel) ;; (cond ;; ((and (null count) (null buffer)) ;; (wait-next channel ;; :count ;; (cffi:with-foreign-object (p-frame-size :uint) ;; (let ((r (ach-wait-next (ach-handle-pointer channel) ;; (cffi:null-pointer) 0 p-frame-size))) ;; (assert (= (cffi:foreign-enum-value 'ach-status :overflow) ;; r) () "Invalid status getting size: ~A" ;; (status-keyword r))) ;; (cffi:mem-ref p-frame-size :uint)))) ;; ((and count (null buffer)) ;; (get-last channel :buffer (make-octet-vector count))) ;; (buffer ;; (let ((frame-size) (r)) ;; (cffi:with-foreign-object (p-frame-size :uint) ;; (cffi-sys:with-pointer-to-vector-data (pbuf buffer) ;; (setq r (ach-get-last (ach-handle-pointer channel) ;; pbuf (length buffer) p-frame-size))) ;; (setq frame-size (cffi:mem-ref p-frame-size :uint))) ;; (unless (eq :ok (status-keyword r)) ;; (ach-status (status-keyword r) "Reading frame")) ;; ;;FIXME: handle this ;; (assert (= frame-size (length buffer)) () "Mismatched frame size") ;; (values buffer frame-size (cffi:foreign-enum-keyword 'ach-status r)))))) ;; ;;;;;;;;;;;;;;;;;;;;; ;; ;;; CHILD PROCESS ;;; ;; ;;;;;;;;;;;;;;;;;;;;; ;; (defun ach-open (channel-name &key (direction :input) last) ;; "Open an ach channel" ;; (let ((proc-input (when (or (eq direction :output) ;; (eq direction :input-sync)) ;; :stream)) ;; (proc-output (when (or (eq direction :input) ;; (eq direction :input-sync)) ;; :stream))) ;; (make-channel ;; :direction direction ;; :process (sb-ext:run-program "achpipe" ;; `( ;; ,(case direction ;; (:input "-s") ;; (:input-sync "-S") ;; (:output "-p") ;; (otherwise (error "Invalid direction: ~A" ;; direction))) ;; ,channel-name ;; ,@(when last (list "--last"))) ;; :search t ;; :wait nil ;; :input proc-input ;; ;;:input-element-type '(unsigned-byte 8) ;; :output proc-output ;; ;;:output-element-type '(unsigned-byte 8) ;; :error *standard-output*)))) ;; ;;:error "/tmp/achlisperr")))) ;; ;;(defun read-bytes-dammit (buffer stream) ;; ;; (declare (octet-vector buffer)) ;; ;; (if (eq (stream-element-type stream) 'unsigned-byte) ;; ;; (read-sequence buffer stream) ;; ;; (dotimes (i (length buffer)) ;; ;; (setf (aref buffer i) ;; ;; (read-byte stream))))) ;; (defun write-bytes-dammit (buffer stream) ;; (declare (octet-vector buffer)) ;; (if (eq (stream-element-type stream) 'unsigned-byte) ;; (write-sequence buffer stream) ;; (dotimes (i (length buffer)) ;; (write-byte (aref buffer i) stream )))) ;; (defun ach-read (channel &optional buffer) ;; "read a frame from the channel" ;; (declare (type (or null octet-vector) buffer)) ;; (assert (or (eq :input (channel-direction channel)) ;; (eq :input-sync (channel-direction channel))) ;; () "Channel direction must be :INPUT, not ~S" ;; (channel-direction channel)) ;; (let ((s (channel-output channel)) ;; ;;(size-buf (make-array 12 :element-type 'unsigned-byte))) ;; (size-buf (make-size-buf))) ;; (read-sequence size-buf s) ;; (assert (= *size-delim* ;; (decode-uint size-buf :little 0)) () ;; "Invalid size delimiter: ~A" (subseq size-buf 0 4)) ;; (assert (= *data-delim* ;; (decode-uint size-buf :little 8)) () ;; "Invalid size delimiter: ~A" (subseq size-buf 8)) ;; (let* ((size (decode-uint size-buf :big 4)) ;; ;;(buffer (make-array size :element-type '(unsigned-byte 8)))) ;; (buffer (if (= size (length buffer)) buffer ;; (make-octet-vector size)))) ;; ;(read-bytes-dammit buffer s) ;; (read-sequence buffer s) ;; buffer))) ;; (defun ach-write (channel buffer) ;; "write a frame to the channel" ;; (declare (octet-vector buffer)) ;; (assert (eq :output (channel-direction channel)) () ;; "Channel direction must be :OUTPUT, not ~S" ;; (channel-direction channel)) ;; (let ((s (channel-input channel)) ;; ;;(size-buf (make-array 12 :element-type 'unsigned-byte))) ;; (size-buf (make-size-buf))) ;; (encode-int *size-delim* :little 0) ;; (encode-int (length buffer) :big 4) ;; (encode-int *data-delim* :little 8) ;; (write-sequence size-buf s) ;; (write-sequence buffer s))) ;; ;;(write-bytes-dammit size-buf s) ;; ;;(write-bytes-dammit buffer s))) ;; (defun ach-status (channel) ;; (sb-ext:process-status (channel-process channel))) ;; (defun ach-close (channel) ;; "Close ach channel" ;; (sb-ext:process-kill (channel-process channel) sb-posix:sigterm) ;; (sb-ext:process-wait (channel-process channel) t) ;; (sb-ext:process-close (channel-process channel)) ;; (setf (channel-direction channel) nil) ;; channel) ;; ;;;;;;;;;;;;;;;;;;;;;;;;;; ;; ;;; CONTINUOUS READING ;;; ;; ;;;;;;;;;;;;;;;;;;;;;;;;;; ;; ;;; maintain a background thread that will continuously read the ;; ;;; channel ;; (defun make-listener (channel-name &key last) ;; ;;(declare (optimize (speed 3) (safety 0))) ;; (let ((lock (sb-thread:make-mutex)) ;; (buffer (make-octet-vector 0)) ;; (continue t)) ;; (declare (octet-vector buffer)) ;; (let ((thread ; start the listening thread ;; (sb-thread:make-thread ;; (lambda () (let ((channel (ach-open channel-name ;; :direction :input :last last))) ;; (unwind-protect (loop ;; while continue ;; for tmp-buffer = (ach-read channel) ;; do (sb-thread:with-mutex (lock) ;; (setq buffer tmp-buffer))) ;; (ach-close channel)))) ;; :name (concatenate 'string "ach-listener-" channel-name)))) ;; ;; return a closure to get the next buffer or terminate the listener ;; (lambda (&key terminate) ;; (if terminate ;; ;; stop the listener ;; (progn ;; ;; FIXME: be more robust ;; (setq continue nil) ;; (sb-thread:join-thread thread)) ;; ;; get the buffer ;; (progn ;; (sb-thread:with-mutex (lock) ;; (copy-seq buffer)))))))) ;;; Synchronous communication ;; (defun send-sync-cmd (channel last) ;; (write-sequence (if last +last-cmd+ +next-cmd+) ;; (channel-input channel)) ;; (finish-output (channel-input channel))) ;; (defun make-ach-sync (channel-name) ;; (let ((channel (ach-open channel-name :direction :input-sync))) ;; (let ((fun (lambda (&key (last t) terminate channel-hook) ;; (cond ;; (terminate ;; ;; close channel ;; (ach-close channel)) ;; (channel-hook ;; (funcall channel-hook channel)) ;; (t ;; ;; read channel ;; (progn ;; ;; send cmd ;; (send-sync-cmd channel last) ;; ;; get data ;; (ach-read channel))))))) ;; (sb-ext:finalize fun (lambda () (ach-close channel))) ;; fun)))
true
;;;; -*- Lisp -*- ;;;; ;;;; Copyright (c) 2009-2011, Georgia Tech Research Corporation ;;;; All rights reserved. ;;;; ;;;; Author(s): PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> ;;;; Georgia Tech Humanoid Robotics Lab ;;;; Under Direction of Prof. Mike Stilman ;;;; ;;;; ;;;; This file is provided under the following "BSD-style" License: ;;;; ;;;; ;;;; Redistribution and use in source and binary forms, with or ;;;; without modification, are permitted provided that the following ;;;; conditions are met: ;;;; ;;;; * Redistributions of source code must retain the above copyright ;;;; notice, this list of conditions and the following disclaimer. ;;;; ;;;; * Redistributions in binary form must reproduce the above ;;;; copyright notice, this list of conditions and the following ;;;; disclaimer in the documentation and/or other materials provided ;;;; with the distribution. ;;;; ;;;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND ;;;; CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, ;;;; INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF ;;;; MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE ;;;; DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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. ;; Author: PI:NAME:<NAME>END_PI (in-package :ach) ;;(declaim (optimize (speed 3) (safety 0))) ;;;;;;;;;;;;;;;;; ;;; CONSTANTS ;;; ;;;;;;;;;;;;;;;;; ;; let's make the delimiters int32s. That'll be faster to compare, right? (declaim (type (unsigned-byte 32) *size-delim* *data-delim*)) (defparameter *size-delim* (decode-uint (map-into (make-octet-vector 4) #'char-code "size") :little)) (defparameter *data-delim* (decode-uint (map-into (make-octet-vector 4) #'char-code "data") :little)) (defparameter +next-cmd+ (map-into (make-octet-vector 4) #'char-code "next")) (defparameter +last-cmd+ (map-into (make-octet-vector 4) #'char-code "last")) (defparameter +poll-cmd+ (map-into (make-octet-vector 4) #'char-code "poll")) ;(defparameter +next-cmd+ "next") ;(defparameter +last-cmd+ "last") ;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; GENERAL INTERACTION ;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;; (defstruct channel mode synchronous transport name host reuse-buffer buffer) (defun channel-input (channel) (socket-stream (channel-transport channel))) (defun channel-output (channel) (socket-stream (channel-transport channel))) (declaim (inline make-size-buf)) (defun make-size-buf () (make-octet-vector 12)) (defun ach-stream-read (stream &optional buffer) "read a frame from the stream or return nil if closed. If buffer is specified, it may, but does not have to, be used." (declare (type (or null octet-vector) buffer)) (let* ((size-buf (make-size-buf)) (n-read (read-sequence size-buf stream))) (declare (dynamic-extent size-buf)) (unless (zerop n-read) (assert (= *size-delim* (the (unsigned-byte 32) (decode-uint size-buf :little 0))) () "Invalid size delimiter: ~A, ~&buffer: ~A~&msg: ~A" (subseq size-buf 0 4) size-buf (concatenate 'string (map 'string #'code-char size-buf) (loop for i below 80 for c = (code-char (read-byte stream)) collect c until (char-equal c #\Newline)))) (assert (= *data-delim* (the (unsigned-byte 32) (decode-uint size-buf :little 8))) () "Invalid data delimiter: ~A, ~&buffer: ~A~&msg: ~A" (subseq size-buf 8) size-buf (map 'string #'code-char size-buf)) (let* ((size (decode-uint size-buf :big 4)) (buffer (if (and buffer (= size (length buffer))) buffer (make-octet-vector size)))) (declare (fixnum size)) (read-sequence buffer stream) buffer)))) (defun ach-stream-write (stream buffer) "write a frame to the stream" (declare (stream stream) (octet-vector buffer)) (let ((size-buf (make-size-buf))) (encode-int *size-delim* :little size-buf 0) (encode-int (length buffer) :big size-buf 4) (encode-int *data-delim* :little size-buf 8) (write-sequence size-buf stream) (write-sequence buffer stream))) (defun ach-stream-write-string (stream string) (declare (simple-string string)) (write-sequence (map-into (make-octet-vector (length string)) #'char-code string) stream)) ;;;;;;;;;;;;;;; ;;; SOCKETS ;;; ;;;;;;;;;;;;;;; (defun ach-connect (channel-name &key (host "localhost") (port 8075) (mode :subscribe) (synchronous t) reuse-buffer) (declare (string channel-name host) (fixnum port) (symbol mode)) (assert (or (eq mode :subscribe) (eq mode :publish)) () "Invalid mode: ~A" mode) (assert (if synchronous (eq mode :subscribe) t) () "Can only SUBSCRIBE when SYNCHRONOUS.") (let* ((sock (socket-connect host port :element-type '(unsigned-byte 8))) (s (socket-stream sock))) (flet ((write-header (label value) (ach-stream-write-string s (format nil "~&~A: ~A~%" label value)))) (write-header "channel" channel-name) (write-header "mode" (cond ((eq mode :subscribe) "subscribe") ((eq mode :publish) "publish") (t (error "Invalid mode, again...: ~A" mode)))) (when synchronous (write-header "synchronous" "perry"))) (write-byte (char-code #\Newline) s) (force-output s) (make-channel :mode mode :synchronous synchronous :transport sock :name channel-name :host host :reuse-buffer reuse-buffer))) (defun ach-disconnect (channel) (socket-close (channel-transport channel))) (defun ach-sock-sync-cmd (stream command) (declare (stream stream) (type (octet-vector 4) command)) (write-sequence command stream) (finish-output stream)) (defun which-buffer (channel buffer-arg) (or buffer-arg (and (channel-reuse-buffer channel) (channel-buffer channel)))) (defmacro def-ach-getter (name cmd) `(defun ,name (channel &optional buffer) (assert (and (eq (channel-mode channel) :subscribe) (channel-synchronous channel)) () "Invalid channel for synchronous command: ~A" channel) (ach-sock-sync-cmd (channel-input channel) ,cmd) (let ((buffer (ach-stream-read (channel-output channel) (or buffer (and (channel-reuse-buffer channel) (channel-buffer channel)))))) (when (channel-reuse-buffer channel) (setf (channel-buffer channel) buffer)) buffer))) (def-ach-getter ach-next +next-cmd+) (def-ach-getter ach-last +last-cmd+) (def-ach-getter ach-poll +poll-cmd+) (defun ach-send (channel buffer) (assert (eq (channel-mode channel) :publish) () "Invalid channel mode for put") (ach-stream-write (channel-input channel) buffer) (force-output (channel-output channel))) ;;;;;;;;;;;;; ;;; UTILS ;;; ;;;;;;;;;;;;; (defmacro ach-closef (&rest places) `(progn ,@(loop for place in places collect `(when (and (boundp ',place) ,place) (ach:ach-close ,place) (setq ,place nil))))) (defgeneric ach-map (result-type function thing)) (defmethod ach-map ((result-type (eql nil)) (function function) (thing stream)) (loop for frame = (ach-stream-read thing) while frame do (funcall function frame))) (defmethod ach-map ((result-type (eql 'list)) (function function) (thing stream)) (loop for frame = (ach-stream-read thing) while frame collect (funcall function frame))) (defmethod ach-map (result-type (function function) (thing pathname)) (with-open-file (file thing :direction :input :element-type '(unsigned-byte 8)) (ach-map result-type function file))) (defmethod ach-map (result-type (function function) (thing string)) (ach-map result-type function (pathname thing))) (defun ach-log-start (directory &rest channels) (sb-ext:run-program "achlog" (concatenate 'list (list "-v" "-d" directory) channels) :output t :search t :wait nil)) (defun ach-log-stop (process) (sb-ext:process-kill process 15) ;(sb-ext:process-close process) nil) (defmacro with-ach-log ((directory &rest channels) &body body) (let ((var (gensym))) `(let ((,var (ach-log-start ,directory ,@channels))) (unwind-protect (progn ,@body) (ach-log-stop ,var))))) ;; (defun wait-next (channel &key count buffer) ;; (assert (and (ach-handle-opened channel) ;; (ach-handle-pointer channel)) () ;; "Invalid channel: ~A" channel) ;; (cond ;; ((and (null count) (null buffer)) ;; (wait-next channel ;; :count ;; (cffi:with-foreign-object (p-frame-size :uint) ;; (let ((r (ach-wait-next (ach-handle-pointer channel) ;; (cffi:null-pointer) 0 p-frame-size))) ;; (assert (= (cffi:foreign-enum-value 'ach-status :overflow) ;; r) () "Invalid status getting size: ~A" ;; (status-keyword r))) ;; (cffi:mem-ref p-frame-size :uint)))) ;; ((and count (null buffer)) ;; (get-last channel :buffer (make-octet-vector count))) ;; (buffer ;; (let ((frame-size) (r)) ;; (cffi:with-foreign-object (p-frame-size :uint) ;; (cffi-sys:with-pointer-to-vector-data (pbuf buffer) ;; (setq r (ach-get-last (ach-handle-pointer channel) ;; pbuf (length buffer) p-frame-size))) ;; (setq frame-size (cffi:mem-ref p-frame-size :uint))) ;; (unless (eq :ok (status-keyword r)) ;; (ach-status (status-keyword r) "Reading frame")) ;; ;;FIXME: handle this ;; (assert (= frame-size (length buffer)) () "Mismatched frame size") ;; (values buffer frame-size (cffi:foreign-enum-keyword 'ach-status r)))))) ;; ;;;;;;;;;;;;;;;;;;;;; ;; ;;; CHILD PROCESS ;;; ;; ;;;;;;;;;;;;;;;;;;;;; ;; (defun ach-open (channel-name &key (direction :input) last) ;; "Open an ach channel" ;; (let ((proc-input (when (or (eq direction :output) ;; (eq direction :input-sync)) ;; :stream)) ;; (proc-output (when (or (eq direction :input) ;; (eq direction :input-sync)) ;; :stream))) ;; (make-channel ;; :direction direction ;; :process (sb-ext:run-program "achpipe" ;; `( ;; ,(case direction ;; (:input "-s") ;; (:input-sync "-S") ;; (:output "-p") ;; (otherwise (error "Invalid direction: ~A" ;; direction))) ;; ,channel-name ;; ,@(when last (list "--last"))) ;; :search t ;; :wait nil ;; :input proc-input ;; ;;:input-element-type '(unsigned-byte 8) ;; :output proc-output ;; ;;:output-element-type '(unsigned-byte 8) ;; :error *standard-output*)))) ;; ;;:error "/tmp/achlisperr")))) ;; ;;(defun read-bytes-dammit (buffer stream) ;; ;; (declare (octet-vector buffer)) ;; ;; (if (eq (stream-element-type stream) 'unsigned-byte) ;; ;; (read-sequence buffer stream) ;; ;; (dotimes (i (length buffer)) ;; ;; (setf (aref buffer i) ;; ;; (read-byte stream))))) ;; (defun write-bytes-dammit (buffer stream) ;; (declare (octet-vector buffer)) ;; (if (eq (stream-element-type stream) 'unsigned-byte) ;; (write-sequence buffer stream) ;; (dotimes (i (length buffer)) ;; (write-byte (aref buffer i) stream )))) ;; (defun ach-read (channel &optional buffer) ;; "read a frame from the channel" ;; (declare (type (or null octet-vector) buffer)) ;; (assert (or (eq :input (channel-direction channel)) ;; (eq :input-sync (channel-direction channel))) ;; () "Channel direction must be :INPUT, not ~S" ;; (channel-direction channel)) ;; (let ((s (channel-output channel)) ;; ;;(size-buf (make-array 12 :element-type 'unsigned-byte))) ;; (size-buf (make-size-buf))) ;; (read-sequence size-buf s) ;; (assert (= *size-delim* ;; (decode-uint size-buf :little 0)) () ;; "Invalid size delimiter: ~A" (subseq size-buf 0 4)) ;; (assert (= *data-delim* ;; (decode-uint size-buf :little 8)) () ;; "Invalid size delimiter: ~A" (subseq size-buf 8)) ;; (let* ((size (decode-uint size-buf :big 4)) ;; ;;(buffer (make-array size :element-type '(unsigned-byte 8)))) ;; (buffer (if (= size (length buffer)) buffer ;; (make-octet-vector size)))) ;; ;(read-bytes-dammit buffer s) ;; (read-sequence buffer s) ;; buffer))) ;; (defun ach-write (channel buffer) ;; "write a frame to the channel" ;; (declare (octet-vector buffer)) ;; (assert (eq :output (channel-direction channel)) () ;; "Channel direction must be :OUTPUT, not ~S" ;; (channel-direction channel)) ;; (let ((s (channel-input channel)) ;; ;;(size-buf (make-array 12 :element-type 'unsigned-byte))) ;; (size-buf (make-size-buf))) ;; (encode-int *size-delim* :little 0) ;; (encode-int (length buffer) :big 4) ;; (encode-int *data-delim* :little 8) ;; (write-sequence size-buf s) ;; (write-sequence buffer s))) ;; ;;(write-bytes-dammit size-buf s) ;; ;;(write-bytes-dammit buffer s))) ;; (defun ach-status (channel) ;; (sb-ext:process-status (channel-process channel))) ;; (defun ach-close (channel) ;; "Close ach channel" ;; (sb-ext:process-kill (channel-process channel) sb-posix:sigterm) ;; (sb-ext:process-wait (channel-process channel) t) ;; (sb-ext:process-close (channel-process channel)) ;; (setf (channel-direction channel) nil) ;; channel) ;; ;;;;;;;;;;;;;;;;;;;;;;;;;; ;; ;;; CONTINUOUS READING ;;; ;; ;;;;;;;;;;;;;;;;;;;;;;;;;; ;; ;;; maintain a background thread that will continuously read the ;; ;;; channel ;; (defun make-listener (channel-name &key last) ;; ;;(declare (optimize (speed 3) (safety 0))) ;; (let ((lock (sb-thread:make-mutex)) ;; (buffer (make-octet-vector 0)) ;; (continue t)) ;; (declare (octet-vector buffer)) ;; (let ((thread ; start the listening thread ;; (sb-thread:make-thread ;; (lambda () (let ((channel (ach-open channel-name ;; :direction :input :last last))) ;; (unwind-protect (loop ;; while continue ;; for tmp-buffer = (ach-read channel) ;; do (sb-thread:with-mutex (lock) ;; (setq buffer tmp-buffer))) ;; (ach-close channel)))) ;; :name (concatenate 'string "ach-listener-" channel-name)))) ;; ;; return a closure to get the next buffer or terminate the listener ;; (lambda (&key terminate) ;; (if terminate ;; ;; stop the listener ;; (progn ;; ;; FIXME: be more robust ;; (setq continue nil) ;; (sb-thread:join-thread thread)) ;; ;; get the buffer ;; (progn ;; (sb-thread:with-mutex (lock) ;; (copy-seq buffer)))))))) ;;; Synchronous communication ;; (defun send-sync-cmd (channel last) ;; (write-sequence (if last +last-cmd+ +next-cmd+) ;; (channel-input channel)) ;; (finish-output (channel-input channel))) ;; (defun make-ach-sync (channel-name) ;; (let ((channel (ach-open channel-name :direction :input-sync))) ;; (let ((fun (lambda (&key (last t) terminate channel-hook) ;; (cond ;; (terminate ;; ;; close channel ;; (ach-close channel)) ;; (channel-hook ;; (funcall channel-hook channel)) ;; (t ;; ;; read channel ;; (progn ;; ;; send cmd ;; (send-sync-cmd channel last) ;; ;; get data ;; (ach-read channel))))))) ;; (sb-ext:finalize fun (lambda () (ach-close channel))) ;; fun)))
[ { "context": "; Bit-vector rules\n;\n; Copyright (C) 2008-2011 Eric Smith and Stanford University\n; Copyright (C) 2013-2020", "end": 57, "score": 0.9991294741630554, "start": 47, "tag": "NAME", "value": "Eric Smith" }, { "context": "ense. See the file books/3BSD-mod.txt.\n;\n; Author: Eric Smith ([email protected])\n\n;;;;;;;;;;;;;;;;;;;;;;;", "end": 268, "score": 0.9995664358139038, "start": 258, "tag": "NAME", "value": "Eric Smith" }, { "context": " file books/3BSD-mod.txt.\n;\n; Author: Eric Smith ([email protected])\n\n;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;", "end": 292, "score": 0.9999305009841919, "start": 270, "tag": "EMAIL", "value": "[email protected]" } ]
books/kestrel/axe/bv-rules.lisp
ayazhafiz/acl2
0
; Bit-vector rules ; ; Copyright (C) 2008-2011 Eric Smith and Stanford University ; Copyright (C) 2013-2020 Kestrel Institute ; Copyright (C) 2016-2020 Kestrel Technology, LLC ; ; License: A 3-clause BSD license. See the file books/3BSD-mod.txt. ; ; Author: Eric Smith ([email protected]) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (in-package "ACL2") (include-book "kestrel/bv/rules6" :dir :system) (local (include-book "kestrel/library-wrappers/arithmetic-top-with-meta" :dir :system)) (local (in-theory (disable expt))) ;yuck? (defthm bvcat-bvxor-neighbors-hack3 (implies (and (equal low2 (+ 1 high)) (equal j (+ high 1 (- low))) (equal k (+ high2 1 (- low2))) (<= low high) (<= low2 high2) (natp high) (natp low) (natp high2) (natp low2) ) (equal (bvcat k (BVXOR k (slice high2 low2 y) (slice high2 low2 x)) j (BVXOR j (slice high low y) (slice high low x))) (bvxor (+ 1 high2 (- low)) (slice high2 low y) (slice high2 low x)))) :hints (("Goal" :use () :in-theory (e/d (;bvxor ) ( ;BVXOR-TRIM-ARG1 ;BVXOR-CANCEL BVXOR-CANCEL-alt BVXOR-CANCEL-cross-2 ))) ;why the disables? )) ;yuck.. (defthmd bvcat-bvxor-neighbors-hack4 (implies (and (equal n (+ 1 high)) (equal j (+ high 1 (- low))) (natp high) (natp n) (natp low) (<= low high) ) (equal (bvcat 1 (BVXOR 1 (getbit n y) (getbit n x)) j (BVXOR j (slice high low y) (slice high low x))) (bvxor (+ 1 n (- low)) (slice n low y) (slice n low x)))) :hints (("Goal" :use ((:instance bvcat-bvxor-neighbors-hack3 (high2 n) (low2 n) (k 1))) :in-theory (disable bvcat-bvxor-neighbors-hack3))) :otf-flg t) ;; Used in CLAIM! (DEFTHMd BACKCHAIN-SIGNED-BYTE-P-TO-UNSIGNED-BYTE-P-non-const (IMPLIES (AND ;(SYNTAXP (CONSTANT-SYNTAXP SIZE)) (< 0 SIZE) (UNSIGNED-BYTE-P (1- SIZE) I)) (SIGNED-BYTE-P SIZE I)) :HINTS (("Goal" :IN-THEORY (E/d (SIGNED-BYTE-P UNSIGNED-BYTE-P) (;HACK-6 ))))) ;fixme pretty special purpose (defthm bvif-hack (equal (bvif 8 test1 (bvif 8 test2 a b) (bvif 8 test2 b a)) (bvif 8 (xor test1 test2) b a)) :hints (("Goal" :in-theory (e/d (xor bvif myif) (;bvchop-bvchop ))))) (defthm bvif-hack-gen (implies (and (integerp size) (< 0 size)) (equal (bvif size test1 (bvif size test2 a b) (bvif size test2 b a)) (bvif size (xor test1 test2) b a))) :hints (("Goal" :in-theory (e/d (xor bvif myif) (;bvchop-bvchop ))))) (defthm bvif-of-logext-1 (implies (and (<= size size2) (natp size) (integerp size2) ;new (< 0 size)) (equal (bvif size test (logext size2 x) y) (bvif size test x y))) :hints (("Goal" :cases ((integerp x)) :in-theory (e/d (bvif BVCHOP-WHEN-I-IS-NOT-AN-INTEGER) (;BVCHOP-BVCHOP ))))) (defthm bvif-of-logext-2 (implies (and (<= size size2) (integerp size2) (natp size) (< 0 size)) (equal (bvif size test y (logext size2 x)) (bvif size test y x))) :hints (("Goal" :in-theory (e/d (bvif BVCHOP-WHEN-I-IS-NOT-AN-INTEGER) (;BVCHOP-BVCHOP ))))) (defthm myif-equal-bit-0-expt-2-n (implies (and (unsigned-byte-p 1 bit) (natp n)) (equal (myif (equal bit 0) 0 (expt 2 n)) (bvcat 1 bit n 0))) :hints (("Goal" :in-theory (enable myif)))) (defthm myif-equal-bit-0-constant-version (implies (and (syntaxp (quotep k)) (equal k (expt 2 (+ -1 (integer-length k)))) (< 0 (integer-length k)) (unsigned-byte-p 1 bit)) (equal (myif (equal bit 0) 0 k) (bvcat 1 bit (+ -1 (integer-length k)) 0))) :hints (("Goal" :use (:instance myif-equal-bit-0-expt-2-n (n (+ -1 (integer-length k)) ))))) ;BOZO can this loop? (defthm bvchop-32-times-subst (implies (and (equal (bvchop 32 x) (bvchop 32 free)) ;binds the variable FREE (syntaxp (smaller-termp free x)) (integerp x) (integerp z) (integerp free) ) (EQUAL (BVCHOP 32 (* z x)) (BVCHOP 32 (* z free)))) :hints (("Goal" :use ((:instance bvchop-n-times-drop (n 32) (x x) (y z)) (:instance bvchop-n-times-drop (n 32) (x free) (y z))) :in-theory (disable bvchop-n-times-drop)))) (defthmd apply-logext-32-to-both-sides (implies (and (equal x y) (equal a (logext 32 x)) (equal b (logext 32 y))) (equal (equal a b) t))) (defthmd apply-logext-32-to-both-sides-alt (implies (and (equal y x) (equal b (logext 32 x)) (equal a (logext 32 y))) (equal (equal a b) t))) ;yikes, don't we want to go the other way? (defthm bvchop-of-sbp-equal-constant (implies (and (syntaxp (quotep k)) (signed-byte-p 32 x) ;backchain limit? ) (equal (equal k (bvchop 32 x)) (and (unsigned-byte-p 32 k) (equal (logext 32 k) x)))) :hints (("Goal" :in-theory (enable apply-logext-32-to-both-sides-alt apply-logext-32-to-both-sides)))) ;for example, we prefer ;(EQUAL '0 (BVCAT '1 x '7 '0)) ;to: ;(EQUAL '0 (LOGEXT '8 (BVCAT '1 x '7 '0))) ;is this one okay? (defthm add-bvchops-to-equality-of-sbps-5 (implies (and (syntaxp (and (quotep y) (consp x) (member-equal (car x) *trimmable-operators*))) (integerp newsize) (< 0 newsize)) (equal (equal (logext newsize x) y) (if (integerp x) ;remove the other case? (and (signed-byte-p newsize y) (equal (bvchop newsize x) (bvchop newsize y))) (equal 0 y)))) :hints (("Goal" :cases ((integerp x)) :use (:instance add-bvchops-to-equality-of-sbps-4)))) (defthm logext-equal-logext-rewrite (implies (and (integerp x) (integerp size) (< 0 size)) (equal (EQUAL (LOGEXT size x) (LOGEXT size y)) (equal (bvchop size x) (bvchop size y)))) :hints (("Goal" :in-theory (enable ADD-BVCHOPS-TO-EQUALITY-OF-SBPS-4)))) (DEFTHM GETBIT-0-OF-TIMES-constant (IMPLIES (AND (syntaxp (and (quotep x) (not (unsigned-byte-p 1 (unquote x))))) (INTEGERP X) (INTEGERP Y)) (EQUAL (GETBIT 0 (* X Y)) (GETBIT 0 (* (GETBIT 0 X) Y)))) :HINTS (("Goal" :use (:instance bvchop-n-times-drop (n 1)) :IN-THEORY (E/D (GETBIT) (BVCHOP-1-BECOMES-GETBIT SLICE-BECOMES-GETBIT bvchop-n-times-drop))))) ;bozo more (defthm bvchop-times-logext-32 (implies (and (integerp x) (integerp y)) (equal (BVCHOP 32 (* x (LOGEXT 32 y))) (BVCHOP 32 (* x y)))) :hints (("Goal" :in-theory (disable bvchop-n-times-drop) :use ((:instance bvchop-n-times-drop (n 32) (x (logext 32 y)) (y x)) (:instance bvchop-n-times-drop (n 32) (x y) (y x)))))) ;sort of strength reduction ;gen ;can loop? (defthmd floor-by-4 (implies (integerp x) (equal (floor x 4) (logtail 2 x))) :hints (("Goal" :in-theory (enable logtail)))) (theory-invariant (incompatible (:rewrite FLOOR-BY-4) (:DEFINITION LOGTAIL))) (theory-invariant (incompatible (:rewrite logapp-0) (:rewrite times-4-becomes-logapp))) ;move (defthm unsigned-byte-p-of-slice-lemma (implies (and (unsigned-byte-p (+ n low) x) (natp n) (natp low) (natp high) ) (equal (unsigned-byte-p n (slice high low x)) t)) :hints (("Goal" :in-theory (e/d (slice) (anti-slice))))) (defthm logext-of-plus-of-logext (implies (and (<= smallsize bigsize) (integerp smallsize) (integerp bigsize) (< 0 smallsize) (force (integerp x)) (force (integerp y))) (equal (LOGEXT smallsize (+ x (LOGEXT bigsize y))) (LOGEXT smallsize (+ x y)))) :hints (("Goal" :in-theory (e/d (ADD-BVCHOPS-TO-EQUALITY-OF-SBPS-4) (;BVPLUS-RECOLLAPSE ))))) (defthm logext-of-plus-of-logext-alt (implies (and (<= smallsize bigsize) (integerp smallsize) (integerp bigsize) (< 0 smallsize) (force (integerp x)) (force (integerp y))) (equal (LOGEXT smallsize (+ (LOGEXT bigsize y) x)) (LOGEXT smallsize (+ x y)))) :hints (("Goal" :in-theory (e/d (ADD-BVCHOPS-TO-EQUALITY-OF-SBPS-4) (logext))))) ;slow? (defthm slice-of-plus-of-logext-gen (implies (and (< high size) (natp high) (integerp size) (<= low high) (natp low) (force (integerp x)) (force (integerp y))) (equal (SLICE high low (+ x (LOGEXT size y))) (SLICE high low (+ x y)) )) :hints (("Goal" :in-theory (e/d (SLICE bvchop-of-logtail) (anti-slice LOGEXT-OF-LOGTAIL-BECOMES-LOGEXT-OF-SLICE LOGTAIL-OF-LOGEXT))))) ;todo: (theory-invariant (incompatible (:rewrite LOGEXT-OF-LOGTAIL-BECOMES-LOGEXT-OF-SLICE) (:rewrite slice))) (defthm slice-of-plus-of-logext-gen-alt (implies (and (< high size) (natp high) (integerp size) (<= low high) (natp low) (force (integerp x)) (force (integerp y))) (equal (slice high low (+ (logext size y) x)) (slice high low (+ x y)) )) :hints (("Goal" :in-theory (e/d (slice) (anti-slice LOGEXT-OF-LOGTAIL-BECOMES-LOGEXT-OF-SLICE LOGEXT-of-logtail))))) ;instead, inner sum should go to bvplus... (defthm bvxor-of-sum-logext (implies (and (<= size size2) (natp size) (natp size2) (integerp y) (integerp z)) (equal (bvxor size x (+ (logext size2 y) z)) (bvxor size x (+ y z)))) :hints (("Goal" :in-theory (e/d (bvxor) (logxor-bvchop-bvchop))))) ;instead, inner sum should go to bvplus... ;BOZO handle this stuff better? (defthm bvxor-of-sum-logext-alt (implies (and (<= size size2) (natp size) (natp size2) (integerp y) (integerp z)) (equal (bvxor size x (+ z (logext size2 y))) (bvxor size x (+ y z)))) :hints (("Goal" :in-theory (e/d (bvxor) (logxor-bvchop-bvchop))))) ;trying this and the above... (in-theory (disable bvxor-of-slice-tighten-1 bvxor-of-slice-tighten-2 bvxor-of-slice-tighten-alt bvxor-of-slice-tighten)) ;drop? ;bozo gen (or match usb claims in rhs?) (defthmd bvplus-bound (< (bvplus 2 x y) 4) :hints (("Goal" :in-theory (e/d (bvplus) (;anti-bvplus ))))) (defthm logext-of-bv-plus-equal-plus-rewrite (implies (and (integerp x) ;hyps are new (integerp y)) (equal (EQUAL (LOGEXT 32 (BVPLUS 32 x y)) (+ x y)) (signed-byte-p 32 (+ x y)))) :hints (("Goal" :in-theory (e/d (BVPLUS) (;anti-bvplus logext-of-plus))))) ;move? (defthmd usb-of-bvplus-from-bounds (implies (and (< x (- (expt 2 n) k)) ;use bvlt? (natp x) (natp k) (natp n)) (unsigned-byte-p n (bvplus m k x))) :hints (("Goal" :in-theory (e/d (bvplus ;usb-plus-from-bounds ) ( ))))) ; rules needed to prove the lemmas that result from my tool (mostly size junk) (theory-invariant (incompatible (:rewrite LOGAPP-0) (:rewrite LOGAPP-RECOLLECT-FROM-SHIFT))) (theory-invariant (incompatible (:rewrite rewrite-unsigned-byte-p-when-term-size-is-larger) (:rewrite logtail-equal-0))) ;; essentialy, we are subtracting 1, chopping, and then adding 1 back (defthm +-of-1-and-bvchop-of-ones-and-x (implies (integerp x) (equal (+ 1 (bvchop 31 (+ 2147483647 x))) (if (equal 0 (bvchop 31 x)) 2147483648 (bvchop 31 x)))) :hints (("Goal" :in-theory (enable bvchop-of-sum-cases)))) (defthm logext-when-low-bits-known (implies (and (equal (bvchop 31 x) free) (syntaxp (quotep free))) (equal (logext 32 x) (if (equal 0 (getbit 31 x)) free (+ (- (expt 2 31)) free)))) :hints (("Goal" :in-theory (enable logext)))) (defthm logext-negative-linear-cheap (implies (equal (getbit 31 x) 1) (< (logext 32 x) 0)) :rule-classes ((:linear :backchain-limit-lst (0))) :hints (("Goal" :in-theory (enable logext))))
89867
; Bit-vector rules ; ; Copyright (C) 2008-2011 <NAME> and Stanford University ; Copyright (C) 2013-2020 Kestrel Institute ; Copyright (C) 2016-2020 Kestrel Technology, LLC ; ; License: A 3-clause BSD license. See the file books/3BSD-mod.txt. ; ; Author: <NAME> (<EMAIL>) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (in-package "ACL2") (include-book "kestrel/bv/rules6" :dir :system) (local (include-book "kestrel/library-wrappers/arithmetic-top-with-meta" :dir :system)) (local (in-theory (disable expt))) ;yuck? (defthm bvcat-bvxor-neighbors-hack3 (implies (and (equal low2 (+ 1 high)) (equal j (+ high 1 (- low))) (equal k (+ high2 1 (- low2))) (<= low high) (<= low2 high2) (natp high) (natp low) (natp high2) (natp low2) ) (equal (bvcat k (BVXOR k (slice high2 low2 y) (slice high2 low2 x)) j (BVXOR j (slice high low y) (slice high low x))) (bvxor (+ 1 high2 (- low)) (slice high2 low y) (slice high2 low x)))) :hints (("Goal" :use () :in-theory (e/d (;bvxor ) ( ;BVXOR-TRIM-ARG1 ;BVXOR-CANCEL BVXOR-CANCEL-alt BVXOR-CANCEL-cross-2 ))) ;why the disables? )) ;yuck.. (defthmd bvcat-bvxor-neighbors-hack4 (implies (and (equal n (+ 1 high)) (equal j (+ high 1 (- low))) (natp high) (natp n) (natp low) (<= low high) ) (equal (bvcat 1 (BVXOR 1 (getbit n y) (getbit n x)) j (BVXOR j (slice high low y) (slice high low x))) (bvxor (+ 1 n (- low)) (slice n low y) (slice n low x)))) :hints (("Goal" :use ((:instance bvcat-bvxor-neighbors-hack3 (high2 n) (low2 n) (k 1))) :in-theory (disable bvcat-bvxor-neighbors-hack3))) :otf-flg t) ;; Used in CLAIM! (DEFTHMd BACKCHAIN-SIGNED-BYTE-P-TO-UNSIGNED-BYTE-P-non-const (IMPLIES (AND ;(SYNTAXP (CONSTANT-SYNTAXP SIZE)) (< 0 SIZE) (UNSIGNED-BYTE-P (1- SIZE) I)) (SIGNED-BYTE-P SIZE I)) :HINTS (("Goal" :IN-THEORY (E/d (SIGNED-BYTE-P UNSIGNED-BYTE-P) (;HACK-6 ))))) ;fixme pretty special purpose (defthm bvif-hack (equal (bvif 8 test1 (bvif 8 test2 a b) (bvif 8 test2 b a)) (bvif 8 (xor test1 test2) b a)) :hints (("Goal" :in-theory (e/d (xor bvif myif) (;bvchop-bvchop ))))) (defthm bvif-hack-gen (implies (and (integerp size) (< 0 size)) (equal (bvif size test1 (bvif size test2 a b) (bvif size test2 b a)) (bvif size (xor test1 test2) b a))) :hints (("Goal" :in-theory (e/d (xor bvif myif) (;bvchop-bvchop ))))) (defthm bvif-of-logext-1 (implies (and (<= size size2) (natp size) (integerp size2) ;new (< 0 size)) (equal (bvif size test (logext size2 x) y) (bvif size test x y))) :hints (("Goal" :cases ((integerp x)) :in-theory (e/d (bvif BVCHOP-WHEN-I-IS-NOT-AN-INTEGER) (;BVCHOP-BVCHOP ))))) (defthm bvif-of-logext-2 (implies (and (<= size size2) (integerp size2) (natp size) (< 0 size)) (equal (bvif size test y (logext size2 x)) (bvif size test y x))) :hints (("Goal" :in-theory (e/d (bvif BVCHOP-WHEN-I-IS-NOT-AN-INTEGER) (;BVCHOP-BVCHOP ))))) (defthm myif-equal-bit-0-expt-2-n (implies (and (unsigned-byte-p 1 bit) (natp n)) (equal (myif (equal bit 0) 0 (expt 2 n)) (bvcat 1 bit n 0))) :hints (("Goal" :in-theory (enable myif)))) (defthm myif-equal-bit-0-constant-version (implies (and (syntaxp (quotep k)) (equal k (expt 2 (+ -1 (integer-length k)))) (< 0 (integer-length k)) (unsigned-byte-p 1 bit)) (equal (myif (equal bit 0) 0 k) (bvcat 1 bit (+ -1 (integer-length k)) 0))) :hints (("Goal" :use (:instance myif-equal-bit-0-expt-2-n (n (+ -1 (integer-length k)) ))))) ;BOZO can this loop? (defthm bvchop-32-times-subst (implies (and (equal (bvchop 32 x) (bvchop 32 free)) ;binds the variable FREE (syntaxp (smaller-termp free x)) (integerp x) (integerp z) (integerp free) ) (EQUAL (BVCHOP 32 (* z x)) (BVCHOP 32 (* z free)))) :hints (("Goal" :use ((:instance bvchop-n-times-drop (n 32) (x x) (y z)) (:instance bvchop-n-times-drop (n 32) (x free) (y z))) :in-theory (disable bvchop-n-times-drop)))) (defthmd apply-logext-32-to-both-sides (implies (and (equal x y) (equal a (logext 32 x)) (equal b (logext 32 y))) (equal (equal a b) t))) (defthmd apply-logext-32-to-both-sides-alt (implies (and (equal y x) (equal b (logext 32 x)) (equal a (logext 32 y))) (equal (equal a b) t))) ;yikes, don't we want to go the other way? (defthm bvchop-of-sbp-equal-constant (implies (and (syntaxp (quotep k)) (signed-byte-p 32 x) ;backchain limit? ) (equal (equal k (bvchop 32 x)) (and (unsigned-byte-p 32 k) (equal (logext 32 k) x)))) :hints (("Goal" :in-theory (enable apply-logext-32-to-both-sides-alt apply-logext-32-to-both-sides)))) ;for example, we prefer ;(EQUAL '0 (BVCAT '1 x '7 '0)) ;to: ;(EQUAL '0 (LOGEXT '8 (BVCAT '1 x '7 '0))) ;is this one okay? (defthm add-bvchops-to-equality-of-sbps-5 (implies (and (syntaxp (and (quotep y) (consp x) (member-equal (car x) *trimmable-operators*))) (integerp newsize) (< 0 newsize)) (equal (equal (logext newsize x) y) (if (integerp x) ;remove the other case? (and (signed-byte-p newsize y) (equal (bvchop newsize x) (bvchop newsize y))) (equal 0 y)))) :hints (("Goal" :cases ((integerp x)) :use (:instance add-bvchops-to-equality-of-sbps-4)))) (defthm logext-equal-logext-rewrite (implies (and (integerp x) (integerp size) (< 0 size)) (equal (EQUAL (LOGEXT size x) (LOGEXT size y)) (equal (bvchop size x) (bvchop size y)))) :hints (("Goal" :in-theory (enable ADD-BVCHOPS-TO-EQUALITY-OF-SBPS-4)))) (DEFTHM GETBIT-0-OF-TIMES-constant (IMPLIES (AND (syntaxp (and (quotep x) (not (unsigned-byte-p 1 (unquote x))))) (INTEGERP X) (INTEGERP Y)) (EQUAL (GETBIT 0 (* X Y)) (GETBIT 0 (* (GETBIT 0 X) Y)))) :HINTS (("Goal" :use (:instance bvchop-n-times-drop (n 1)) :IN-THEORY (E/D (GETBIT) (BVCHOP-1-BECOMES-GETBIT SLICE-BECOMES-GETBIT bvchop-n-times-drop))))) ;bozo more (defthm bvchop-times-logext-32 (implies (and (integerp x) (integerp y)) (equal (BVCHOP 32 (* x (LOGEXT 32 y))) (BVCHOP 32 (* x y)))) :hints (("Goal" :in-theory (disable bvchop-n-times-drop) :use ((:instance bvchop-n-times-drop (n 32) (x (logext 32 y)) (y x)) (:instance bvchop-n-times-drop (n 32) (x y) (y x)))))) ;sort of strength reduction ;gen ;can loop? (defthmd floor-by-4 (implies (integerp x) (equal (floor x 4) (logtail 2 x))) :hints (("Goal" :in-theory (enable logtail)))) (theory-invariant (incompatible (:rewrite FLOOR-BY-4) (:DEFINITION LOGTAIL))) (theory-invariant (incompatible (:rewrite logapp-0) (:rewrite times-4-becomes-logapp))) ;move (defthm unsigned-byte-p-of-slice-lemma (implies (and (unsigned-byte-p (+ n low) x) (natp n) (natp low) (natp high) ) (equal (unsigned-byte-p n (slice high low x)) t)) :hints (("Goal" :in-theory (e/d (slice) (anti-slice))))) (defthm logext-of-plus-of-logext (implies (and (<= smallsize bigsize) (integerp smallsize) (integerp bigsize) (< 0 smallsize) (force (integerp x)) (force (integerp y))) (equal (LOGEXT smallsize (+ x (LOGEXT bigsize y))) (LOGEXT smallsize (+ x y)))) :hints (("Goal" :in-theory (e/d (ADD-BVCHOPS-TO-EQUALITY-OF-SBPS-4) (;BVPLUS-RECOLLAPSE ))))) (defthm logext-of-plus-of-logext-alt (implies (and (<= smallsize bigsize) (integerp smallsize) (integerp bigsize) (< 0 smallsize) (force (integerp x)) (force (integerp y))) (equal (LOGEXT smallsize (+ (LOGEXT bigsize y) x)) (LOGEXT smallsize (+ x y)))) :hints (("Goal" :in-theory (e/d (ADD-BVCHOPS-TO-EQUALITY-OF-SBPS-4) (logext))))) ;slow? (defthm slice-of-plus-of-logext-gen (implies (and (< high size) (natp high) (integerp size) (<= low high) (natp low) (force (integerp x)) (force (integerp y))) (equal (SLICE high low (+ x (LOGEXT size y))) (SLICE high low (+ x y)) )) :hints (("Goal" :in-theory (e/d (SLICE bvchop-of-logtail) (anti-slice LOGEXT-OF-LOGTAIL-BECOMES-LOGEXT-OF-SLICE LOGTAIL-OF-LOGEXT))))) ;todo: (theory-invariant (incompatible (:rewrite LOGEXT-OF-LOGTAIL-BECOMES-LOGEXT-OF-SLICE) (:rewrite slice))) (defthm slice-of-plus-of-logext-gen-alt (implies (and (< high size) (natp high) (integerp size) (<= low high) (natp low) (force (integerp x)) (force (integerp y))) (equal (slice high low (+ (logext size y) x)) (slice high low (+ x y)) )) :hints (("Goal" :in-theory (e/d (slice) (anti-slice LOGEXT-OF-LOGTAIL-BECOMES-LOGEXT-OF-SLICE LOGEXT-of-logtail))))) ;instead, inner sum should go to bvplus... (defthm bvxor-of-sum-logext (implies (and (<= size size2) (natp size) (natp size2) (integerp y) (integerp z)) (equal (bvxor size x (+ (logext size2 y) z)) (bvxor size x (+ y z)))) :hints (("Goal" :in-theory (e/d (bvxor) (logxor-bvchop-bvchop))))) ;instead, inner sum should go to bvplus... ;BOZO handle this stuff better? (defthm bvxor-of-sum-logext-alt (implies (and (<= size size2) (natp size) (natp size2) (integerp y) (integerp z)) (equal (bvxor size x (+ z (logext size2 y))) (bvxor size x (+ y z)))) :hints (("Goal" :in-theory (e/d (bvxor) (logxor-bvchop-bvchop))))) ;trying this and the above... (in-theory (disable bvxor-of-slice-tighten-1 bvxor-of-slice-tighten-2 bvxor-of-slice-tighten-alt bvxor-of-slice-tighten)) ;drop? ;bozo gen (or match usb claims in rhs?) (defthmd bvplus-bound (< (bvplus 2 x y) 4) :hints (("Goal" :in-theory (e/d (bvplus) (;anti-bvplus ))))) (defthm logext-of-bv-plus-equal-plus-rewrite (implies (and (integerp x) ;hyps are new (integerp y)) (equal (EQUAL (LOGEXT 32 (BVPLUS 32 x y)) (+ x y)) (signed-byte-p 32 (+ x y)))) :hints (("Goal" :in-theory (e/d (BVPLUS) (;anti-bvplus logext-of-plus))))) ;move? (defthmd usb-of-bvplus-from-bounds (implies (and (< x (- (expt 2 n) k)) ;use bvlt? (natp x) (natp k) (natp n)) (unsigned-byte-p n (bvplus m k x))) :hints (("Goal" :in-theory (e/d (bvplus ;usb-plus-from-bounds ) ( ))))) ; rules needed to prove the lemmas that result from my tool (mostly size junk) (theory-invariant (incompatible (:rewrite LOGAPP-0) (:rewrite LOGAPP-RECOLLECT-FROM-SHIFT))) (theory-invariant (incompatible (:rewrite rewrite-unsigned-byte-p-when-term-size-is-larger) (:rewrite logtail-equal-0))) ;; essentialy, we are subtracting 1, chopping, and then adding 1 back (defthm +-of-1-and-bvchop-of-ones-and-x (implies (integerp x) (equal (+ 1 (bvchop 31 (+ 2147483647 x))) (if (equal 0 (bvchop 31 x)) 2147483648 (bvchop 31 x)))) :hints (("Goal" :in-theory (enable bvchop-of-sum-cases)))) (defthm logext-when-low-bits-known (implies (and (equal (bvchop 31 x) free) (syntaxp (quotep free))) (equal (logext 32 x) (if (equal 0 (getbit 31 x)) free (+ (- (expt 2 31)) free)))) :hints (("Goal" :in-theory (enable logext)))) (defthm logext-negative-linear-cheap (implies (equal (getbit 31 x) 1) (< (logext 32 x) 0)) :rule-classes ((:linear :backchain-limit-lst (0))) :hints (("Goal" :in-theory (enable logext))))
true
; Bit-vector rules ; ; Copyright (C) 2008-2011 PI:NAME:<NAME>END_PI and Stanford University ; Copyright (C) 2013-2020 Kestrel Institute ; Copyright (C) 2016-2020 Kestrel Technology, LLC ; ; License: A 3-clause BSD license. See the file books/3BSD-mod.txt. ; ; Author: PI:NAME:<NAME>END_PI (PI:EMAIL:<EMAIL>END_PI) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (in-package "ACL2") (include-book "kestrel/bv/rules6" :dir :system) (local (include-book "kestrel/library-wrappers/arithmetic-top-with-meta" :dir :system)) (local (in-theory (disable expt))) ;yuck? (defthm bvcat-bvxor-neighbors-hack3 (implies (and (equal low2 (+ 1 high)) (equal j (+ high 1 (- low))) (equal k (+ high2 1 (- low2))) (<= low high) (<= low2 high2) (natp high) (natp low) (natp high2) (natp low2) ) (equal (bvcat k (BVXOR k (slice high2 low2 y) (slice high2 low2 x)) j (BVXOR j (slice high low y) (slice high low x))) (bvxor (+ 1 high2 (- low)) (slice high2 low y) (slice high2 low x)))) :hints (("Goal" :use () :in-theory (e/d (;bvxor ) ( ;BVXOR-TRIM-ARG1 ;BVXOR-CANCEL BVXOR-CANCEL-alt BVXOR-CANCEL-cross-2 ))) ;why the disables? )) ;yuck.. (defthmd bvcat-bvxor-neighbors-hack4 (implies (and (equal n (+ 1 high)) (equal j (+ high 1 (- low))) (natp high) (natp n) (natp low) (<= low high) ) (equal (bvcat 1 (BVXOR 1 (getbit n y) (getbit n x)) j (BVXOR j (slice high low y) (slice high low x))) (bvxor (+ 1 n (- low)) (slice n low y) (slice n low x)))) :hints (("Goal" :use ((:instance bvcat-bvxor-neighbors-hack3 (high2 n) (low2 n) (k 1))) :in-theory (disable bvcat-bvxor-neighbors-hack3))) :otf-flg t) ;; Used in CLAIM! (DEFTHMd BACKCHAIN-SIGNED-BYTE-P-TO-UNSIGNED-BYTE-P-non-const (IMPLIES (AND ;(SYNTAXP (CONSTANT-SYNTAXP SIZE)) (< 0 SIZE) (UNSIGNED-BYTE-P (1- SIZE) I)) (SIGNED-BYTE-P SIZE I)) :HINTS (("Goal" :IN-THEORY (E/d (SIGNED-BYTE-P UNSIGNED-BYTE-P) (;HACK-6 ))))) ;fixme pretty special purpose (defthm bvif-hack (equal (bvif 8 test1 (bvif 8 test2 a b) (bvif 8 test2 b a)) (bvif 8 (xor test1 test2) b a)) :hints (("Goal" :in-theory (e/d (xor bvif myif) (;bvchop-bvchop ))))) (defthm bvif-hack-gen (implies (and (integerp size) (< 0 size)) (equal (bvif size test1 (bvif size test2 a b) (bvif size test2 b a)) (bvif size (xor test1 test2) b a))) :hints (("Goal" :in-theory (e/d (xor bvif myif) (;bvchop-bvchop ))))) (defthm bvif-of-logext-1 (implies (and (<= size size2) (natp size) (integerp size2) ;new (< 0 size)) (equal (bvif size test (logext size2 x) y) (bvif size test x y))) :hints (("Goal" :cases ((integerp x)) :in-theory (e/d (bvif BVCHOP-WHEN-I-IS-NOT-AN-INTEGER) (;BVCHOP-BVCHOP ))))) (defthm bvif-of-logext-2 (implies (and (<= size size2) (integerp size2) (natp size) (< 0 size)) (equal (bvif size test y (logext size2 x)) (bvif size test y x))) :hints (("Goal" :in-theory (e/d (bvif BVCHOP-WHEN-I-IS-NOT-AN-INTEGER) (;BVCHOP-BVCHOP ))))) (defthm myif-equal-bit-0-expt-2-n (implies (and (unsigned-byte-p 1 bit) (natp n)) (equal (myif (equal bit 0) 0 (expt 2 n)) (bvcat 1 bit n 0))) :hints (("Goal" :in-theory (enable myif)))) (defthm myif-equal-bit-0-constant-version (implies (and (syntaxp (quotep k)) (equal k (expt 2 (+ -1 (integer-length k)))) (< 0 (integer-length k)) (unsigned-byte-p 1 bit)) (equal (myif (equal bit 0) 0 k) (bvcat 1 bit (+ -1 (integer-length k)) 0))) :hints (("Goal" :use (:instance myif-equal-bit-0-expt-2-n (n (+ -1 (integer-length k)) ))))) ;BOZO can this loop? (defthm bvchop-32-times-subst (implies (and (equal (bvchop 32 x) (bvchop 32 free)) ;binds the variable FREE (syntaxp (smaller-termp free x)) (integerp x) (integerp z) (integerp free) ) (EQUAL (BVCHOP 32 (* z x)) (BVCHOP 32 (* z free)))) :hints (("Goal" :use ((:instance bvchop-n-times-drop (n 32) (x x) (y z)) (:instance bvchop-n-times-drop (n 32) (x free) (y z))) :in-theory (disable bvchop-n-times-drop)))) (defthmd apply-logext-32-to-both-sides (implies (and (equal x y) (equal a (logext 32 x)) (equal b (logext 32 y))) (equal (equal a b) t))) (defthmd apply-logext-32-to-both-sides-alt (implies (and (equal y x) (equal b (logext 32 x)) (equal a (logext 32 y))) (equal (equal a b) t))) ;yikes, don't we want to go the other way? (defthm bvchop-of-sbp-equal-constant (implies (and (syntaxp (quotep k)) (signed-byte-p 32 x) ;backchain limit? ) (equal (equal k (bvchop 32 x)) (and (unsigned-byte-p 32 k) (equal (logext 32 k) x)))) :hints (("Goal" :in-theory (enable apply-logext-32-to-both-sides-alt apply-logext-32-to-both-sides)))) ;for example, we prefer ;(EQUAL '0 (BVCAT '1 x '7 '0)) ;to: ;(EQUAL '0 (LOGEXT '8 (BVCAT '1 x '7 '0))) ;is this one okay? (defthm add-bvchops-to-equality-of-sbps-5 (implies (and (syntaxp (and (quotep y) (consp x) (member-equal (car x) *trimmable-operators*))) (integerp newsize) (< 0 newsize)) (equal (equal (logext newsize x) y) (if (integerp x) ;remove the other case? (and (signed-byte-p newsize y) (equal (bvchop newsize x) (bvchop newsize y))) (equal 0 y)))) :hints (("Goal" :cases ((integerp x)) :use (:instance add-bvchops-to-equality-of-sbps-4)))) (defthm logext-equal-logext-rewrite (implies (and (integerp x) (integerp size) (< 0 size)) (equal (EQUAL (LOGEXT size x) (LOGEXT size y)) (equal (bvchop size x) (bvchop size y)))) :hints (("Goal" :in-theory (enable ADD-BVCHOPS-TO-EQUALITY-OF-SBPS-4)))) (DEFTHM GETBIT-0-OF-TIMES-constant (IMPLIES (AND (syntaxp (and (quotep x) (not (unsigned-byte-p 1 (unquote x))))) (INTEGERP X) (INTEGERP Y)) (EQUAL (GETBIT 0 (* X Y)) (GETBIT 0 (* (GETBIT 0 X) Y)))) :HINTS (("Goal" :use (:instance bvchop-n-times-drop (n 1)) :IN-THEORY (E/D (GETBIT) (BVCHOP-1-BECOMES-GETBIT SLICE-BECOMES-GETBIT bvchop-n-times-drop))))) ;bozo more (defthm bvchop-times-logext-32 (implies (and (integerp x) (integerp y)) (equal (BVCHOP 32 (* x (LOGEXT 32 y))) (BVCHOP 32 (* x y)))) :hints (("Goal" :in-theory (disable bvchop-n-times-drop) :use ((:instance bvchop-n-times-drop (n 32) (x (logext 32 y)) (y x)) (:instance bvchop-n-times-drop (n 32) (x y) (y x)))))) ;sort of strength reduction ;gen ;can loop? (defthmd floor-by-4 (implies (integerp x) (equal (floor x 4) (logtail 2 x))) :hints (("Goal" :in-theory (enable logtail)))) (theory-invariant (incompatible (:rewrite FLOOR-BY-4) (:DEFINITION LOGTAIL))) (theory-invariant (incompatible (:rewrite logapp-0) (:rewrite times-4-becomes-logapp))) ;move (defthm unsigned-byte-p-of-slice-lemma (implies (and (unsigned-byte-p (+ n low) x) (natp n) (natp low) (natp high) ) (equal (unsigned-byte-p n (slice high low x)) t)) :hints (("Goal" :in-theory (e/d (slice) (anti-slice))))) (defthm logext-of-plus-of-logext (implies (and (<= smallsize bigsize) (integerp smallsize) (integerp bigsize) (< 0 smallsize) (force (integerp x)) (force (integerp y))) (equal (LOGEXT smallsize (+ x (LOGEXT bigsize y))) (LOGEXT smallsize (+ x y)))) :hints (("Goal" :in-theory (e/d (ADD-BVCHOPS-TO-EQUALITY-OF-SBPS-4) (;BVPLUS-RECOLLAPSE ))))) (defthm logext-of-plus-of-logext-alt (implies (and (<= smallsize bigsize) (integerp smallsize) (integerp bigsize) (< 0 smallsize) (force (integerp x)) (force (integerp y))) (equal (LOGEXT smallsize (+ (LOGEXT bigsize y) x)) (LOGEXT smallsize (+ x y)))) :hints (("Goal" :in-theory (e/d (ADD-BVCHOPS-TO-EQUALITY-OF-SBPS-4) (logext))))) ;slow? (defthm slice-of-plus-of-logext-gen (implies (and (< high size) (natp high) (integerp size) (<= low high) (natp low) (force (integerp x)) (force (integerp y))) (equal (SLICE high low (+ x (LOGEXT size y))) (SLICE high low (+ x y)) )) :hints (("Goal" :in-theory (e/d (SLICE bvchop-of-logtail) (anti-slice LOGEXT-OF-LOGTAIL-BECOMES-LOGEXT-OF-SLICE LOGTAIL-OF-LOGEXT))))) ;todo: (theory-invariant (incompatible (:rewrite LOGEXT-OF-LOGTAIL-BECOMES-LOGEXT-OF-SLICE) (:rewrite slice))) (defthm slice-of-plus-of-logext-gen-alt (implies (and (< high size) (natp high) (integerp size) (<= low high) (natp low) (force (integerp x)) (force (integerp y))) (equal (slice high low (+ (logext size y) x)) (slice high low (+ x y)) )) :hints (("Goal" :in-theory (e/d (slice) (anti-slice LOGEXT-OF-LOGTAIL-BECOMES-LOGEXT-OF-SLICE LOGEXT-of-logtail))))) ;instead, inner sum should go to bvplus... (defthm bvxor-of-sum-logext (implies (and (<= size size2) (natp size) (natp size2) (integerp y) (integerp z)) (equal (bvxor size x (+ (logext size2 y) z)) (bvxor size x (+ y z)))) :hints (("Goal" :in-theory (e/d (bvxor) (logxor-bvchop-bvchop))))) ;instead, inner sum should go to bvplus... ;BOZO handle this stuff better? (defthm bvxor-of-sum-logext-alt (implies (and (<= size size2) (natp size) (natp size2) (integerp y) (integerp z)) (equal (bvxor size x (+ z (logext size2 y))) (bvxor size x (+ y z)))) :hints (("Goal" :in-theory (e/d (bvxor) (logxor-bvchop-bvchop))))) ;trying this and the above... (in-theory (disable bvxor-of-slice-tighten-1 bvxor-of-slice-tighten-2 bvxor-of-slice-tighten-alt bvxor-of-slice-tighten)) ;drop? ;bozo gen (or match usb claims in rhs?) (defthmd bvplus-bound (< (bvplus 2 x y) 4) :hints (("Goal" :in-theory (e/d (bvplus) (;anti-bvplus ))))) (defthm logext-of-bv-plus-equal-plus-rewrite (implies (and (integerp x) ;hyps are new (integerp y)) (equal (EQUAL (LOGEXT 32 (BVPLUS 32 x y)) (+ x y)) (signed-byte-p 32 (+ x y)))) :hints (("Goal" :in-theory (e/d (BVPLUS) (;anti-bvplus logext-of-plus))))) ;move? (defthmd usb-of-bvplus-from-bounds (implies (and (< x (- (expt 2 n) k)) ;use bvlt? (natp x) (natp k) (natp n)) (unsigned-byte-p n (bvplus m k x))) :hints (("Goal" :in-theory (e/d (bvplus ;usb-plus-from-bounds ) ( ))))) ; rules needed to prove the lemmas that result from my tool (mostly size junk) (theory-invariant (incompatible (:rewrite LOGAPP-0) (:rewrite LOGAPP-RECOLLECT-FROM-SHIFT))) (theory-invariant (incompatible (:rewrite rewrite-unsigned-byte-p-when-term-size-is-larger) (:rewrite logtail-equal-0))) ;; essentialy, we are subtracting 1, chopping, and then adding 1 back (defthm +-of-1-and-bvchop-of-ones-and-x (implies (integerp x) (equal (+ 1 (bvchop 31 (+ 2147483647 x))) (if (equal 0 (bvchop 31 x)) 2147483648 (bvchop 31 x)))) :hints (("Goal" :in-theory (enable bvchop-of-sum-cases)))) (defthm logext-when-low-bits-known (implies (and (equal (bvchop 31 x) free) (syntaxp (quotep free))) (equal (logext 32 x) (if (equal 0 (getbit 31 x)) free (+ (- (expt 2 31)) free)))) :hints (("Goal" :in-theory (enable logext)))) (defthm logext-negative-linear-cheap (implies (equal (getbit 31 x) 1) (< (logext 32 x) 0)) :rule-classes ((:linear :backchain-limit-lst (0))) :hints (("Goal" :in-theory (enable logext))))
[ { "context": "rpose: system definition\n;;;; Author: mikel evins\n;;;; Copyright: 2020 by mikel evins\n;;;;\n;;;;", "end": 236, "score": 0.9998456239700317, "start": 225, "tag": "NAME", "value": "mikel evins" }, { "context": "or: mikel evins\n;;;; Copyright: 2020 by mikel evins\n;;;;\n;;;; ***************************************", "end": 276, "score": 0.9998669624328613, "start": 265, "tag": "NAME", "value": "mikel evins" }, { "context": "electus 1.x files using libDelectus\"\n :author \"mikel evins <[email protected]>\"\n :license \"Apache 2.0\"\n ", "end": 1757, "score": 0.9998563528060913, "start": 1746, "tag": "NAME", "value": "mikel evins" }, { "context": "iles using libDelectus\"\n :author \"mikel evins <[email protected]>\"\n :license \"Apache 2.0\"\n :version \"1.5.2\"", "end": 1774, "score": 0.9999257922172546, "start": 1759, "tag": "EMAIL", "value": "[email protected]" }, { "context": "are-csv :cl-intbytes :binascii :uuid :local-time :jonathan :sxql\n :net.bardcode.alist)", "end": 1942, "score": 0.8141230344772339, "start": 1934, "tag": "NAME", "value": "jonathan" } ]
lisp/lecter/lecter.asd
mikelevins/lecter
0
;;;; *********************************************************************** ;;;; ;;;; Name: lecter.asd ;;;; Project: lecter: Delectus 1.x as a library ;;;; Purpose: system definition ;;;; Author: mikel evins ;;;; Copyright: 2020 by mikel evins ;;;; ;;;; *********************************************************************** (in-package #:cl-user) #-quicklisp (let ((quicklisp-init (merge-pathnames "quicklisp/setup.lisp" (user-homedir-pathname)))) (when (probe-file quicklisp-init) (load quicklisp-init))) #-abcl (eval-when (:compile-toplevel :load-toplevel :execute) (ql:quickload :cffi)) ;;; needed in order to load :sqlite on Lispworks ;;; --------------------------------------------------------------------- (eval-when (:compile-toplevel :load-toplevel :execute) (ql:quickload :cffi)) #+(and lispworks darwin) (eval-when (:compile-toplevel :load-toplevel :execute) (pushnew (pathname "/usr/local/Cellar/sqlite/3.33.0/lib/") cffi:*foreign-library-directories*)) ;;; --------------------------------------------------------------------- ;;; needed in order to load :sqlite and :hunchentoot on ABCL: ;;; --------------------------------------------------------------------- ;;; NOTES: need Maven 3.x.x installed to make this work #+abcl (setf abcl-asdf:*mvn-libs-directory* "/usr/local/Cellar/maven/3.6.3_1/libexec/lib/") #+abcl (asdf:defsystem :jna :defsystem-depends-on (abcl-asdf) :components ((:mvn "net.java.dev.jna/jna" :version "5.6.0"))) ;;; --------------------------------------------------------------------- (asdf:defsystem #:lecter :description "Lecter: reading Delectus 1.x files using libDelectus" :author "mikel evins <[email protected]>" :license "Apache 2.0" :version "1.5.2" :serial t :depends-on (:cffi :sqlite :cl-strings :fare-csv :cl-intbytes :binascii :uuid :local-time :jonathan :sxql :net.bardcode.alist) :components ((:module "src" :serial t :components ((:file "package") (:file "version") (:file "cffi") (:file "utils") (:file "identities") (:file "bind") (:file "sql") (:file "sqlite") (:file "conditions") (:file "delectus1"))))) ;;; (asdf:load-system :lecter) ;;; (ql:quickload :lecter)
75611
;;;; *********************************************************************** ;;;; ;;;; Name: lecter.asd ;;;; Project: lecter: Delectus 1.x as a library ;;;; Purpose: system definition ;;;; Author: <NAME> ;;;; Copyright: 2020 by <NAME> ;;;; ;;;; *********************************************************************** (in-package #:cl-user) #-quicklisp (let ((quicklisp-init (merge-pathnames "quicklisp/setup.lisp" (user-homedir-pathname)))) (when (probe-file quicklisp-init) (load quicklisp-init))) #-abcl (eval-when (:compile-toplevel :load-toplevel :execute) (ql:quickload :cffi)) ;;; needed in order to load :sqlite on Lispworks ;;; --------------------------------------------------------------------- (eval-when (:compile-toplevel :load-toplevel :execute) (ql:quickload :cffi)) #+(and lispworks darwin) (eval-when (:compile-toplevel :load-toplevel :execute) (pushnew (pathname "/usr/local/Cellar/sqlite/3.33.0/lib/") cffi:*foreign-library-directories*)) ;;; --------------------------------------------------------------------- ;;; needed in order to load :sqlite and :hunchentoot on ABCL: ;;; --------------------------------------------------------------------- ;;; NOTES: need Maven 3.x.x installed to make this work #+abcl (setf abcl-asdf:*mvn-libs-directory* "/usr/local/Cellar/maven/3.6.3_1/libexec/lib/") #+abcl (asdf:defsystem :jna :defsystem-depends-on (abcl-asdf) :components ((:mvn "net.java.dev.jna/jna" :version "5.6.0"))) ;;; --------------------------------------------------------------------- (asdf:defsystem #:lecter :description "Lecter: reading Delectus 1.x files using libDelectus" :author "<NAME> <<EMAIL>>" :license "Apache 2.0" :version "1.5.2" :serial t :depends-on (:cffi :sqlite :cl-strings :fare-csv :cl-intbytes :binascii :uuid :local-time :<NAME> :sxql :net.bardcode.alist) :components ((:module "src" :serial t :components ((:file "package") (:file "version") (:file "cffi") (:file "utils") (:file "identities") (:file "bind") (:file "sql") (:file "sqlite") (:file "conditions") (:file "delectus1"))))) ;;; (asdf:load-system :lecter) ;;; (ql:quickload :lecter)
true
;;;; *********************************************************************** ;;;; ;;;; Name: lecter.asd ;;;; Project: lecter: Delectus 1.x as a library ;;;; Purpose: system definition ;;;; Author: PI:NAME:<NAME>END_PI ;;;; Copyright: 2020 by PI:NAME:<NAME>END_PI ;;;; ;;;; *********************************************************************** (in-package #:cl-user) #-quicklisp (let ((quicklisp-init (merge-pathnames "quicklisp/setup.lisp" (user-homedir-pathname)))) (when (probe-file quicklisp-init) (load quicklisp-init))) #-abcl (eval-when (:compile-toplevel :load-toplevel :execute) (ql:quickload :cffi)) ;;; needed in order to load :sqlite on Lispworks ;;; --------------------------------------------------------------------- (eval-when (:compile-toplevel :load-toplevel :execute) (ql:quickload :cffi)) #+(and lispworks darwin) (eval-when (:compile-toplevel :load-toplevel :execute) (pushnew (pathname "/usr/local/Cellar/sqlite/3.33.0/lib/") cffi:*foreign-library-directories*)) ;;; --------------------------------------------------------------------- ;;; needed in order to load :sqlite and :hunchentoot on ABCL: ;;; --------------------------------------------------------------------- ;;; NOTES: need Maven 3.x.x installed to make this work #+abcl (setf abcl-asdf:*mvn-libs-directory* "/usr/local/Cellar/maven/3.6.3_1/libexec/lib/") #+abcl (asdf:defsystem :jna :defsystem-depends-on (abcl-asdf) :components ((:mvn "net.java.dev.jna/jna" :version "5.6.0"))) ;;; --------------------------------------------------------------------- (asdf:defsystem #:lecter :description "Lecter: reading Delectus 1.x files using libDelectus" :author "PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>" :license "Apache 2.0" :version "1.5.2" :serial t :depends-on (:cffi :sqlite :cl-strings :fare-csv :cl-intbytes :binascii :uuid :local-time :PI:NAME:<NAME>END_PI :sxql :net.bardcode.alist) :components ((:module "src" :serial t :components ((:file "package") (:file "version") (:file "cffi") (:file "utils") (:file "identities") (:file "bind") (:file "sql") (:file "sqlite") (:file "conditions") (:file "delectus1"))))) ;;; (asdf:load-system :lecter) ;;; (ql:quickload :lecter)
[ { "context": "; DEALINGS IN THE SOFTWARE.\n;\n; Original author: Jared Davis <[email protected]>\n\n(in-package \"MILAWA\")\n(inc", "end": 1356, "score": 0.9995775818824768, "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 \"core\")\n(se", "end": 1377, "score": 0.9999353885650635, "start": 1358, "tag": "EMAIL", "value": "[email protected]" } ]
books/projects/milawa/ACL2/interface/acl2-connection.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 "core") (set-verify-guards-eagerness 2) (set-case-split-limitations nil) (set-well-founded-relation ord<) (set-measure-function rank) ;; Goal checking ;; ;; Since our tactic harness is inside ACL2, we can ask ACL2 if it believes the ;; goals are true using (%check). Of course, this will only work if all the ;; functions involved are already defined inside of ACL2. (defun %check-goal (goal) (declare (xargs :mode :program)) `(ACL2::make-event (ACL2::mv-let (erp val ACL2::state) (ACL2::thm (or ,@goal)) (declare (ignore erp val)) (ACL2::value '(ACL2::value-triple :invisible))))) (defun %aux-check-goals (goals n) (declare (xargs :mode :program)) (if (consp goals) (list* `(ACL2::value-triple (ACL2::cw "Checking goal ~x0~%" ',n)) (%check-goal (car goals)) (%aux-check-goals (cdr goals) (+ 1 n))) nil)) (defun %check-goals (goals) (declare (xargs :mode :program)) `(ACL2::encapsulate () ,@(%aux-check-goals goals 1))) (defmacro %check () ;; Check if ACL2 believes the goals are theorems. `(ACL2::make-event (%check-goals (tactic.harness->goals (ACL2::w ACL2::state))))) ;; Autoadmitting Functions ;; ;; We can look up a function's definition in the ACL2 world, convert it into a ;; Milawa-usable form, and submit it as a Milawa definition. This won't work ;; unless all the functions it calls are already in Milawa, etc., but it's ;; awfully handy. (defun ACL2::get-untranslated-defun (name world) (declare (xargs :mode :program)) (let* ((ev-world (ACL2::decode-logical-name name world))) (ACL2::access-event-tuple-form (ACL2::cddar ev-world)))) (defun ACL2::get-measure (name world) (declare (xargs :mode :program)) (let* ((justification (acl2::fgetprop name 'acl2::justification nil world))) (and justification (ACL2::access ACL2::justification justification :measure)))) (defun find-syntax-defun (name syntax-defuns) (declare (xargs :mode :program)) (if (consp syntax-defuns) (if (equal name (second (car syntax-defuns))) (car syntax-defuns) (find-syntax-defun name (cdr syntax-defuns))) nil)) (defun %autoadmit-fn (name world) (declare (xargs :mode :program)) ;; What about :export support? We should be looking for that instead. (let* ((syntax-defuns (ACL2::get-syntax-defun-entries world)) (this-defun (find-syntax-defun name syntax-defuns)) ;; (untranslated-defun (ACL2::get-untranslated-defun name world)) ;; (real-name (ACL2::deref-macro-name name world)) (measure (ACL2::get-measure name world)) ;; (formals (third untranslated-defun)) (formals (third this-defun)) ;; (body (car (ACL2::last untranslated-defun)))) (body (fourth this-defun))) (if measure `(defsection ,name (%defun ,name ,formals ;; ,(ACL2::clean-up-body (annhialate-declarations body)) ,body :measure ,measure) (local (%auto)) (%admit)) `(defsection ,name (%defun ,name ,formals ;; ,(ACL2::clean-up-body (annhialate-declarations body))) ,body) (%admit))))) (defmacro %autoadmit (name) `(ACL2::make-event (%autoadmit-fn ',name (ACL2::w ACL2::state)))) ;; Automatic "outside-in" rule creation ;; ;; The rule (car (cons x y)) = x is a perfect example of a good outside-in ;; rule because it lets us throw away "y" before we even look at it. I go ;; ahead and generate an outside-in rule from ACL2 rules when: ;; ;; 1. The right-hand side "never increases a variable" ;; 2. There are no syntaxp restrictions, and ;; 3. There are no hypotheses. ;; ;; At one time I also prohibited rules that repeated a variable in their lhs, ;; such as (subsetp x x) = t, under the theory that we would want to give both ;; sides a chance to canonicalize first. But since we're keeping the ;; inside-out version too, I think this is not really much of a problem. ;; ;; Criteria #1 is the main issue. The whole point of outside-in rules is that ;; they'll allow us to avoid rewriting parts of terms by throwing away some ;; variable that they matched. And we don't want to introduce duplicates, ;; e.g., (foo x y (bar x z)) = (baz z z) is probably a bad outside-in rule ;; since if "z" is large then we might have blown up the term considerably. ;; Maybe it makes sense to break this rule when we "know" that z is usually ;; small, but for automatic outside-in rule introduction, I'm not bothering ;; with that. ;; ;; At one time, I also require that at least one variable was decreased. But ;; now I don't require this, since it allows rules like (iff x nil) = (not x) ;; to be made outside-rules, which I think probably helps canonicalize things. ;; ;; Criteria #2 is in place because often syntaxp rules are used to break ;; canonical forms, e.g., to left-associate (+ a (+ b c)) when a,b are ;; constants. We think it's unlikely that they'll be constants before we ;; rewrite them. Moreover, it seems like a reasonable expectation on the ;; part of the syntaxp writer is that their matches are already in ;; canonical form. ;; ;; Criteria #3 is probably overly restrictive. Basically we don't want to ;; introduce huge complicated hyps by instantiating their variables with big ;; expressions. It might pay off to investigate relaxing this somewhat, ;; especially given our caching mechanism. (defthm forcing-mapp-of-clean-update (implies (force (mapp map)) (equal (mapp (clean-update key val map)) t)) :hints(("Goal" :in-theory (e/d (clean-update) (rw.theory-mapp-of-clean-update))))) (defund rw.flag-count-variables (flag x acc) ;; Create a map from variable names to their number of occurrences in a term, ;; x. (declare (xargs :guard (and (if (equal flag 'term) (logic.termp x) (logic.term-listp x)) (mapp acc)) :verify-guards nil)) (if (equal flag 'term) (cond ((logic.constantp x) acc) ((logic.variablep x) (clean-update x (+ 1 (cdr (lookup x acc))) acc)) ((logic.functionp x) (rw.flag-count-variables 'list (logic.function-args x) acc)) ((logic.lambdap x) (rw.flag-count-variables 'list (logic.lambda-actuals x) acc)) (t acc)) (if (consp x) (rw.flag-count-variables 'list (cdr x) (rw.flag-count-variables 'term (car x) acc)) acc))) (defthm forcing-mapp-of-rw.flag-count-variables (implies (force (mapp acc)) (equal (mapp (rw.flag-count-variables flag x acc)) t)) :hints(("Goal" :in-theory (enable rw.flag-count-variables)))) (verify-guards rw.flag-count-variables) (definlined rw.count-variables (x) (declare (xargs :guard (logic.termp x))) (rw.flag-count-variables 'term x nil)) (definlined rw.count-variables-list (x) (declare (xargs :guard (logic.term-listp x))) (rw.flag-count-variables 'list x nil)) (defthm mapp-of-rw.count-variables (equal (mapp (rw.count-variables x)) t) :hints(("Goal" :in-theory (enable rw.count-variables)))) (defund rw.no-count-increases-aux (dom x y) ;; For all the keys listed in domain, is the corresponding value in y never ;; greater than the corresponding value in x? I.e., "did no variables increase?" (declare (xargs :guard (and (mapp x) (mapp y)))) (if (consp dom) (and (<= (cdr (lookup (car dom) y)) (cdr (lookup (car dom) x))) (rw.no-count-increases-aux (cdr dom) x y)) t)) (definlined rw.no-count-increases (x y) ;; For all keys in x, is the corresponding value in y never greater than the ;; corresponding value in x? (declare (xargs :guard (and (mapp x) (mapp y)))) (rw.no-count-increases-aux (fast-domain$ x nil) x y)) (defund rw.some-count-decreases-aux (dom x y) ;; For some key listed in domain, is the corresponding value in y smaller ;; than the corresponding value in x? I.e., "did some variable decrease?" (declare (xargs :guard (and (mapp x) (mapp y)))) (if (consp dom) (or (< (cdr (lookup (car dom) y)) (cdr (lookup (car dom) x))) (rw.some-count-decreases-aux (cdr dom) x y)) nil)) (definlined rw.some-count-decreases (x y) (declare (xargs :guard (and (mapp x) (mapp y)))) (rw.some-count-decreases-aux (fast-domain$ x nil) x y)) (defund rw.looks-good-for-outside-inp (rule) ;; Would we like rule to be an outside-in rule as well? (declare (xargs :guard (rw.rulep rule))) (and (equal (rw.rule->type rule) 'inside) (not (rw.rule->syntax rule)) (not (rw.rule->hyps rule)) (let ((lhsmap (rw.count-variables (rw.rule->lhs rule))) (rhsmap (rw.count-variables (rw.rule->rhs rule)))) (and (subsetp (domain rhsmap) (domain lhsmap)) ;; no new vars please ;; we don't require this anymore. ;; (rw.some-count-decreases lhsmap rhsmap) not any more. (rw.no-count-increases lhsmap rhsmap))))) ;; Translating Rewrite Rules ;; ;; Our first step is to convert the rule's hypotheses into hypp's for Milawa. ;; This is somewhat involved: ;; ;; (1) ACL2 embeds "force" inside the term; we have a separate field in the ;; hypp structure for this. ;; (2) Some ACL2 hyps are syntaxp hyps; we do not consider these to be hyps ;; and store them in a separate part of the rule. ;; (3) ACL2 embeds the backchain limits for the hyps in a separate list, ;; while we store them inside each hyp. ;; ;; We may also need to create additional syntaxp hyps from the loop-stoppers ;; of a rule. (defun make-force-list (x) (declare (xargs :mode :program)) ;; We are given a list of acl2-hyps as terms. We create tuples of the form ;; (forcep term) as follows: ;; (force a) --> (t a) ;; a --> (nil a) (if (consp x) (let ((term (car x))) (if (and (consp term) (equal (car term) 'ACL2::force)) (cons (list t (second term)) (make-force-list (cdr x))) (cons (list nil term) (make-force-list (cdr x))))) nil)) (defun make-syntax-list (x) (declare (xargs :mode :program)) ;; X is a list of (forcep term) tuples. We create tuples of the form ;; (syntaxp forcep term) as follows: ;; (forcep (syntaxp a)) => (t forcep a*) ;; (forcep a) => (nil forcep a) ;; Where a* is the "corrected" version of a. That is, a might include ;; calls of ACL2::quotep, which does not exist in Milawa and must be ;; replaced with MILAWA::logic.constantp. (if (consp x) (let* ((entry (car x)) (forcep (first entry)) (term (second entry))) (if (and (consp term) (equal (car term) 'ACL2::synp)) ;; The hyp is (synp vars form (quote term)) (let* ((syn-term (second (fourth term))) (fix-quotep (ACL2::subst 'logic.constantp 'ACL2::quotep syn-term))) (cons (list t forcep fix-quotep) (make-syntax-list (cdr x)))) ;; This isn't a syntax hyp. (cons (list nil forcep term) (make-syntax-list (cdr x))))) nil)) (defun insert-backchain-limits (x blimits) (declare (xargs :mode :program)) ;; X is a list of (syntaxp forcep term) tuples ;; Blimits is the :backchain-limit-lst from the ACL2 rule ;; We add the blimit to each hyp, creating tuples of the form (blimit syntaxp forcep term) ;; Each blimit is either nil (for no limit) or a number. (if (consp x) (cons (cons (car blimits) (car x)) (insert-backchain-limits (cdr x) (cdr blimits))) nil)) (defun collect-semantic-hyps (x) (declare (xargs :mode :program)) ;; X is a list of (limit syntaxp forcep term) tuples. We build the hypp structures for all ;; of the non-syntaxp hyps. (if (consp x) (let ((limit (first (car x))) (syntaxp (second (car x))) (forcep (third (car x))) (term (fourth (car x)))) (if syntaxp (collect-semantic-hyps (cdr x)) (cons (%hyp-fn term (if forcep 'weak nil) limit) (collect-semantic-hyps (cdr x))))) nil)) (defun collect-syntax-hyps (x) (declare (xargs :mode :program)) ;; X is a list of (limit syntaxp forcep term) tuples. We collect only the ;; terms from all the entries with valid syntaxp pairs. (if (consp x) (let ((syntaxp (second (car x))) (term (fourth (car x)))) (if syntaxp (cons term (collect-syntax-hyps (cdr x))) (collect-syntax-hyps (cdr x)))) nil)) (defun create-loop-stoppers (stoppers) (declare (xargs :mode :program)) ;; Stoppers are a list of (x y . fns) objects. We create a list of ;; (logic.term-< y x) entries. (if (consp stoppers) (let ((x (first (car stoppers))) (y (second (car stoppers)))) (cons (logic.function 'logic.term-< (list y x)) (create-loop-stoppers (cdr stoppers)))) nil)) (defun create-rule-from-rewrite-entry (name entry) (declare (xargs :mode :program)) ;; We return (enabledp . milawa-rule) for an ACL2 rewrite rule entry. (let* ((hyps (third (lookup :hyps entry))) (lhs (third (lookup :lhs entry))) (rhs (third (lookup :rhs entry))) (equiv (second (lookup :equiv entry))) (backchain-limit-lst (second (lookup :backchain-limit-lst entry))) (loop-stopper (second (lookup :loop-stopper entry))) (enabledp (second (lookup :enabledp entry))) (hypmap (insert-backchain-limits (make-syntax-list (make-force-list hyps)) backchain-limit-lst)) (milawa-hyps (collect-semantic-hyps hypmap)) (syntax (revappend (create-loop-stoppers loop-stopper) (collect-syntax-hyps hypmap)))) (cons enabledp (%rule-fn name 'inside milawa-hyps lhs rhs equiv syntax)))) ;; Translating Rule-Classes Nil Rules ;; (defun annhialate-forces (x) (declare (xargs :mode :program)) (if (consp x) (if (and (equal (first x) 'ACL2::force) (tuplep 2 x)) (annhialate-forces (second x)) (cons (annhialate-forces (car x)) (annhialate-forces (cdr x)))) x)) (defun create-rule-from-rule-classes-nil (name entry) (declare (xargs :mode :program)) ;; We return (enabledp . milawa-rule) for an ACL2 :rule-classes nil entry. (let* ((thm (annhialate-forces (third (lookup :theorem entry))))) (cond ((equal (car thm) 'implies) ;; We know implies is boolean, so we can cheat and use equal as the ;; equivalence relation. This turned out to be better than parsing ;; out the hyps separately. (cons nil (%rule-fn name 'manual ; "manual" rules are our equivalent of ACL2's rule-classes nil nil ; hyps thm ; lhs is the whole theorem ''t ; rhs is t 'equal ; equiv is equal nil))) ((memberp (car thm) '(equal iff)) (cons nil (%rule-fn name 'manual nil ; hyps (second thm) ; lhs (third thm) ; rhs (first thm) ; equiv nil))) ; syntax (t (cons nil (%rule-fn name 'manual nil thm ''t 'iff nil)))))) (defun create-rule-from-acl2 (name ACL2::state) ;; Returns (enabledp . milawa-rule) or throws an error. (declare (xargs :mode :program :stobjs ACL2::state)) (let ((info-entries (ACL2::info-fn name ACL2::state))) (if (not (and (tuplep 1 info-entries) (car info-entries))) (ACL2::er hard 'create-rule-from-acl2 "Something seems to be wrong with ~x0.~%~ Its info-entry is: ~x1.~%" name info-entries) (let* ((entry (car info-entries)) (class (first (cdr (lookup :class entry))))) (cond ((equal class :rewrite) (create-rule-from-rewrite-entry name entry)) ((equal class nil) (create-rule-from-rule-classes-nil name entry)) (t (ACL2::er hard 'create-rule-from-acl2 "Don't know how to handle rule-classes ~x0.~%" class))))))) (defmacro %autorule (name) `(ACL2::make-event `(%prove ',(cdr (create-rule-from-acl2 ',name ACL2::state))))) (defun autoprove-fn (name hints ACL2::state) (declare (xargs :mode :program :stobjs ACL2::state)) (let* ((rule+ (create-rule-from-acl2 name ACL2::state)) (enabledp (car rule+)) (rule (cdr rule+))) `(defsection ,name (%prove ',rule) (local (ACL2::progn ,@hints)) (local (%auto)) (%qed) ,@(if enabledp `((%enable default ,name)) nil) ,@(if (rw.looks-good-for-outside-inp rule) (let ((new-name (ACL2::mksym '[OUTSIDE] (rw.rule->name rule)))) `((%raw-add-rule (%rule ,new-name :type outside :hyps ,(rw.rule->hyps rule) :lhs ,(rw.rule->lhs rule) :rhs ,(rw.rule->rhs rule) :equiv ,(rw.rule->equiv rule) :syntax ,(rw.rule->syntax rule))) ,@(if enabledp `((%enable default ,new-name)) nil))) nil)))) (defmacro %autoprove (name &rest hints) `(ACL2::make-event (autoprove-fn ',name ',hints ACL2::state))) (defmacro %autoinduct (name &rest args) ;; Try inducting as suggested by the definition of the function <name>. ;; You can also rename the arguments, e.g., ;; (%autoinduct cdr-induction y) ;; Will try "cdr-induction on y" instead of "cdr-induction on x", which is the ;; default since the argument to cdr-induction is x. `(local (ACL2::make-event (%autoinduct-fn ',name ',args (ACL2::w ACL2::state))))) (defun pair-formals-with-calls (formals calls) ;; Calls are a list of function calls, e.g., ((foo a b) (foo c d) (foo e f)), and formals ;; are the names of the formals, e.g., (x y). We're going to turn these into substitution ;; lists, e.g., ((x . a) (y . b)), ((x . c) (y . d)), etc. (declare (xargs :mode :program)) (if (consp calls) (cons (list2-list formals (logic.function-args (car calls))) (pair-formals-with-calls formals (cdr calls))) nil)) (defun acl2-tests-and-calls-to-induct-pairs (formals x) ;; X is a list of tests-and-calls produced by acl2's induction-machine-for-fn function. We ;; need to walk through it and turn it into a list of conditions and substitutions. (declare (xargs :mode :program)) (if (consp x) (let ((tests (ACL2::access ACL2::tests-and-calls (car x) :tests)) (calls (ACL2::access ACL2::tests-and-calls (car x) :calls))) (cons (list (cond ((and (consp tests) (consp (cdr tests))) (cons 'and tests)) ((consp tests) (car tests)) (t (ACL2::er hard 'acl2-tests-and-calls-to-induct-pairs "A tests-and-calls entry had no tests!~%"))) (pair-formals-with-calls formals calls)) (acl2-tests-and-calls-to-induct-pairs formals (cdr x)))) nil)) (defun %autoinduct-fn (name args world) (declare (xargs :mode :program)) (let* ((syntax-defuns (ACL2::get-syntax-defun-entries world)) (this-defun (find-syntax-defun name syntax-defuns)) (measure (ACL2::get-measure name world)) (formals (third this-defun)) (body (logic.translate (fourth this-defun))) (args* (or args formals))) (cond ((not measure) (ACL2::er hard '%autoinduct-fn "The function ~x0 doesn't seem to have a measure.~%" name)) ((not (same-lengthp args* formals)) (ACL2::er hard '%autoinduct-fn "Wrong number of arguments provided. ~x0 takes ~x1 arguments.~%" name (len formals))) (t (let* ((args-sigma (fast-pair-lists$ formals args* nil)) (body/sigma (logic.substitute body args-sigma)) (measure/sigma (logic.substitute measure args-sigma)) (tests-and-calls (ACL2::induction-machine-for-fn (list name) body/sigma ;; In 3.5, ruler-extenders were added. For ;; 3.4 compatibility we only sometimes add them. #-v3-4 nil))) `(%induct ,measure/sigma ,@(acl2-tests-and-calls-to-induct-pairs args* tests-and-calls)))))))
39597
; 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 "core") (set-verify-guards-eagerness 2) (set-case-split-limitations nil) (set-well-founded-relation ord<) (set-measure-function rank) ;; Goal checking ;; ;; Since our tactic harness is inside ACL2, we can ask ACL2 if it believes the ;; goals are true using (%check). Of course, this will only work if all the ;; functions involved are already defined inside of ACL2. (defun %check-goal (goal) (declare (xargs :mode :program)) `(ACL2::make-event (ACL2::mv-let (erp val ACL2::state) (ACL2::thm (or ,@goal)) (declare (ignore erp val)) (ACL2::value '(ACL2::value-triple :invisible))))) (defun %aux-check-goals (goals n) (declare (xargs :mode :program)) (if (consp goals) (list* `(ACL2::value-triple (ACL2::cw "Checking goal ~x0~%" ',n)) (%check-goal (car goals)) (%aux-check-goals (cdr goals) (+ 1 n))) nil)) (defun %check-goals (goals) (declare (xargs :mode :program)) `(ACL2::encapsulate () ,@(%aux-check-goals goals 1))) (defmacro %check () ;; Check if ACL2 believes the goals are theorems. `(ACL2::make-event (%check-goals (tactic.harness->goals (ACL2::w ACL2::state))))) ;; Autoadmitting Functions ;; ;; We can look up a function's definition in the ACL2 world, convert it into a ;; Milawa-usable form, and submit it as a Milawa definition. This won't work ;; unless all the functions it calls are already in Milawa, etc., but it's ;; awfully handy. (defun ACL2::get-untranslated-defun (name world) (declare (xargs :mode :program)) (let* ((ev-world (ACL2::decode-logical-name name world))) (ACL2::access-event-tuple-form (ACL2::cddar ev-world)))) (defun ACL2::get-measure (name world) (declare (xargs :mode :program)) (let* ((justification (acl2::fgetprop name 'acl2::justification nil world))) (and justification (ACL2::access ACL2::justification justification :measure)))) (defun find-syntax-defun (name syntax-defuns) (declare (xargs :mode :program)) (if (consp syntax-defuns) (if (equal name (second (car syntax-defuns))) (car syntax-defuns) (find-syntax-defun name (cdr syntax-defuns))) nil)) (defun %autoadmit-fn (name world) (declare (xargs :mode :program)) ;; What about :export support? We should be looking for that instead. (let* ((syntax-defuns (ACL2::get-syntax-defun-entries world)) (this-defun (find-syntax-defun name syntax-defuns)) ;; (untranslated-defun (ACL2::get-untranslated-defun name world)) ;; (real-name (ACL2::deref-macro-name name world)) (measure (ACL2::get-measure name world)) ;; (formals (third untranslated-defun)) (formals (third this-defun)) ;; (body (car (ACL2::last untranslated-defun)))) (body (fourth this-defun))) (if measure `(defsection ,name (%defun ,name ,formals ;; ,(ACL2::clean-up-body (annhialate-declarations body)) ,body :measure ,measure) (local (%auto)) (%admit)) `(defsection ,name (%defun ,name ,formals ;; ,(ACL2::clean-up-body (annhialate-declarations body))) ,body) (%admit))))) (defmacro %autoadmit (name) `(ACL2::make-event (%autoadmit-fn ',name (ACL2::w ACL2::state)))) ;; Automatic "outside-in" rule creation ;; ;; The rule (car (cons x y)) = x is a perfect example of a good outside-in ;; rule because it lets us throw away "y" before we even look at it. I go ;; ahead and generate an outside-in rule from ACL2 rules when: ;; ;; 1. The right-hand side "never increases a variable" ;; 2. There are no syntaxp restrictions, and ;; 3. There are no hypotheses. ;; ;; At one time I also prohibited rules that repeated a variable in their lhs, ;; such as (subsetp x x) = t, under the theory that we would want to give both ;; sides a chance to canonicalize first. But since we're keeping the ;; inside-out version too, I think this is not really much of a problem. ;; ;; Criteria #1 is the main issue. The whole point of outside-in rules is that ;; they'll allow us to avoid rewriting parts of terms by throwing away some ;; variable that they matched. And we don't want to introduce duplicates, ;; e.g., (foo x y (bar x z)) = (baz z z) is probably a bad outside-in rule ;; since if "z" is large then we might have blown up the term considerably. ;; Maybe it makes sense to break this rule when we "know" that z is usually ;; small, but for automatic outside-in rule introduction, I'm not bothering ;; with that. ;; ;; At one time, I also require that at least one variable was decreased. But ;; now I don't require this, since it allows rules like (iff x nil) = (not x) ;; to be made outside-rules, which I think probably helps canonicalize things. ;; ;; Criteria #2 is in place because often syntaxp rules are used to break ;; canonical forms, e.g., to left-associate (+ a (+ b c)) when a,b are ;; constants. We think it's unlikely that they'll be constants before we ;; rewrite them. Moreover, it seems like a reasonable expectation on the ;; part of the syntaxp writer is that their matches are already in ;; canonical form. ;; ;; Criteria #3 is probably overly restrictive. Basically we don't want to ;; introduce huge complicated hyps by instantiating their variables with big ;; expressions. It might pay off to investigate relaxing this somewhat, ;; especially given our caching mechanism. (defthm forcing-mapp-of-clean-update (implies (force (mapp map)) (equal (mapp (clean-update key val map)) t)) :hints(("Goal" :in-theory (e/d (clean-update) (rw.theory-mapp-of-clean-update))))) (defund rw.flag-count-variables (flag x acc) ;; Create a map from variable names to their number of occurrences in a term, ;; x. (declare (xargs :guard (and (if (equal flag 'term) (logic.termp x) (logic.term-listp x)) (mapp acc)) :verify-guards nil)) (if (equal flag 'term) (cond ((logic.constantp x) acc) ((logic.variablep x) (clean-update x (+ 1 (cdr (lookup x acc))) acc)) ((logic.functionp x) (rw.flag-count-variables 'list (logic.function-args x) acc)) ((logic.lambdap x) (rw.flag-count-variables 'list (logic.lambda-actuals x) acc)) (t acc)) (if (consp x) (rw.flag-count-variables 'list (cdr x) (rw.flag-count-variables 'term (car x) acc)) acc))) (defthm forcing-mapp-of-rw.flag-count-variables (implies (force (mapp acc)) (equal (mapp (rw.flag-count-variables flag x acc)) t)) :hints(("Goal" :in-theory (enable rw.flag-count-variables)))) (verify-guards rw.flag-count-variables) (definlined rw.count-variables (x) (declare (xargs :guard (logic.termp x))) (rw.flag-count-variables 'term x nil)) (definlined rw.count-variables-list (x) (declare (xargs :guard (logic.term-listp x))) (rw.flag-count-variables 'list x nil)) (defthm mapp-of-rw.count-variables (equal (mapp (rw.count-variables x)) t) :hints(("Goal" :in-theory (enable rw.count-variables)))) (defund rw.no-count-increases-aux (dom x y) ;; For all the keys listed in domain, is the corresponding value in y never ;; greater than the corresponding value in x? I.e., "did no variables increase?" (declare (xargs :guard (and (mapp x) (mapp y)))) (if (consp dom) (and (<= (cdr (lookup (car dom) y)) (cdr (lookup (car dom) x))) (rw.no-count-increases-aux (cdr dom) x y)) t)) (definlined rw.no-count-increases (x y) ;; For all keys in x, is the corresponding value in y never greater than the ;; corresponding value in x? (declare (xargs :guard (and (mapp x) (mapp y)))) (rw.no-count-increases-aux (fast-domain$ x nil) x y)) (defund rw.some-count-decreases-aux (dom x y) ;; For some key listed in domain, is the corresponding value in y smaller ;; than the corresponding value in x? I.e., "did some variable decrease?" (declare (xargs :guard (and (mapp x) (mapp y)))) (if (consp dom) (or (< (cdr (lookup (car dom) y)) (cdr (lookup (car dom) x))) (rw.some-count-decreases-aux (cdr dom) x y)) nil)) (definlined rw.some-count-decreases (x y) (declare (xargs :guard (and (mapp x) (mapp y)))) (rw.some-count-decreases-aux (fast-domain$ x nil) x y)) (defund rw.looks-good-for-outside-inp (rule) ;; Would we like rule to be an outside-in rule as well? (declare (xargs :guard (rw.rulep rule))) (and (equal (rw.rule->type rule) 'inside) (not (rw.rule->syntax rule)) (not (rw.rule->hyps rule)) (let ((lhsmap (rw.count-variables (rw.rule->lhs rule))) (rhsmap (rw.count-variables (rw.rule->rhs rule)))) (and (subsetp (domain rhsmap) (domain lhsmap)) ;; no new vars please ;; we don't require this anymore. ;; (rw.some-count-decreases lhsmap rhsmap) not any more. (rw.no-count-increases lhsmap rhsmap))))) ;; Translating Rewrite Rules ;; ;; Our first step is to convert the rule's hypotheses into hypp's for Milawa. ;; This is somewhat involved: ;; ;; (1) ACL2 embeds "force" inside the term; we have a separate field in the ;; hypp structure for this. ;; (2) Some ACL2 hyps are syntaxp hyps; we do not consider these to be hyps ;; and store them in a separate part of the rule. ;; (3) ACL2 embeds the backchain limits for the hyps in a separate list, ;; while we store them inside each hyp. ;; ;; We may also need to create additional syntaxp hyps from the loop-stoppers ;; of a rule. (defun make-force-list (x) (declare (xargs :mode :program)) ;; We are given a list of acl2-hyps as terms. We create tuples of the form ;; (forcep term) as follows: ;; (force a) --> (t a) ;; a --> (nil a) (if (consp x) (let ((term (car x))) (if (and (consp term) (equal (car term) 'ACL2::force)) (cons (list t (second term)) (make-force-list (cdr x))) (cons (list nil term) (make-force-list (cdr x))))) nil)) (defun make-syntax-list (x) (declare (xargs :mode :program)) ;; X is a list of (forcep term) tuples. We create tuples of the form ;; (syntaxp forcep term) as follows: ;; (forcep (syntaxp a)) => (t forcep a*) ;; (forcep a) => (nil forcep a) ;; Where a* is the "corrected" version of a. That is, a might include ;; calls of ACL2::quotep, which does not exist in Milawa and must be ;; replaced with MILAWA::logic.constantp. (if (consp x) (let* ((entry (car x)) (forcep (first entry)) (term (second entry))) (if (and (consp term) (equal (car term) 'ACL2::synp)) ;; The hyp is (synp vars form (quote term)) (let* ((syn-term (second (fourth term))) (fix-quotep (ACL2::subst 'logic.constantp 'ACL2::quotep syn-term))) (cons (list t forcep fix-quotep) (make-syntax-list (cdr x)))) ;; This isn't a syntax hyp. (cons (list nil forcep term) (make-syntax-list (cdr x))))) nil)) (defun insert-backchain-limits (x blimits) (declare (xargs :mode :program)) ;; X is a list of (syntaxp forcep term) tuples ;; Blimits is the :backchain-limit-lst from the ACL2 rule ;; We add the blimit to each hyp, creating tuples of the form (blimit syntaxp forcep term) ;; Each blimit is either nil (for no limit) or a number. (if (consp x) (cons (cons (car blimits) (car x)) (insert-backchain-limits (cdr x) (cdr blimits))) nil)) (defun collect-semantic-hyps (x) (declare (xargs :mode :program)) ;; X is a list of (limit syntaxp forcep term) tuples. We build the hypp structures for all ;; of the non-syntaxp hyps. (if (consp x) (let ((limit (first (car x))) (syntaxp (second (car x))) (forcep (third (car x))) (term (fourth (car x)))) (if syntaxp (collect-semantic-hyps (cdr x)) (cons (%hyp-fn term (if forcep 'weak nil) limit) (collect-semantic-hyps (cdr x))))) nil)) (defun collect-syntax-hyps (x) (declare (xargs :mode :program)) ;; X is a list of (limit syntaxp forcep term) tuples. We collect only the ;; terms from all the entries with valid syntaxp pairs. (if (consp x) (let ((syntaxp (second (car x))) (term (fourth (car x)))) (if syntaxp (cons term (collect-syntax-hyps (cdr x))) (collect-syntax-hyps (cdr x)))) nil)) (defun create-loop-stoppers (stoppers) (declare (xargs :mode :program)) ;; Stoppers are a list of (x y . fns) objects. We create a list of ;; (logic.term-< y x) entries. (if (consp stoppers) (let ((x (first (car stoppers))) (y (second (car stoppers)))) (cons (logic.function 'logic.term-< (list y x)) (create-loop-stoppers (cdr stoppers)))) nil)) (defun create-rule-from-rewrite-entry (name entry) (declare (xargs :mode :program)) ;; We return (enabledp . milawa-rule) for an ACL2 rewrite rule entry. (let* ((hyps (third (lookup :hyps entry))) (lhs (third (lookup :lhs entry))) (rhs (third (lookup :rhs entry))) (equiv (second (lookup :equiv entry))) (backchain-limit-lst (second (lookup :backchain-limit-lst entry))) (loop-stopper (second (lookup :loop-stopper entry))) (enabledp (second (lookup :enabledp entry))) (hypmap (insert-backchain-limits (make-syntax-list (make-force-list hyps)) backchain-limit-lst)) (milawa-hyps (collect-semantic-hyps hypmap)) (syntax (revappend (create-loop-stoppers loop-stopper) (collect-syntax-hyps hypmap)))) (cons enabledp (%rule-fn name 'inside milawa-hyps lhs rhs equiv syntax)))) ;; Translating Rule-Classes Nil Rules ;; (defun annhialate-forces (x) (declare (xargs :mode :program)) (if (consp x) (if (and (equal (first x) 'ACL2::force) (tuplep 2 x)) (annhialate-forces (second x)) (cons (annhialate-forces (car x)) (annhialate-forces (cdr x)))) x)) (defun create-rule-from-rule-classes-nil (name entry) (declare (xargs :mode :program)) ;; We return (enabledp . milawa-rule) for an ACL2 :rule-classes nil entry. (let* ((thm (annhialate-forces (third (lookup :theorem entry))))) (cond ((equal (car thm) 'implies) ;; We know implies is boolean, so we can cheat and use equal as the ;; equivalence relation. This turned out to be better than parsing ;; out the hyps separately. (cons nil (%rule-fn name 'manual ; "manual" rules are our equivalent of ACL2's rule-classes nil nil ; hyps thm ; lhs is the whole theorem ''t ; rhs is t 'equal ; equiv is equal nil))) ((memberp (car thm) '(equal iff)) (cons nil (%rule-fn name 'manual nil ; hyps (second thm) ; lhs (third thm) ; rhs (first thm) ; equiv nil))) ; syntax (t (cons nil (%rule-fn name 'manual nil thm ''t 'iff nil)))))) (defun create-rule-from-acl2 (name ACL2::state) ;; Returns (enabledp . milawa-rule) or throws an error. (declare (xargs :mode :program :stobjs ACL2::state)) (let ((info-entries (ACL2::info-fn name ACL2::state))) (if (not (and (tuplep 1 info-entries) (car info-entries))) (ACL2::er hard 'create-rule-from-acl2 "Something seems to be wrong with ~x0.~%~ Its info-entry is: ~x1.~%" name info-entries) (let* ((entry (car info-entries)) (class (first (cdr (lookup :class entry))))) (cond ((equal class :rewrite) (create-rule-from-rewrite-entry name entry)) ((equal class nil) (create-rule-from-rule-classes-nil name entry)) (t (ACL2::er hard 'create-rule-from-acl2 "Don't know how to handle rule-classes ~x0.~%" class))))))) (defmacro %autorule (name) `(ACL2::make-event `(%prove ',(cdr (create-rule-from-acl2 ',name ACL2::state))))) (defun autoprove-fn (name hints ACL2::state) (declare (xargs :mode :program :stobjs ACL2::state)) (let* ((rule+ (create-rule-from-acl2 name ACL2::state)) (enabledp (car rule+)) (rule (cdr rule+))) `(defsection ,name (%prove ',rule) (local (ACL2::progn ,@hints)) (local (%auto)) (%qed) ,@(if enabledp `((%enable default ,name)) nil) ,@(if (rw.looks-good-for-outside-inp rule) (let ((new-name (ACL2::mksym '[OUTSIDE] (rw.rule->name rule)))) `((%raw-add-rule (%rule ,new-name :type outside :hyps ,(rw.rule->hyps rule) :lhs ,(rw.rule->lhs rule) :rhs ,(rw.rule->rhs rule) :equiv ,(rw.rule->equiv rule) :syntax ,(rw.rule->syntax rule))) ,@(if enabledp `((%enable default ,new-name)) nil))) nil)))) (defmacro %autoprove (name &rest hints) `(ACL2::make-event (autoprove-fn ',name ',hints ACL2::state))) (defmacro %autoinduct (name &rest args) ;; Try inducting as suggested by the definition of the function <name>. ;; You can also rename the arguments, e.g., ;; (%autoinduct cdr-induction y) ;; Will try "cdr-induction on y" instead of "cdr-induction on x", which is the ;; default since the argument to cdr-induction is x. `(local (ACL2::make-event (%autoinduct-fn ',name ',args (ACL2::w ACL2::state))))) (defun pair-formals-with-calls (formals calls) ;; Calls are a list of function calls, e.g., ((foo a b) (foo c d) (foo e f)), and formals ;; are the names of the formals, e.g., (x y). We're going to turn these into substitution ;; lists, e.g., ((x . a) (y . b)), ((x . c) (y . d)), etc. (declare (xargs :mode :program)) (if (consp calls) (cons (list2-list formals (logic.function-args (car calls))) (pair-formals-with-calls formals (cdr calls))) nil)) (defun acl2-tests-and-calls-to-induct-pairs (formals x) ;; X is a list of tests-and-calls produced by acl2's induction-machine-for-fn function. We ;; need to walk through it and turn it into a list of conditions and substitutions. (declare (xargs :mode :program)) (if (consp x) (let ((tests (ACL2::access ACL2::tests-and-calls (car x) :tests)) (calls (ACL2::access ACL2::tests-and-calls (car x) :calls))) (cons (list (cond ((and (consp tests) (consp (cdr tests))) (cons 'and tests)) ((consp tests) (car tests)) (t (ACL2::er hard 'acl2-tests-and-calls-to-induct-pairs "A tests-and-calls entry had no tests!~%"))) (pair-formals-with-calls formals calls)) (acl2-tests-and-calls-to-induct-pairs formals (cdr x)))) nil)) (defun %autoinduct-fn (name args world) (declare (xargs :mode :program)) (let* ((syntax-defuns (ACL2::get-syntax-defun-entries world)) (this-defun (find-syntax-defun name syntax-defuns)) (measure (ACL2::get-measure name world)) (formals (third this-defun)) (body (logic.translate (fourth this-defun))) (args* (or args formals))) (cond ((not measure) (ACL2::er hard '%autoinduct-fn "The function ~x0 doesn't seem to have a measure.~%" name)) ((not (same-lengthp args* formals)) (ACL2::er hard '%autoinduct-fn "Wrong number of arguments provided. ~x0 takes ~x1 arguments.~%" name (len formals))) (t (let* ((args-sigma (fast-pair-lists$ formals args* nil)) (body/sigma (logic.substitute body args-sigma)) (measure/sigma (logic.substitute measure args-sigma)) (tests-and-calls (ACL2::induction-machine-for-fn (list name) body/sigma ;; In 3.5, ruler-extenders were added. For ;; 3.4 compatibility we only sometimes add them. #-v3-4 nil))) `(%induct ,measure/sigma ,@(acl2-tests-and-calls-to-induct-pairs args* tests-and-calls)))))))
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 "core") (set-verify-guards-eagerness 2) (set-case-split-limitations nil) (set-well-founded-relation ord<) (set-measure-function rank) ;; Goal checking ;; ;; Since our tactic harness is inside ACL2, we can ask ACL2 if it believes the ;; goals are true using (%check). Of course, this will only work if all the ;; functions involved are already defined inside of ACL2. (defun %check-goal (goal) (declare (xargs :mode :program)) `(ACL2::make-event (ACL2::mv-let (erp val ACL2::state) (ACL2::thm (or ,@goal)) (declare (ignore erp val)) (ACL2::value '(ACL2::value-triple :invisible))))) (defun %aux-check-goals (goals n) (declare (xargs :mode :program)) (if (consp goals) (list* `(ACL2::value-triple (ACL2::cw "Checking goal ~x0~%" ',n)) (%check-goal (car goals)) (%aux-check-goals (cdr goals) (+ 1 n))) nil)) (defun %check-goals (goals) (declare (xargs :mode :program)) `(ACL2::encapsulate () ,@(%aux-check-goals goals 1))) (defmacro %check () ;; Check if ACL2 believes the goals are theorems. `(ACL2::make-event (%check-goals (tactic.harness->goals (ACL2::w ACL2::state))))) ;; Autoadmitting Functions ;; ;; We can look up a function's definition in the ACL2 world, convert it into a ;; Milawa-usable form, and submit it as a Milawa definition. This won't work ;; unless all the functions it calls are already in Milawa, etc., but it's ;; awfully handy. (defun ACL2::get-untranslated-defun (name world) (declare (xargs :mode :program)) (let* ((ev-world (ACL2::decode-logical-name name world))) (ACL2::access-event-tuple-form (ACL2::cddar ev-world)))) (defun ACL2::get-measure (name world) (declare (xargs :mode :program)) (let* ((justification (acl2::fgetprop name 'acl2::justification nil world))) (and justification (ACL2::access ACL2::justification justification :measure)))) (defun find-syntax-defun (name syntax-defuns) (declare (xargs :mode :program)) (if (consp syntax-defuns) (if (equal name (second (car syntax-defuns))) (car syntax-defuns) (find-syntax-defun name (cdr syntax-defuns))) nil)) (defun %autoadmit-fn (name world) (declare (xargs :mode :program)) ;; What about :export support? We should be looking for that instead. (let* ((syntax-defuns (ACL2::get-syntax-defun-entries world)) (this-defun (find-syntax-defun name syntax-defuns)) ;; (untranslated-defun (ACL2::get-untranslated-defun name world)) ;; (real-name (ACL2::deref-macro-name name world)) (measure (ACL2::get-measure name world)) ;; (formals (third untranslated-defun)) (formals (third this-defun)) ;; (body (car (ACL2::last untranslated-defun)))) (body (fourth this-defun))) (if measure `(defsection ,name (%defun ,name ,formals ;; ,(ACL2::clean-up-body (annhialate-declarations body)) ,body :measure ,measure) (local (%auto)) (%admit)) `(defsection ,name (%defun ,name ,formals ;; ,(ACL2::clean-up-body (annhialate-declarations body))) ,body) (%admit))))) (defmacro %autoadmit (name) `(ACL2::make-event (%autoadmit-fn ',name (ACL2::w ACL2::state)))) ;; Automatic "outside-in" rule creation ;; ;; The rule (car (cons x y)) = x is a perfect example of a good outside-in ;; rule because it lets us throw away "y" before we even look at it. I go ;; ahead and generate an outside-in rule from ACL2 rules when: ;; ;; 1. The right-hand side "never increases a variable" ;; 2. There are no syntaxp restrictions, and ;; 3. There are no hypotheses. ;; ;; At one time I also prohibited rules that repeated a variable in their lhs, ;; such as (subsetp x x) = t, under the theory that we would want to give both ;; sides a chance to canonicalize first. But since we're keeping the ;; inside-out version too, I think this is not really much of a problem. ;; ;; Criteria #1 is the main issue. The whole point of outside-in rules is that ;; they'll allow us to avoid rewriting parts of terms by throwing away some ;; variable that they matched. And we don't want to introduce duplicates, ;; e.g., (foo x y (bar x z)) = (baz z z) is probably a bad outside-in rule ;; since if "z" is large then we might have blown up the term considerably. ;; Maybe it makes sense to break this rule when we "know" that z is usually ;; small, but for automatic outside-in rule introduction, I'm not bothering ;; with that. ;; ;; At one time, I also require that at least one variable was decreased. But ;; now I don't require this, since it allows rules like (iff x nil) = (not x) ;; to be made outside-rules, which I think probably helps canonicalize things. ;; ;; Criteria #2 is in place because often syntaxp rules are used to break ;; canonical forms, e.g., to left-associate (+ a (+ b c)) when a,b are ;; constants. We think it's unlikely that they'll be constants before we ;; rewrite them. Moreover, it seems like a reasonable expectation on the ;; part of the syntaxp writer is that their matches are already in ;; canonical form. ;; ;; Criteria #3 is probably overly restrictive. Basically we don't want to ;; introduce huge complicated hyps by instantiating their variables with big ;; expressions. It might pay off to investigate relaxing this somewhat, ;; especially given our caching mechanism. (defthm forcing-mapp-of-clean-update (implies (force (mapp map)) (equal (mapp (clean-update key val map)) t)) :hints(("Goal" :in-theory (e/d (clean-update) (rw.theory-mapp-of-clean-update))))) (defund rw.flag-count-variables (flag x acc) ;; Create a map from variable names to their number of occurrences in a term, ;; x. (declare (xargs :guard (and (if (equal flag 'term) (logic.termp x) (logic.term-listp x)) (mapp acc)) :verify-guards nil)) (if (equal flag 'term) (cond ((logic.constantp x) acc) ((logic.variablep x) (clean-update x (+ 1 (cdr (lookup x acc))) acc)) ((logic.functionp x) (rw.flag-count-variables 'list (logic.function-args x) acc)) ((logic.lambdap x) (rw.flag-count-variables 'list (logic.lambda-actuals x) acc)) (t acc)) (if (consp x) (rw.flag-count-variables 'list (cdr x) (rw.flag-count-variables 'term (car x) acc)) acc))) (defthm forcing-mapp-of-rw.flag-count-variables (implies (force (mapp acc)) (equal (mapp (rw.flag-count-variables flag x acc)) t)) :hints(("Goal" :in-theory (enable rw.flag-count-variables)))) (verify-guards rw.flag-count-variables) (definlined rw.count-variables (x) (declare (xargs :guard (logic.termp x))) (rw.flag-count-variables 'term x nil)) (definlined rw.count-variables-list (x) (declare (xargs :guard (logic.term-listp x))) (rw.flag-count-variables 'list x nil)) (defthm mapp-of-rw.count-variables (equal (mapp (rw.count-variables x)) t) :hints(("Goal" :in-theory (enable rw.count-variables)))) (defund rw.no-count-increases-aux (dom x y) ;; For all the keys listed in domain, is the corresponding value in y never ;; greater than the corresponding value in x? I.e., "did no variables increase?" (declare (xargs :guard (and (mapp x) (mapp y)))) (if (consp dom) (and (<= (cdr (lookup (car dom) y)) (cdr (lookup (car dom) x))) (rw.no-count-increases-aux (cdr dom) x y)) t)) (definlined rw.no-count-increases (x y) ;; For all keys in x, is the corresponding value in y never greater than the ;; corresponding value in x? (declare (xargs :guard (and (mapp x) (mapp y)))) (rw.no-count-increases-aux (fast-domain$ x nil) x y)) (defund rw.some-count-decreases-aux (dom x y) ;; For some key listed in domain, is the corresponding value in y smaller ;; than the corresponding value in x? I.e., "did some variable decrease?" (declare (xargs :guard (and (mapp x) (mapp y)))) (if (consp dom) (or (< (cdr (lookup (car dom) y)) (cdr (lookup (car dom) x))) (rw.some-count-decreases-aux (cdr dom) x y)) nil)) (definlined rw.some-count-decreases (x y) (declare (xargs :guard (and (mapp x) (mapp y)))) (rw.some-count-decreases-aux (fast-domain$ x nil) x y)) (defund rw.looks-good-for-outside-inp (rule) ;; Would we like rule to be an outside-in rule as well? (declare (xargs :guard (rw.rulep rule))) (and (equal (rw.rule->type rule) 'inside) (not (rw.rule->syntax rule)) (not (rw.rule->hyps rule)) (let ((lhsmap (rw.count-variables (rw.rule->lhs rule))) (rhsmap (rw.count-variables (rw.rule->rhs rule)))) (and (subsetp (domain rhsmap) (domain lhsmap)) ;; no new vars please ;; we don't require this anymore. ;; (rw.some-count-decreases lhsmap rhsmap) not any more. (rw.no-count-increases lhsmap rhsmap))))) ;; Translating Rewrite Rules ;; ;; Our first step is to convert the rule's hypotheses into hypp's for Milawa. ;; This is somewhat involved: ;; ;; (1) ACL2 embeds "force" inside the term; we have a separate field in the ;; hypp structure for this. ;; (2) Some ACL2 hyps are syntaxp hyps; we do not consider these to be hyps ;; and store them in a separate part of the rule. ;; (3) ACL2 embeds the backchain limits for the hyps in a separate list, ;; while we store them inside each hyp. ;; ;; We may also need to create additional syntaxp hyps from the loop-stoppers ;; of a rule. (defun make-force-list (x) (declare (xargs :mode :program)) ;; We are given a list of acl2-hyps as terms. We create tuples of the form ;; (forcep term) as follows: ;; (force a) --> (t a) ;; a --> (nil a) (if (consp x) (let ((term (car x))) (if (and (consp term) (equal (car term) 'ACL2::force)) (cons (list t (second term)) (make-force-list (cdr x))) (cons (list nil term) (make-force-list (cdr x))))) nil)) (defun make-syntax-list (x) (declare (xargs :mode :program)) ;; X is a list of (forcep term) tuples. We create tuples of the form ;; (syntaxp forcep term) as follows: ;; (forcep (syntaxp a)) => (t forcep a*) ;; (forcep a) => (nil forcep a) ;; Where a* is the "corrected" version of a. That is, a might include ;; calls of ACL2::quotep, which does not exist in Milawa and must be ;; replaced with MILAWA::logic.constantp. (if (consp x) (let* ((entry (car x)) (forcep (first entry)) (term (second entry))) (if (and (consp term) (equal (car term) 'ACL2::synp)) ;; The hyp is (synp vars form (quote term)) (let* ((syn-term (second (fourth term))) (fix-quotep (ACL2::subst 'logic.constantp 'ACL2::quotep syn-term))) (cons (list t forcep fix-quotep) (make-syntax-list (cdr x)))) ;; This isn't a syntax hyp. (cons (list nil forcep term) (make-syntax-list (cdr x))))) nil)) (defun insert-backchain-limits (x blimits) (declare (xargs :mode :program)) ;; X is a list of (syntaxp forcep term) tuples ;; Blimits is the :backchain-limit-lst from the ACL2 rule ;; We add the blimit to each hyp, creating tuples of the form (blimit syntaxp forcep term) ;; Each blimit is either nil (for no limit) or a number. (if (consp x) (cons (cons (car blimits) (car x)) (insert-backchain-limits (cdr x) (cdr blimits))) nil)) (defun collect-semantic-hyps (x) (declare (xargs :mode :program)) ;; X is a list of (limit syntaxp forcep term) tuples. We build the hypp structures for all ;; of the non-syntaxp hyps. (if (consp x) (let ((limit (first (car x))) (syntaxp (second (car x))) (forcep (third (car x))) (term (fourth (car x)))) (if syntaxp (collect-semantic-hyps (cdr x)) (cons (%hyp-fn term (if forcep 'weak nil) limit) (collect-semantic-hyps (cdr x))))) nil)) (defun collect-syntax-hyps (x) (declare (xargs :mode :program)) ;; X is a list of (limit syntaxp forcep term) tuples. We collect only the ;; terms from all the entries with valid syntaxp pairs. (if (consp x) (let ((syntaxp (second (car x))) (term (fourth (car x)))) (if syntaxp (cons term (collect-syntax-hyps (cdr x))) (collect-syntax-hyps (cdr x)))) nil)) (defun create-loop-stoppers (stoppers) (declare (xargs :mode :program)) ;; Stoppers are a list of (x y . fns) objects. We create a list of ;; (logic.term-< y x) entries. (if (consp stoppers) (let ((x (first (car stoppers))) (y (second (car stoppers)))) (cons (logic.function 'logic.term-< (list y x)) (create-loop-stoppers (cdr stoppers)))) nil)) (defun create-rule-from-rewrite-entry (name entry) (declare (xargs :mode :program)) ;; We return (enabledp . milawa-rule) for an ACL2 rewrite rule entry. (let* ((hyps (third (lookup :hyps entry))) (lhs (third (lookup :lhs entry))) (rhs (third (lookup :rhs entry))) (equiv (second (lookup :equiv entry))) (backchain-limit-lst (second (lookup :backchain-limit-lst entry))) (loop-stopper (second (lookup :loop-stopper entry))) (enabledp (second (lookup :enabledp entry))) (hypmap (insert-backchain-limits (make-syntax-list (make-force-list hyps)) backchain-limit-lst)) (milawa-hyps (collect-semantic-hyps hypmap)) (syntax (revappend (create-loop-stoppers loop-stopper) (collect-syntax-hyps hypmap)))) (cons enabledp (%rule-fn name 'inside milawa-hyps lhs rhs equiv syntax)))) ;; Translating Rule-Classes Nil Rules ;; (defun annhialate-forces (x) (declare (xargs :mode :program)) (if (consp x) (if (and (equal (first x) 'ACL2::force) (tuplep 2 x)) (annhialate-forces (second x)) (cons (annhialate-forces (car x)) (annhialate-forces (cdr x)))) x)) (defun create-rule-from-rule-classes-nil (name entry) (declare (xargs :mode :program)) ;; We return (enabledp . milawa-rule) for an ACL2 :rule-classes nil entry. (let* ((thm (annhialate-forces (third (lookup :theorem entry))))) (cond ((equal (car thm) 'implies) ;; We know implies is boolean, so we can cheat and use equal as the ;; equivalence relation. This turned out to be better than parsing ;; out the hyps separately. (cons nil (%rule-fn name 'manual ; "manual" rules are our equivalent of ACL2's rule-classes nil nil ; hyps thm ; lhs is the whole theorem ''t ; rhs is t 'equal ; equiv is equal nil))) ((memberp (car thm) '(equal iff)) (cons nil (%rule-fn name 'manual nil ; hyps (second thm) ; lhs (third thm) ; rhs (first thm) ; equiv nil))) ; syntax (t (cons nil (%rule-fn name 'manual nil thm ''t 'iff nil)))))) (defun create-rule-from-acl2 (name ACL2::state) ;; Returns (enabledp . milawa-rule) or throws an error. (declare (xargs :mode :program :stobjs ACL2::state)) (let ((info-entries (ACL2::info-fn name ACL2::state))) (if (not (and (tuplep 1 info-entries) (car info-entries))) (ACL2::er hard 'create-rule-from-acl2 "Something seems to be wrong with ~x0.~%~ Its info-entry is: ~x1.~%" name info-entries) (let* ((entry (car info-entries)) (class (first (cdr (lookup :class entry))))) (cond ((equal class :rewrite) (create-rule-from-rewrite-entry name entry)) ((equal class nil) (create-rule-from-rule-classes-nil name entry)) (t (ACL2::er hard 'create-rule-from-acl2 "Don't know how to handle rule-classes ~x0.~%" class))))))) (defmacro %autorule (name) `(ACL2::make-event `(%prove ',(cdr (create-rule-from-acl2 ',name ACL2::state))))) (defun autoprove-fn (name hints ACL2::state) (declare (xargs :mode :program :stobjs ACL2::state)) (let* ((rule+ (create-rule-from-acl2 name ACL2::state)) (enabledp (car rule+)) (rule (cdr rule+))) `(defsection ,name (%prove ',rule) (local (ACL2::progn ,@hints)) (local (%auto)) (%qed) ,@(if enabledp `((%enable default ,name)) nil) ,@(if (rw.looks-good-for-outside-inp rule) (let ((new-name (ACL2::mksym '[OUTSIDE] (rw.rule->name rule)))) `((%raw-add-rule (%rule ,new-name :type outside :hyps ,(rw.rule->hyps rule) :lhs ,(rw.rule->lhs rule) :rhs ,(rw.rule->rhs rule) :equiv ,(rw.rule->equiv rule) :syntax ,(rw.rule->syntax rule))) ,@(if enabledp `((%enable default ,new-name)) nil))) nil)))) (defmacro %autoprove (name &rest hints) `(ACL2::make-event (autoprove-fn ',name ',hints ACL2::state))) (defmacro %autoinduct (name &rest args) ;; Try inducting as suggested by the definition of the function <name>. ;; You can also rename the arguments, e.g., ;; (%autoinduct cdr-induction y) ;; Will try "cdr-induction on y" instead of "cdr-induction on x", which is the ;; default since the argument to cdr-induction is x. `(local (ACL2::make-event (%autoinduct-fn ',name ',args (ACL2::w ACL2::state))))) (defun pair-formals-with-calls (formals calls) ;; Calls are a list of function calls, e.g., ((foo a b) (foo c d) (foo e f)), and formals ;; are the names of the formals, e.g., (x y). We're going to turn these into substitution ;; lists, e.g., ((x . a) (y . b)), ((x . c) (y . d)), etc. (declare (xargs :mode :program)) (if (consp calls) (cons (list2-list formals (logic.function-args (car calls))) (pair-formals-with-calls formals (cdr calls))) nil)) (defun acl2-tests-and-calls-to-induct-pairs (formals x) ;; X is a list of tests-and-calls produced by acl2's induction-machine-for-fn function. We ;; need to walk through it and turn it into a list of conditions and substitutions. (declare (xargs :mode :program)) (if (consp x) (let ((tests (ACL2::access ACL2::tests-and-calls (car x) :tests)) (calls (ACL2::access ACL2::tests-and-calls (car x) :calls))) (cons (list (cond ((and (consp tests) (consp (cdr tests))) (cons 'and tests)) ((consp tests) (car tests)) (t (ACL2::er hard 'acl2-tests-and-calls-to-induct-pairs "A tests-and-calls entry had no tests!~%"))) (pair-formals-with-calls formals calls)) (acl2-tests-and-calls-to-induct-pairs formals (cdr x)))) nil)) (defun %autoinduct-fn (name args world) (declare (xargs :mode :program)) (let* ((syntax-defuns (ACL2::get-syntax-defun-entries world)) (this-defun (find-syntax-defun name syntax-defuns)) (measure (ACL2::get-measure name world)) (formals (third this-defun)) (body (logic.translate (fourth this-defun))) (args* (or args formals))) (cond ((not measure) (ACL2::er hard '%autoinduct-fn "The function ~x0 doesn't seem to have a measure.~%" name)) ((not (same-lengthp args* formals)) (ACL2::er hard '%autoinduct-fn "Wrong number of arguments provided. ~x0 takes ~x1 arguments.~%" name (len formals))) (t (let* ((args-sigma (fast-pair-lists$ formals args* nil)) (body/sigma (logic.substitute body args-sigma)) (measure/sigma (logic.substitute measure args-sigma)) (tests-and-calls (ACL2::induction-machine-for-fn (list name) body/sigma ;; In 3.5, ruler-extenders were added. For ;; 3.4 compatibility we only sometimes add them. #-v3-4 nil))) `(%induct ,measure/sigma ,@(acl2-tests-and-calls-to-induct-pairs args* tests-and-calls)))))))
[ { "context": "; Copyright (C) 2000 Panagiotis Manolios\n \n; This program is free software; you can redis", "end": 41, "score": 0.9998782873153687, "start": 22, "tag": "NAME", "value": "Panagiotis Manolios" }, { "context": "ass Ave, Cambridge, MA 02139, USA.\n \n; Written by Panagiotis Manolios who can be reached as follows.\n \n; Email: pete@c", "end": 774, "score": 0.9998797178268433, "start": 755, "tag": "NAME", "value": "Panagiotis Manolios" }, { "context": "anolios who can be reached as follows.\n \n; Email: [email protected]\n \n; Postal Mail:\n; Department of Computer Scien", "end": 836, "score": 0.9999295473098755, "start": 818, "tag": "EMAIL", "value": "[email protected]" } ]
books/workshops/2000/manolios/pipeline/pipeline/deterministic-systems/128/netlist/ma128net.lisp
ragerdl/acl2-defthm-rc2
1
; Copyright (C) 2000 Panagiotis Manolios ; 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., 675 Mass Ave, Cambridge, MA 02139, USA. ; Written by Panagiotis Manolios who can be reached as follows. ; Email: [email protected] ; Postal Mail: ; Department of Computer Science ; The University of Texas at Austin ; Austin, TX 78701 USA (in-package "ACL2") (include-book "netlist") (include-book "../serial/ma128serial") (defun MAnet-state (pc regs mem latch1 latch2 exc-on) (list 'MAnet pc regs mem latch1 latch2 exc-on)) (defun MAnet-p (MA) (equal (car MA) 'Manet)) (defun MAnet-step-regs (MA) (let ((latch2 (nth (MA-latch2) MA))) (if (and (nth (latch2-validp) latch2) (bor (equal (nth (latch2-op) latch2) 0) (equal (nth (latch2-op) latch2) 1))) (update-valuation (nth (latch2-rc) latch2) (net-ALU (nth (latch2-op) latch2) (nth (latch2-ra-val) latch2) (nth (latch2-rb-val) latch2)) (nth (MA-regs) MA)) (nth (MA-regs) MA)))) ; I may want to write this in terms of committed-MA (defun committed-MAnet (MA) (let ((pc (nth (MA-pc) MA)) (regs (nth (MA-regs) MA)) (mem (nth (MA-mem) MA)) (latch1 (nth (MA-latch1) MA)) (latch2 (nth (MA-latch2) MA)) (exc-on (nth (MA-exc-on) MA))) (MAnet-state (- pc (shift-pc latch1 latch2)) regs mem (update-nth (latch1-validp) nil latch1) (update-nth (latch2-validp) nil latch2) exc-on))) (defun MAnet-step (MA) (let* ((cMA (committed-MAnet MA)) (cpc (nth (MA-pc) cMA)) (regs (convert-regs (nth (MA-regs) MA))) (mem (nth (MA-mem) MA)) (latch2 (nth (MA-latch2) MA)) (exc-on (nth (MA-exc-on) MA)) (op (nth (latch2-op) latch2)) (ra-val (nth (latch2-ra-val) latch2)) (rb-val (nth (latch2-rb-val) latch2))) (if (and exc-on (nth (latch2-validp) latch2) (net-excp op ra-val rb-val) (bor (equal op 0) (equal op 1))) (MAnet-state (exc-step-pc cpc regs mem) (exc-step-regs cpc regs mem) (exc-step-mem cpc regs mem) (exc-step-latch1 cpc regs mem) (exc-step-latch2 cpc regs mem) (exc-step-exc-on cpc regs mem)) (MAnet-state (MA-step-pc MA) (MAnet-step-regs MA) mem (step-latch1 MA) (serial-step-latch2 MA) exc-on)))) (defun good-MAnet (ma) (manet-p ma)) (defun MAnet-to-MAserial (MAnet) (MAserial-state (nth (MA-pc) MAnet) (nth (MA-regs) MAnet) (nth (MA-mem) MAnet) (nth (MA-latch1) MAnet) (nth (MA-latch2) MAnet) (nth (MA-exc-on) MAnet))) (defun MAnet-rank (MA) (declare (ignore MA)) 0)
12856
; Copyright (C) 2000 <NAME> ; 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., 675 Mass Ave, Cambridge, MA 02139, USA. ; Written by <NAME> who can be reached as follows. ; Email: <EMAIL> ; Postal Mail: ; Department of Computer Science ; The University of Texas at Austin ; Austin, TX 78701 USA (in-package "ACL2") (include-book "netlist") (include-book "../serial/ma128serial") (defun MAnet-state (pc regs mem latch1 latch2 exc-on) (list 'MAnet pc regs mem latch1 latch2 exc-on)) (defun MAnet-p (MA) (equal (car MA) 'Manet)) (defun MAnet-step-regs (MA) (let ((latch2 (nth (MA-latch2) MA))) (if (and (nth (latch2-validp) latch2) (bor (equal (nth (latch2-op) latch2) 0) (equal (nth (latch2-op) latch2) 1))) (update-valuation (nth (latch2-rc) latch2) (net-ALU (nth (latch2-op) latch2) (nth (latch2-ra-val) latch2) (nth (latch2-rb-val) latch2)) (nth (MA-regs) MA)) (nth (MA-regs) MA)))) ; I may want to write this in terms of committed-MA (defun committed-MAnet (MA) (let ((pc (nth (MA-pc) MA)) (regs (nth (MA-regs) MA)) (mem (nth (MA-mem) MA)) (latch1 (nth (MA-latch1) MA)) (latch2 (nth (MA-latch2) MA)) (exc-on (nth (MA-exc-on) MA))) (MAnet-state (- pc (shift-pc latch1 latch2)) regs mem (update-nth (latch1-validp) nil latch1) (update-nth (latch2-validp) nil latch2) exc-on))) (defun MAnet-step (MA) (let* ((cMA (committed-MAnet MA)) (cpc (nth (MA-pc) cMA)) (regs (convert-regs (nth (MA-regs) MA))) (mem (nth (MA-mem) MA)) (latch2 (nth (MA-latch2) MA)) (exc-on (nth (MA-exc-on) MA)) (op (nth (latch2-op) latch2)) (ra-val (nth (latch2-ra-val) latch2)) (rb-val (nth (latch2-rb-val) latch2))) (if (and exc-on (nth (latch2-validp) latch2) (net-excp op ra-val rb-val) (bor (equal op 0) (equal op 1))) (MAnet-state (exc-step-pc cpc regs mem) (exc-step-regs cpc regs mem) (exc-step-mem cpc regs mem) (exc-step-latch1 cpc regs mem) (exc-step-latch2 cpc regs mem) (exc-step-exc-on cpc regs mem)) (MAnet-state (MA-step-pc MA) (MAnet-step-regs MA) mem (step-latch1 MA) (serial-step-latch2 MA) exc-on)))) (defun good-MAnet (ma) (manet-p ma)) (defun MAnet-to-MAserial (MAnet) (MAserial-state (nth (MA-pc) MAnet) (nth (MA-regs) MAnet) (nth (MA-mem) MAnet) (nth (MA-latch1) MAnet) (nth (MA-latch2) MAnet) (nth (MA-exc-on) MAnet))) (defun MAnet-rank (MA) (declare (ignore MA)) 0)
true
; Copyright (C) 2000 PI:NAME:<NAME>END_PI ; 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., 675 Mass Ave, Cambridge, MA 02139, USA. ; Written by PI:NAME:<NAME>END_PI who can be reached as follows. ; Email: PI:EMAIL:<EMAIL>END_PI ; Postal Mail: ; Department of Computer Science ; The University of Texas at Austin ; Austin, TX 78701 USA (in-package "ACL2") (include-book "netlist") (include-book "../serial/ma128serial") (defun MAnet-state (pc regs mem latch1 latch2 exc-on) (list 'MAnet pc regs mem latch1 latch2 exc-on)) (defun MAnet-p (MA) (equal (car MA) 'Manet)) (defun MAnet-step-regs (MA) (let ((latch2 (nth (MA-latch2) MA))) (if (and (nth (latch2-validp) latch2) (bor (equal (nth (latch2-op) latch2) 0) (equal (nth (latch2-op) latch2) 1))) (update-valuation (nth (latch2-rc) latch2) (net-ALU (nth (latch2-op) latch2) (nth (latch2-ra-val) latch2) (nth (latch2-rb-val) latch2)) (nth (MA-regs) MA)) (nth (MA-regs) MA)))) ; I may want to write this in terms of committed-MA (defun committed-MAnet (MA) (let ((pc (nth (MA-pc) MA)) (regs (nth (MA-regs) MA)) (mem (nth (MA-mem) MA)) (latch1 (nth (MA-latch1) MA)) (latch2 (nth (MA-latch2) MA)) (exc-on (nth (MA-exc-on) MA))) (MAnet-state (- pc (shift-pc latch1 latch2)) regs mem (update-nth (latch1-validp) nil latch1) (update-nth (latch2-validp) nil latch2) exc-on))) (defun MAnet-step (MA) (let* ((cMA (committed-MAnet MA)) (cpc (nth (MA-pc) cMA)) (regs (convert-regs (nth (MA-regs) MA))) (mem (nth (MA-mem) MA)) (latch2 (nth (MA-latch2) MA)) (exc-on (nth (MA-exc-on) MA)) (op (nth (latch2-op) latch2)) (ra-val (nth (latch2-ra-val) latch2)) (rb-val (nth (latch2-rb-val) latch2))) (if (and exc-on (nth (latch2-validp) latch2) (net-excp op ra-val rb-val) (bor (equal op 0) (equal op 1))) (MAnet-state (exc-step-pc cpc regs mem) (exc-step-regs cpc regs mem) (exc-step-mem cpc regs mem) (exc-step-latch1 cpc regs mem) (exc-step-latch2 cpc regs mem) (exc-step-exc-on cpc regs mem)) (MAnet-state (MA-step-pc MA) (MAnet-step-regs MA) mem (step-latch1 MA) (serial-step-latch2 MA) exc-on)))) (defun good-MAnet (ma) (manet-p ma)) (defun MAnet-to-MAserial (MAnet) (MAserial-state (nth (MA-pc) MAnet) (nth (MA-regs) MAnet) (nth (MA-mem) MAnet) (nth (MA-latch1) MAnet) (nth (MA-latch2) MAnet) (nth (MA-exc-on) MAnet))) (defun MAnet-rank (MA) (declare (ignore MA)) 0)
[ { "context": "he LICENSE file distributed with ACL2.\n;\n; Author: Alessandro Coglio ([email protected])\n\n;;;;;;;;;;;;;;;;;;;;;;;;;;;", "end": 202, "score": 0.9998786449432373, "start": 185, "tag": "NAME", "value": "Alessandro Coglio" }, { "context": "ributed with ACL2.\n;\n; Author: Alessandro Coglio ([email protected])\n\n;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;", "end": 222, "score": 0.9999297857284546, "start": 204, "tag": "EMAIL", "value": "[email protected]" } ]
books/kestrel/std/system/flatten-ands-in-lit.lisp
mayankmanj/acl2
305
; Standard System Library ; ; Copyright (C) 2019 Kestrel Institute (http://www.kestrel.edu) ; ; License: A 3-clause BSD license. See the LICENSE file distributed with ACL2. ; ; Author: Alessandro Coglio ([email protected]) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (in-package "ACL2") (include-book "xdoc/constructors" :dir :system) (local (include-book "std/typed-lists/pseudo-term-listp" :dir :system)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defsection std/system/flatten-ands-in-lit :parents (std/system/term-transformations) :short (xdoc::topstring "Theorems about " (xdoc::seetopic "system-utilities" "@('flatten-ands-in-lit')") ".") (defthm pseudo-term-listp-of-flatten-ands-in-lit (implies (pseudo-termp term) (pseudo-term-listp (flatten-ands-in-lit term))))) (in-theory (disable flatten-ands-in-lit))
14530
; Standard System Library ; ; Copyright (C) 2019 Kestrel Institute (http://www.kestrel.edu) ; ; License: A 3-clause BSD license. See the LICENSE file distributed with ACL2. ; ; Author: <NAME> (<EMAIL>) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (in-package "ACL2") (include-book "xdoc/constructors" :dir :system) (local (include-book "std/typed-lists/pseudo-term-listp" :dir :system)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defsection std/system/flatten-ands-in-lit :parents (std/system/term-transformations) :short (xdoc::topstring "Theorems about " (xdoc::seetopic "system-utilities" "@('flatten-ands-in-lit')") ".") (defthm pseudo-term-listp-of-flatten-ands-in-lit (implies (pseudo-termp term) (pseudo-term-listp (flatten-ands-in-lit term))))) (in-theory (disable flatten-ands-in-lit))
true
; Standard System Library ; ; Copyright (C) 2019 Kestrel Institute (http://www.kestrel.edu) ; ; License: A 3-clause BSD license. See the LICENSE file distributed with ACL2. ; ; Author: PI:NAME:<NAME>END_PI (PI:EMAIL:<EMAIL>END_PI) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (in-package "ACL2") (include-book "xdoc/constructors" :dir :system) (local (include-book "std/typed-lists/pseudo-term-listp" :dir :system)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defsection std/system/flatten-ands-in-lit :parents (std/system/term-transformations) :short (xdoc::topstring "Theorems about " (xdoc::seetopic "system-utilities" "@('flatten-ands-in-lit')") ".") (defthm pseudo-term-listp-of-flatten-ands-in-lit (implies (pseudo-termp term) (pseudo-term-listp (flatten-ands-in-lit term))))) (in-theory (disable flatten-ands-in-lit))
[ { "context": "------\"\n||#\n\n;; Changes (into Lisp) Copyright 2019 Andrew Kenneth Wolven\n;; <[email protected]>\n;;\n;; Permission is hereby", "end": 1286, "score": 0.9998530745506287, "start": 1265, "tag": "NAME", "value": "Andrew Kenneth Wolven" }, { "context": "to Lisp) Copyright 2019 Andrew Kenneth Wolven\n;; <[email protected]>\n;;\n;; Permission is hereby granted, free of char", "end": 1308, "score": 0.99992436170578, "start": 1291, "tag": "EMAIL", "value": "[email protected]" } ]
vulkan/vk-funcs.lisp
Hectarea1996/common-vulkan
0
;;; this file is automatically generated, do not edit #|| "Copyright (c) 2015-2017 The Khronos Group Inc. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and/or associated documentation files (the \"Materials\"), to deal in the Materials without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Materials, and to permit persons to whom the Materials are 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 Materials. THE MATERIALS ARE 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 MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS. ------------------------------------------------------------------------" ||# ;; Changes (into Lisp) Copyright 2019 Andrew Kenneth Wolven ;; <[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 :cvk) (defvkdevextfun ("vkAcquireNextImage2KHX" vkAcquireNextImage2KHX) VkResult (device VkDevice) (pAcquireInfo (:pointer (:struct VkAcquireNextImageInfoKHX))) (pImageIndex (:pointer :uint32))) (cffi:defcfun ("vkAcquireNextImageKHR" vkAcquireNextImageKHR) VkResult (device VkDevice) (swapchain VkSwapchainKHR) ;; :EXTERNSYNC "true" (timeout :uint64) (semaphore VkSemaphore) ;; :OPTIONAL "true" :EXTERNSYNC "true" (fence VkFence) ;; :OPTIONAL "true" :EXTERNSYNC "true" (pImageIndex (:pointer :uint32))) (defvkinstextfun ("vkAcquireXlibDisplayEXT" vkAcquireXlibDisplayEXT) VkResult (physicalDevice VkPhysicalDevice) (dpy (:pointer Display)) (display VkDisplayKHR)) (cffi:defcfun ("vkAllocateCommandBuffers" vkAllocateCommandBuffers) VkResult (device VkDevice) (pAllocateInfo (:pointer (:struct VkCommandBufferAllocateInfo))) ;; :EXTERNSYNC "pAllocateInfo::commandPool" (pCommandBuffers (:pointer VkCommandBuffer))) ;; :LEN "pAllocateInfo::commandBufferCount" (cffi:defcfun ("vkAllocateDescriptorSets" vkAllocateDescriptorSets) VkResult (device VkDevice) (pAllocateInfo (:pointer (:struct VkDescriptorSetAllocateInfo))) ;; :EXTERNSYNC "pAllocateInfo::descriptorPool" (pDescriptorSets (:pointer VkDescriptorSet))) ;; :LEN "pAllocateInfo::descriptorSetCount" (cffi:defcfun ("vkAllocateMemory" vkAllocateMemory) VkResult (device VkDevice) (pAllocateInfo (:pointer (:struct VkMemoryAllocateInfo))) (pAllocator (:pointer (:struct VkAllocationCallbacks))) ;; :OPTIONAL "true" (pMemory (:pointer VkDeviceMemory))) (cffi:defcfun ("vkBeginCommandBuffer" vkBeginCommandBuffer) VkResult (commandBuffer VkCommandBuffer) ;; :EXTERNSYNC "true" (pBeginInfo (:pointer (:struct VkCommandBufferBeginInfo)))) (cffi:defcfun ("vkBindBufferMemory" vkBindBufferMemory) VkResult (device VkDevice) (buffer VkBuffer) ;; :EXTERNSYNC "true" (memory VkDeviceMemory) (memoryOffset VkDeviceSize)) (defvkdevextfun ("vkBindBufferMemory2KHX" vkBindBufferMemory2KHX) VkResult (device VkDevice) (bindInfoCount :uint32) (pBindInfos (:pointer (:struct VkBindBufferMemoryInfoKHX)))) ;; :LEN "bindInfoCount" (cffi:defcfun ("vkBindImageMemory" vkBindImageMemory) VkResult (device VkDevice) (image VkImage) ;; :EXTERNSYNC "true" (memory VkDeviceMemory) (memoryOffset VkDeviceSize)) (defvkdevextfun ("vkBindImageMemory2KHX" vkBindImageMemory2KHX) VkResult (device VkDevice) (bindInfoCount :uint32) (pBindInfos (:pointer (:struct VkBindImageMemoryInfoKHX)))) ;; :LEN "bindInfoCount" (cffi:defcfun ("vkCmdBeginQuery" vkCmdBeginQuery) :void (commandBuffer VkCommandBuffer) ;; :EXTERNSYNC "true" (queryPool VkQueryPool) (query :uint32) (flags VkQueryControlFlags)) ;; :OPTIONAL "true" (cffi:defcfun ("vkCmdBeginRenderPass" vkCmdBeginRenderPass) :void (commandBuffer VkCommandBuffer) ;; :EXTERNSYNC "true" (pRenderPassBegin (:pointer (:struct VkRenderPassBeginInfo))) (contents VkSubpassContents)) (cffi:defcfun ("vkCmdBindDescriptorSets" vkCmdBindDescriptorSets) :void (commandBuffer VkCommandBuffer) ;; :EXTERNSYNC "true" (pipelineBindPoint VkPipelineBindPoint) (layout VkPipelineLayout) (firstSet :uint32) (descriptorSetCount :uint32) (pDescriptorSets (:pointer VkDescriptorSet)) ;; :LEN "descriptorSetCount" (dynamicOffsetCount :uint32) ;; :OPTIONAL "true" (pDynamicOffsets (:pointer :uint32))) ;; :LEN "dynamicOffsetCount" (cffi:defcfun ("vkCmdBindIndexBuffer" vkCmdBindIndexBuffer) :void (commandBuffer VkCommandBuffer) ;; :EXTERNSYNC "true" (buffer VkBuffer) (offset VkDeviceSize) (indexType VkIndexType)) (cffi:defcfun ("vkCmdBindPipeline" vkCmdBindPipeline) :void (commandBuffer VkCommandBuffer) ;; :EXTERNSYNC "true" (pipelineBindPoint VkPipelineBindPoint) (pipeline VkPipeline)) (cffi:defcfun ("vkCmdBindVertexBuffers" vkCmdBindVertexBuffers) :void (commandBuffer VkCommandBuffer) ;; :EXTERNSYNC "true" (firstBinding :uint32) (bindingCount :uint32) (pBuffers (:pointer VkBuffer)) ;; :LEN "bindingCount" (pOffsets (:pointer VkDeviceSize))) ;; :LEN "bindingCount" (cffi:defcfun ("vkCmdBlitImage" vkCmdBlitImage) :void (commandBuffer VkCommandBuffer) ;; :EXTERNSYNC "true" (srcImage VkImage) (srcImageLayout VkImageLayout) (dstImage VkImage) (dstImageLayout VkImageLayout) (regionCount :uint32) (pRegions (:pointer (:struct VkImageBlit))) ;; :LEN "regionCount" (filter VkFilter)) (cffi:defcfun ("vkCmdClearAttachments" vkCmdClearAttachments) :void (commandBuffer VkCommandBuffer) ;; :EXTERNSYNC "true" (attachmentCount :uint32) (pAttachments (:pointer (:struct VkClearAttachment))) ;; :LEN "attachmentCount" (rectCount :uint32) (pRects (:pointer (:struct VkClearRect)))) ;; :LEN "rectCount" (cffi:defcfun ("vkCmdClearColorImage" vkCmdClearColorImage) :void (commandBuffer VkCommandBuffer) ;; :EXTERNSYNC "true" (image VkImage) (imageLayout VkImageLayout) (pColor (:pointer (:union VkClearColorValue))) (rangeCount :uint32) (pRanges (:pointer (:struct VkImageSubresourceRange)))) ;; :LEN "rangeCount" (cffi:defcfun ("vkCmdClearDepthStencilImage" vkCmdClearDepthStencilImage) :void (commandBuffer VkCommandBuffer) ;; :EXTERNSYNC "true" (image VkImage) (imageLayout VkImageLayout) (pDepthStencil (:pointer (:struct VkClearDepthStencilValue))) (rangeCount :uint32) (pRanges (:pointer (:struct VkImageSubresourceRange)))) ;; :LEN "rangeCount" (cffi:defcfun ("vkCmdCopyBuffer" vkCmdCopyBuffer) :void (commandBuffer VkCommandBuffer) ;; :EXTERNSYNC "true" (srcBuffer VkBuffer) (dstBuffer VkBuffer) (regionCount :uint32) (pRegions (:pointer (:struct VkBufferCopy)))) ;; :LEN "regionCount" (cffi:defcfun ("vkCmdCopyBufferToImage" vkCmdCopyBufferToImage) :void (commandBuffer VkCommandBuffer) ;; :EXTERNSYNC "true" (srcBuffer VkBuffer) (dstImage VkImage) (dstImageLayout VkImageLayout) (regionCount :uint32) (pRegions (:pointer (:struct VkBufferImageCopy)))) ;; :LEN "regionCount" (cffi:defcfun ("vkCmdCopyImage" vkCmdCopyImage) :void (commandBuffer VkCommandBuffer) ;; :EXTERNSYNC "true" (srcImage VkImage) (srcImageLayout VkImageLayout) (dstImage VkImage) (dstImageLayout VkImageLayout) (regionCount :uint32) (pRegions (:pointer (:struct VkImageCopy)))) ;; :LEN "regionCount" (cffi:defcfun ("vkCmdCopyImageToBuffer" vkCmdCopyImageToBuffer) :void (commandBuffer VkCommandBuffer) ;; :EXTERNSYNC "true" (srcImage VkImage) (srcImageLayout VkImageLayout) (dstBuffer VkBuffer) (regionCount :uint32) (pRegions (:pointer (:struct VkBufferImageCopy)))) ;; :LEN "regionCount" (cffi:defcfun ("vkCmdCopyQueryPoolResults" vkCmdCopyQueryPoolResults) :void (commandBuffer VkCommandBuffer) ;; :EXTERNSYNC "true" (queryPool VkQueryPool) (firstQuery :uint32) (queryCount :uint32) (dstBuffer VkBuffer) (dstOffset VkDeviceSize) (stride VkDeviceSize) (flags VkQueryResultFlags)) ;; :OPTIONAL "true" (defvkdevextfun ("vkCmdDebugMarkerBeginEXT" vkCmdDebugMarkerBeginEXT) :void (commandBuffer VkCommandBuffer) (pMarkerInfo (:pointer (:struct VkDebugMarkerMarkerInfoEXT)))) (defvkdevextfun ("vkCmdDebugMarkerEndEXT" vkCmdDebugMarkerEndEXT) :void (commandBuffer VkCommandBuffer)) (defvkdevextfun ("vkCmdDebugMarkerInsertEXT" vkCmdDebugMarkerInsertEXT) :void (commandBuffer VkCommandBuffer) (pMarkerInfo (:pointer (:struct VkDebugMarkerMarkerInfoEXT)))) (cffi:defcfun ("vkCmdDispatch" vkCmdDispatch) :void (commandBuffer VkCommandBuffer) ;; :EXTERNSYNC "true" (groupCountX :uint32) (groupCountY :uint32) (groupCountZ :uint32)) (defvkdevextfun ("vkCmdDispatchBaseKHX" vkCmdDispatchBaseKHX) :void (commandBuffer VkCommandBuffer) ;; :EXTERNSYNC "true" (baseGroupX :uint32) (baseGroupY :uint32) (baseGroupZ :uint32) (groupCountX :uint32) (groupCountY :uint32) (groupCountZ :uint32)) (cffi:defcfun ("vkCmdDispatchIndirect" vkCmdDispatchIndirect) :void (commandBuffer VkCommandBuffer) ;; :EXTERNSYNC "true" (buffer VkBuffer) (offset VkDeviceSize)) (cffi:defcfun ("vkCmdDraw" vkCmdDraw) :void (commandBuffer VkCommandBuffer) ;; :EXTERNSYNC "true" (vertexCount :uint32) (instanceCount :uint32) (firstVertex :uint32) (firstInstance :uint32)) (cffi:defcfun ("vkCmdDrawIndexed" vkCmdDrawIndexed) :void (commandBuffer VkCommandBuffer) ;; :EXTERNSYNC "true" (indexCount :uint32) (instanceCount :uint32) (firstIndex :uint32) (vertexOffset :int32) (firstInstance :uint32)) (cffi:defcfun ("vkCmdDrawIndexedIndirect" vkCmdDrawIndexedIndirect) :void (commandBuffer VkCommandBuffer) ;; :EXTERNSYNC "true" (buffer VkBuffer) (offset VkDeviceSize) (drawCount :uint32) (stride :uint32)) (defvkdevextfun ("vkCmdDrawIndexedIndirectCountAMD" vkCmdDrawIndexedIndirectCountAMD) :void (commandBuffer VkCommandBuffer) ;; :EXTERNSYNC "true" (buffer VkBuffer) (offset VkDeviceSize) (countBuffer VkBuffer) (countBufferOffset VkDeviceSize) (maxDrawCount :uint32) (stride :uint32)) (cffi:defcfun ("vkCmdDrawIndirect" vkCmdDrawIndirect) :void (commandBuffer VkCommandBuffer) ;; :EXTERNSYNC "true" (buffer VkBuffer) (offset VkDeviceSize) (drawCount :uint32) (stride :uint32)) (defvkdevextfun ("vkCmdDrawIndirectCountAMD" vkCmdDrawIndirectCountAMD) :void (commandBuffer VkCommandBuffer) ;; :EXTERNSYNC "true" (buffer VkBuffer) (offset VkDeviceSize) (countBuffer VkBuffer) (countBufferOffset VkDeviceSize) (maxDrawCount :uint32) (stride :uint32)) (cffi:defcfun ("vkCmdEndQuery" vkCmdEndQuery) :void (commandBuffer VkCommandBuffer) ;; :EXTERNSYNC "true" (queryPool VkQueryPool) (query :uint32)) (cffi:defcfun ("vkCmdEndRenderPass" vkCmdEndRenderPass) :void (commandBuffer VkCommandBuffer)) ;; :EXTERNSYNC "true" (cffi:defcfun ("vkCmdExecuteCommands" vkCmdExecuteCommands) :void (commandBuffer VkCommandBuffer) ;; :EXTERNSYNC "true" (commandBufferCount :uint32) (pCommandBuffers (:pointer VkCommandBuffer))) ;; :LEN "commandBufferCount" (cffi:defcfun ("vkCmdFillBuffer" vkCmdFillBuffer) :void (commandBuffer VkCommandBuffer) ;; :EXTERNSYNC "true" (dstBuffer VkBuffer) (dstOffset VkDeviceSize) (size VkDeviceSize) (data :uint32)) (cffi:defcfun ("vkCmdNextSubpass" vkCmdNextSubpass) :void (commandBuffer VkCommandBuffer) ;; :EXTERNSYNC "true" (contents VkSubpassContents)) (cffi:defcfun ("vkCmdPipelineBarrier" vkCmdPipelineBarrier) :void (commandBuffer VkCommandBuffer) ;; :EXTERNSYNC "true" (srcStageMask VkPipelineStageFlags) (dstStageMask VkPipelineStageFlags) (dependencyFlags VkDependencyFlags) ;; :OPTIONAL "true" (memoryBarrierCount :uint32) ;; :OPTIONAL "true" (pMemoryBarriers (:pointer (:struct VkMemoryBarrier))) ;; :LEN "memoryBarrierCount" (bufferMemoryBarrierCount :uint32) ;; :OPTIONAL "true" (pBufferMemoryBarriers (:pointer (:struct VkBufferMemoryBarrier))) ;; :LEN "bufferMemoryBarrierCount" (imageMemoryBarrierCount :uint32) ;; :OPTIONAL "true" (pImageMemoryBarriers (:pointer (:struct VkImageMemoryBarrier)))) ;; :LEN "imageMemoryBarrierCount" (defvkdevextfun ("vkCmdProcessCommandsNVX" vkCmdProcessCommandsNVX) :void (commandBuffer VkCommandBuffer) ;; :EXTERNSYNC "true" (pProcessCommandsInfo (:pointer (:struct VkCmdProcessCommandsInfoNVX)))) (cffi:defcfun ("vkCmdPushConstants" vkCmdPushConstants) :void (commandBuffer VkCommandBuffer) ;; :EXTERNSYNC "true" (layout VkPipelineLayout) (stageFlags VkShaderStageFlags) (offset :uint32) (size :uint32) (pValues (:pointer :void))) ;; :LEN "size" (defvkdevextfun ("vkCmdPushDescriptorSetKHR" vkCmdPushDescriptorSetKHR) :void (commandBuffer VkCommandBuffer) ;; :EXTERNSYNC "true" (pipelineBindPoint VkPipelineBindPoint) (layout VkPipelineLayout) (set :uint32) (descriptorWriteCount :uint32) (pDescriptorWrites (:pointer (:struct VkWriteDescriptorSet)))) ;; :LEN "descriptorWriteCount" (defvkdevextfun ("vkCmdPushDescriptorSetWithTemplateKHR" vkCmdPushDescriptorSetWithTemplateKHR) :void (commandBuffer VkCommandBuffer) ;; :EXTERNSYNC "true" (descriptorUpdateTemplate VkDescriptorUpdateTemplateKHR) (layout VkPipelineLayout) (set :uint32) (pData (:pointer :void))) (defvkdevextfun ("vkCmdReserveSpaceForCommandsNVX" vkCmdReserveSpaceForCommandsNVX) :void (commandBuffer VkCommandBuffer) ;; :EXTERNSYNC "true" (pReserveSpaceInfo (:pointer (:struct VkCmdReserveSpaceForCommandsInfoNVX)))) (cffi:defcfun ("vkCmdResetEvent" vkCmdResetEvent) :void (commandBuffer VkCommandBuffer) ;; :EXTERNSYNC "true" (event VkEvent) (stageMask VkPipelineStageFlags)) (cffi:defcfun ("vkCmdResetQueryPool" vkCmdResetQueryPool) :void (commandBuffer VkCommandBuffer) ;; :EXTERNSYNC "true" (queryPool VkQueryPool) (firstQuery :uint32) (queryCount :uint32)) (cffi:defcfun ("vkCmdResolveImage" vkCmdResolveImage) :void (commandBuffer VkCommandBuffer) ;; :EXTERNSYNC "true" (srcImage VkImage) (srcImageLayout VkImageLayout) (dstImage VkImage) (dstImageLayout VkImageLayout) (regionCount :uint32) (pRegions (:pointer (:struct VkImageResolve)))) ;; :LEN "regionCount" (cffi:defcfun ("vkCmdSetBlendConstants" vkCmdSetBlendConstants) :void (commandBuffer VkCommandBuffer) ;; :EXTERNSYNC "true" (blendConstants :float)) (cffi:defcfun ("vkCmdSetDepthBias" vkCmdSetDepthBias) :void (commandBuffer VkCommandBuffer) ;; :EXTERNSYNC "true" (depthBiasConstantFactor :float) (depthBiasClamp :float) (depthBiasSlopeFactor :float)) (cffi:defcfun ("vkCmdSetDepthBounds" vkCmdSetDepthBounds) :void (commandBuffer VkCommandBuffer) ;; :EXTERNSYNC "true" (minDepthBounds :float) (maxDepthBounds :float)) (defvkdevextfun ("vkCmdSetDeviceMaskKHX" vkCmdSetDeviceMaskKHX) :void (commandBuffer VkCommandBuffer) ;; :EXTERNSYNC "true" (deviceMask :uint32)) (defvkdevextfun ("vkCmdSetDiscardRectangleEXT" vkCmdSetDiscardRectangleEXT) :void (commandBuffer VkCommandBuffer) ;; :EXTERNSYNC "true" (firstDiscardRectangle :uint32) (discardRectangleCount :uint32) (pDiscardRectangles (:pointer (:struct VkRect2D)))) ;; :LEN "discardRectangleCount" (cffi:defcfun ("vkCmdSetEvent" vkCmdSetEvent) :void (commandBuffer VkCommandBuffer) ;; :EXTERNSYNC "true" (event VkEvent) (stageMask VkPipelineStageFlags)) (cffi:defcfun ("vkCmdSetLineWidth" vkCmdSetLineWidth) :void (commandBuffer VkCommandBuffer) ;; :EXTERNSYNC "true" (lineWidth :float)) (cffi:defcfun ("vkCmdSetScissor" vkCmdSetScissor) :void (commandBuffer VkCommandBuffer) ;; :EXTERNSYNC "true" (firstScissor :uint32) (scissorCount :uint32) (pScissors (:pointer (:struct VkRect2D)))) ;; :LEN "scissorCount" (cffi:defcfun ("vkCmdSetStencilCompareMask" vkCmdSetStencilCompareMask) :void (commandBuffer VkCommandBuffer) ;; :EXTERNSYNC "true" (faceMask VkStencilFaceFlags) (compareMask :uint32)) (cffi:defcfun ("vkCmdSetStencilReference" vkCmdSetStencilReference) :void (commandBuffer VkCommandBuffer) ;; :EXTERNSYNC "true" (faceMask VkStencilFaceFlags) (reference :uint32)) (cffi:defcfun ("vkCmdSetStencilWriteMask" vkCmdSetStencilWriteMask) :void (commandBuffer VkCommandBuffer) ;; :EXTERNSYNC "true" (faceMask VkStencilFaceFlags) (writeMask :uint32)) (cffi:defcfun ("vkCmdSetViewport" vkCmdSetViewport) :void (commandBuffer VkCommandBuffer) ;; :EXTERNSYNC "true" (firstViewport :uint32) (viewportCount :uint32) (pViewports (:pointer (:struct VkViewport)))) ;; :LEN "viewportCount" :NOAUTOVALIDITY "true" (defvkdevextfun ("vkCmdSetViewportWScalingNV" vkCmdSetViewportWScalingNV) :void (commandBuffer VkCommandBuffer) ;; :EXTERNSYNC "true" (firstViewport :uint32) (viewportCount :uint32) (pViewportWScalings (:pointer (:struct VkViewportWScalingNV)))) ;; :LEN "viewportCount" :NOAUTOVALIDITY "true" (cffi:defcfun ("vkCmdUpdateBuffer" vkCmdUpdateBuffer) :void (commandBuffer VkCommandBuffer) ;; :EXTERNSYNC "true" (dstBuffer VkBuffer) (dstOffset VkDeviceSize) (dataSize VkDeviceSize) (pData (:pointer :void))) ;; :LEN "dataSize" (cffi:defcfun ("vkCmdWaitEvents" vkCmdWaitEvents) :void (commandBuffer VkCommandBuffer) ;; :EXTERNSYNC "true" (eventCount :uint32) (pEvents (:pointer VkEvent)) ;; :LEN "eventCount" (srcStageMask VkPipelineStageFlags) (dstStageMask VkPipelineStageFlags) (memoryBarrierCount :uint32) ;; :OPTIONAL "true" (pMemoryBarriers (:pointer (:struct VkMemoryBarrier))) ;; :LEN "memoryBarrierCount" (bufferMemoryBarrierCount :uint32) ;; :OPTIONAL "true" (pBufferMemoryBarriers (:pointer (:struct VkBufferMemoryBarrier))) ;; :LEN "bufferMemoryBarrierCount" (imageMemoryBarrierCount :uint32) ;; :OPTIONAL "true" (pImageMemoryBarriers (:pointer (:struct VkImageMemoryBarrier)))) ;; :LEN "imageMemoryBarrierCount" (cffi:defcfun ("vkCmdWriteTimestamp" vkCmdWriteTimestamp) :void (commandBuffer VkCommandBuffer) ;; :EXTERNSYNC "true" (pipelineStage VkPipelineStageFlagBits) (queryPool VkQueryPool) (query :uint32)) (defvkinstextfun ("vkCreateAndroidSurfaceKHR" vkCreateAndroidSurfaceKHR) VkResult (instance VkInstance) (pCreateInfo (:pointer (:struct VkAndroidSurfaceCreateInfoKHR))) (pAllocator (:pointer (:struct VkAllocationCallbacks))) ;; :OPTIONAL "true" (pSurface (:pointer VkSurfaceKHR))) (cffi:defcfun ("vkCreateBuffer" vkCreateBuffer) VkResult (device VkDevice) (pCreateInfo (:pointer (:struct VkBufferCreateInfo))) (pAllocator (:pointer (:struct VkAllocationCallbacks))) ;; :OPTIONAL "true" (pBuffer (:pointer VkBuffer))) (cffi:defcfun ("vkCreateBufferView" vkCreateBufferView) VkResult (device VkDevice) (pCreateInfo (:pointer (:struct VkBufferViewCreateInfo))) (pAllocator (:pointer (:struct VkAllocationCallbacks))) ;; :OPTIONAL "true" (pView (:pointer VkBufferView))) (cffi:defcfun ("vkCreateCommandPool" vkCreateCommandPool) VkResult (device VkDevice) (pCreateInfo (:pointer (:struct VkCommandPoolCreateInfo))) (pAllocator (:pointer (:struct VkAllocationCallbacks))) ;; :OPTIONAL "true" (pCommandPool (:pointer VkCommandPool))) (cffi:defcfun ("vkCreateComputePipelines" vkCreateComputePipelines) VkResult (device VkDevice) (pipelineCache VkPipelineCache) ;; :OPTIONAL "true" (createInfoCount :uint32) (pCreateInfos (:pointer (:struct VkComputePipelineCreateInfo))) ;; :LEN "createInfoCount" (pAllocator (:pointer (:struct VkAllocationCallbacks))) ;; :OPTIONAL "true" (pPipelines (:pointer VkPipeline))) ;; :LEN "createInfoCount" (defvkinstextfun ("vkCreateDebugReportCallbackEXT" vkCreateDebugReportCallbackEXT) VkResult (instance VkInstance) (pCreateInfo (:pointer (:struct VkDebugReportCallbackCreateInfoEXT))) (pAllocator (:pointer (:struct VkAllocationCallbacks))) ;; :OPTIONAL "true" (pCallback (:pointer VkDebugReportCallbackEXT))) (cffi:defcfun ("vkCreateDescriptorPool" vkCreateDescriptorPool) VkResult (device VkDevice) (pCreateInfo (:pointer (:struct VkDescriptorPoolCreateInfo))) (pAllocator (:pointer (:struct VkAllocationCallbacks))) ;; :OPTIONAL "true" (pDescriptorPool (:pointer VkDescriptorPool))) (cffi:defcfun ("vkCreateDescriptorSetLayout" vkCreateDescriptorSetLayout) VkResult (device VkDevice) (pCreateInfo (:pointer (:struct VkDescriptorSetLayoutCreateInfo))) (pAllocator (:pointer (:struct VkAllocationCallbacks))) ;; :OPTIONAL "true" (pSetLayout (:pointer VkDescriptorSetLayout))) (defvkdevextfun ("vkCreateDescriptorUpdateTemplateKHR" vkCreateDescriptorUpdateTemplateKHR) VkResult (device VkDevice) (pCreateInfo (:pointer (:struct VkDescriptorUpdateTemplateCreateInfoKHR))) (pAllocator (:pointer (:struct VkAllocationCallbacks))) ;; :OPTIONAL "true" (pDescriptorUpdateTemplate (:pointer VkDescriptorUpdateTemplateKHR))) (cffi:defcfun ("vkCreateDevice" vkCreateDevice) VkResult (physicalDevice VkPhysicalDevice) (pCreateInfo (:pointer (:struct VkDeviceCreateInfo))) (pAllocator (:pointer (:struct VkAllocationCallbacks))) ;; :OPTIONAL "true" (pDevice (:pointer VkDevice))) (cffi:defcfun ("vkCreateDisplayModeKHR" vkCreateDisplayModeKHR) VkResult (physicalDevice VkPhysicalDevice) (display VkDisplayKHR) ;; :EXTERNSYNC "true" (pCreateInfo (:pointer (:struct VkDisplayModeCreateInfoKHR))) (pAllocator (:pointer (:struct VkAllocationCallbacks))) ;; :OPTIONAL "true" (pMode (:pointer VkDisplayModeKHR))) (cffi:defcfun ("vkCreateDisplayPlaneSurfaceKHR" vkCreateDisplayPlaneSurfaceKHR) VkResult (instance VkInstance) (pCreateInfo (:pointer (:struct VkDisplaySurfaceCreateInfoKHR))) (pAllocator (:pointer (:struct VkAllocationCallbacks))) ;; :OPTIONAL "true" (pSurface (:pointer VkSurfaceKHR))) (cffi:defcfun ("vkCreateEvent" vkCreateEvent) VkResult (device VkDevice) (pCreateInfo (:pointer (:struct VkEventCreateInfo))) (pAllocator (:pointer (:struct VkAllocationCallbacks))) ;; :OPTIONAL "true" (pEvent (:pointer VkEvent))) (cffi:defcfun ("vkCreateFence" vkCreateFence) VkResult (device VkDevice) (pCreateInfo (:pointer (:struct VkFenceCreateInfo))) (pAllocator (:pointer (:struct VkAllocationCallbacks))) ;; :OPTIONAL "true" (pFence (:pointer VkFence))) (cffi:defcfun ("vkCreateFramebuffer" vkCreateFramebuffer) VkResult (device VkDevice) (pCreateInfo (:pointer (:struct VkFramebufferCreateInfo))) (pAllocator (:pointer (:struct VkAllocationCallbacks))) ;; :OPTIONAL "true" (pFramebuffer (:pointer VkFramebuffer))) (cffi:defcfun ("vkCreateGraphicsPipelines" vkCreateGraphicsPipelines) VkResult (device VkDevice) (pipelineCache VkPipelineCache) ;; :OPTIONAL "true" (createInfoCount :uint32) (pCreateInfos (:pointer (:struct VkGraphicsPipelineCreateInfo))) ;; :LEN "createInfoCount" (pAllocator (:pointer (:struct VkAllocationCallbacks))) ;; :OPTIONAL "true" (pPipelines (:pointer VkPipeline))) ;; :LEN "createInfoCount" (defvkinstextfun ("vkCreateIOSSurfaceMVK" vkCreateIOSSurfaceMVK) VkResult (instance VkInstance) (pCreateInfo (:pointer (:struct VkIOSSurfaceCreateInfoMVK))) (pAllocator (:pointer (:struct VkAllocationCallbacks))) ;; :OPTIONAL "true" (pSurface (:pointer VkSurfaceKHR))) (cffi:defcfun ("vkCreateImage" vkCreateImage) VkResult (device VkDevice) (pCreateInfo (:pointer (:struct VkImageCreateInfo))) (pAllocator (:pointer (:struct VkAllocationCallbacks))) ;; :OPTIONAL "true" (pImage (:pointer VkImage))) (cffi:defcfun ("vkCreateImageView" vkCreateImageView) VkResult (device VkDevice) (pCreateInfo (:pointer (:struct VkImageViewCreateInfo))) (pAllocator (:pointer (:struct VkAllocationCallbacks))) ;; :OPTIONAL "true" (pView (:pointer VkImageView))) (defvkdevextfun ("vkCreateIndirectCommandsLayoutNVX" vkCreateIndirectCommandsLayoutNVX) VkResult (device VkDevice) (pCreateInfo (:pointer (:struct VkIndirectCommandsLayoutCreateInfoNVX))) (pAllocator (:pointer (:struct VkAllocationCallbacks))) ;; :OPTIONAL "true" (pIndirectCommandsLayout (:pointer VkIndirectCommandsLayoutNVX))) (cffi:defcfun ("vkCreateInstance" vkCreateInstance) VkResult (pCreateInfo (:pointer (:struct VkInstanceCreateInfo))) (pAllocator (:pointer (:struct VkAllocationCallbacks))) ;; :OPTIONAL "true" (pInstance (:pointer VkInstance))) (defvkinstextfun ("vkCreateMacOSSurfaceMVK" vkCreateMacOSSurfaceMVK) VkResult (instance VkInstance) (pCreateInfo (:pointer (:struct VkMacOSSurfaceCreateInfoMVK))) (pAllocator (:pointer (:struct VkAllocationCallbacks))) ;; :OPTIONAL "true" (pSurface (:pointer VkSurfaceKHR))) (defvkinstextfun ("vkCreateMirSurfaceKHR" vkCreateMirSurfaceKHR) VkResult (instance VkInstance) (pCreateInfo (:pointer (:struct VkMirSurfaceCreateInfoKHR))) (pAllocator (:pointer (:struct VkAllocationCallbacks))) ;; :OPTIONAL "true" (pSurface (:pointer VkSurfaceKHR))) (defvkdevextfun ("vkCreateObjectTableNVX" vkCreateObjectTableNVX) VkResult (device VkDevice) (pCreateInfo (:pointer (:struct VkObjectTableCreateInfoNVX))) (pAllocator (:pointer (:struct VkAllocationCallbacks))) ;; :OPTIONAL "true" (pObjectTable (:pointer VkObjectTableNVX))) (cffi:defcfun ("vkCreatePipelineCache" vkCreatePipelineCache) VkResult (device VkDevice) (pCreateInfo (:pointer (:struct VkPipelineCacheCreateInfo))) (pAllocator (:pointer (:struct VkAllocationCallbacks))) ;; :OPTIONAL "true" (pPipelineCache (:pointer VkPipelineCache))) (cffi:defcfun ("vkCreatePipelineLayout" vkCreatePipelineLayout) VkResult (device VkDevice) (pCreateInfo (:pointer (:struct VkPipelineLayoutCreateInfo))) (pAllocator (:pointer (:struct VkAllocationCallbacks))) ;; :OPTIONAL "true" (pPipelineLayout (:pointer VkPipelineLayout))) (cffi:defcfun ("vkCreateQueryPool" vkCreateQueryPool) VkResult (device VkDevice) (pCreateInfo (:pointer (:struct VkQueryPoolCreateInfo))) (pAllocator (:pointer (:struct VkAllocationCallbacks))) ;; :OPTIONAL "true" (pQueryPool (:pointer VkQueryPool))) (cffi:defcfun ("vkCreateRenderPass" vkCreateRenderPass) VkResult (device VkDevice) (pCreateInfo (:pointer (:struct VkRenderPassCreateInfo))) (pAllocator (:pointer (:struct VkAllocationCallbacks))) ;; :OPTIONAL "true" (pRenderPass (:pointer VkRenderPass))) (cffi:defcfun ("vkCreateSampler" vkCreateSampler) VkResult (device VkDevice) (pCreateInfo (:pointer (:struct VkSamplerCreateInfo))) (pAllocator (:pointer (:struct VkAllocationCallbacks))) ;; :OPTIONAL "true" (pSampler (:pointer VkSampler))) (cffi:defcfun ("vkCreateSemaphore" vkCreateSemaphore) VkResult (device VkDevice) (pCreateInfo (:pointer (:struct VkSemaphoreCreateInfo))) (pAllocator (:pointer (:struct VkAllocationCallbacks))) ;; :OPTIONAL "true" (pSemaphore (:pointer VkSemaphore))) (cffi:defcfun ("vkCreateShaderModule" vkCreateShaderModule) VkResult (device VkDevice) (pCreateInfo (:pointer (:struct VkShaderModuleCreateInfo))) (pAllocator (:pointer (:struct VkAllocationCallbacks))) ;; :OPTIONAL "true" (pShaderModule (:pointer VkShaderModule))) (cffi:defcfun ("vkCreateSharedSwapchainsKHR" vkCreateSharedSwapchainsKHR) VkResult (device VkDevice) (swapchainCount :uint32) (pCreateInfos (:pointer (:struct VkSwapchainCreateInfoKHR))) ;; :LEN "swapchainCount" :EXTERNSYNC "pCreateInfos[].surface,pCreateInfos[].oldSwapchain" (pAllocator (:pointer (:struct VkAllocationCallbacks))) ;; :OPTIONAL "true" (pSwapchains (:pointer VkSwapchainKHR))) ;; :LEN "swapchainCount" (cffi:defcfun ("vkCreateSwapchainKHR" vkCreateSwapchainKHR) VkResult (device VkDevice) (pCreateInfo (:pointer (:struct VkSwapchainCreateInfoKHR))) ;; :EXTERNSYNC "pCreateInfo.surface,pCreateInfo.oldSwapchain" (pAllocator (:pointer (:struct VkAllocationCallbacks))) ;; :OPTIONAL "true" (pSwapchain (:pointer VkSwapchainKHR))) (defvkinstextfun ("vkCreateViSurfaceNN" vkCreateViSurfaceNN) VkResult (instance VkInstance) (pCreateInfo (:pointer (:struct VkViSurfaceCreateInfoNN))) (pAllocator (:pointer (:struct VkAllocationCallbacks))) ;; :OPTIONAL "true" (pSurface (:pointer VkSurfaceKHR))) (defvkinstextfun ("vkCreateWaylandSurfaceKHR" vkCreateWaylandSurfaceKHR) VkResult (instance VkInstance) (pCreateInfo (:pointer (:struct VkWaylandSurfaceCreateInfoKHR))) (pAllocator (:pointer (:struct VkAllocationCallbacks))) ;; :OPTIONAL "true" (pSurface (:pointer VkSurfaceKHR))) (cffi:defcfun ("vkCreateWin32SurfaceKHR" vkCreateWin32SurfaceKHR) VkResult (instance VkInstance) (pCreateInfo (:pointer (:struct VkWin32SurfaceCreateInfoKHR))) (pAllocator (:pointer (:struct VkAllocationCallbacks))) ;; :OPTIONAL "true" (pSurface (:pointer VkSurfaceKHR))) (defvkinstextfun ("vkCreateXcbSurfaceKHR" vkCreateXcbSurfaceKHR) VkResult (instance VkInstance) (pCreateInfo (:pointer (:struct VkXcbSurfaceCreateInfoKHR))) (pAllocator (:pointer (:struct VkAllocationCallbacks))) ;; :OPTIONAL "true" (pSurface (:pointer VkSurfaceKHR))) (defvkinstextfun ("vkCreateXlibSurfaceKHR" vkCreateXlibSurfaceKHR) VkResult (instance VkInstance) (pCreateInfo (:pointer (:struct VkXlibSurfaceCreateInfoKHR))) (pAllocator (:pointer (:struct VkAllocationCallbacks))) ;; :OPTIONAL "true" (pSurface (:pointer VkSurfaceKHR))) (defvkdevextfun ("vkDebugMarkerSetObjectNameEXT" vkDebugMarkerSetObjectNameEXT) VkResult (device VkDevice) (pNameInfo (:pointer (:struct VkDebugMarkerObjectNameInfoEXT)))) ;; :EXTERNSYNC "pNameInfo.object" (defvkdevextfun ("vkDebugMarkerSetObjectTagEXT" vkDebugMarkerSetObjectTagEXT) VkResult (device VkDevice) (pTagInfo (:pointer (:struct VkDebugMarkerObjectTagInfoEXT)))) ;; :EXTERNSYNC "pTagInfo.object" (defvkinstextfun ("vkDebugReportMessageEXT" vkDebugReportMessageEXT) :void (instance VkInstance) (flags VkDebugReportFlagsEXT) (objectType VkDebugReportObjectTypeEXT) (object :uint64) (location size-t) (messageCode :int32) (pLayerPrefix (:pointer :char)) ;; :LEN "null-terminated" (pMessage (:pointer :char))) ;; :LEN "null-terminated" (cffi:defcfun ("vkDestroyBuffer" vkDestroyBuffer) :void (device VkDevice) (buffer VkBuffer) ;; :OPTIONAL "true" :EXTERNSYNC "true" (pAllocator (:pointer (:struct VkAllocationCallbacks)))) ;; :OPTIONAL "true" (cffi:defcfun ("vkDestroyBufferView" vkDestroyBufferView) :void (device VkDevice) (bufferView VkBufferView) ;; :OPTIONAL "true" :EXTERNSYNC "true" (pAllocator (:pointer (:struct VkAllocationCallbacks)))) ;; :OPTIONAL "true" (cffi:defcfun ("vkDestroyCommandPool" vkDestroyCommandPool) :void (device VkDevice) (commandPool VkCommandPool) ;; :OPTIONAL "true" :EXTERNSYNC "true" (pAllocator (:pointer (:struct VkAllocationCallbacks)))) ;; :OPTIONAL "true" (defvkinstextfun ("vkDestroyDebugReportCallbackEXT" vkDestroyDebugReportCallbackEXT) :void (instance VkInstance) (callback VkDebugReportCallbackEXT) ;; :EXTERNSYNC "true" (pAllocator (:pointer (:struct VkAllocationCallbacks)))) ;; :OPTIONAL "true" (cffi:defcfun ("vkDestroyDescriptorPool" vkDestroyDescriptorPool) :void (device VkDevice) (descriptorPool VkDescriptorPool) ;; :OPTIONAL "true" :EXTERNSYNC "true" (pAllocator (:pointer (:struct VkAllocationCallbacks)))) ;; :OPTIONAL "true" (cffi:defcfun ("vkDestroyDescriptorSetLayout" vkDestroyDescriptorSetLayout) :void (device VkDevice) (descriptorSetLayout VkDescriptorSetLayout) ;; :OPTIONAL "true" :EXTERNSYNC "true" (pAllocator (:pointer (:struct VkAllocationCallbacks)))) ;; :OPTIONAL "true" (defvkdevextfun ("vkDestroyDescriptorUpdateTemplateKHR" vkDestroyDescriptorUpdateTemplateKHR) :void (device VkDevice) (descriptorUpdateTemplate VkDescriptorUpdateTemplateKHR) ;; :OPTIONAL "true" :EXTERNSYNC "true" (pAllocator (:pointer (:struct VkAllocationCallbacks)))) ;; :OPTIONAL "true" (cffi:defcfun ("vkDestroyDevice" vkDestroyDevice) :void (device VkDevice) ;; :OPTIONAL "true" :EXTERNSYNC "true" (pAllocator (:pointer (:struct VkAllocationCallbacks)))) ;; :OPTIONAL "true" (cffi:defcfun ("vkDestroyEvent" vkDestroyEvent) :void (device VkDevice) (event VkEvent) ;; :OPTIONAL "true" :EXTERNSYNC "true" (pAllocator (:pointer (:struct VkAllocationCallbacks)))) ;; :OPTIONAL "true" (cffi:defcfun ("vkDestroyFence" vkDestroyFence) :void (device VkDevice) (fence VkFence) ;; :OPTIONAL "true" :EXTERNSYNC "true" (pAllocator (:pointer (:struct VkAllocationCallbacks)))) ;; :OPTIONAL "true" (cffi:defcfun ("vkDestroyFramebuffer" vkDestroyFramebuffer) :void (device VkDevice) (framebuffer VkFramebuffer) ;; :OPTIONAL "true" :EXTERNSYNC "true" (pAllocator (:pointer (:struct VkAllocationCallbacks)))) ;; :OPTIONAL "true" (cffi:defcfun ("vkDestroyImage" vkDestroyImage) :void (device VkDevice) (image VkImage) ;; :OPTIONAL "true" :EXTERNSYNC "true" (pAllocator (:pointer (:struct VkAllocationCallbacks)))) ;; :OPTIONAL "true" (cffi:defcfun ("vkDestroyImageView" vkDestroyImageView) :void (device VkDevice) (imageView VkImageView) ;; :OPTIONAL "true" :EXTERNSYNC "true" (pAllocator (:pointer (:struct VkAllocationCallbacks)))) ;; :OPTIONAL "true" (defvkdevextfun ("vkDestroyIndirectCommandsLayoutNVX" vkDestroyIndirectCommandsLayoutNVX) :void (device VkDevice) (indirectCommandsLayout VkIndirectCommandsLayoutNVX) (pAllocator (:pointer (:struct VkAllocationCallbacks)))) ;; :OPTIONAL "true" (cffi:defcfun ("vkDestroyInstance" vkDestroyInstance) :void (instance VkInstance) ;; :OPTIONAL "true" :EXTERNSYNC "true" (pAllocator (:pointer (:struct VkAllocationCallbacks)))) ;; :OPTIONAL "true" (defvkdevextfun ("vkDestroyObjectTableNVX" vkDestroyObjectTableNVX) :void (device VkDevice) (objectTable VkObjectTableNVX) ;; :EXTERNSYNC "true" (pAllocator (:pointer (:struct VkAllocationCallbacks)))) ;; :OPTIONAL "true" (cffi:defcfun ("vkDestroyPipeline" vkDestroyPipeline) :void (device VkDevice) (pipeline VkPipeline) ;; :OPTIONAL "true" :EXTERNSYNC "true" (pAllocator (:pointer (:struct VkAllocationCallbacks)))) ;; :OPTIONAL "true" (cffi:defcfun ("vkDestroyPipelineCache" vkDestroyPipelineCache) :void (device VkDevice) (pipelineCache VkPipelineCache) ;; :OPTIONAL "true" :EXTERNSYNC "true" (pAllocator (:pointer (:struct VkAllocationCallbacks)))) ;; :OPTIONAL "true" (cffi:defcfun ("vkDestroyPipelineLayout" vkDestroyPipelineLayout) :void (device VkDevice) (pipelineLayout VkPipelineLayout) ;; :OPTIONAL "true" :EXTERNSYNC "true" (pAllocator (:pointer (:struct VkAllocationCallbacks)))) ;; :OPTIONAL "true" (cffi:defcfun ("vkDestroyQueryPool" vkDestroyQueryPool) :void (device VkDevice) (queryPool VkQueryPool) ;; :OPTIONAL "true" :EXTERNSYNC "true" (pAllocator (:pointer (:struct VkAllocationCallbacks)))) ;; :OPTIONAL "true" (cffi:defcfun ("vkDestroyRenderPass" vkDestroyRenderPass) :void (device VkDevice) (renderPass VkRenderPass) ;; :OPTIONAL "true" :EXTERNSYNC "true" (pAllocator (:pointer (:struct VkAllocationCallbacks)))) ;; :OPTIONAL "true" (cffi:defcfun ("vkDestroySampler" vkDestroySampler) :void (device VkDevice) (sampler VkSampler) ;; :OPTIONAL "true" :EXTERNSYNC "true" (pAllocator (:pointer (:struct VkAllocationCallbacks)))) ;; :OPTIONAL "true" (cffi:defcfun ("vkDestroySemaphore" vkDestroySemaphore) :void (device VkDevice) (semaphore VkSemaphore) ;; :OPTIONAL "true" :EXTERNSYNC "true" (pAllocator (:pointer (:struct VkAllocationCallbacks)))) ;; :OPTIONAL "true" (cffi:defcfun ("vkDestroyShaderModule" vkDestroyShaderModule) :void (device VkDevice) (shaderModule VkShaderModule) ;; :OPTIONAL "true" :EXTERNSYNC "true" (pAllocator (:pointer (:struct VkAllocationCallbacks)))) ;; :OPTIONAL "true" (cffi:defcfun ("vkDestroySurfaceKHR" vkDestroySurfaceKHR) :void (instance VkInstance) (surface VkSurfaceKHR) ;; :OPTIONAL "true" :EXTERNSYNC "true" (pAllocator (:pointer (:struct VkAllocationCallbacks)))) ;; :OPTIONAL "true" (cffi:defcfun ("vkDestroySwapchainKHR" vkDestroySwapchainKHR) :void (device VkDevice) (swapchain VkSwapchainKHR) ;; :OPTIONAL "true" :EXTERNSYNC "true" (pAllocator (:pointer (:struct VkAllocationCallbacks)))) ;; :OPTIONAL "true" (cffi:defcfun ("vkDeviceWaitIdle" vkDeviceWaitIdle) VkResult (device VkDevice)) (defvkdevextfun ("vkDisplayPowerControlEXT" vkDisplayPowerControlEXT) VkResult (device VkDevice) (display VkDisplayKHR) (pDisplayPowerInfo (:pointer (:struct VkDisplayPowerInfoEXT)))) (cffi:defcfun ("vkEndCommandBuffer" vkEndCommandBuffer) VkResult (commandBuffer VkCommandBuffer)) ;; :EXTERNSYNC "true" (cffi:defcfun ("vkEnumerateDeviceExtensionProperties" vkEnumerateDeviceExtensionProperties) VkResult (physicalDevice VkPhysicalDevice) (pLayerName (:pointer :char)) ;; :OPTIONAL "true" :LEN "null-terminated" (pPropertyCount (:pointer :uint32)) ;; :OPTIONAL "false,true" (pProperties (:pointer (:struct VkExtensionProperties)))) ;; :OPTIONAL "true" :LEN "pPropertyCount" (cffi:defcfun ("vkEnumerateDeviceLayerProperties" vkEnumerateDeviceLayerProperties) VkResult (physicalDevice VkPhysicalDevice) (pPropertyCount (:pointer :uint32)) ;; :OPTIONAL "false,true" (pProperties (:pointer (:struct VkLayerProperties)))) ;; :OPTIONAL "true" :LEN "pPropertyCount" (cffi:defcfun ("vkEnumerateInstanceExtensionProperties" vkEnumerateInstanceExtensionProperties) VkResult (pLayerName (:pointer :char)) ;; :OPTIONAL "true" :LEN "null-terminated" (pPropertyCount (:pointer :uint32)) ;; :OPTIONAL "false,true" (pProperties (:pointer (:struct VkExtensionProperties)))) ;; :OPTIONAL "true" :LEN "pPropertyCount" (cffi:defcfun ("vkEnumerateInstanceLayerProperties" vkEnumerateInstanceLayerProperties) VkResult (pPropertyCount (:pointer :uint32)) ;; :OPTIONAL "false,true" (pProperties (:pointer (:struct VkLayerProperties)))) ;; :OPTIONAL "true" :LEN "pPropertyCount" (defvkinstextfun ("vkEnumeratePhysicalDeviceGroupsKHX" vkEnumeratePhysicalDeviceGroupsKHX) VkResult (instance VkInstance) (pPhysicalDeviceGroupCount (:pointer :uint32)) ;; :OPTIONAL "false,true" (pPhysicalDeviceGroupProperties (:pointer (:struct VkPhysicalDeviceGroupPropertiesKHX)))) ;; :OPTIONAL "true" :LEN "pPhysicalDeviceGroupCount" (cffi:defcfun ("vkEnumeratePhysicalDevices" vkEnumeratePhysicalDevices) VkResult (instance VkInstance) (pPhysicalDeviceCount (:pointer :uint32)) ;; :OPTIONAL "false,true" (pPhysicalDevices (:pointer VkPhysicalDevice))) ;; :OPTIONAL "true" :LEN "pPhysicalDeviceCount" (cffi:defcfun ("vkFlushMappedMemoryRanges" vkFlushMappedMemoryRanges) VkResult (device VkDevice) (memoryRangeCount :uint32) (pMemoryRanges (:pointer (:struct VkMappedMemoryRange)))) ;; :LEN "memoryRangeCount" (cffi:defcfun ("vkFreeCommandBuffers" vkFreeCommandBuffers) :void (device VkDevice) (commandPool VkCommandPool) ;; :EXTERNSYNC "true" (commandBufferCount :uint32) (pCommandBuffers (:pointer VkCommandBuffer))) ;; :LEN "commandBufferCount" :NOAUTOVALIDITY "true" :EXTERNSYNC "true" (cffi:defcfun ("vkFreeDescriptorSets" vkFreeDescriptorSets) VkResult (device VkDevice) (descriptorPool VkDescriptorPool) ;; :EXTERNSYNC "true" (descriptorSetCount :uint32) (pDescriptorSets (:pointer VkDescriptorSet))) ;; :LEN "descriptorSetCount" :NOAUTOVALIDITY "true" :EXTERNSYNC "true" (cffi:defcfun ("vkFreeMemory" vkFreeMemory) :void (device VkDevice) (memory VkDeviceMemory) ;; :OPTIONAL "true" :EXTERNSYNC "true" (pAllocator (:pointer (:struct VkAllocationCallbacks)))) ;; :OPTIONAL "true" (cffi:defcfun ("vkGetBufferMemoryRequirements" vkGetBufferMemoryRequirements) :void (device VkDevice) (buffer VkBuffer) (pMemoryRequirements (:pointer (:struct VkMemoryRequirements)))) (defvkdevextfun ("vkGetDeviceGroupPeerMemoryFeaturesKHX" vkGetDeviceGroupPeerMemoryFeaturesKHX) :void (device VkDevice) (heapIndex :uint32) (localDeviceIndex :uint32) (remoteDeviceIndex :uint32) (pPeerMemoryFeatures (:pointer VkPeerMemoryFeatureFlagsKHX))) (defvkdevextfun ("vkGetDeviceGroupPresentCapabilitiesKHX" vkGetDeviceGroupPresentCapabilitiesKHX) VkResult (device VkDevice) (pDeviceGroupPresentCapabilities (:pointer (:struct VkDeviceGroupPresentCapabilitiesKHX)))) (defvkdevextfun ("vkGetDeviceGroupSurfacePresentModesKHX" vkGetDeviceGroupSurfacePresentModesKHX) VkResult (device VkDevice) (surface VkSurfaceKHR) ;; :EXTERNSYNC "true" (pModes (:pointer VkDeviceGroupPresentModeFlagsKHX))) (cffi:defcfun ("vkGetDeviceMemoryCommitment" vkGetDeviceMemoryCommitment) :void (device VkDevice) (memory VkDeviceMemory) (pCommittedMemoryInBytes (:pointer VkDeviceSize))) (cffi:defcfun ("vkGetDeviceProcAddr" vkGetDeviceProcAddr) PFN_vkVoidFunction (device VkDevice) (pName (:pointer :char))) ;; :LEN "null-terminated" (cffi:defcfun ("vkGetDeviceQueue" vkGetDeviceQueue) :void (device VkDevice) (queueFamilyIndex :uint32) (queueIndex :uint32) (pQueue (:pointer VkQueue))) (cffi:defcfun ("vkGetDisplayModePropertiesKHR" vkGetDisplayModePropertiesKHR) VkResult (physicalDevice VkPhysicalDevice) (display VkDisplayKHR) (pPropertyCount (:pointer :uint32)) ;; :OPTIONAL "false,true" (pProperties (:pointer (:struct VkDisplayModePropertiesKHR)))) ;; :OPTIONAL "true" :LEN "pPropertyCount" (cffi:defcfun ("vkGetDisplayPlaneCapabilitiesKHR" vkGetDisplayPlaneCapabilitiesKHR) VkResult (physicalDevice VkPhysicalDevice) (mode VkDisplayModeKHR) ;; :EXTERNSYNC "true" (planeIndex :uint32) (pCapabilities (:pointer (:struct VkDisplayPlaneCapabilitiesKHR)))) (cffi:defcfun ("vkGetDisplayPlaneSupportedDisplaysKHR" vkGetDisplayPlaneSupportedDisplaysKHR) VkResult (physicalDevice VkPhysicalDevice) (planeIndex :uint32) (pDisplayCount (:pointer :uint32)) ;; :OPTIONAL "false,true" (pDisplays (:pointer VkDisplayKHR))) ;; :OPTIONAL "true" :LEN "pDisplayCount" (cffi:defcfun ("vkGetEventStatus" vkGetEventStatus) VkResult (device VkDevice) (event VkEvent)) (cffi:defcfun ("vkGetFenceStatus" vkGetFenceStatus) VkResult (device VkDevice) (fence VkFence)) (cffi:defcfun ("vkGetImageMemoryRequirements" vkGetImageMemoryRequirements) :void (device VkDevice) (image VkImage) (pMemoryRequirements (:pointer (:struct VkMemoryRequirements)))) (cffi:defcfun ("vkGetImageSparseMemoryRequirements" vkGetImageSparseMemoryRequirements) :void (device VkDevice) (image VkImage) (pSparseMemoryRequirementCount (:pointer :uint32)) ;; :OPTIONAL "false,true" (pSparseMemoryRequirements (:pointer (:struct VkSparseImageMemoryRequirements)))) ;; :OPTIONAL "true" :LEN "pSparseMemoryRequirementCount" (cffi:defcfun ("vkGetImageSubresourceLayout" vkGetImageSubresourceLayout) :void (device VkDevice) (image VkImage) (pSubresource (:pointer (:struct VkImageSubresource))) (pLayout (:pointer (:struct VkSubresourceLayout)))) (cffi:defcfun ("vkGetInstanceProcAddr" vkGetInstanceProcAddr) PFN_vkVoidFunction (instance VkInstance) ;; :OPTIONAL "true" (pName (:pointer :char))) ;; :LEN "null-terminated" (defvkdevextfun ("vkGetMemoryFdKHX" vkGetMemoryFdKHX) VkResult (device VkDevice) (memory VkDeviceMemory) (handleType VkExternalMemoryHandleTypeFlagBitsKHX) (pFd (:pointer :int))) (defvkdevextfun ("vkGetMemoryFdPropertiesKHX" vkGetMemoryFdPropertiesKHX) VkResult (device VkDevice) (handleType VkExternalMemoryHandleTypeFlagBitsKHX) (fd :int) (pMemoryFdProperties (:pointer (:struct VkMemoryFdPropertiesKHX)))) (defvkdevextfun ("vkGetMemoryWin32HandleKHX" vkGetMemoryWin32HandleKHX) VkResult (device VkDevice) (memory VkDeviceMemory) (handleType VkExternalMemoryHandleTypeFlagBitsKHX) (pHandle (:pointer HANDLE))) (defvkdevextfun ("vkGetMemoryWin32HandleNV" vkGetMemoryWin32HandleNV) VkResult (device VkDevice) (memory VkDeviceMemory) (handleType VkExternalMemoryHandleTypeFlagsNV) (pHandle (:pointer HANDLE))) (defvkdevextfun ("vkGetMemoryWin32HandlePropertiesKHX" vkGetMemoryWin32HandlePropertiesKHX) VkResult (device VkDevice) (handleType VkExternalMemoryHandleTypeFlagBitsKHX) (handle HANDLE) (pMemoryWin32HandleProperties (:pointer (:struct VkMemoryWin32HandlePropertiesKHX)))) (defvkdevextfun ("vkGetPastPresentationTimingGOOGLE" vkGetPastPresentationTimingGOOGLE) VkResult (device VkDevice) (swapchain VkSwapchainKHR) ;; :EXTERNSYNC "true" (pPresentationTimingCount (:pointer :uint32)) ;; :OPTIONAL "false,true" (pPresentationTimings (:pointer (:struct VkPastPresentationTimingGOOGLE)))) ;; :OPTIONAL "true" :LEN "pPresentationTimingCount" (cffi:defcfun ("vkGetPhysicalDeviceDisplayPlanePropertiesKHR" vkGetPhysicalDeviceDisplayPlanePropertiesKHR) VkResult (physicalDevice VkPhysicalDevice) (pPropertyCount (:pointer :uint32)) ;; :OPTIONAL "false,true" (pProperties (:pointer (:struct VkDisplayPlanePropertiesKHR)))) ;; :OPTIONAL "true" :LEN "pPropertyCount" (cffi:defcfun ("vkGetPhysicalDeviceDisplayPropertiesKHR" vkGetPhysicalDeviceDisplayPropertiesKHR) VkResult (physicalDevice VkPhysicalDevice) (pPropertyCount (:pointer :uint32)) ;; :OPTIONAL "false,true" (pProperties (:pointer (:struct VkDisplayPropertiesKHR)))) ;; :OPTIONAL "true" :LEN "pPropertyCount" (defvkinstextfun ("vkGetPhysicalDeviceExternalBufferPropertiesKHX" vkGetPhysicalDeviceExternalBufferPropertiesKHX) :void (physicalDevice VkPhysicalDevice) (pExternalBufferInfo (:pointer (:struct VkPhysicalDeviceExternalBufferInfoKHX))) (pExternalBufferProperties (:pointer (:struct VkExternalBufferPropertiesKHX)))) (defvkinstextfun ("vkGetPhysicalDeviceExternalImageFormatPropertiesNV" vkGetPhysicalDeviceExternalImageFormatPropertiesNV) VkResult (physicalDevice VkPhysicalDevice) (format VkFormat) (type VkImageType) (tiling VkImageTiling) (usage VkImageUsageFlags) (flags VkImageCreateFlags) ;; :OPTIONAL "true" (externalHandleType VkExternalMemoryHandleTypeFlagsNV) ;; :OPTIONAL "true" (pExternalImageFormatProperties (:pointer (:struct VkExternalImageFormatPropertiesNV)))) (defvkinstextfun ("vkGetPhysicalDeviceExternalSemaphorePropertiesKHX" vkGetPhysicalDeviceExternalSemaphorePropertiesKHX) :void (physicalDevice VkPhysicalDevice) (pExternalSemaphoreInfo (:pointer (:struct VkPhysicalDeviceExternalSemaphoreInfoKHX))) (pExternalSemaphoreProperties (:pointer (:struct VkExternalSemaphorePropertiesKHX)))) (cffi:defcfun ("vkGetPhysicalDeviceFeatures" vkGetPhysicalDeviceFeatures) :void (physicalDevice VkPhysicalDevice) (pFeatures (:pointer (:struct VkPhysicalDeviceFeatures)))) (defvkinstextfun ("vkGetPhysicalDeviceFeatures2KHR" vkGetPhysicalDeviceFeatures2KHR) :void (physicalDevice VkPhysicalDevice) (pFeatures (:pointer (:struct VkPhysicalDeviceFeatures2KHR)))) (cffi:defcfun ("vkGetPhysicalDeviceFormatProperties" vkGetPhysicalDeviceFormatProperties) :void (physicalDevice VkPhysicalDevice) (format VkFormat) (pFormatProperties (:pointer (:struct VkFormatProperties)))) (defvkinstextfun ("vkGetPhysicalDeviceFormatProperties2KHR" vkGetPhysicalDeviceFormatProperties2KHR) :void (physicalDevice VkPhysicalDevice) (format VkFormat) (pFormatProperties (:pointer (:struct VkFormatProperties2KHR)))) (defvkdevextfun ("vkGetPhysicalDeviceGeneratedCommandsPropertiesNVX" vkGetPhysicalDeviceGeneratedCommandsPropertiesNVX) :void (physicalDevice VkPhysicalDevice) (pFeatures (:pointer (:struct VkDeviceGeneratedCommandsFeaturesNVX))) (pLimits (:pointer (:struct VkDeviceGeneratedCommandsLimitsNVX)))) (cffi:defcfun ("vkGetPhysicalDeviceImageFormatProperties" vkGetPhysicalDeviceImageFormatProperties) VkResult (physicalDevice VkPhysicalDevice) (format VkFormat) (type VkImageType) (tiling VkImageTiling) (usage VkImageUsageFlags) (flags VkImageCreateFlags) ;; :OPTIONAL "true" (pImageFormatProperties (:pointer (:struct VkImageFormatProperties)))) (defvkinstextfun ("vkGetPhysicalDeviceImageFormatProperties2KHR" vkGetPhysicalDeviceImageFormatProperties2KHR) VkResult (physicalDevice VkPhysicalDevice) (pImageFormatInfo (:pointer (:struct VkPhysicalDeviceImageFormatInfo2KHR))) (pImageFormatProperties (:pointer (:struct VkImageFormatProperties2KHR)))) (cffi:defcfun ("vkGetPhysicalDeviceMemoryProperties" vkGetPhysicalDeviceMemoryProperties) :void (physicalDevice VkPhysicalDevice) (pMemoryProperties (:pointer (:struct VkPhysicalDeviceMemoryProperties)))) (defvkinstextfun ("vkGetPhysicalDeviceMemoryProperties2KHR" vkGetPhysicalDeviceMemoryProperties2KHR) :void (physicalDevice VkPhysicalDevice) (pMemoryProperties (:pointer (:struct VkPhysicalDeviceMemoryProperties2KHR)))) (defvkinstextfun ("vkGetPhysicalDeviceMirPresentationSupportKHR" vkGetPhysicalDeviceMirPresentationSupportKHR) VkBool32 (physicalDevice VkPhysicalDevice) (queueFamilyIndex :uint32) (connection (:pointer MirConnection))) (defvkdevextfun ("vkGetPhysicalDevicePresentRectanglesKHX" vkGetPhysicalDevicePresentRectanglesKHX) VkResult (physicalDevice VkPhysicalDevice) (surface VkSurfaceKHR) ;; :EXTERNSYNC "true" (pRectCount (:pointer :uint32)) ;; :OPTIONAL "false,true" (pRects (:pointer (:struct VkRect2D)))) ;; :OPTIONAL "true" :LEN "pRectCount" (cffi:defcfun ("vkGetPhysicalDeviceProperties" vkGetPhysicalDeviceProperties) :void (physicalDevice VkPhysicalDevice) (pProperties (:pointer (:struct VkPhysicalDeviceProperties)))) (defvkinstextfun ("vkGetPhysicalDeviceProperties2KHR" vkGetPhysicalDeviceProperties2KHR) :void (physicalDevice VkPhysicalDevice) (pProperties (:pointer (:struct VkPhysicalDeviceProperties2KHR)))) (cffi:defcfun ("vkGetPhysicalDeviceQueueFamilyProperties" vkGetPhysicalDeviceQueueFamilyProperties) :void (physicalDevice VkPhysicalDevice) (pQueueFamilyPropertyCount (:pointer :uint32)) ;; :OPTIONAL "false,true" (pQueueFamilyProperties (:pointer (:struct VkQueueFamilyProperties)))) ;; :OPTIONAL "true" :LEN "pQueueFamilyPropertyCount" (defvkinstextfun ("vkGetPhysicalDeviceQueueFamilyProperties2KHR" vkGetPhysicalDeviceQueueFamilyProperties2KHR) :void (physicalDevice VkPhysicalDevice) (pQueueFamilyPropertyCount (:pointer :uint32)) ;; :OPTIONAL "false,true" (pQueueFamilyProperties (:pointer (:struct VkQueueFamilyProperties2KHR)))) ;; :OPTIONAL "true" :LEN "pQueueFamilyPropertyCount" (cffi:defcfun ("vkGetPhysicalDeviceSparseImageFormatProperties" vkGetPhysicalDeviceSparseImageFormatProperties) :void (physicalDevice VkPhysicalDevice) (format VkFormat) (type VkImageType) (samples VkSampleCountFlagBits) (usage VkImageUsageFlags) (tiling VkImageTiling) (pPropertyCount (:pointer :uint32)) ;; :OPTIONAL "false,true" (pProperties (:pointer (:struct VkSparseImageFormatProperties)))) ;; :OPTIONAL "true" :LEN "pPropertyCount" (defvkinstextfun ("vkGetPhysicalDeviceSparseImageFormatProperties2KHR" vkGetPhysicalDeviceSparseImageFormatProperties2KHR) :void (physicalDevice VkPhysicalDevice) (pFormatInfo (:pointer (:struct VkPhysicalDeviceSparseImageFormatInfo2KHR))) (pPropertyCount (:pointer :uint32)) ;; :OPTIONAL "false,true" (pProperties (:pointer (:struct VkSparseImageFormatProperties2KHR)))) ;; :OPTIONAL "true" :LEN "pPropertyCount" (defvkinstextfun ("vkGetPhysicalDeviceSurfaceCapabilities2EXT" vkGetPhysicalDeviceSurfaceCapabilities2EXT) VkResult (physicalDevice VkPhysicalDevice) (surface VkSurfaceKHR) (pSurfaceCapabilities (:pointer (:struct VkSurfaceCapabilities2EXT)))) (defvkinstextfun ("vkGetPhysicalDeviceSurfaceCapabilities2KHR" vkGetPhysicalDeviceSurfaceCapabilities2KHR) VkResult (physicalDevice VkPhysicalDevice) (pSurfaceInfo (:pointer (:struct VkPhysicalDeviceSurfaceInfo2KHR))) (pSurfaceCapabilities (:pointer (:struct VkSurfaceCapabilities2KHR)))) (cffi:defcfun ("vkGetPhysicalDeviceSurfaceCapabilitiesKHR" vkGetPhysicalDeviceSurfaceCapabilitiesKHR) VkResult (physicalDevice VkPhysicalDevice) (surface VkSurfaceKHR) (pSurfaceCapabilities (:pointer (:struct VkSurfaceCapabilitiesKHR)))) (defvkinstextfun ("vkGetPhysicalDeviceSurfaceFormats2KHR" vkGetPhysicalDeviceSurfaceFormats2KHR) VkResult (physicalDevice VkPhysicalDevice) (pSurfaceInfo (:pointer (:struct VkPhysicalDeviceSurfaceInfo2KHR))) (pSurfaceFormatCount (:pointer :uint32)) ;; :OPTIONAL "false,true" (pSurfaceFormats (:pointer (:struct VkSurfaceFormat2KHR)))) ;; :OPTIONAL "true" :LEN "pSurfaceFormatCount" (cffi:defcfun ("vkGetPhysicalDeviceSurfaceFormatsKHR" vkGetPhysicalDeviceSurfaceFormatsKHR) VkResult (physicalDevice VkPhysicalDevice) (surface VkSurfaceKHR) (pSurfaceFormatCount (:pointer :uint32)) ;; :OPTIONAL "false,true" (pSurfaceFormats (:pointer (:struct VkSurfaceFormatKHR)))) ;; :OPTIONAL "true" :LEN "pSurfaceFormatCount" (cffi:defcfun ("vkGetPhysicalDeviceSurfacePresentModesKHR" vkGetPhysicalDeviceSurfacePresentModesKHR) VkResult (physicalDevice VkPhysicalDevice) (surface VkSurfaceKHR) (pPresentModeCount (:pointer :uint32)) ;; :OPTIONAL "false,true" (pPresentModes (:pointer VkPresentModeKHR))) ;; :OPTIONAL "true" :LEN "pPresentModeCount" (cffi:defcfun ("vkGetPhysicalDeviceSurfaceSupportKHR" vkGetPhysicalDeviceSurfaceSupportKHR) VkResult (physicalDevice VkPhysicalDevice) (queueFamilyIndex :uint32) (surface VkSurfaceKHR) (pSupported (:pointer VkBool32))) (defvkinstextfun ("vkGetPhysicalDeviceWaylandPresentationSupportKHR" vkGetPhysicalDeviceWaylandPresentationSupportKHR) VkBool32 (physicalDevice VkPhysicalDevice) (queueFamilyIndex :uint32) (display (:pointer (:struct wl_display)))) (cffi:defcfun ("vkGetPhysicalDeviceWin32PresentationSupportKHR" vkGetPhysicalDeviceWin32PresentationSupportKHR) VkBool32 (physicalDevice VkPhysicalDevice) (queueFamilyIndex :uint32)) (defvkinstextfun ("vkGetPhysicalDeviceXlibPresentationSupportKHR" vkGetPhysicalDeviceXlibPresentationSupportKHR) VkBool32 (physicalDevice VkPhysicalDevice) (queueFamilyIndex :uint32) (dpy (:pointer Display)) (visualID VisualID)) (cffi:defcfun ("vkGetPipelineCacheData" vkGetPipelineCacheData) VkResult (device VkDevice) (pipelineCache VkPipelineCache) (pDataSize (:pointer size-t)) ;; :OPTIONAL "false,true" (pData (:pointer :void))) ;; :OPTIONAL "true" :LEN "pDataSize" (cffi:defcfun ("vkGetQueryPoolResults" vkGetQueryPoolResults) VkResult (device VkDevice) (queryPool VkQueryPool) (firstQuery :uint32) (queryCount :uint32) (dataSize size-t) (pData (:pointer :void)) ;; :LEN "dataSize" (stride VkDeviceSize) (flags VkQueryResultFlags)) ;; :OPTIONAL "true" (defvkinstextfun ("vkGetRandROutputDisplayEXT" vkGetRandROutputDisplayEXT) VkResult (physicalDevice VkPhysicalDevice) (dpy (:pointer Display)) (rrOutput RROutput) (pDisplay (:pointer VkDisplayKHR))) (defvkdevextfun ("vkGetRefreshCycleDurationGOOGLE" vkGetRefreshCycleDurationGOOGLE) VkResult (device VkDevice) (swapchain VkSwapchainKHR) ;; :EXTERNSYNC "true" (pDisplayTimingProperties (:pointer (:struct VkRefreshCycleDurationGOOGLE)))) (cffi:defcfun ("vkGetRenderAreaGranularity" vkGetRenderAreaGranularity) :void (device VkDevice) (renderPass VkRenderPass) (pGranularity (:pointer (:struct VkExtent2D)))) (defvkdevextfun ("vkGetSemaphoreFdKHX" vkGetSemaphoreFdKHX) VkResult (device VkDevice) (semaphore VkSemaphore) (handleType VkExternalSemaphoreHandleTypeFlagBitsKHX) (pFd (:pointer :int))) (defvkdevextfun ("vkGetSemaphoreWin32HandleKHX" vkGetSemaphoreWin32HandleKHX) VkResult (device VkDevice) (semaphore VkSemaphore) (handleType VkExternalSemaphoreHandleTypeFlagBitsKHX) (pHandle (:pointer HANDLE))) (defvkdevextfun ("vkGetSwapchainCounterEXT" vkGetSwapchainCounterEXT) VkResult (device VkDevice) (swapchain VkSwapchainKHR) (counter VkSurfaceCounterFlagBitsEXT) (pCounterValue (:pointer :uint64))) (cffi:defcfun ("vkGetSwapchainImagesKHR" vkGetSwapchainImagesKHR) VkResult (device VkDevice) (swapchain VkSwapchainKHR) (pSwapchainImageCount (:pointer :uint32)) ;; :OPTIONAL "false,true" (pSwapchainImages (:pointer VkImage))) ;; :OPTIONAL "true" :LEN "pSwapchainImageCount" (defvkdevextfun ("vkGetSwapchainStatusKHR" vkGetSwapchainStatusKHR) VkResult (device VkDevice) (swapchain VkSwapchainKHR)) ;; :EXTERNSYNC "true" (defvkdevextfun ("vkImportSemaphoreFdKHX" vkImportSemaphoreFdKHX) VkResult (device VkDevice) (pImportSemaphoreFdInfo (:pointer (:struct VkImportSemaphoreFdInfoKHX)))) (defvkdevextfun ("vkImportSemaphoreWin32HandleKHX" vkImportSemaphoreWin32HandleKHX) VkResult (device VkDevice) (pImportSemaphoreWin32HandleInfo (:pointer (:struct VkImportSemaphoreWin32HandleInfoKHX)))) (cffi:defcfun ("vkInvalidateMappedMemoryRanges" vkInvalidateMappedMemoryRanges) VkResult (device VkDevice) (memoryRangeCount :uint32) (pMemoryRanges (:pointer (:struct VkMappedMemoryRange)))) ;; :LEN "memoryRangeCount" (cffi:defcfun ("vkMapMemory" vkMapMemory) VkResult (device VkDevice) (memory VkDeviceMemory) ;; :EXTERNSYNC "true" (offset VkDeviceSize) (size VkDeviceSize) (flags VkMemoryMapFlags) ;; :OPTIONAL "true" (ppData (:pointer (:pointer :void)))) (cffi:defcfun ("vkMergePipelineCaches" vkMergePipelineCaches) VkResult (device VkDevice) (dstCache VkPipelineCache) ;; :EXTERNSYNC "true" (srcCacheCount :uint32) (pSrcCaches (:pointer VkPipelineCache))) ;; :LEN "srcCacheCount" (cffi:defcfun ("vkQueueBindSparse" vkQueueBindSparse) VkResult (queue VkQueue) ;; :EXTERNSYNC "true" (bindInfoCount :uint32) ;; :OPTIONAL "true" (pBindInfo (:pointer (:struct VkBindSparseInfo))) ;; :LEN "bindInfoCount" :EXTERNSYNC "pBindInfo[].pWaitSemaphores[],pBindInfo[].pSignalSemaphores[],pBindInfo[].pBufferBinds[].buffer,pBindInfo[].pImageOpaqueBinds[].image,pBindInfo[].pImageBinds[].image" (fence VkFence)) ;; :OPTIONAL "true" :EXTERNSYNC "true" (cffi:defcfun ("vkQueuePresentKHR" vkQueuePresentKHR) VkResult (queue VkQueue) ;; :EXTERNSYNC "true" (pPresentInfo (:pointer (:struct VkPresentInfoKHR)))) ;; :EXTERNSYNC "pPresentInfo.pWaitSemaphores[],pPresentInfo.pSwapchains[]" (cffi:defcfun ("vkQueueSubmit" vkQueueSubmit) VkResult (queue VkQueue) ;; :EXTERNSYNC "true" (submitCount :uint32) ;; :OPTIONAL "true" (pSubmits (:pointer (:struct VkSubmitInfo))) ;; :LEN "submitCount" :EXTERNSYNC "pSubmits[].pWaitSemaphores[],pSubmits[].pSignalSemaphores[]" (fence VkFence)) ;; :OPTIONAL "true" :EXTERNSYNC "true" (cffi:defcfun ("vkQueueWaitIdle" vkQueueWaitIdle) VkResult (queue VkQueue)) (defvkdevextfun ("vkRegisterDeviceEventEXT" vkRegisterDeviceEventEXT) VkResult (device VkDevice) (pDeviceEventInfo (:pointer (:struct VkDeviceEventInfoEXT))) (pAllocator (:pointer (:struct VkAllocationCallbacks))) (pFence (:pointer VkFence))) (defvkdevextfun ("vkRegisterDisplayEventEXT" vkRegisterDisplayEventEXT) VkResult (device VkDevice) (display VkDisplayKHR) (pDisplayEventInfo (:pointer (:struct VkDisplayEventInfoEXT))) (pAllocator (:pointer (:struct VkAllocationCallbacks))) (pFence (:pointer VkFence))) (defvkdevextfun ("vkRegisterObjectsNVX" vkRegisterObjectsNVX) VkResult (device VkDevice) (objectTable VkObjectTableNVX) ;; :EXTERNSYNC "true" (objectCount :uint32) (ppObjectTableEntries (:pointer (:pointer (:struct VkObjectTableEntryNVX)))) ;; :LEN "objectCount" (pObjectIndices (:pointer :uint32))) ;; :LEN "objectCount" (defvkinstextfun ("vkReleaseDisplayEXT" vkReleaseDisplayEXT) VkResult (physicalDevice VkPhysicalDevice) (display VkDisplayKHR)) (cffi:defcfun ("vkResetCommandBuffer" vkResetCommandBuffer) VkResult (commandBuffer VkCommandBuffer) ;; :EXTERNSYNC "true" (flags VkCommandBufferResetFlags)) ;; :OPTIONAL "true" (cffi:defcfun ("vkResetCommandPool" vkResetCommandPool) VkResult (device VkDevice) (commandPool VkCommandPool) ;; :EXTERNSYNC "true" (flags VkCommandPoolResetFlags)) ;; :OPTIONAL "true" (cffi:defcfun ("vkResetDescriptorPool" vkResetDescriptorPool) VkResult (device VkDevice) (descriptorPool VkDescriptorPool) ;; :EXTERNSYNC "true" (flags VkDescriptorPoolResetFlags)) ;; :OPTIONAL "true" (cffi:defcfun ("vkResetEvent" vkResetEvent) VkResult (device VkDevice) (event VkEvent)) ;; :EXTERNSYNC "true" (cffi:defcfun ("vkResetFences" vkResetFences) VkResult (device VkDevice) (fenceCount :uint32) (pFences (:pointer VkFence))) ;; :LEN "fenceCount" :EXTERNSYNC "true" (cffi:defcfun ("vkSetEvent" vkSetEvent) VkResult (device VkDevice) (event VkEvent)) ;; :EXTERNSYNC "true" (defvkdevextfun ("vkSetHdrMetadataEXT" vkSetHdrMetadataEXT) :void (device VkDevice) (swapchainCount :uint32) (pSwapchains (:pointer VkSwapchainKHR)) ;; :LEN "swapchainCount" (pMetadata (:pointer (:struct VkHdrMetadataEXT)))) ;; :LEN "swapchainCount" (defvkdevextfun ("vkTrimCommandPoolKHR" vkTrimCommandPoolKHR) :void (device VkDevice) (commandPool VkCommandPool) ;; :EXTERNSYNC "true" (flags VkCommandPoolTrimFlagsKHR)) ;; :OPTIONAL "true" (cffi:defcfun ("vkUnmapMemory" vkUnmapMemory) :void (device VkDevice) (memory VkDeviceMemory)) ;; :EXTERNSYNC "true" (defvkdevextfun ("vkUnregisterObjectsNVX" vkUnregisterObjectsNVX) VkResult (device VkDevice) (objectTable VkObjectTableNVX) ;; :EXTERNSYNC "true" (objectCount :uint32) (pObjectEntryTypes (:pointer VkObjectEntryTypeNVX)) ;; :LEN "objectCount" (pObjectIndices (:pointer :uint32))) ;; :LEN "objectCount" (defvkdevextfun ("vkUpdateDescriptorSetWithTemplateKHR" vkUpdateDescriptorSetWithTemplateKHR) :void (device VkDevice) (descriptorSet VkDescriptorSet) ;; :EXTERNSYNC "true" (descriptorUpdateTemplate VkDescriptorUpdateTemplateKHR) (pData (:pointer :void))) (cffi:defcfun ("vkUpdateDescriptorSets" vkUpdateDescriptorSets) :void (device VkDevice) (descriptorWriteCount :uint32) ;; :OPTIONAL "true" (pDescriptorWrites (:pointer (:struct VkWriteDescriptorSet))) ;; :LEN "descriptorWriteCount" :EXTERNSYNC "pDescriptorWrites[].dstSet" (descriptorCopyCount :uint32) ;; :OPTIONAL "true" (pDescriptorCopies (:pointer (:struct VkCopyDescriptorSet)))) ;; :LEN "descriptorCopyCount" :EXTERNSYNC "pDescriptorCopies[].dstSet" (cffi:defcfun ("vkWaitForFences" vkWaitForFences) VkResult (device VkDevice) (fenceCount :uint32) (pFences (:pointer VkFence)) ;; :LEN "fenceCount" (waitAll VkBool32) (timeout :uint64))
63926
;;; this file is automatically generated, do not edit #|| "Copyright (c) 2015-2017 The Khronos Group Inc. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and/or associated documentation files (the \"Materials\"), to deal in the Materials without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Materials, and to permit persons to whom the Materials are 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 Materials. THE MATERIALS ARE 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 MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS. ------------------------------------------------------------------------" ||# ;; Changes (into Lisp) Copyright 2019 <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 :cvk) (defvkdevextfun ("vkAcquireNextImage2KHX" vkAcquireNextImage2KHX) VkResult (device VkDevice) (pAcquireInfo (:pointer (:struct VkAcquireNextImageInfoKHX))) (pImageIndex (:pointer :uint32))) (cffi:defcfun ("vkAcquireNextImageKHR" vkAcquireNextImageKHR) VkResult (device VkDevice) (swapchain VkSwapchainKHR) ;; :EXTERNSYNC "true" (timeout :uint64) (semaphore VkSemaphore) ;; :OPTIONAL "true" :EXTERNSYNC "true" (fence VkFence) ;; :OPTIONAL "true" :EXTERNSYNC "true" (pImageIndex (:pointer :uint32))) (defvkinstextfun ("vkAcquireXlibDisplayEXT" vkAcquireXlibDisplayEXT) VkResult (physicalDevice VkPhysicalDevice) (dpy (:pointer Display)) (display VkDisplayKHR)) (cffi:defcfun ("vkAllocateCommandBuffers" vkAllocateCommandBuffers) VkResult (device VkDevice) (pAllocateInfo (:pointer (:struct VkCommandBufferAllocateInfo))) ;; :EXTERNSYNC "pAllocateInfo::commandPool" (pCommandBuffers (:pointer VkCommandBuffer))) ;; :LEN "pAllocateInfo::commandBufferCount" (cffi:defcfun ("vkAllocateDescriptorSets" vkAllocateDescriptorSets) VkResult (device VkDevice) (pAllocateInfo (:pointer (:struct VkDescriptorSetAllocateInfo))) ;; :EXTERNSYNC "pAllocateInfo::descriptorPool" (pDescriptorSets (:pointer VkDescriptorSet))) ;; :LEN "pAllocateInfo::descriptorSetCount" (cffi:defcfun ("vkAllocateMemory" vkAllocateMemory) VkResult (device VkDevice) (pAllocateInfo (:pointer (:struct VkMemoryAllocateInfo))) (pAllocator (:pointer (:struct VkAllocationCallbacks))) ;; :OPTIONAL "true" (pMemory (:pointer VkDeviceMemory))) (cffi:defcfun ("vkBeginCommandBuffer" vkBeginCommandBuffer) VkResult (commandBuffer VkCommandBuffer) ;; :EXTERNSYNC "true" (pBeginInfo (:pointer (:struct VkCommandBufferBeginInfo)))) (cffi:defcfun ("vkBindBufferMemory" vkBindBufferMemory) VkResult (device VkDevice) (buffer VkBuffer) ;; :EXTERNSYNC "true" (memory VkDeviceMemory) (memoryOffset VkDeviceSize)) (defvkdevextfun ("vkBindBufferMemory2KHX" vkBindBufferMemory2KHX) VkResult (device VkDevice) (bindInfoCount :uint32) (pBindInfos (:pointer (:struct VkBindBufferMemoryInfoKHX)))) ;; :LEN "bindInfoCount" (cffi:defcfun ("vkBindImageMemory" vkBindImageMemory) VkResult (device VkDevice) (image VkImage) ;; :EXTERNSYNC "true" (memory VkDeviceMemory) (memoryOffset VkDeviceSize)) (defvkdevextfun ("vkBindImageMemory2KHX" vkBindImageMemory2KHX) VkResult (device VkDevice) (bindInfoCount :uint32) (pBindInfos (:pointer (:struct VkBindImageMemoryInfoKHX)))) ;; :LEN "bindInfoCount" (cffi:defcfun ("vkCmdBeginQuery" vkCmdBeginQuery) :void (commandBuffer VkCommandBuffer) ;; :EXTERNSYNC "true" (queryPool VkQueryPool) (query :uint32) (flags VkQueryControlFlags)) ;; :OPTIONAL "true" (cffi:defcfun ("vkCmdBeginRenderPass" vkCmdBeginRenderPass) :void (commandBuffer VkCommandBuffer) ;; :EXTERNSYNC "true" (pRenderPassBegin (:pointer (:struct VkRenderPassBeginInfo))) (contents VkSubpassContents)) (cffi:defcfun ("vkCmdBindDescriptorSets" vkCmdBindDescriptorSets) :void (commandBuffer VkCommandBuffer) ;; :EXTERNSYNC "true" (pipelineBindPoint VkPipelineBindPoint) (layout VkPipelineLayout) (firstSet :uint32) (descriptorSetCount :uint32) (pDescriptorSets (:pointer VkDescriptorSet)) ;; :LEN "descriptorSetCount" (dynamicOffsetCount :uint32) ;; :OPTIONAL "true" (pDynamicOffsets (:pointer :uint32))) ;; :LEN "dynamicOffsetCount" (cffi:defcfun ("vkCmdBindIndexBuffer" vkCmdBindIndexBuffer) :void (commandBuffer VkCommandBuffer) ;; :EXTERNSYNC "true" (buffer VkBuffer) (offset VkDeviceSize) (indexType VkIndexType)) (cffi:defcfun ("vkCmdBindPipeline" vkCmdBindPipeline) :void (commandBuffer VkCommandBuffer) ;; :EXTERNSYNC "true" (pipelineBindPoint VkPipelineBindPoint) (pipeline VkPipeline)) (cffi:defcfun ("vkCmdBindVertexBuffers" vkCmdBindVertexBuffers) :void (commandBuffer VkCommandBuffer) ;; :EXTERNSYNC "true" (firstBinding :uint32) (bindingCount :uint32) (pBuffers (:pointer VkBuffer)) ;; :LEN "bindingCount" (pOffsets (:pointer VkDeviceSize))) ;; :LEN "bindingCount" (cffi:defcfun ("vkCmdBlitImage" vkCmdBlitImage) :void (commandBuffer VkCommandBuffer) ;; :EXTERNSYNC "true" (srcImage VkImage) (srcImageLayout VkImageLayout) (dstImage VkImage) (dstImageLayout VkImageLayout) (regionCount :uint32) (pRegions (:pointer (:struct VkImageBlit))) ;; :LEN "regionCount" (filter VkFilter)) (cffi:defcfun ("vkCmdClearAttachments" vkCmdClearAttachments) :void (commandBuffer VkCommandBuffer) ;; :EXTERNSYNC "true" (attachmentCount :uint32) (pAttachments (:pointer (:struct VkClearAttachment))) ;; :LEN "attachmentCount" (rectCount :uint32) (pRects (:pointer (:struct VkClearRect)))) ;; :LEN "rectCount" (cffi:defcfun ("vkCmdClearColorImage" vkCmdClearColorImage) :void (commandBuffer VkCommandBuffer) ;; :EXTERNSYNC "true" (image VkImage) (imageLayout VkImageLayout) (pColor (:pointer (:union VkClearColorValue))) (rangeCount :uint32) (pRanges (:pointer (:struct VkImageSubresourceRange)))) ;; :LEN "rangeCount" (cffi:defcfun ("vkCmdClearDepthStencilImage" vkCmdClearDepthStencilImage) :void (commandBuffer VkCommandBuffer) ;; :EXTERNSYNC "true" (image VkImage) (imageLayout VkImageLayout) (pDepthStencil (:pointer (:struct VkClearDepthStencilValue))) (rangeCount :uint32) (pRanges (:pointer (:struct VkImageSubresourceRange)))) ;; :LEN "rangeCount" (cffi:defcfun ("vkCmdCopyBuffer" vkCmdCopyBuffer) :void (commandBuffer VkCommandBuffer) ;; :EXTERNSYNC "true" (srcBuffer VkBuffer) (dstBuffer VkBuffer) (regionCount :uint32) (pRegions (:pointer (:struct VkBufferCopy)))) ;; :LEN "regionCount" (cffi:defcfun ("vkCmdCopyBufferToImage" vkCmdCopyBufferToImage) :void (commandBuffer VkCommandBuffer) ;; :EXTERNSYNC "true" (srcBuffer VkBuffer) (dstImage VkImage) (dstImageLayout VkImageLayout) (regionCount :uint32) (pRegions (:pointer (:struct VkBufferImageCopy)))) ;; :LEN "regionCount" (cffi:defcfun ("vkCmdCopyImage" vkCmdCopyImage) :void (commandBuffer VkCommandBuffer) ;; :EXTERNSYNC "true" (srcImage VkImage) (srcImageLayout VkImageLayout) (dstImage VkImage) (dstImageLayout VkImageLayout) (regionCount :uint32) (pRegions (:pointer (:struct VkImageCopy)))) ;; :LEN "regionCount" (cffi:defcfun ("vkCmdCopyImageToBuffer" vkCmdCopyImageToBuffer) :void (commandBuffer VkCommandBuffer) ;; :EXTERNSYNC "true" (srcImage VkImage) (srcImageLayout VkImageLayout) (dstBuffer VkBuffer) (regionCount :uint32) (pRegions (:pointer (:struct VkBufferImageCopy)))) ;; :LEN "regionCount" (cffi:defcfun ("vkCmdCopyQueryPoolResults" vkCmdCopyQueryPoolResults) :void (commandBuffer VkCommandBuffer) ;; :EXTERNSYNC "true" (queryPool VkQueryPool) (firstQuery :uint32) (queryCount :uint32) (dstBuffer VkBuffer) (dstOffset VkDeviceSize) (stride VkDeviceSize) (flags VkQueryResultFlags)) ;; :OPTIONAL "true" (defvkdevextfun ("vkCmdDebugMarkerBeginEXT" vkCmdDebugMarkerBeginEXT) :void (commandBuffer VkCommandBuffer) (pMarkerInfo (:pointer (:struct VkDebugMarkerMarkerInfoEXT)))) (defvkdevextfun ("vkCmdDebugMarkerEndEXT" vkCmdDebugMarkerEndEXT) :void (commandBuffer VkCommandBuffer)) (defvkdevextfun ("vkCmdDebugMarkerInsertEXT" vkCmdDebugMarkerInsertEXT) :void (commandBuffer VkCommandBuffer) (pMarkerInfo (:pointer (:struct VkDebugMarkerMarkerInfoEXT)))) (cffi:defcfun ("vkCmdDispatch" vkCmdDispatch) :void (commandBuffer VkCommandBuffer) ;; :EXTERNSYNC "true" (groupCountX :uint32) (groupCountY :uint32) (groupCountZ :uint32)) (defvkdevextfun ("vkCmdDispatchBaseKHX" vkCmdDispatchBaseKHX) :void (commandBuffer VkCommandBuffer) ;; :EXTERNSYNC "true" (baseGroupX :uint32) (baseGroupY :uint32) (baseGroupZ :uint32) (groupCountX :uint32) (groupCountY :uint32) (groupCountZ :uint32)) (cffi:defcfun ("vkCmdDispatchIndirect" vkCmdDispatchIndirect) :void (commandBuffer VkCommandBuffer) ;; :EXTERNSYNC "true" (buffer VkBuffer) (offset VkDeviceSize)) (cffi:defcfun ("vkCmdDraw" vkCmdDraw) :void (commandBuffer VkCommandBuffer) ;; :EXTERNSYNC "true" (vertexCount :uint32) (instanceCount :uint32) (firstVertex :uint32) (firstInstance :uint32)) (cffi:defcfun ("vkCmdDrawIndexed" vkCmdDrawIndexed) :void (commandBuffer VkCommandBuffer) ;; :EXTERNSYNC "true" (indexCount :uint32) (instanceCount :uint32) (firstIndex :uint32) (vertexOffset :int32) (firstInstance :uint32)) (cffi:defcfun ("vkCmdDrawIndexedIndirect" vkCmdDrawIndexedIndirect) :void (commandBuffer VkCommandBuffer) ;; :EXTERNSYNC "true" (buffer VkBuffer) (offset VkDeviceSize) (drawCount :uint32) (stride :uint32)) (defvkdevextfun ("vkCmdDrawIndexedIndirectCountAMD" vkCmdDrawIndexedIndirectCountAMD) :void (commandBuffer VkCommandBuffer) ;; :EXTERNSYNC "true" (buffer VkBuffer) (offset VkDeviceSize) (countBuffer VkBuffer) (countBufferOffset VkDeviceSize) (maxDrawCount :uint32) (stride :uint32)) (cffi:defcfun ("vkCmdDrawIndirect" vkCmdDrawIndirect) :void (commandBuffer VkCommandBuffer) ;; :EXTERNSYNC "true" (buffer VkBuffer) (offset VkDeviceSize) (drawCount :uint32) (stride :uint32)) (defvkdevextfun ("vkCmdDrawIndirectCountAMD" vkCmdDrawIndirectCountAMD) :void (commandBuffer VkCommandBuffer) ;; :EXTERNSYNC "true" (buffer VkBuffer) (offset VkDeviceSize) (countBuffer VkBuffer) (countBufferOffset VkDeviceSize) (maxDrawCount :uint32) (stride :uint32)) (cffi:defcfun ("vkCmdEndQuery" vkCmdEndQuery) :void (commandBuffer VkCommandBuffer) ;; :EXTERNSYNC "true" (queryPool VkQueryPool) (query :uint32)) (cffi:defcfun ("vkCmdEndRenderPass" vkCmdEndRenderPass) :void (commandBuffer VkCommandBuffer)) ;; :EXTERNSYNC "true" (cffi:defcfun ("vkCmdExecuteCommands" vkCmdExecuteCommands) :void (commandBuffer VkCommandBuffer) ;; :EXTERNSYNC "true" (commandBufferCount :uint32) (pCommandBuffers (:pointer VkCommandBuffer))) ;; :LEN "commandBufferCount" (cffi:defcfun ("vkCmdFillBuffer" vkCmdFillBuffer) :void (commandBuffer VkCommandBuffer) ;; :EXTERNSYNC "true" (dstBuffer VkBuffer) (dstOffset VkDeviceSize) (size VkDeviceSize) (data :uint32)) (cffi:defcfun ("vkCmdNextSubpass" vkCmdNextSubpass) :void (commandBuffer VkCommandBuffer) ;; :EXTERNSYNC "true" (contents VkSubpassContents)) (cffi:defcfun ("vkCmdPipelineBarrier" vkCmdPipelineBarrier) :void (commandBuffer VkCommandBuffer) ;; :EXTERNSYNC "true" (srcStageMask VkPipelineStageFlags) (dstStageMask VkPipelineStageFlags) (dependencyFlags VkDependencyFlags) ;; :OPTIONAL "true" (memoryBarrierCount :uint32) ;; :OPTIONAL "true" (pMemoryBarriers (:pointer (:struct VkMemoryBarrier))) ;; :LEN "memoryBarrierCount" (bufferMemoryBarrierCount :uint32) ;; :OPTIONAL "true" (pBufferMemoryBarriers (:pointer (:struct VkBufferMemoryBarrier))) ;; :LEN "bufferMemoryBarrierCount" (imageMemoryBarrierCount :uint32) ;; :OPTIONAL "true" (pImageMemoryBarriers (:pointer (:struct VkImageMemoryBarrier)))) ;; :LEN "imageMemoryBarrierCount" (defvkdevextfun ("vkCmdProcessCommandsNVX" vkCmdProcessCommandsNVX) :void (commandBuffer VkCommandBuffer) ;; :EXTERNSYNC "true" (pProcessCommandsInfo (:pointer (:struct VkCmdProcessCommandsInfoNVX)))) (cffi:defcfun ("vkCmdPushConstants" vkCmdPushConstants) :void (commandBuffer VkCommandBuffer) ;; :EXTERNSYNC "true" (layout VkPipelineLayout) (stageFlags VkShaderStageFlags) (offset :uint32) (size :uint32) (pValues (:pointer :void))) ;; :LEN "size" (defvkdevextfun ("vkCmdPushDescriptorSetKHR" vkCmdPushDescriptorSetKHR) :void (commandBuffer VkCommandBuffer) ;; :EXTERNSYNC "true" (pipelineBindPoint VkPipelineBindPoint) (layout VkPipelineLayout) (set :uint32) (descriptorWriteCount :uint32) (pDescriptorWrites (:pointer (:struct VkWriteDescriptorSet)))) ;; :LEN "descriptorWriteCount" (defvkdevextfun ("vkCmdPushDescriptorSetWithTemplateKHR" vkCmdPushDescriptorSetWithTemplateKHR) :void (commandBuffer VkCommandBuffer) ;; :EXTERNSYNC "true" (descriptorUpdateTemplate VkDescriptorUpdateTemplateKHR) (layout VkPipelineLayout) (set :uint32) (pData (:pointer :void))) (defvkdevextfun ("vkCmdReserveSpaceForCommandsNVX" vkCmdReserveSpaceForCommandsNVX) :void (commandBuffer VkCommandBuffer) ;; :EXTERNSYNC "true" (pReserveSpaceInfo (:pointer (:struct VkCmdReserveSpaceForCommandsInfoNVX)))) (cffi:defcfun ("vkCmdResetEvent" vkCmdResetEvent) :void (commandBuffer VkCommandBuffer) ;; :EXTERNSYNC "true" (event VkEvent) (stageMask VkPipelineStageFlags)) (cffi:defcfun ("vkCmdResetQueryPool" vkCmdResetQueryPool) :void (commandBuffer VkCommandBuffer) ;; :EXTERNSYNC "true" (queryPool VkQueryPool) (firstQuery :uint32) (queryCount :uint32)) (cffi:defcfun ("vkCmdResolveImage" vkCmdResolveImage) :void (commandBuffer VkCommandBuffer) ;; :EXTERNSYNC "true" (srcImage VkImage) (srcImageLayout VkImageLayout) (dstImage VkImage) (dstImageLayout VkImageLayout) (regionCount :uint32) (pRegions (:pointer (:struct VkImageResolve)))) ;; :LEN "regionCount" (cffi:defcfun ("vkCmdSetBlendConstants" vkCmdSetBlendConstants) :void (commandBuffer VkCommandBuffer) ;; :EXTERNSYNC "true" (blendConstants :float)) (cffi:defcfun ("vkCmdSetDepthBias" vkCmdSetDepthBias) :void (commandBuffer VkCommandBuffer) ;; :EXTERNSYNC "true" (depthBiasConstantFactor :float) (depthBiasClamp :float) (depthBiasSlopeFactor :float)) (cffi:defcfun ("vkCmdSetDepthBounds" vkCmdSetDepthBounds) :void (commandBuffer VkCommandBuffer) ;; :EXTERNSYNC "true" (minDepthBounds :float) (maxDepthBounds :float)) (defvkdevextfun ("vkCmdSetDeviceMaskKHX" vkCmdSetDeviceMaskKHX) :void (commandBuffer VkCommandBuffer) ;; :EXTERNSYNC "true" (deviceMask :uint32)) (defvkdevextfun ("vkCmdSetDiscardRectangleEXT" vkCmdSetDiscardRectangleEXT) :void (commandBuffer VkCommandBuffer) ;; :EXTERNSYNC "true" (firstDiscardRectangle :uint32) (discardRectangleCount :uint32) (pDiscardRectangles (:pointer (:struct VkRect2D)))) ;; :LEN "discardRectangleCount" (cffi:defcfun ("vkCmdSetEvent" vkCmdSetEvent) :void (commandBuffer VkCommandBuffer) ;; :EXTERNSYNC "true" (event VkEvent) (stageMask VkPipelineStageFlags)) (cffi:defcfun ("vkCmdSetLineWidth" vkCmdSetLineWidth) :void (commandBuffer VkCommandBuffer) ;; :EXTERNSYNC "true" (lineWidth :float)) (cffi:defcfun ("vkCmdSetScissor" vkCmdSetScissor) :void (commandBuffer VkCommandBuffer) ;; :EXTERNSYNC "true" (firstScissor :uint32) (scissorCount :uint32) (pScissors (:pointer (:struct VkRect2D)))) ;; :LEN "scissorCount" (cffi:defcfun ("vkCmdSetStencilCompareMask" vkCmdSetStencilCompareMask) :void (commandBuffer VkCommandBuffer) ;; :EXTERNSYNC "true" (faceMask VkStencilFaceFlags) (compareMask :uint32)) (cffi:defcfun ("vkCmdSetStencilReference" vkCmdSetStencilReference) :void (commandBuffer VkCommandBuffer) ;; :EXTERNSYNC "true" (faceMask VkStencilFaceFlags) (reference :uint32)) (cffi:defcfun ("vkCmdSetStencilWriteMask" vkCmdSetStencilWriteMask) :void (commandBuffer VkCommandBuffer) ;; :EXTERNSYNC "true" (faceMask VkStencilFaceFlags) (writeMask :uint32)) (cffi:defcfun ("vkCmdSetViewport" vkCmdSetViewport) :void (commandBuffer VkCommandBuffer) ;; :EXTERNSYNC "true" (firstViewport :uint32) (viewportCount :uint32) (pViewports (:pointer (:struct VkViewport)))) ;; :LEN "viewportCount" :NOAUTOVALIDITY "true" (defvkdevextfun ("vkCmdSetViewportWScalingNV" vkCmdSetViewportWScalingNV) :void (commandBuffer VkCommandBuffer) ;; :EXTERNSYNC "true" (firstViewport :uint32) (viewportCount :uint32) (pViewportWScalings (:pointer (:struct VkViewportWScalingNV)))) ;; :LEN "viewportCount" :NOAUTOVALIDITY "true" (cffi:defcfun ("vkCmdUpdateBuffer" vkCmdUpdateBuffer) :void (commandBuffer VkCommandBuffer) ;; :EXTERNSYNC "true" (dstBuffer VkBuffer) (dstOffset VkDeviceSize) (dataSize VkDeviceSize) (pData (:pointer :void))) ;; :LEN "dataSize" (cffi:defcfun ("vkCmdWaitEvents" vkCmdWaitEvents) :void (commandBuffer VkCommandBuffer) ;; :EXTERNSYNC "true" (eventCount :uint32) (pEvents (:pointer VkEvent)) ;; :LEN "eventCount" (srcStageMask VkPipelineStageFlags) (dstStageMask VkPipelineStageFlags) (memoryBarrierCount :uint32) ;; :OPTIONAL "true" (pMemoryBarriers (:pointer (:struct VkMemoryBarrier))) ;; :LEN "memoryBarrierCount" (bufferMemoryBarrierCount :uint32) ;; :OPTIONAL "true" (pBufferMemoryBarriers (:pointer (:struct VkBufferMemoryBarrier))) ;; :LEN "bufferMemoryBarrierCount" (imageMemoryBarrierCount :uint32) ;; :OPTIONAL "true" (pImageMemoryBarriers (:pointer (:struct VkImageMemoryBarrier)))) ;; :LEN "imageMemoryBarrierCount" (cffi:defcfun ("vkCmdWriteTimestamp" vkCmdWriteTimestamp) :void (commandBuffer VkCommandBuffer) ;; :EXTERNSYNC "true" (pipelineStage VkPipelineStageFlagBits) (queryPool VkQueryPool) (query :uint32)) (defvkinstextfun ("vkCreateAndroidSurfaceKHR" vkCreateAndroidSurfaceKHR) VkResult (instance VkInstance) (pCreateInfo (:pointer (:struct VkAndroidSurfaceCreateInfoKHR))) (pAllocator (:pointer (:struct VkAllocationCallbacks))) ;; :OPTIONAL "true" (pSurface (:pointer VkSurfaceKHR))) (cffi:defcfun ("vkCreateBuffer" vkCreateBuffer) VkResult (device VkDevice) (pCreateInfo (:pointer (:struct VkBufferCreateInfo))) (pAllocator (:pointer (:struct VkAllocationCallbacks))) ;; :OPTIONAL "true" (pBuffer (:pointer VkBuffer))) (cffi:defcfun ("vkCreateBufferView" vkCreateBufferView) VkResult (device VkDevice) (pCreateInfo (:pointer (:struct VkBufferViewCreateInfo))) (pAllocator (:pointer (:struct VkAllocationCallbacks))) ;; :OPTIONAL "true" (pView (:pointer VkBufferView))) (cffi:defcfun ("vkCreateCommandPool" vkCreateCommandPool) VkResult (device VkDevice) (pCreateInfo (:pointer (:struct VkCommandPoolCreateInfo))) (pAllocator (:pointer (:struct VkAllocationCallbacks))) ;; :OPTIONAL "true" (pCommandPool (:pointer VkCommandPool))) (cffi:defcfun ("vkCreateComputePipelines" vkCreateComputePipelines) VkResult (device VkDevice) (pipelineCache VkPipelineCache) ;; :OPTIONAL "true" (createInfoCount :uint32) (pCreateInfos (:pointer (:struct VkComputePipelineCreateInfo))) ;; :LEN "createInfoCount" (pAllocator (:pointer (:struct VkAllocationCallbacks))) ;; :OPTIONAL "true" (pPipelines (:pointer VkPipeline))) ;; :LEN "createInfoCount" (defvkinstextfun ("vkCreateDebugReportCallbackEXT" vkCreateDebugReportCallbackEXT) VkResult (instance VkInstance) (pCreateInfo (:pointer (:struct VkDebugReportCallbackCreateInfoEXT))) (pAllocator (:pointer (:struct VkAllocationCallbacks))) ;; :OPTIONAL "true" (pCallback (:pointer VkDebugReportCallbackEXT))) (cffi:defcfun ("vkCreateDescriptorPool" vkCreateDescriptorPool) VkResult (device VkDevice) (pCreateInfo (:pointer (:struct VkDescriptorPoolCreateInfo))) (pAllocator (:pointer (:struct VkAllocationCallbacks))) ;; :OPTIONAL "true" (pDescriptorPool (:pointer VkDescriptorPool))) (cffi:defcfun ("vkCreateDescriptorSetLayout" vkCreateDescriptorSetLayout) VkResult (device VkDevice) (pCreateInfo (:pointer (:struct VkDescriptorSetLayoutCreateInfo))) (pAllocator (:pointer (:struct VkAllocationCallbacks))) ;; :OPTIONAL "true" (pSetLayout (:pointer VkDescriptorSetLayout))) (defvkdevextfun ("vkCreateDescriptorUpdateTemplateKHR" vkCreateDescriptorUpdateTemplateKHR) VkResult (device VkDevice) (pCreateInfo (:pointer (:struct VkDescriptorUpdateTemplateCreateInfoKHR))) (pAllocator (:pointer (:struct VkAllocationCallbacks))) ;; :OPTIONAL "true" (pDescriptorUpdateTemplate (:pointer VkDescriptorUpdateTemplateKHR))) (cffi:defcfun ("vkCreateDevice" vkCreateDevice) VkResult (physicalDevice VkPhysicalDevice) (pCreateInfo (:pointer (:struct VkDeviceCreateInfo))) (pAllocator (:pointer (:struct VkAllocationCallbacks))) ;; :OPTIONAL "true" (pDevice (:pointer VkDevice))) (cffi:defcfun ("vkCreateDisplayModeKHR" vkCreateDisplayModeKHR) VkResult (physicalDevice VkPhysicalDevice) (display VkDisplayKHR) ;; :EXTERNSYNC "true" (pCreateInfo (:pointer (:struct VkDisplayModeCreateInfoKHR))) (pAllocator (:pointer (:struct VkAllocationCallbacks))) ;; :OPTIONAL "true" (pMode (:pointer VkDisplayModeKHR))) (cffi:defcfun ("vkCreateDisplayPlaneSurfaceKHR" vkCreateDisplayPlaneSurfaceKHR) VkResult (instance VkInstance) (pCreateInfo (:pointer (:struct VkDisplaySurfaceCreateInfoKHR))) (pAllocator (:pointer (:struct VkAllocationCallbacks))) ;; :OPTIONAL "true" (pSurface (:pointer VkSurfaceKHR))) (cffi:defcfun ("vkCreateEvent" vkCreateEvent) VkResult (device VkDevice) (pCreateInfo (:pointer (:struct VkEventCreateInfo))) (pAllocator (:pointer (:struct VkAllocationCallbacks))) ;; :OPTIONAL "true" (pEvent (:pointer VkEvent))) (cffi:defcfun ("vkCreateFence" vkCreateFence) VkResult (device VkDevice) (pCreateInfo (:pointer (:struct VkFenceCreateInfo))) (pAllocator (:pointer (:struct VkAllocationCallbacks))) ;; :OPTIONAL "true" (pFence (:pointer VkFence))) (cffi:defcfun ("vkCreateFramebuffer" vkCreateFramebuffer) VkResult (device VkDevice) (pCreateInfo (:pointer (:struct VkFramebufferCreateInfo))) (pAllocator (:pointer (:struct VkAllocationCallbacks))) ;; :OPTIONAL "true" (pFramebuffer (:pointer VkFramebuffer))) (cffi:defcfun ("vkCreateGraphicsPipelines" vkCreateGraphicsPipelines) VkResult (device VkDevice) (pipelineCache VkPipelineCache) ;; :OPTIONAL "true" (createInfoCount :uint32) (pCreateInfos (:pointer (:struct VkGraphicsPipelineCreateInfo))) ;; :LEN "createInfoCount" (pAllocator (:pointer (:struct VkAllocationCallbacks))) ;; :OPTIONAL "true" (pPipelines (:pointer VkPipeline))) ;; :LEN "createInfoCount" (defvkinstextfun ("vkCreateIOSSurfaceMVK" vkCreateIOSSurfaceMVK) VkResult (instance VkInstance) (pCreateInfo (:pointer (:struct VkIOSSurfaceCreateInfoMVK))) (pAllocator (:pointer (:struct VkAllocationCallbacks))) ;; :OPTIONAL "true" (pSurface (:pointer VkSurfaceKHR))) (cffi:defcfun ("vkCreateImage" vkCreateImage) VkResult (device VkDevice) (pCreateInfo (:pointer (:struct VkImageCreateInfo))) (pAllocator (:pointer (:struct VkAllocationCallbacks))) ;; :OPTIONAL "true" (pImage (:pointer VkImage))) (cffi:defcfun ("vkCreateImageView" vkCreateImageView) VkResult (device VkDevice) (pCreateInfo (:pointer (:struct VkImageViewCreateInfo))) (pAllocator (:pointer (:struct VkAllocationCallbacks))) ;; :OPTIONAL "true" (pView (:pointer VkImageView))) (defvkdevextfun ("vkCreateIndirectCommandsLayoutNVX" vkCreateIndirectCommandsLayoutNVX) VkResult (device VkDevice) (pCreateInfo (:pointer (:struct VkIndirectCommandsLayoutCreateInfoNVX))) (pAllocator (:pointer (:struct VkAllocationCallbacks))) ;; :OPTIONAL "true" (pIndirectCommandsLayout (:pointer VkIndirectCommandsLayoutNVX))) (cffi:defcfun ("vkCreateInstance" vkCreateInstance) VkResult (pCreateInfo (:pointer (:struct VkInstanceCreateInfo))) (pAllocator (:pointer (:struct VkAllocationCallbacks))) ;; :OPTIONAL "true" (pInstance (:pointer VkInstance))) (defvkinstextfun ("vkCreateMacOSSurfaceMVK" vkCreateMacOSSurfaceMVK) VkResult (instance VkInstance) (pCreateInfo (:pointer (:struct VkMacOSSurfaceCreateInfoMVK))) (pAllocator (:pointer (:struct VkAllocationCallbacks))) ;; :OPTIONAL "true" (pSurface (:pointer VkSurfaceKHR))) (defvkinstextfun ("vkCreateMirSurfaceKHR" vkCreateMirSurfaceKHR) VkResult (instance VkInstance) (pCreateInfo (:pointer (:struct VkMirSurfaceCreateInfoKHR))) (pAllocator (:pointer (:struct VkAllocationCallbacks))) ;; :OPTIONAL "true" (pSurface (:pointer VkSurfaceKHR))) (defvkdevextfun ("vkCreateObjectTableNVX" vkCreateObjectTableNVX) VkResult (device VkDevice) (pCreateInfo (:pointer (:struct VkObjectTableCreateInfoNVX))) (pAllocator (:pointer (:struct VkAllocationCallbacks))) ;; :OPTIONAL "true" (pObjectTable (:pointer VkObjectTableNVX))) (cffi:defcfun ("vkCreatePipelineCache" vkCreatePipelineCache) VkResult (device VkDevice) (pCreateInfo (:pointer (:struct VkPipelineCacheCreateInfo))) (pAllocator (:pointer (:struct VkAllocationCallbacks))) ;; :OPTIONAL "true" (pPipelineCache (:pointer VkPipelineCache))) (cffi:defcfun ("vkCreatePipelineLayout" vkCreatePipelineLayout) VkResult (device VkDevice) (pCreateInfo (:pointer (:struct VkPipelineLayoutCreateInfo))) (pAllocator (:pointer (:struct VkAllocationCallbacks))) ;; :OPTIONAL "true" (pPipelineLayout (:pointer VkPipelineLayout))) (cffi:defcfun ("vkCreateQueryPool" vkCreateQueryPool) VkResult (device VkDevice) (pCreateInfo (:pointer (:struct VkQueryPoolCreateInfo))) (pAllocator (:pointer (:struct VkAllocationCallbacks))) ;; :OPTIONAL "true" (pQueryPool (:pointer VkQueryPool))) (cffi:defcfun ("vkCreateRenderPass" vkCreateRenderPass) VkResult (device VkDevice) (pCreateInfo (:pointer (:struct VkRenderPassCreateInfo))) (pAllocator (:pointer (:struct VkAllocationCallbacks))) ;; :OPTIONAL "true" (pRenderPass (:pointer VkRenderPass))) (cffi:defcfun ("vkCreateSampler" vkCreateSampler) VkResult (device VkDevice) (pCreateInfo (:pointer (:struct VkSamplerCreateInfo))) (pAllocator (:pointer (:struct VkAllocationCallbacks))) ;; :OPTIONAL "true" (pSampler (:pointer VkSampler))) (cffi:defcfun ("vkCreateSemaphore" vkCreateSemaphore) VkResult (device VkDevice) (pCreateInfo (:pointer (:struct VkSemaphoreCreateInfo))) (pAllocator (:pointer (:struct VkAllocationCallbacks))) ;; :OPTIONAL "true" (pSemaphore (:pointer VkSemaphore))) (cffi:defcfun ("vkCreateShaderModule" vkCreateShaderModule) VkResult (device VkDevice) (pCreateInfo (:pointer (:struct VkShaderModuleCreateInfo))) (pAllocator (:pointer (:struct VkAllocationCallbacks))) ;; :OPTIONAL "true" (pShaderModule (:pointer VkShaderModule))) (cffi:defcfun ("vkCreateSharedSwapchainsKHR" vkCreateSharedSwapchainsKHR) VkResult (device VkDevice) (swapchainCount :uint32) (pCreateInfos (:pointer (:struct VkSwapchainCreateInfoKHR))) ;; :LEN "swapchainCount" :EXTERNSYNC "pCreateInfos[].surface,pCreateInfos[].oldSwapchain" (pAllocator (:pointer (:struct VkAllocationCallbacks))) ;; :OPTIONAL "true" (pSwapchains (:pointer VkSwapchainKHR))) ;; :LEN "swapchainCount" (cffi:defcfun ("vkCreateSwapchainKHR" vkCreateSwapchainKHR) VkResult (device VkDevice) (pCreateInfo (:pointer (:struct VkSwapchainCreateInfoKHR))) ;; :EXTERNSYNC "pCreateInfo.surface,pCreateInfo.oldSwapchain" (pAllocator (:pointer (:struct VkAllocationCallbacks))) ;; :OPTIONAL "true" (pSwapchain (:pointer VkSwapchainKHR))) (defvkinstextfun ("vkCreateViSurfaceNN" vkCreateViSurfaceNN) VkResult (instance VkInstance) (pCreateInfo (:pointer (:struct VkViSurfaceCreateInfoNN))) (pAllocator (:pointer (:struct VkAllocationCallbacks))) ;; :OPTIONAL "true" (pSurface (:pointer VkSurfaceKHR))) (defvkinstextfun ("vkCreateWaylandSurfaceKHR" vkCreateWaylandSurfaceKHR) VkResult (instance VkInstance) (pCreateInfo (:pointer (:struct VkWaylandSurfaceCreateInfoKHR))) (pAllocator (:pointer (:struct VkAllocationCallbacks))) ;; :OPTIONAL "true" (pSurface (:pointer VkSurfaceKHR))) (cffi:defcfun ("vkCreateWin32SurfaceKHR" vkCreateWin32SurfaceKHR) VkResult (instance VkInstance) (pCreateInfo (:pointer (:struct VkWin32SurfaceCreateInfoKHR))) (pAllocator (:pointer (:struct VkAllocationCallbacks))) ;; :OPTIONAL "true" (pSurface (:pointer VkSurfaceKHR))) (defvkinstextfun ("vkCreateXcbSurfaceKHR" vkCreateXcbSurfaceKHR) VkResult (instance VkInstance) (pCreateInfo (:pointer (:struct VkXcbSurfaceCreateInfoKHR))) (pAllocator (:pointer (:struct VkAllocationCallbacks))) ;; :OPTIONAL "true" (pSurface (:pointer VkSurfaceKHR))) (defvkinstextfun ("vkCreateXlibSurfaceKHR" vkCreateXlibSurfaceKHR) VkResult (instance VkInstance) (pCreateInfo (:pointer (:struct VkXlibSurfaceCreateInfoKHR))) (pAllocator (:pointer (:struct VkAllocationCallbacks))) ;; :OPTIONAL "true" (pSurface (:pointer VkSurfaceKHR))) (defvkdevextfun ("vkDebugMarkerSetObjectNameEXT" vkDebugMarkerSetObjectNameEXT) VkResult (device VkDevice) (pNameInfo (:pointer (:struct VkDebugMarkerObjectNameInfoEXT)))) ;; :EXTERNSYNC "pNameInfo.object" (defvkdevextfun ("vkDebugMarkerSetObjectTagEXT" vkDebugMarkerSetObjectTagEXT) VkResult (device VkDevice) (pTagInfo (:pointer (:struct VkDebugMarkerObjectTagInfoEXT)))) ;; :EXTERNSYNC "pTagInfo.object" (defvkinstextfun ("vkDebugReportMessageEXT" vkDebugReportMessageEXT) :void (instance VkInstance) (flags VkDebugReportFlagsEXT) (objectType VkDebugReportObjectTypeEXT) (object :uint64) (location size-t) (messageCode :int32) (pLayerPrefix (:pointer :char)) ;; :LEN "null-terminated" (pMessage (:pointer :char))) ;; :LEN "null-terminated" (cffi:defcfun ("vkDestroyBuffer" vkDestroyBuffer) :void (device VkDevice) (buffer VkBuffer) ;; :OPTIONAL "true" :EXTERNSYNC "true" (pAllocator (:pointer (:struct VkAllocationCallbacks)))) ;; :OPTIONAL "true" (cffi:defcfun ("vkDestroyBufferView" vkDestroyBufferView) :void (device VkDevice) (bufferView VkBufferView) ;; :OPTIONAL "true" :EXTERNSYNC "true" (pAllocator (:pointer (:struct VkAllocationCallbacks)))) ;; :OPTIONAL "true" (cffi:defcfun ("vkDestroyCommandPool" vkDestroyCommandPool) :void (device VkDevice) (commandPool VkCommandPool) ;; :OPTIONAL "true" :EXTERNSYNC "true" (pAllocator (:pointer (:struct VkAllocationCallbacks)))) ;; :OPTIONAL "true" (defvkinstextfun ("vkDestroyDebugReportCallbackEXT" vkDestroyDebugReportCallbackEXT) :void (instance VkInstance) (callback VkDebugReportCallbackEXT) ;; :EXTERNSYNC "true" (pAllocator (:pointer (:struct VkAllocationCallbacks)))) ;; :OPTIONAL "true" (cffi:defcfun ("vkDestroyDescriptorPool" vkDestroyDescriptorPool) :void (device VkDevice) (descriptorPool VkDescriptorPool) ;; :OPTIONAL "true" :EXTERNSYNC "true" (pAllocator (:pointer (:struct VkAllocationCallbacks)))) ;; :OPTIONAL "true" (cffi:defcfun ("vkDestroyDescriptorSetLayout" vkDestroyDescriptorSetLayout) :void (device VkDevice) (descriptorSetLayout VkDescriptorSetLayout) ;; :OPTIONAL "true" :EXTERNSYNC "true" (pAllocator (:pointer (:struct VkAllocationCallbacks)))) ;; :OPTIONAL "true" (defvkdevextfun ("vkDestroyDescriptorUpdateTemplateKHR" vkDestroyDescriptorUpdateTemplateKHR) :void (device VkDevice) (descriptorUpdateTemplate VkDescriptorUpdateTemplateKHR) ;; :OPTIONAL "true" :EXTERNSYNC "true" (pAllocator (:pointer (:struct VkAllocationCallbacks)))) ;; :OPTIONAL "true" (cffi:defcfun ("vkDestroyDevice" vkDestroyDevice) :void (device VkDevice) ;; :OPTIONAL "true" :EXTERNSYNC "true" (pAllocator (:pointer (:struct VkAllocationCallbacks)))) ;; :OPTIONAL "true" (cffi:defcfun ("vkDestroyEvent" vkDestroyEvent) :void (device VkDevice) (event VkEvent) ;; :OPTIONAL "true" :EXTERNSYNC "true" (pAllocator (:pointer (:struct VkAllocationCallbacks)))) ;; :OPTIONAL "true" (cffi:defcfun ("vkDestroyFence" vkDestroyFence) :void (device VkDevice) (fence VkFence) ;; :OPTIONAL "true" :EXTERNSYNC "true" (pAllocator (:pointer (:struct VkAllocationCallbacks)))) ;; :OPTIONAL "true" (cffi:defcfun ("vkDestroyFramebuffer" vkDestroyFramebuffer) :void (device VkDevice) (framebuffer VkFramebuffer) ;; :OPTIONAL "true" :EXTERNSYNC "true" (pAllocator (:pointer (:struct VkAllocationCallbacks)))) ;; :OPTIONAL "true" (cffi:defcfun ("vkDestroyImage" vkDestroyImage) :void (device VkDevice) (image VkImage) ;; :OPTIONAL "true" :EXTERNSYNC "true" (pAllocator (:pointer (:struct VkAllocationCallbacks)))) ;; :OPTIONAL "true" (cffi:defcfun ("vkDestroyImageView" vkDestroyImageView) :void (device VkDevice) (imageView VkImageView) ;; :OPTIONAL "true" :EXTERNSYNC "true" (pAllocator (:pointer (:struct VkAllocationCallbacks)))) ;; :OPTIONAL "true" (defvkdevextfun ("vkDestroyIndirectCommandsLayoutNVX" vkDestroyIndirectCommandsLayoutNVX) :void (device VkDevice) (indirectCommandsLayout VkIndirectCommandsLayoutNVX) (pAllocator (:pointer (:struct VkAllocationCallbacks)))) ;; :OPTIONAL "true" (cffi:defcfun ("vkDestroyInstance" vkDestroyInstance) :void (instance VkInstance) ;; :OPTIONAL "true" :EXTERNSYNC "true" (pAllocator (:pointer (:struct VkAllocationCallbacks)))) ;; :OPTIONAL "true" (defvkdevextfun ("vkDestroyObjectTableNVX" vkDestroyObjectTableNVX) :void (device VkDevice) (objectTable VkObjectTableNVX) ;; :EXTERNSYNC "true" (pAllocator (:pointer (:struct VkAllocationCallbacks)))) ;; :OPTIONAL "true" (cffi:defcfun ("vkDestroyPipeline" vkDestroyPipeline) :void (device VkDevice) (pipeline VkPipeline) ;; :OPTIONAL "true" :EXTERNSYNC "true" (pAllocator (:pointer (:struct VkAllocationCallbacks)))) ;; :OPTIONAL "true" (cffi:defcfun ("vkDestroyPipelineCache" vkDestroyPipelineCache) :void (device VkDevice) (pipelineCache VkPipelineCache) ;; :OPTIONAL "true" :EXTERNSYNC "true" (pAllocator (:pointer (:struct VkAllocationCallbacks)))) ;; :OPTIONAL "true" (cffi:defcfun ("vkDestroyPipelineLayout" vkDestroyPipelineLayout) :void (device VkDevice) (pipelineLayout VkPipelineLayout) ;; :OPTIONAL "true" :EXTERNSYNC "true" (pAllocator (:pointer (:struct VkAllocationCallbacks)))) ;; :OPTIONAL "true" (cffi:defcfun ("vkDestroyQueryPool" vkDestroyQueryPool) :void (device VkDevice) (queryPool VkQueryPool) ;; :OPTIONAL "true" :EXTERNSYNC "true" (pAllocator (:pointer (:struct VkAllocationCallbacks)))) ;; :OPTIONAL "true" (cffi:defcfun ("vkDestroyRenderPass" vkDestroyRenderPass) :void (device VkDevice) (renderPass VkRenderPass) ;; :OPTIONAL "true" :EXTERNSYNC "true" (pAllocator (:pointer (:struct VkAllocationCallbacks)))) ;; :OPTIONAL "true" (cffi:defcfun ("vkDestroySampler" vkDestroySampler) :void (device VkDevice) (sampler VkSampler) ;; :OPTIONAL "true" :EXTERNSYNC "true" (pAllocator (:pointer (:struct VkAllocationCallbacks)))) ;; :OPTIONAL "true" (cffi:defcfun ("vkDestroySemaphore" vkDestroySemaphore) :void (device VkDevice) (semaphore VkSemaphore) ;; :OPTIONAL "true" :EXTERNSYNC "true" (pAllocator (:pointer (:struct VkAllocationCallbacks)))) ;; :OPTIONAL "true" (cffi:defcfun ("vkDestroyShaderModule" vkDestroyShaderModule) :void (device VkDevice) (shaderModule VkShaderModule) ;; :OPTIONAL "true" :EXTERNSYNC "true" (pAllocator (:pointer (:struct VkAllocationCallbacks)))) ;; :OPTIONAL "true" (cffi:defcfun ("vkDestroySurfaceKHR" vkDestroySurfaceKHR) :void (instance VkInstance) (surface VkSurfaceKHR) ;; :OPTIONAL "true" :EXTERNSYNC "true" (pAllocator (:pointer (:struct VkAllocationCallbacks)))) ;; :OPTIONAL "true" (cffi:defcfun ("vkDestroySwapchainKHR" vkDestroySwapchainKHR) :void (device VkDevice) (swapchain VkSwapchainKHR) ;; :OPTIONAL "true" :EXTERNSYNC "true" (pAllocator (:pointer (:struct VkAllocationCallbacks)))) ;; :OPTIONAL "true" (cffi:defcfun ("vkDeviceWaitIdle" vkDeviceWaitIdle) VkResult (device VkDevice)) (defvkdevextfun ("vkDisplayPowerControlEXT" vkDisplayPowerControlEXT) VkResult (device VkDevice) (display VkDisplayKHR) (pDisplayPowerInfo (:pointer (:struct VkDisplayPowerInfoEXT)))) (cffi:defcfun ("vkEndCommandBuffer" vkEndCommandBuffer) VkResult (commandBuffer VkCommandBuffer)) ;; :EXTERNSYNC "true" (cffi:defcfun ("vkEnumerateDeviceExtensionProperties" vkEnumerateDeviceExtensionProperties) VkResult (physicalDevice VkPhysicalDevice) (pLayerName (:pointer :char)) ;; :OPTIONAL "true" :LEN "null-terminated" (pPropertyCount (:pointer :uint32)) ;; :OPTIONAL "false,true" (pProperties (:pointer (:struct VkExtensionProperties)))) ;; :OPTIONAL "true" :LEN "pPropertyCount" (cffi:defcfun ("vkEnumerateDeviceLayerProperties" vkEnumerateDeviceLayerProperties) VkResult (physicalDevice VkPhysicalDevice) (pPropertyCount (:pointer :uint32)) ;; :OPTIONAL "false,true" (pProperties (:pointer (:struct VkLayerProperties)))) ;; :OPTIONAL "true" :LEN "pPropertyCount" (cffi:defcfun ("vkEnumerateInstanceExtensionProperties" vkEnumerateInstanceExtensionProperties) VkResult (pLayerName (:pointer :char)) ;; :OPTIONAL "true" :LEN "null-terminated" (pPropertyCount (:pointer :uint32)) ;; :OPTIONAL "false,true" (pProperties (:pointer (:struct VkExtensionProperties)))) ;; :OPTIONAL "true" :LEN "pPropertyCount" (cffi:defcfun ("vkEnumerateInstanceLayerProperties" vkEnumerateInstanceLayerProperties) VkResult (pPropertyCount (:pointer :uint32)) ;; :OPTIONAL "false,true" (pProperties (:pointer (:struct VkLayerProperties)))) ;; :OPTIONAL "true" :LEN "pPropertyCount" (defvkinstextfun ("vkEnumeratePhysicalDeviceGroupsKHX" vkEnumeratePhysicalDeviceGroupsKHX) VkResult (instance VkInstance) (pPhysicalDeviceGroupCount (:pointer :uint32)) ;; :OPTIONAL "false,true" (pPhysicalDeviceGroupProperties (:pointer (:struct VkPhysicalDeviceGroupPropertiesKHX)))) ;; :OPTIONAL "true" :LEN "pPhysicalDeviceGroupCount" (cffi:defcfun ("vkEnumeratePhysicalDevices" vkEnumeratePhysicalDevices) VkResult (instance VkInstance) (pPhysicalDeviceCount (:pointer :uint32)) ;; :OPTIONAL "false,true" (pPhysicalDevices (:pointer VkPhysicalDevice))) ;; :OPTIONAL "true" :LEN "pPhysicalDeviceCount" (cffi:defcfun ("vkFlushMappedMemoryRanges" vkFlushMappedMemoryRanges) VkResult (device VkDevice) (memoryRangeCount :uint32) (pMemoryRanges (:pointer (:struct VkMappedMemoryRange)))) ;; :LEN "memoryRangeCount" (cffi:defcfun ("vkFreeCommandBuffers" vkFreeCommandBuffers) :void (device VkDevice) (commandPool VkCommandPool) ;; :EXTERNSYNC "true" (commandBufferCount :uint32) (pCommandBuffers (:pointer VkCommandBuffer))) ;; :LEN "commandBufferCount" :NOAUTOVALIDITY "true" :EXTERNSYNC "true" (cffi:defcfun ("vkFreeDescriptorSets" vkFreeDescriptorSets) VkResult (device VkDevice) (descriptorPool VkDescriptorPool) ;; :EXTERNSYNC "true" (descriptorSetCount :uint32) (pDescriptorSets (:pointer VkDescriptorSet))) ;; :LEN "descriptorSetCount" :NOAUTOVALIDITY "true" :EXTERNSYNC "true" (cffi:defcfun ("vkFreeMemory" vkFreeMemory) :void (device VkDevice) (memory VkDeviceMemory) ;; :OPTIONAL "true" :EXTERNSYNC "true" (pAllocator (:pointer (:struct VkAllocationCallbacks)))) ;; :OPTIONAL "true" (cffi:defcfun ("vkGetBufferMemoryRequirements" vkGetBufferMemoryRequirements) :void (device VkDevice) (buffer VkBuffer) (pMemoryRequirements (:pointer (:struct VkMemoryRequirements)))) (defvkdevextfun ("vkGetDeviceGroupPeerMemoryFeaturesKHX" vkGetDeviceGroupPeerMemoryFeaturesKHX) :void (device VkDevice) (heapIndex :uint32) (localDeviceIndex :uint32) (remoteDeviceIndex :uint32) (pPeerMemoryFeatures (:pointer VkPeerMemoryFeatureFlagsKHX))) (defvkdevextfun ("vkGetDeviceGroupPresentCapabilitiesKHX" vkGetDeviceGroupPresentCapabilitiesKHX) VkResult (device VkDevice) (pDeviceGroupPresentCapabilities (:pointer (:struct VkDeviceGroupPresentCapabilitiesKHX)))) (defvkdevextfun ("vkGetDeviceGroupSurfacePresentModesKHX" vkGetDeviceGroupSurfacePresentModesKHX) VkResult (device VkDevice) (surface VkSurfaceKHR) ;; :EXTERNSYNC "true" (pModes (:pointer VkDeviceGroupPresentModeFlagsKHX))) (cffi:defcfun ("vkGetDeviceMemoryCommitment" vkGetDeviceMemoryCommitment) :void (device VkDevice) (memory VkDeviceMemory) (pCommittedMemoryInBytes (:pointer VkDeviceSize))) (cffi:defcfun ("vkGetDeviceProcAddr" vkGetDeviceProcAddr) PFN_vkVoidFunction (device VkDevice) (pName (:pointer :char))) ;; :LEN "null-terminated" (cffi:defcfun ("vkGetDeviceQueue" vkGetDeviceQueue) :void (device VkDevice) (queueFamilyIndex :uint32) (queueIndex :uint32) (pQueue (:pointer VkQueue))) (cffi:defcfun ("vkGetDisplayModePropertiesKHR" vkGetDisplayModePropertiesKHR) VkResult (physicalDevice VkPhysicalDevice) (display VkDisplayKHR) (pPropertyCount (:pointer :uint32)) ;; :OPTIONAL "false,true" (pProperties (:pointer (:struct VkDisplayModePropertiesKHR)))) ;; :OPTIONAL "true" :LEN "pPropertyCount" (cffi:defcfun ("vkGetDisplayPlaneCapabilitiesKHR" vkGetDisplayPlaneCapabilitiesKHR) VkResult (physicalDevice VkPhysicalDevice) (mode VkDisplayModeKHR) ;; :EXTERNSYNC "true" (planeIndex :uint32) (pCapabilities (:pointer (:struct VkDisplayPlaneCapabilitiesKHR)))) (cffi:defcfun ("vkGetDisplayPlaneSupportedDisplaysKHR" vkGetDisplayPlaneSupportedDisplaysKHR) VkResult (physicalDevice VkPhysicalDevice) (planeIndex :uint32) (pDisplayCount (:pointer :uint32)) ;; :OPTIONAL "false,true" (pDisplays (:pointer VkDisplayKHR))) ;; :OPTIONAL "true" :LEN "pDisplayCount" (cffi:defcfun ("vkGetEventStatus" vkGetEventStatus) VkResult (device VkDevice) (event VkEvent)) (cffi:defcfun ("vkGetFenceStatus" vkGetFenceStatus) VkResult (device VkDevice) (fence VkFence)) (cffi:defcfun ("vkGetImageMemoryRequirements" vkGetImageMemoryRequirements) :void (device VkDevice) (image VkImage) (pMemoryRequirements (:pointer (:struct VkMemoryRequirements)))) (cffi:defcfun ("vkGetImageSparseMemoryRequirements" vkGetImageSparseMemoryRequirements) :void (device VkDevice) (image VkImage) (pSparseMemoryRequirementCount (:pointer :uint32)) ;; :OPTIONAL "false,true" (pSparseMemoryRequirements (:pointer (:struct VkSparseImageMemoryRequirements)))) ;; :OPTIONAL "true" :LEN "pSparseMemoryRequirementCount" (cffi:defcfun ("vkGetImageSubresourceLayout" vkGetImageSubresourceLayout) :void (device VkDevice) (image VkImage) (pSubresource (:pointer (:struct VkImageSubresource))) (pLayout (:pointer (:struct VkSubresourceLayout)))) (cffi:defcfun ("vkGetInstanceProcAddr" vkGetInstanceProcAddr) PFN_vkVoidFunction (instance VkInstance) ;; :OPTIONAL "true" (pName (:pointer :char))) ;; :LEN "null-terminated" (defvkdevextfun ("vkGetMemoryFdKHX" vkGetMemoryFdKHX) VkResult (device VkDevice) (memory VkDeviceMemory) (handleType VkExternalMemoryHandleTypeFlagBitsKHX) (pFd (:pointer :int))) (defvkdevextfun ("vkGetMemoryFdPropertiesKHX" vkGetMemoryFdPropertiesKHX) VkResult (device VkDevice) (handleType VkExternalMemoryHandleTypeFlagBitsKHX) (fd :int) (pMemoryFdProperties (:pointer (:struct VkMemoryFdPropertiesKHX)))) (defvkdevextfun ("vkGetMemoryWin32HandleKHX" vkGetMemoryWin32HandleKHX) VkResult (device VkDevice) (memory VkDeviceMemory) (handleType VkExternalMemoryHandleTypeFlagBitsKHX) (pHandle (:pointer HANDLE))) (defvkdevextfun ("vkGetMemoryWin32HandleNV" vkGetMemoryWin32HandleNV) VkResult (device VkDevice) (memory VkDeviceMemory) (handleType VkExternalMemoryHandleTypeFlagsNV) (pHandle (:pointer HANDLE))) (defvkdevextfun ("vkGetMemoryWin32HandlePropertiesKHX" vkGetMemoryWin32HandlePropertiesKHX) VkResult (device VkDevice) (handleType VkExternalMemoryHandleTypeFlagBitsKHX) (handle HANDLE) (pMemoryWin32HandleProperties (:pointer (:struct VkMemoryWin32HandlePropertiesKHX)))) (defvkdevextfun ("vkGetPastPresentationTimingGOOGLE" vkGetPastPresentationTimingGOOGLE) VkResult (device VkDevice) (swapchain VkSwapchainKHR) ;; :EXTERNSYNC "true" (pPresentationTimingCount (:pointer :uint32)) ;; :OPTIONAL "false,true" (pPresentationTimings (:pointer (:struct VkPastPresentationTimingGOOGLE)))) ;; :OPTIONAL "true" :LEN "pPresentationTimingCount" (cffi:defcfun ("vkGetPhysicalDeviceDisplayPlanePropertiesKHR" vkGetPhysicalDeviceDisplayPlanePropertiesKHR) VkResult (physicalDevice VkPhysicalDevice) (pPropertyCount (:pointer :uint32)) ;; :OPTIONAL "false,true" (pProperties (:pointer (:struct VkDisplayPlanePropertiesKHR)))) ;; :OPTIONAL "true" :LEN "pPropertyCount" (cffi:defcfun ("vkGetPhysicalDeviceDisplayPropertiesKHR" vkGetPhysicalDeviceDisplayPropertiesKHR) VkResult (physicalDevice VkPhysicalDevice) (pPropertyCount (:pointer :uint32)) ;; :OPTIONAL "false,true" (pProperties (:pointer (:struct VkDisplayPropertiesKHR)))) ;; :OPTIONAL "true" :LEN "pPropertyCount" (defvkinstextfun ("vkGetPhysicalDeviceExternalBufferPropertiesKHX" vkGetPhysicalDeviceExternalBufferPropertiesKHX) :void (physicalDevice VkPhysicalDevice) (pExternalBufferInfo (:pointer (:struct VkPhysicalDeviceExternalBufferInfoKHX))) (pExternalBufferProperties (:pointer (:struct VkExternalBufferPropertiesKHX)))) (defvkinstextfun ("vkGetPhysicalDeviceExternalImageFormatPropertiesNV" vkGetPhysicalDeviceExternalImageFormatPropertiesNV) VkResult (physicalDevice VkPhysicalDevice) (format VkFormat) (type VkImageType) (tiling VkImageTiling) (usage VkImageUsageFlags) (flags VkImageCreateFlags) ;; :OPTIONAL "true" (externalHandleType VkExternalMemoryHandleTypeFlagsNV) ;; :OPTIONAL "true" (pExternalImageFormatProperties (:pointer (:struct VkExternalImageFormatPropertiesNV)))) (defvkinstextfun ("vkGetPhysicalDeviceExternalSemaphorePropertiesKHX" vkGetPhysicalDeviceExternalSemaphorePropertiesKHX) :void (physicalDevice VkPhysicalDevice) (pExternalSemaphoreInfo (:pointer (:struct VkPhysicalDeviceExternalSemaphoreInfoKHX))) (pExternalSemaphoreProperties (:pointer (:struct VkExternalSemaphorePropertiesKHX)))) (cffi:defcfun ("vkGetPhysicalDeviceFeatures" vkGetPhysicalDeviceFeatures) :void (physicalDevice VkPhysicalDevice) (pFeatures (:pointer (:struct VkPhysicalDeviceFeatures)))) (defvkinstextfun ("vkGetPhysicalDeviceFeatures2KHR" vkGetPhysicalDeviceFeatures2KHR) :void (physicalDevice VkPhysicalDevice) (pFeatures (:pointer (:struct VkPhysicalDeviceFeatures2KHR)))) (cffi:defcfun ("vkGetPhysicalDeviceFormatProperties" vkGetPhysicalDeviceFormatProperties) :void (physicalDevice VkPhysicalDevice) (format VkFormat) (pFormatProperties (:pointer (:struct VkFormatProperties)))) (defvkinstextfun ("vkGetPhysicalDeviceFormatProperties2KHR" vkGetPhysicalDeviceFormatProperties2KHR) :void (physicalDevice VkPhysicalDevice) (format VkFormat) (pFormatProperties (:pointer (:struct VkFormatProperties2KHR)))) (defvkdevextfun ("vkGetPhysicalDeviceGeneratedCommandsPropertiesNVX" vkGetPhysicalDeviceGeneratedCommandsPropertiesNVX) :void (physicalDevice VkPhysicalDevice) (pFeatures (:pointer (:struct VkDeviceGeneratedCommandsFeaturesNVX))) (pLimits (:pointer (:struct VkDeviceGeneratedCommandsLimitsNVX)))) (cffi:defcfun ("vkGetPhysicalDeviceImageFormatProperties" vkGetPhysicalDeviceImageFormatProperties) VkResult (physicalDevice VkPhysicalDevice) (format VkFormat) (type VkImageType) (tiling VkImageTiling) (usage VkImageUsageFlags) (flags VkImageCreateFlags) ;; :OPTIONAL "true" (pImageFormatProperties (:pointer (:struct VkImageFormatProperties)))) (defvkinstextfun ("vkGetPhysicalDeviceImageFormatProperties2KHR" vkGetPhysicalDeviceImageFormatProperties2KHR) VkResult (physicalDevice VkPhysicalDevice) (pImageFormatInfo (:pointer (:struct VkPhysicalDeviceImageFormatInfo2KHR))) (pImageFormatProperties (:pointer (:struct VkImageFormatProperties2KHR)))) (cffi:defcfun ("vkGetPhysicalDeviceMemoryProperties" vkGetPhysicalDeviceMemoryProperties) :void (physicalDevice VkPhysicalDevice) (pMemoryProperties (:pointer (:struct VkPhysicalDeviceMemoryProperties)))) (defvkinstextfun ("vkGetPhysicalDeviceMemoryProperties2KHR" vkGetPhysicalDeviceMemoryProperties2KHR) :void (physicalDevice VkPhysicalDevice) (pMemoryProperties (:pointer (:struct VkPhysicalDeviceMemoryProperties2KHR)))) (defvkinstextfun ("vkGetPhysicalDeviceMirPresentationSupportKHR" vkGetPhysicalDeviceMirPresentationSupportKHR) VkBool32 (physicalDevice VkPhysicalDevice) (queueFamilyIndex :uint32) (connection (:pointer MirConnection))) (defvkdevextfun ("vkGetPhysicalDevicePresentRectanglesKHX" vkGetPhysicalDevicePresentRectanglesKHX) VkResult (physicalDevice VkPhysicalDevice) (surface VkSurfaceKHR) ;; :EXTERNSYNC "true" (pRectCount (:pointer :uint32)) ;; :OPTIONAL "false,true" (pRects (:pointer (:struct VkRect2D)))) ;; :OPTIONAL "true" :LEN "pRectCount" (cffi:defcfun ("vkGetPhysicalDeviceProperties" vkGetPhysicalDeviceProperties) :void (physicalDevice VkPhysicalDevice) (pProperties (:pointer (:struct VkPhysicalDeviceProperties)))) (defvkinstextfun ("vkGetPhysicalDeviceProperties2KHR" vkGetPhysicalDeviceProperties2KHR) :void (physicalDevice VkPhysicalDevice) (pProperties (:pointer (:struct VkPhysicalDeviceProperties2KHR)))) (cffi:defcfun ("vkGetPhysicalDeviceQueueFamilyProperties" vkGetPhysicalDeviceQueueFamilyProperties) :void (physicalDevice VkPhysicalDevice) (pQueueFamilyPropertyCount (:pointer :uint32)) ;; :OPTIONAL "false,true" (pQueueFamilyProperties (:pointer (:struct VkQueueFamilyProperties)))) ;; :OPTIONAL "true" :LEN "pQueueFamilyPropertyCount" (defvkinstextfun ("vkGetPhysicalDeviceQueueFamilyProperties2KHR" vkGetPhysicalDeviceQueueFamilyProperties2KHR) :void (physicalDevice VkPhysicalDevice) (pQueueFamilyPropertyCount (:pointer :uint32)) ;; :OPTIONAL "false,true" (pQueueFamilyProperties (:pointer (:struct VkQueueFamilyProperties2KHR)))) ;; :OPTIONAL "true" :LEN "pQueueFamilyPropertyCount" (cffi:defcfun ("vkGetPhysicalDeviceSparseImageFormatProperties" vkGetPhysicalDeviceSparseImageFormatProperties) :void (physicalDevice VkPhysicalDevice) (format VkFormat) (type VkImageType) (samples VkSampleCountFlagBits) (usage VkImageUsageFlags) (tiling VkImageTiling) (pPropertyCount (:pointer :uint32)) ;; :OPTIONAL "false,true" (pProperties (:pointer (:struct VkSparseImageFormatProperties)))) ;; :OPTIONAL "true" :LEN "pPropertyCount" (defvkinstextfun ("vkGetPhysicalDeviceSparseImageFormatProperties2KHR" vkGetPhysicalDeviceSparseImageFormatProperties2KHR) :void (physicalDevice VkPhysicalDevice) (pFormatInfo (:pointer (:struct VkPhysicalDeviceSparseImageFormatInfo2KHR))) (pPropertyCount (:pointer :uint32)) ;; :OPTIONAL "false,true" (pProperties (:pointer (:struct VkSparseImageFormatProperties2KHR)))) ;; :OPTIONAL "true" :LEN "pPropertyCount" (defvkinstextfun ("vkGetPhysicalDeviceSurfaceCapabilities2EXT" vkGetPhysicalDeviceSurfaceCapabilities2EXT) VkResult (physicalDevice VkPhysicalDevice) (surface VkSurfaceKHR) (pSurfaceCapabilities (:pointer (:struct VkSurfaceCapabilities2EXT)))) (defvkinstextfun ("vkGetPhysicalDeviceSurfaceCapabilities2KHR" vkGetPhysicalDeviceSurfaceCapabilities2KHR) VkResult (physicalDevice VkPhysicalDevice) (pSurfaceInfo (:pointer (:struct VkPhysicalDeviceSurfaceInfo2KHR))) (pSurfaceCapabilities (:pointer (:struct VkSurfaceCapabilities2KHR)))) (cffi:defcfun ("vkGetPhysicalDeviceSurfaceCapabilitiesKHR" vkGetPhysicalDeviceSurfaceCapabilitiesKHR) VkResult (physicalDevice VkPhysicalDevice) (surface VkSurfaceKHR) (pSurfaceCapabilities (:pointer (:struct VkSurfaceCapabilitiesKHR)))) (defvkinstextfun ("vkGetPhysicalDeviceSurfaceFormats2KHR" vkGetPhysicalDeviceSurfaceFormats2KHR) VkResult (physicalDevice VkPhysicalDevice) (pSurfaceInfo (:pointer (:struct VkPhysicalDeviceSurfaceInfo2KHR))) (pSurfaceFormatCount (:pointer :uint32)) ;; :OPTIONAL "false,true" (pSurfaceFormats (:pointer (:struct VkSurfaceFormat2KHR)))) ;; :OPTIONAL "true" :LEN "pSurfaceFormatCount" (cffi:defcfun ("vkGetPhysicalDeviceSurfaceFormatsKHR" vkGetPhysicalDeviceSurfaceFormatsKHR) VkResult (physicalDevice VkPhysicalDevice) (surface VkSurfaceKHR) (pSurfaceFormatCount (:pointer :uint32)) ;; :OPTIONAL "false,true" (pSurfaceFormats (:pointer (:struct VkSurfaceFormatKHR)))) ;; :OPTIONAL "true" :LEN "pSurfaceFormatCount" (cffi:defcfun ("vkGetPhysicalDeviceSurfacePresentModesKHR" vkGetPhysicalDeviceSurfacePresentModesKHR) VkResult (physicalDevice VkPhysicalDevice) (surface VkSurfaceKHR) (pPresentModeCount (:pointer :uint32)) ;; :OPTIONAL "false,true" (pPresentModes (:pointer VkPresentModeKHR))) ;; :OPTIONAL "true" :LEN "pPresentModeCount" (cffi:defcfun ("vkGetPhysicalDeviceSurfaceSupportKHR" vkGetPhysicalDeviceSurfaceSupportKHR) VkResult (physicalDevice VkPhysicalDevice) (queueFamilyIndex :uint32) (surface VkSurfaceKHR) (pSupported (:pointer VkBool32))) (defvkinstextfun ("vkGetPhysicalDeviceWaylandPresentationSupportKHR" vkGetPhysicalDeviceWaylandPresentationSupportKHR) VkBool32 (physicalDevice VkPhysicalDevice) (queueFamilyIndex :uint32) (display (:pointer (:struct wl_display)))) (cffi:defcfun ("vkGetPhysicalDeviceWin32PresentationSupportKHR" vkGetPhysicalDeviceWin32PresentationSupportKHR) VkBool32 (physicalDevice VkPhysicalDevice) (queueFamilyIndex :uint32)) (defvkinstextfun ("vkGetPhysicalDeviceXlibPresentationSupportKHR" vkGetPhysicalDeviceXlibPresentationSupportKHR) VkBool32 (physicalDevice VkPhysicalDevice) (queueFamilyIndex :uint32) (dpy (:pointer Display)) (visualID VisualID)) (cffi:defcfun ("vkGetPipelineCacheData" vkGetPipelineCacheData) VkResult (device VkDevice) (pipelineCache VkPipelineCache) (pDataSize (:pointer size-t)) ;; :OPTIONAL "false,true" (pData (:pointer :void))) ;; :OPTIONAL "true" :LEN "pDataSize" (cffi:defcfun ("vkGetQueryPoolResults" vkGetQueryPoolResults) VkResult (device VkDevice) (queryPool VkQueryPool) (firstQuery :uint32) (queryCount :uint32) (dataSize size-t) (pData (:pointer :void)) ;; :LEN "dataSize" (stride VkDeviceSize) (flags VkQueryResultFlags)) ;; :OPTIONAL "true" (defvkinstextfun ("vkGetRandROutputDisplayEXT" vkGetRandROutputDisplayEXT) VkResult (physicalDevice VkPhysicalDevice) (dpy (:pointer Display)) (rrOutput RROutput) (pDisplay (:pointer VkDisplayKHR))) (defvkdevextfun ("vkGetRefreshCycleDurationGOOGLE" vkGetRefreshCycleDurationGOOGLE) VkResult (device VkDevice) (swapchain VkSwapchainKHR) ;; :EXTERNSYNC "true" (pDisplayTimingProperties (:pointer (:struct VkRefreshCycleDurationGOOGLE)))) (cffi:defcfun ("vkGetRenderAreaGranularity" vkGetRenderAreaGranularity) :void (device VkDevice) (renderPass VkRenderPass) (pGranularity (:pointer (:struct VkExtent2D)))) (defvkdevextfun ("vkGetSemaphoreFdKHX" vkGetSemaphoreFdKHX) VkResult (device VkDevice) (semaphore VkSemaphore) (handleType VkExternalSemaphoreHandleTypeFlagBitsKHX) (pFd (:pointer :int))) (defvkdevextfun ("vkGetSemaphoreWin32HandleKHX" vkGetSemaphoreWin32HandleKHX) VkResult (device VkDevice) (semaphore VkSemaphore) (handleType VkExternalSemaphoreHandleTypeFlagBitsKHX) (pHandle (:pointer HANDLE))) (defvkdevextfun ("vkGetSwapchainCounterEXT" vkGetSwapchainCounterEXT) VkResult (device VkDevice) (swapchain VkSwapchainKHR) (counter VkSurfaceCounterFlagBitsEXT) (pCounterValue (:pointer :uint64))) (cffi:defcfun ("vkGetSwapchainImagesKHR" vkGetSwapchainImagesKHR) VkResult (device VkDevice) (swapchain VkSwapchainKHR) (pSwapchainImageCount (:pointer :uint32)) ;; :OPTIONAL "false,true" (pSwapchainImages (:pointer VkImage))) ;; :OPTIONAL "true" :LEN "pSwapchainImageCount" (defvkdevextfun ("vkGetSwapchainStatusKHR" vkGetSwapchainStatusKHR) VkResult (device VkDevice) (swapchain VkSwapchainKHR)) ;; :EXTERNSYNC "true" (defvkdevextfun ("vkImportSemaphoreFdKHX" vkImportSemaphoreFdKHX) VkResult (device VkDevice) (pImportSemaphoreFdInfo (:pointer (:struct VkImportSemaphoreFdInfoKHX)))) (defvkdevextfun ("vkImportSemaphoreWin32HandleKHX" vkImportSemaphoreWin32HandleKHX) VkResult (device VkDevice) (pImportSemaphoreWin32HandleInfo (:pointer (:struct VkImportSemaphoreWin32HandleInfoKHX)))) (cffi:defcfun ("vkInvalidateMappedMemoryRanges" vkInvalidateMappedMemoryRanges) VkResult (device VkDevice) (memoryRangeCount :uint32) (pMemoryRanges (:pointer (:struct VkMappedMemoryRange)))) ;; :LEN "memoryRangeCount" (cffi:defcfun ("vkMapMemory" vkMapMemory) VkResult (device VkDevice) (memory VkDeviceMemory) ;; :EXTERNSYNC "true" (offset VkDeviceSize) (size VkDeviceSize) (flags VkMemoryMapFlags) ;; :OPTIONAL "true" (ppData (:pointer (:pointer :void)))) (cffi:defcfun ("vkMergePipelineCaches" vkMergePipelineCaches) VkResult (device VkDevice) (dstCache VkPipelineCache) ;; :EXTERNSYNC "true" (srcCacheCount :uint32) (pSrcCaches (:pointer VkPipelineCache))) ;; :LEN "srcCacheCount" (cffi:defcfun ("vkQueueBindSparse" vkQueueBindSparse) VkResult (queue VkQueue) ;; :EXTERNSYNC "true" (bindInfoCount :uint32) ;; :OPTIONAL "true" (pBindInfo (:pointer (:struct VkBindSparseInfo))) ;; :LEN "bindInfoCount" :EXTERNSYNC "pBindInfo[].pWaitSemaphores[],pBindInfo[].pSignalSemaphores[],pBindInfo[].pBufferBinds[].buffer,pBindInfo[].pImageOpaqueBinds[].image,pBindInfo[].pImageBinds[].image" (fence VkFence)) ;; :OPTIONAL "true" :EXTERNSYNC "true" (cffi:defcfun ("vkQueuePresentKHR" vkQueuePresentKHR) VkResult (queue VkQueue) ;; :EXTERNSYNC "true" (pPresentInfo (:pointer (:struct VkPresentInfoKHR)))) ;; :EXTERNSYNC "pPresentInfo.pWaitSemaphores[],pPresentInfo.pSwapchains[]" (cffi:defcfun ("vkQueueSubmit" vkQueueSubmit) VkResult (queue VkQueue) ;; :EXTERNSYNC "true" (submitCount :uint32) ;; :OPTIONAL "true" (pSubmits (:pointer (:struct VkSubmitInfo))) ;; :LEN "submitCount" :EXTERNSYNC "pSubmits[].pWaitSemaphores[],pSubmits[].pSignalSemaphores[]" (fence VkFence)) ;; :OPTIONAL "true" :EXTERNSYNC "true" (cffi:defcfun ("vkQueueWaitIdle" vkQueueWaitIdle) VkResult (queue VkQueue)) (defvkdevextfun ("vkRegisterDeviceEventEXT" vkRegisterDeviceEventEXT) VkResult (device VkDevice) (pDeviceEventInfo (:pointer (:struct VkDeviceEventInfoEXT))) (pAllocator (:pointer (:struct VkAllocationCallbacks))) (pFence (:pointer VkFence))) (defvkdevextfun ("vkRegisterDisplayEventEXT" vkRegisterDisplayEventEXT) VkResult (device VkDevice) (display VkDisplayKHR) (pDisplayEventInfo (:pointer (:struct VkDisplayEventInfoEXT))) (pAllocator (:pointer (:struct VkAllocationCallbacks))) (pFence (:pointer VkFence))) (defvkdevextfun ("vkRegisterObjectsNVX" vkRegisterObjectsNVX) VkResult (device VkDevice) (objectTable VkObjectTableNVX) ;; :EXTERNSYNC "true" (objectCount :uint32) (ppObjectTableEntries (:pointer (:pointer (:struct VkObjectTableEntryNVX)))) ;; :LEN "objectCount" (pObjectIndices (:pointer :uint32))) ;; :LEN "objectCount" (defvkinstextfun ("vkReleaseDisplayEXT" vkReleaseDisplayEXT) VkResult (physicalDevice VkPhysicalDevice) (display VkDisplayKHR)) (cffi:defcfun ("vkResetCommandBuffer" vkResetCommandBuffer) VkResult (commandBuffer VkCommandBuffer) ;; :EXTERNSYNC "true" (flags VkCommandBufferResetFlags)) ;; :OPTIONAL "true" (cffi:defcfun ("vkResetCommandPool" vkResetCommandPool) VkResult (device VkDevice) (commandPool VkCommandPool) ;; :EXTERNSYNC "true" (flags VkCommandPoolResetFlags)) ;; :OPTIONAL "true" (cffi:defcfun ("vkResetDescriptorPool" vkResetDescriptorPool) VkResult (device VkDevice) (descriptorPool VkDescriptorPool) ;; :EXTERNSYNC "true" (flags VkDescriptorPoolResetFlags)) ;; :OPTIONAL "true" (cffi:defcfun ("vkResetEvent" vkResetEvent) VkResult (device VkDevice) (event VkEvent)) ;; :EXTERNSYNC "true" (cffi:defcfun ("vkResetFences" vkResetFences) VkResult (device VkDevice) (fenceCount :uint32) (pFences (:pointer VkFence))) ;; :LEN "fenceCount" :EXTERNSYNC "true" (cffi:defcfun ("vkSetEvent" vkSetEvent) VkResult (device VkDevice) (event VkEvent)) ;; :EXTERNSYNC "true" (defvkdevextfun ("vkSetHdrMetadataEXT" vkSetHdrMetadataEXT) :void (device VkDevice) (swapchainCount :uint32) (pSwapchains (:pointer VkSwapchainKHR)) ;; :LEN "swapchainCount" (pMetadata (:pointer (:struct VkHdrMetadataEXT)))) ;; :LEN "swapchainCount" (defvkdevextfun ("vkTrimCommandPoolKHR" vkTrimCommandPoolKHR) :void (device VkDevice) (commandPool VkCommandPool) ;; :EXTERNSYNC "true" (flags VkCommandPoolTrimFlagsKHR)) ;; :OPTIONAL "true" (cffi:defcfun ("vkUnmapMemory" vkUnmapMemory) :void (device VkDevice) (memory VkDeviceMemory)) ;; :EXTERNSYNC "true" (defvkdevextfun ("vkUnregisterObjectsNVX" vkUnregisterObjectsNVX) VkResult (device VkDevice) (objectTable VkObjectTableNVX) ;; :EXTERNSYNC "true" (objectCount :uint32) (pObjectEntryTypes (:pointer VkObjectEntryTypeNVX)) ;; :LEN "objectCount" (pObjectIndices (:pointer :uint32))) ;; :LEN "objectCount" (defvkdevextfun ("vkUpdateDescriptorSetWithTemplateKHR" vkUpdateDescriptorSetWithTemplateKHR) :void (device VkDevice) (descriptorSet VkDescriptorSet) ;; :EXTERNSYNC "true" (descriptorUpdateTemplate VkDescriptorUpdateTemplateKHR) (pData (:pointer :void))) (cffi:defcfun ("vkUpdateDescriptorSets" vkUpdateDescriptorSets) :void (device VkDevice) (descriptorWriteCount :uint32) ;; :OPTIONAL "true" (pDescriptorWrites (:pointer (:struct VkWriteDescriptorSet))) ;; :LEN "descriptorWriteCount" :EXTERNSYNC "pDescriptorWrites[].dstSet" (descriptorCopyCount :uint32) ;; :OPTIONAL "true" (pDescriptorCopies (:pointer (:struct VkCopyDescriptorSet)))) ;; :LEN "descriptorCopyCount" :EXTERNSYNC "pDescriptorCopies[].dstSet" (cffi:defcfun ("vkWaitForFences" vkWaitForFences) VkResult (device VkDevice) (fenceCount :uint32) (pFences (:pointer VkFence)) ;; :LEN "fenceCount" (waitAll VkBool32) (timeout :uint64))
true
;;; this file is automatically generated, do not edit #|| "Copyright (c) 2015-2017 The Khronos Group Inc. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and/or associated documentation files (the \"Materials\"), to deal in the Materials without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Materials, and to permit persons to whom the Materials are 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 Materials. THE MATERIALS ARE 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 MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS. ------------------------------------------------------------------------" ||# ;; Changes (into Lisp) Copyright 2019 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 :cvk) (defvkdevextfun ("vkAcquireNextImage2KHX" vkAcquireNextImage2KHX) VkResult (device VkDevice) (pAcquireInfo (:pointer (:struct VkAcquireNextImageInfoKHX))) (pImageIndex (:pointer :uint32))) (cffi:defcfun ("vkAcquireNextImageKHR" vkAcquireNextImageKHR) VkResult (device VkDevice) (swapchain VkSwapchainKHR) ;; :EXTERNSYNC "true" (timeout :uint64) (semaphore VkSemaphore) ;; :OPTIONAL "true" :EXTERNSYNC "true" (fence VkFence) ;; :OPTIONAL "true" :EXTERNSYNC "true" (pImageIndex (:pointer :uint32))) (defvkinstextfun ("vkAcquireXlibDisplayEXT" vkAcquireXlibDisplayEXT) VkResult (physicalDevice VkPhysicalDevice) (dpy (:pointer Display)) (display VkDisplayKHR)) (cffi:defcfun ("vkAllocateCommandBuffers" vkAllocateCommandBuffers) VkResult (device VkDevice) (pAllocateInfo (:pointer (:struct VkCommandBufferAllocateInfo))) ;; :EXTERNSYNC "pAllocateInfo::commandPool" (pCommandBuffers (:pointer VkCommandBuffer))) ;; :LEN "pAllocateInfo::commandBufferCount" (cffi:defcfun ("vkAllocateDescriptorSets" vkAllocateDescriptorSets) VkResult (device VkDevice) (pAllocateInfo (:pointer (:struct VkDescriptorSetAllocateInfo))) ;; :EXTERNSYNC "pAllocateInfo::descriptorPool" (pDescriptorSets (:pointer VkDescriptorSet))) ;; :LEN "pAllocateInfo::descriptorSetCount" (cffi:defcfun ("vkAllocateMemory" vkAllocateMemory) VkResult (device VkDevice) (pAllocateInfo (:pointer (:struct VkMemoryAllocateInfo))) (pAllocator (:pointer (:struct VkAllocationCallbacks))) ;; :OPTIONAL "true" (pMemory (:pointer VkDeviceMemory))) (cffi:defcfun ("vkBeginCommandBuffer" vkBeginCommandBuffer) VkResult (commandBuffer VkCommandBuffer) ;; :EXTERNSYNC "true" (pBeginInfo (:pointer (:struct VkCommandBufferBeginInfo)))) (cffi:defcfun ("vkBindBufferMemory" vkBindBufferMemory) VkResult (device VkDevice) (buffer VkBuffer) ;; :EXTERNSYNC "true" (memory VkDeviceMemory) (memoryOffset VkDeviceSize)) (defvkdevextfun ("vkBindBufferMemory2KHX" vkBindBufferMemory2KHX) VkResult (device VkDevice) (bindInfoCount :uint32) (pBindInfos (:pointer (:struct VkBindBufferMemoryInfoKHX)))) ;; :LEN "bindInfoCount" (cffi:defcfun ("vkBindImageMemory" vkBindImageMemory) VkResult (device VkDevice) (image VkImage) ;; :EXTERNSYNC "true" (memory VkDeviceMemory) (memoryOffset VkDeviceSize)) (defvkdevextfun ("vkBindImageMemory2KHX" vkBindImageMemory2KHX) VkResult (device VkDevice) (bindInfoCount :uint32) (pBindInfos (:pointer (:struct VkBindImageMemoryInfoKHX)))) ;; :LEN "bindInfoCount" (cffi:defcfun ("vkCmdBeginQuery" vkCmdBeginQuery) :void (commandBuffer VkCommandBuffer) ;; :EXTERNSYNC "true" (queryPool VkQueryPool) (query :uint32) (flags VkQueryControlFlags)) ;; :OPTIONAL "true" (cffi:defcfun ("vkCmdBeginRenderPass" vkCmdBeginRenderPass) :void (commandBuffer VkCommandBuffer) ;; :EXTERNSYNC "true" (pRenderPassBegin (:pointer (:struct VkRenderPassBeginInfo))) (contents VkSubpassContents)) (cffi:defcfun ("vkCmdBindDescriptorSets" vkCmdBindDescriptorSets) :void (commandBuffer VkCommandBuffer) ;; :EXTERNSYNC "true" (pipelineBindPoint VkPipelineBindPoint) (layout VkPipelineLayout) (firstSet :uint32) (descriptorSetCount :uint32) (pDescriptorSets (:pointer VkDescriptorSet)) ;; :LEN "descriptorSetCount" (dynamicOffsetCount :uint32) ;; :OPTIONAL "true" (pDynamicOffsets (:pointer :uint32))) ;; :LEN "dynamicOffsetCount" (cffi:defcfun ("vkCmdBindIndexBuffer" vkCmdBindIndexBuffer) :void (commandBuffer VkCommandBuffer) ;; :EXTERNSYNC "true" (buffer VkBuffer) (offset VkDeviceSize) (indexType VkIndexType)) (cffi:defcfun ("vkCmdBindPipeline" vkCmdBindPipeline) :void (commandBuffer VkCommandBuffer) ;; :EXTERNSYNC "true" (pipelineBindPoint VkPipelineBindPoint) (pipeline VkPipeline)) (cffi:defcfun ("vkCmdBindVertexBuffers" vkCmdBindVertexBuffers) :void (commandBuffer VkCommandBuffer) ;; :EXTERNSYNC "true" (firstBinding :uint32) (bindingCount :uint32) (pBuffers (:pointer VkBuffer)) ;; :LEN "bindingCount" (pOffsets (:pointer VkDeviceSize))) ;; :LEN "bindingCount" (cffi:defcfun ("vkCmdBlitImage" vkCmdBlitImage) :void (commandBuffer VkCommandBuffer) ;; :EXTERNSYNC "true" (srcImage VkImage) (srcImageLayout VkImageLayout) (dstImage VkImage) (dstImageLayout VkImageLayout) (regionCount :uint32) (pRegions (:pointer (:struct VkImageBlit))) ;; :LEN "regionCount" (filter VkFilter)) (cffi:defcfun ("vkCmdClearAttachments" vkCmdClearAttachments) :void (commandBuffer VkCommandBuffer) ;; :EXTERNSYNC "true" (attachmentCount :uint32) (pAttachments (:pointer (:struct VkClearAttachment))) ;; :LEN "attachmentCount" (rectCount :uint32) (pRects (:pointer (:struct VkClearRect)))) ;; :LEN "rectCount" (cffi:defcfun ("vkCmdClearColorImage" vkCmdClearColorImage) :void (commandBuffer VkCommandBuffer) ;; :EXTERNSYNC "true" (image VkImage) (imageLayout VkImageLayout) (pColor (:pointer (:union VkClearColorValue))) (rangeCount :uint32) (pRanges (:pointer (:struct VkImageSubresourceRange)))) ;; :LEN "rangeCount" (cffi:defcfun ("vkCmdClearDepthStencilImage" vkCmdClearDepthStencilImage) :void (commandBuffer VkCommandBuffer) ;; :EXTERNSYNC "true" (image VkImage) (imageLayout VkImageLayout) (pDepthStencil (:pointer (:struct VkClearDepthStencilValue))) (rangeCount :uint32) (pRanges (:pointer (:struct VkImageSubresourceRange)))) ;; :LEN "rangeCount" (cffi:defcfun ("vkCmdCopyBuffer" vkCmdCopyBuffer) :void (commandBuffer VkCommandBuffer) ;; :EXTERNSYNC "true" (srcBuffer VkBuffer) (dstBuffer VkBuffer) (regionCount :uint32) (pRegions (:pointer (:struct VkBufferCopy)))) ;; :LEN "regionCount" (cffi:defcfun ("vkCmdCopyBufferToImage" vkCmdCopyBufferToImage) :void (commandBuffer VkCommandBuffer) ;; :EXTERNSYNC "true" (srcBuffer VkBuffer) (dstImage VkImage) (dstImageLayout VkImageLayout) (regionCount :uint32) (pRegions (:pointer (:struct VkBufferImageCopy)))) ;; :LEN "regionCount" (cffi:defcfun ("vkCmdCopyImage" vkCmdCopyImage) :void (commandBuffer VkCommandBuffer) ;; :EXTERNSYNC "true" (srcImage VkImage) (srcImageLayout VkImageLayout) (dstImage VkImage) (dstImageLayout VkImageLayout) (regionCount :uint32) (pRegions (:pointer (:struct VkImageCopy)))) ;; :LEN "regionCount" (cffi:defcfun ("vkCmdCopyImageToBuffer" vkCmdCopyImageToBuffer) :void (commandBuffer VkCommandBuffer) ;; :EXTERNSYNC "true" (srcImage VkImage) (srcImageLayout VkImageLayout) (dstBuffer VkBuffer) (regionCount :uint32) (pRegions (:pointer (:struct VkBufferImageCopy)))) ;; :LEN "regionCount" (cffi:defcfun ("vkCmdCopyQueryPoolResults" vkCmdCopyQueryPoolResults) :void (commandBuffer VkCommandBuffer) ;; :EXTERNSYNC "true" (queryPool VkQueryPool) (firstQuery :uint32) (queryCount :uint32) (dstBuffer VkBuffer) (dstOffset VkDeviceSize) (stride VkDeviceSize) (flags VkQueryResultFlags)) ;; :OPTIONAL "true" (defvkdevextfun ("vkCmdDebugMarkerBeginEXT" vkCmdDebugMarkerBeginEXT) :void (commandBuffer VkCommandBuffer) (pMarkerInfo (:pointer (:struct VkDebugMarkerMarkerInfoEXT)))) (defvkdevextfun ("vkCmdDebugMarkerEndEXT" vkCmdDebugMarkerEndEXT) :void (commandBuffer VkCommandBuffer)) (defvkdevextfun ("vkCmdDebugMarkerInsertEXT" vkCmdDebugMarkerInsertEXT) :void (commandBuffer VkCommandBuffer) (pMarkerInfo (:pointer (:struct VkDebugMarkerMarkerInfoEXT)))) (cffi:defcfun ("vkCmdDispatch" vkCmdDispatch) :void (commandBuffer VkCommandBuffer) ;; :EXTERNSYNC "true" (groupCountX :uint32) (groupCountY :uint32) (groupCountZ :uint32)) (defvkdevextfun ("vkCmdDispatchBaseKHX" vkCmdDispatchBaseKHX) :void (commandBuffer VkCommandBuffer) ;; :EXTERNSYNC "true" (baseGroupX :uint32) (baseGroupY :uint32) (baseGroupZ :uint32) (groupCountX :uint32) (groupCountY :uint32) (groupCountZ :uint32)) (cffi:defcfun ("vkCmdDispatchIndirect" vkCmdDispatchIndirect) :void (commandBuffer VkCommandBuffer) ;; :EXTERNSYNC "true" (buffer VkBuffer) (offset VkDeviceSize)) (cffi:defcfun ("vkCmdDraw" vkCmdDraw) :void (commandBuffer VkCommandBuffer) ;; :EXTERNSYNC "true" (vertexCount :uint32) (instanceCount :uint32) (firstVertex :uint32) (firstInstance :uint32)) (cffi:defcfun ("vkCmdDrawIndexed" vkCmdDrawIndexed) :void (commandBuffer VkCommandBuffer) ;; :EXTERNSYNC "true" (indexCount :uint32) (instanceCount :uint32) (firstIndex :uint32) (vertexOffset :int32) (firstInstance :uint32)) (cffi:defcfun ("vkCmdDrawIndexedIndirect" vkCmdDrawIndexedIndirect) :void (commandBuffer VkCommandBuffer) ;; :EXTERNSYNC "true" (buffer VkBuffer) (offset VkDeviceSize) (drawCount :uint32) (stride :uint32)) (defvkdevextfun ("vkCmdDrawIndexedIndirectCountAMD" vkCmdDrawIndexedIndirectCountAMD) :void (commandBuffer VkCommandBuffer) ;; :EXTERNSYNC "true" (buffer VkBuffer) (offset VkDeviceSize) (countBuffer VkBuffer) (countBufferOffset VkDeviceSize) (maxDrawCount :uint32) (stride :uint32)) (cffi:defcfun ("vkCmdDrawIndirect" vkCmdDrawIndirect) :void (commandBuffer VkCommandBuffer) ;; :EXTERNSYNC "true" (buffer VkBuffer) (offset VkDeviceSize) (drawCount :uint32) (stride :uint32)) (defvkdevextfun ("vkCmdDrawIndirectCountAMD" vkCmdDrawIndirectCountAMD) :void (commandBuffer VkCommandBuffer) ;; :EXTERNSYNC "true" (buffer VkBuffer) (offset VkDeviceSize) (countBuffer VkBuffer) (countBufferOffset VkDeviceSize) (maxDrawCount :uint32) (stride :uint32)) (cffi:defcfun ("vkCmdEndQuery" vkCmdEndQuery) :void (commandBuffer VkCommandBuffer) ;; :EXTERNSYNC "true" (queryPool VkQueryPool) (query :uint32)) (cffi:defcfun ("vkCmdEndRenderPass" vkCmdEndRenderPass) :void (commandBuffer VkCommandBuffer)) ;; :EXTERNSYNC "true" (cffi:defcfun ("vkCmdExecuteCommands" vkCmdExecuteCommands) :void (commandBuffer VkCommandBuffer) ;; :EXTERNSYNC "true" (commandBufferCount :uint32) (pCommandBuffers (:pointer VkCommandBuffer))) ;; :LEN "commandBufferCount" (cffi:defcfun ("vkCmdFillBuffer" vkCmdFillBuffer) :void (commandBuffer VkCommandBuffer) ;; :EXTERNSYNC "true" (dstBuffer VkBuffer) (dstOffset VkDeviceSize) (size VkDeviceSize) (data :uint32)) (cffi:defcfun ("vkCmdNextSubpass" vkCmdNextSubpass) :void (commandBuffer VkCommandBuffer) ;; :EXTERNSYNC "true" (contents VkSubpassContents)) (cffi:defcfun ("vkCmdPipelineBarrier" vkCmdPipelineBarrier) :void (commandBuffer VkCommandBuffer) ;; :EXTERNSYNC "true" (srcStageMask VkPipelineStageFlags) (dstStageMask VkPipelineStageFlags) (dependencyFlags VkDependencyFlags) ;; :OPTIONAL "true" (memoryBarrierCount :uint32) ;; :OPTIONAL "true" (pMemoryBarriers (:pointer (:struct VkMemoryBarrier))) ;; :LEN "memoryBarrierCount" (bufferMemoryBarrierCount :uint32) ;; :OPTIONAL "true" (pBufferMemoryBarriers (:pointer (:struct VkBufferMemoryBarrier))) ;; :LEN "bufferMemoryBarrierCount" (imageMemoryBarrierCount :uint32) ;; :OPTIONAL "true" (pImageMemoryBarriers (:pointer (:struct VkImageMemoryBarrier)))) ;; :LEN "imageMemoryBarrierCount" (defvkdevextfun ("vkCmdProcessCommandsNVX" vkCmdProcessCommandsNVX) :void (commandBuffer VkCommandBuffer) ;; :EXTERNSYNC "true" (pProcessCommandsInfo (:pointer (:struct VkCmdProcessCommandsInfoNVX)))) (cffi:defcfun ("vkCmdPushConstants" vkCmdPushConstants) :void (commandBuffer VkCommandBuffer) ;; :EXTERNSYNC "true" (layout VkPipelineLayout) (stageFlags VkShaderStageFlags) (offset :uint32) (size :uint32) (pValues (:pointer :void))) ;; :LEN "size" (defvkdevextfun ("vkCmdPushDescriptorSetKHR" vkCmdPushDescriptorSetKHR) :void (commandBuffer VkCommandBuffer) ;; :EXTERNSYNC "true" (pipelineBindPoint VkPipelineBindPoint) (layout VkPipelineLayout) (set :uint32) (descriptorWriteCount :uint32) (pDescriptorWrites (:pointer (:struct VkWriteDescriptorSet)))) ;; :LEN "descriptorWriteCount" (defvkdevextfun ("vkCmdPushDescriptorSetWithTemplateKHR" vkCmdPushDescriptorSetWithTemplateKHR) :void (commandBuffer VkCommandBuffer) ;; :EXTERNSYNC "true" (descriptorUpdateTemplate VkDescriptorUpdateTemplateKHR) (layout VkPipelineLayout) (set :uint32) (pData (:pointer :void))) (defvkdevextfun ("vkCmdReserveSpaceForCommandsNVX" vkCmdReserveSpaceForCommandsNVX) :void (commandBuffer VkCommandBuffer) ;; :EXTERNSYNC "true" (pReserveSpaceInfo (:pointer (:struct VkCmdReserveSpaceForCommandsInfoNVX)))) (cffi:defcfun ("vkCmdResetEvent" vkCmdResetEvent) :void (commandBuffer VkCommandBuffer) ;; :EXTERNSYNC "true" (event VkEvent) (stageMask VkPipelineStageFlags)) (cffi:defcfun ("vkCmdResetQueryPool" vkCmdResetQueryPool) :void (commandBuffer VkCommandBuffer) ;; :EXTERNSYNC "true" (queryPool VkQueryPool) (firstQuery :uint32) (queryCount :uint32)) (cffi:defcfun ("vkCmdResolveImage" vkCmdResolveImage) :void (commandBuffer VkCommandBuffer) ;; :EXTERNSYNC "true" (srcImage VkImage) (srcImageLayout VkImageLayout) (dstImage VkImage) (dstImageLayout VkImageLayout) (regionCount :uint32) (pRegions (:pointer (:struct VkImageResolve)))) ;; :LEN "regionCount" (cffi:defcfun ("vkCmdSetBlendConstants" vkCmdSetBlendConstants) :void (commandBuffer VkCommandBuffer) ;; :EXTERNSYNC "true" (blendConstants :float)) (cffi:defcfun ("vkCmdSetDepthBias" vkCmdSetDepthBias) :void (commandBuffer VkCommandBuffer) ;; :EXTERNSYNC "true" (depthBiasConstantFactor :float) (depthBiasClamp :float) (depthBiasSlopeFactor :float)) (cffi:defcfun ("vkCmdSetDepthBounds" vkCmdSetDepthBounds) :void (commandBuffer VkCommandBuffer) ;; :EXTERNSYNC "true" (minDepthBounds :float) (maxDepthBounds :float)) (defvkdevextfun ("vkCmdSetDeviceMaskKHX" vkCmdSetDeviceMaskKHX) :void (commandBuffer VkCommandBuffer) ;; :EXTERNSYNC "true" (deviceMask :uint32)) (defvkdevextfun ("vkCmdSetDiscardRectangleEXT" vkCmdSetDiscardRectangleEXT) :void (commandBuffer VkCommandBuffer) ;; :EXTERNSYNC "true" (firstDiscardRectangle :uint32) (discardRectangleCount :uint32) (pDiscardRectangles (:pointer (:struct VkRect2D)))) ;; :LEN "discardRectangleCount" (cffi:defcfun ("vkCmdSetEvent" vkCmdSetEvent) :void (commandBuffer VkCommandBuffer) ;; :EXTERNSYNC "true" (event VkEvent) (stageMask VkPipelineStageFlags)) (cffi:defcfun ("vkCmdSetLineWidth" vkCmdSetLineWidth) :void (commandBuffer VkCommandBuffer) ;; :EXTERNSYNC "true" (lineWidth :float)) (cffi:defcfun ("vkCmdSetScissor" vkCmdSetScissor) :void (commandBuffer VkCommandBuffer) ;; :EXTERNSYNC "true" (firstScissor :uint32) (scissorCount :uint32) (pScissors (:pointer (:struct VkRect2D)))) ;; :LEN "scissorCount" (cffi:defcfun ("vkCmdSetStencilCompareMask" vkCmdSetStencilCompareMask) :void (commandBuffer VkCommandBuffer) ;; :EXTERNSYNC "true" (faceMask VkStencilFaceFlags) (compareMask :uint32)) (cffi:defcfun ("vkCmdSetStencilReference" vkCmdSetStencilReference) :void (commandBuffer VkCommandBuffer) ;; :EXTERNSYNC "true" (faceMask VkStencilFaceFlags) (reference :uint32)) (cffi:defcfun ("vkCmdSetStencilWriteMask" vkCmdSetStencilWriteMask) :void (commandBuffer VkCommandBuffer) ;; :EXTERNSYNC "true" (faceMask VkStencilFaceFlags) (writeMask :uint32)) (cffi:defcfun ("vkCmdSetViewport" vkCmdSetViewport) :void (commandBuffer VkCommandBuffer) ;; :EXTERNSYNC "true" (firstViewport :uint32) (viewportCount :uint32) (pViewports (:pointer (:struct VkViewport)))) ;; :LEN "viewportCount" :NOAUTOVALIDITY "true" (defvkdevextfun ("vkCmdSetViewportWScalingNV" vkCmdSetViewportWScalingNV) :void (commandBuffer VkCommandBuffer) ;; :EXTERNSYNC "true" (firstViewport :uint32) (viewportCount :uint32) (pViewportWScalings (:pointer (:struct VkViewportWScalingNV)))) ;; :LEN "viewportCount" :NOAUTOVALIDITY "true" (cffi:defcfun ("vkCmdUpdateBuffer" vkCmdUpdateBuffer) :void (commandBuffer VkCommandBuffer) ;; :EXTERNSYNC "true" (dstBuffer VkBuffer) (dstOffset VkDeviceSize) (dataSize VkDeviceSize) (pData (:pointer :void))) ;; :LEN "dataSize" (cffi:defcfun ("vkCmdWaitEvents" vkCmdWaitEvents) :void (commandBuffer VkCommandBuffer) ;; :EXTERNSYNC "true" (eventCount :uint32) (pEvents (:pointer VkEvent)) ;; :LEN "eventCount" (srcStageMask VkPipelineStageFlags) (dstStageMask VkPipelineStageFlags) (memoryBarrierCount :uint32) ;; :OPTIONAL "true" (pMemoryBarriers (:pointer (:struct VkMemoryBarrier))) ;; :LEN "memoryBarrierCount" (bufferMemoryBarrierCount :uint32) ;; :OPTIONAL "true" (pBufferMemoryBarriers (:pointer (:struct VkBufferMemoryBarrier))) ;; :LEN "bufferMemoryBarrierCount" (imageMemoryBarrierCount :uint32) ;; :OPTIONAL "true" (pImageMemoryBarriers (:pointer (:struct VkImageMemoryBarrier)))) ;; :LEN "imageMemoryBarrierCount" (cffi:defcfun ("vkCmdWriteTimestamp" vkCmdWriteTimestamp) :void (commandBuffer VkCommandBuffer) ;; :EXTERNSYNC "true" (pipelineStage VkPipelineStageFlagBits) (queryPool VkQueryPool) (query :uint32)) (defvkinstextfun ("vkCreateAndroidSurfaceKHR" vkCreateAndroidSurfaceKHR) VkResult (instance VkInstance) (pCreateInfo (:pointer (:struct VkAndroidSurfaceCreateInfoKHR))) (pAllocator (:pointer (:struct VkAllocationCallbacks))) ;; :OPTIONAL "true" (pSurface (:pointer VkSurfaceKHR))) (cffi:defcfun ("vkCreateBuffer" vkCreateBuffer) VkResult (device VkDevice) (pCreateInfo (:pointer (:struct VkBufferCreateInfo))) (pAllocator (:pointer (:struct VkAllocationCallbacks))) ;; :OPTIONAL "true" (pBuffer (:pointer VkBuffer))) (cffi:defcfun ("vkCreateBufferView" vkCreateBufferView) VkResult (device VkDevice) (pCreateInfo (:pointer (:struct VkBufferViewCreateInfo))) (pAllocator (:pointer (:struct VkAllocationCallbacks))) ;; :OPTIONAL "true" (pView (:pointer VkBufferView))) (cffi:defcfun ("vkCreateCommandPool" vkCreateCommandPool) VkResult (device VkDevice) (pCreateInfo (:pointer (:struct VkCommandPoolCreateInfo))) (pAllocator (:pointer (:struct VkAllocationCallbacks))) ;; :OPTIONAL "true" (pCommandPool (:pointer VkCommandPool))) (cffi:defcfun ("vkCreateComputePipelines" vkCreateComputePipelines) VkResult (device VkDevice) (pipelineCache VkPipelineCache) ;; :OPTIONAL "true" (createInfoCount :uint32) (pCreateInfos (:pointer (:struct VkComputePipelineCreateInfo))) ;; :LEN "createInfoCount" (pAllocator (:pointer (:struct VkAllocationCallbacks))) ;; :OPTIONAL "true" (pPipelines (:pointer VkPipeline))) ;; :LEN "createInfoCount" (defvkinstextfun ("vkCreateDebugReportCallbackEXT" vkCreateDebugReportCallbackEXT) VkResult (instance VkInstance) (pCreateInfo (:pointer (:struct VkDebugReportCallbackCreateInfoEXT))) (pAllocator (:pointer (:struct VkAllocationCallbacks))) ;; :OPTIONAL "true" (pCallback (:pointer VkDebugReportCallbackEXT))) (cffi:defcfun ("vkCreateDescriptorPool" vkCreateDescriptorPool) VkResult (device VkDevice) (pCreateInfo (:pointer (:struct VkDescriptorPoolCreateInfo))) (pAllocator (:pointer (:struct VkAllocationCallbacks))) ;; :OPTIONAL "true" (pDescriptorPool (:pointer VkDescriptorPool))) (cffi:defcfun ("vkCreateDescriptorSetLayout" vkCreateDescriptorSetLayout) VkResult (device VkDevice) (pCreateInfo (:pointer (:struct VkDescriptorSetLayoutCreateInfo))) (pAllocator (:pointer (:struct VkAllocationCallbacks))) ;; :OPTIONAL "true" (pSetLayout (:pointer VkDescriptorSetLayout))) (defvkdevextfun ("vkCreateDescriptorUpdateTemplateKHR" vkCreateDescriptorUpdateTemplateKHR) VkResult (device VkDevice) (pCreateInfo (:pointer (:struct VkDescriptorUpdateTemplateCreateInfoKHR))) (pAllocator (:pointer (:struct VkAllocationCallbacks))) ;; :OPTIONAL "true" (pDescriptorUpdateTemplate (:pointer VkDescriptorUpdateTemplateKHR))) (cffi:defcfun ("vkCreateDevice" vkCreateDevice) VkResult (physicalDevice VkPhysicalDevice) (pCreateInfo (:pointer (:struct VkDeviceCreateInfo))) (pAllocator (:pointer (:struct VkAllocationCallbacks))) ;; :OPTIONAL "true" (pDevice (:pointer VkDevice))) (cffi:defcfun ("vkCreateDisplayModeKHR" vkCreateDisplayModeKHR) VkResult (physicalDevice VkPhysicalDevice) (display VkDisplayKHR) ;; :EXTERNSYNC "true" (pCreateInfo (:pointer (:struct VkDisplayModeCreateInfoKHR))) (pAllocator (:pointer (:struct VkAllocationCallbacks))) ;; :OPTIONAL "true" (pMode (:pointer VkDisplayModeKHR))) (cffi:defcfun ("vkCreateDisplayPlaneSurfaceKHR" vkCreateDisplayPlaneSurfaceKHR) VkResult (instance VkInstance) (pCreateInfo (:pointer (:struct VkDisplaySurfaceCreateInfoKHR))) (pAllocator (:pointer (:struct VkAllocationCallbacks))) ;; :OPTIONAL "true" (pSurface (:pointer VkSurfaceKHR))) (cffi:defcfun ("vkCreateEvent" vkCreateEvent) VkResult (device VkDevice) (pCreateInfo (:pointer (:struct VkEventCreateInfo))) (pAllocator (:pointer (:struct VkAllocationCallbacks))) ;; :OPTIONAL "true" (pEvent (:pointer VkEvent))) (cffi:defcfun ("vkCreateFence" vkCreateFence) VkResult (device VkDevice) (pCreateInfo (:pointer (:struct VkFenceCreateInfo))) (pAllocator (:pointer (:struct VkAllocationCallbacks))) ;; :OPTIONAL "true" (pFence (:pointer VkFence))) (cffi:defcfun ("vkCreateFramebuffer" vkCreateFramebuffer) VkResult (device VkDevice) (pCreateInfo (:pointer (:struct VkFramebufferCreateInfo))) (pAllocator (:pointer (:struct VkAllocationCallbacks))) ;; :OPTIONAL "true" (pFramebuffer (:pointer VkFramebuffer))) (cffi:defcfun ("vkCreateGraphicsPipelines" vkCreateGraphicsPipelines) VkResult (device VkDevice) (pipelineCache VkPipelineCache) ;; :OPTIONAL "true" (createInfoCount :uint32) (pCreateInfos (:pointer (:struct VkGraphicsPipelineCreateInfo))) ;; :LEN "createInfoCount" (pAllocator (:pointer (:struct VkAllocationCallbacks))) ;; :OPTIONAL "true" (pPipelines (:pointer VkPipeline))) ;; :LEN "createInfoCount" (defvkinstextfun ("vkCreateIOSSurfaceMVK" vkCreateIOSSurfaceMVK) VkResult (instance VkInstance) (pCreateInfo (:pointer (:struct VkIOSSurfaceCreateInfoMVK))) (pAllocator (:pointer (:struct VkAllocationCallbacks))) ;; :OPTIONAL "true" (pSurface (:pointer VkSurfaceKHR))) (cffi:defcfun ("vkCreateImage" vkCreateImage) VkResult (device VkDevice) (pCreateInfo (:pointer (:struct VkImageCreateInfo))) (pAllocator (:pointer (:struct VkAllocationCallbacks))) ;; :OPTIONAL "true" (pImage (:pointer VkImage))) (cffi:defcfun ("vkCreateImageView" vkCreateImageView) VkResult (device VkDevice) (pCreateInfo (:pointer (:struct VkImageViewCreateInfo))) (pAllocator (:pointer (:struct VkAllocationCallbacks))) ;; :OPTIONAL "true" (pView (:pointer VkImageView))) (defvkdevextfun ("vkCreateIndirectCommandsLayoutNVX" vkCreateIndirectCommandsLayoutNVX) VkResult (device VkDevice) (pCreateInfo (:pointer (:struct VkIndirectCommandsLayoutCreateInfoNVX))) (pAllocator (:pointer (:struct VkAllocationCallbacks))) ;; :OPTIONAL "true" (pIndirectCommandsLayout (:pointer VkIndirectCommandsLayoutNVX))) (cffi:defcfun ("vkCreateInstance" vkCreateInstance) VkResult (pCreateInfo (:pointer (:struct VkInstanceCreateInfo))) (pAllocator (:pointer (:struct VkAllocationCallbacks))) ;; :OPTIONAL "true" (pInstance (:pointer VkInstance))) (defvkinstextfun ("vkCreateMacOSSurfaceMVK" vkCreateMacOSSurfaceMVK) VkResult (instance VkInstance) (pCreateInfo (:pointer (:struct VkMacOSSurfaceCreateInfoMVK))) (pAllocator (:pointer (:struct VkAllocationCallbacks))) ;; :OPTIONAL "true" (pSurface (:pointer VkSurfaceKHR))) (defvkinstextfun ("vkCreateMirSurfaceKHR" vkCreateMirSurfaceKHR) VkResult (instance VkInstance) (pCreateInfo (:pointer (:struct VkMirSurfaceCreateInfoKHR))) (pAllocator (:pointer (:struct VkAllocationCallbacks))) ;; :OPTIONAL "true" (pSurface (:pointer VkSurfaceKHR))) (defvkdevextfun ("vkCreateObjectTableNVX" vkCreateObjectTableNVX) VkResult (device VkDevice) (pCreateInfo (:pointer (:struct VkObjectTableCreateInfoNVX))) (pAllocator (:pointer (:struct VkAllocationCallbacks))) ;; :OPTIONAL "true" (pObjectTable (:pointer VkObjectTableNVX))) (cffi:defcfun ("vkCreatePipelineCache" vkCreatePipelineCache) VkResult (device VkDevice) (pCreateInfo (:pointer (:struct VkPipelineCacheCreateInfo))) (pAllocator (:pointer (:struct VkAllocationCallbacks))) ;; :OPTIONAL "true" (pPipelineCache (:pointer VkPipelineCache))) (cffi:defcfun ("vkCreatePipelineLayout" vkCreatePipelineLayout) VkResult (device VkDevice) (pCreateInfo (:pointer (:struct VkPipelineLayoutCreateInfo))) (pAllocator (:pointer (:struct VkAllocationCallbacks))) ;; :OPTIONAL "true" (pPipelineLayout (:pointer VkPipelineLayout))) (cffi:defcfun ("vkCreateQueryPool" vkCreateQueryPool) VkResult (device VkDevice) (pCreateInfo (:pointer (:struct VkQueryPoolCreateInfo))) (pAllocator (:pointer (:struct VkAllocationCallbacks))) ;; :OPTIONAL "true" (pQueryPool (:pointer VkQueryPool))) (cffi:defcfun ("vkCreateRenderPass" vkCreateRenderPass) VkResult (device VkDevice) (pCreateInfo (:pointer (:struct VkRenderPassCreateInfo))) (pAllocator (:pointer (:struct VkAllocationCallbacks))) ;; :OPTIONAL "true" (pRenderPass (:pointer VkRenderPass))) (cffi:defcfun ("vkCreateSampler" vkCreateSampler) VkResult (device VkDevice) (pCreateInfo (:pointer (:struct VkSamplerCreateInfo))) (pAllocator (:pointer (:struct VkAllocationCallbacks))) ;; :OPTIONAL "true" (pSampler (:pointer VkSampler))) (cffi:defcfun ("vkCreateSemaphore" vkCreateSemaphore) VkResult (device VkDevice) (pCreateInfo (:pointer (:struct VkSemaphoreCreateInfo))) (pAllocator (:pointer (:struct VkAllocationCallbacks))) ;; :OPTIONAL "true" (pSemaphore (:pointer VkSemaphore))) (cffi:defcfun ("vkCreateShaderModule" vkCreateShaderModule) VkResult (device VkDevice) (pCreateInfo (:pointer (:struct VkShaderModuleCreateInfo))) (pAllocator (:pointer (:struct VkAllocationCallbacks))) ;; :OPTIONAL "true" (pShaderModule (:pointer VkShaderModule))) (cffi:defcfun ("vkCreateSharedSwapchainsKHR" vkCreateSharedSwapchainsKHR) VkResult (device VkDevice) (swapchainCount :uint32) (pCreateInfos (:pointer (:struct VkSwapchainCreateInfoKHR))) ;; :LEN "swapchainCount" :EXTERNSYNC "pCreateInfos[].surface,pCreateInfos[].oldSwapchain" (pAllocator (:pointer (:struct VkAllocationCallbacks))) ;; :OPTIONAL "true" (pSwapchains (:pointer VkSwapchainKHR))) ;; :LEN "swapchainCount" (cffi:defcfun ("vkCreateSwapchainKHR" vkCreateSwapchainKHR) VkResult (device VkDevice) (pCreateInfo (:pointer (:struct VkSwapchainCreateInfoKHR))) ;; :EXTERNSYNC "pCreateInfo.surface,pCreateInfo.oldSwapchain" (pAllocator (:pointer (:struct VkAllocationCallbacks))) ;; :OPTIONAL "true" (pSwapchain (:pointer VkSwapchainKHR))) (defvkinstextfun ("vkCreateViSurfaceNN" vkCreateViSurfaceNN) VkResult (instance VkInstance) (pCreateInfo (:pointer (:struct VkViSurfaceCreateInfoNN))) (pAllocator (:pointer (:struct VkAllocationCallbacks))) ;; :OPTIONAL "true" (pSurface (:pointer VkSurfaceKHR))) (defvkinstextfun ("vkCreateWaylandSurfaceKHR" vkCreateWaylandSurfaceKHR) VkResult (instance VkInstance) (pCreateInfo (:pointer (:struct VkWaylandSurfaceCreateInfoKHR))) (pAllocator (:pointer (:struct VkAllocationCallbacks))) ;; :OPTIONAL "true" (pSurface (:pointer VkSurfaceKHR))) (cffi:defcfun ("vkCreateWin32SurfaceKHR" vkCreateWin32SurfaceKHR) VkResult (instance VkInstance) (pCreateInfo (:pointer (:struct VkWin32SurfaceCreateInfoKHR))) (pAllocator (:pointer (:struct VkAllocationCallbacks))) ;; :OPTIONAL "true" (pSurface (:pointer VkSurfaceKHR))) (defvkinstextfun ("vkCreateXcbSurfaceKHR" vkCreateXcbSurfaceKHR) VkResult (instance VkInstance) (pCreateInfo (:pointer (:struct VkXcbSurfaceCreateInfoKHR))) (pAllocator (:pointer (:struct VkAllocationCallbacks))) ;; :OPTIONAL "true" (pSurface (:pointer VkSurfaceKHR))) (defvkinstextfun ("vkCreateXlibSurfaceKHR" vkCreateXlibSurfaceKHR) VkResult (instance VkInstance) (pCreateInfo (:pointer (:struct VkXlibSurfaceCreateInfoKHR))) (pAllocator (:pointer (:struct VkAllocationCallbacks))) ;; :OPTIONAL "true" (pSurface (:pointer VkSurfaceKHR))) (defvkdevextfun ("vkDebugMarkerSetObjectNameEXT" vkDebugMarkerSetObjectNameEXT) VkResult (device VkDevice) (pNameInfo (:pointer (:struct VkDebugMarkerObjectNameInfoEXT)))) ;; :EXTERNSYNC "pNameInfo.object" (defvkdevextfun ("vkDebugMarkerSetObjectTagEXT" vkDebugMarkerSetObjectTagEXT) VkResult (device VkDevice) (pTagInfo (:pointer (:struct VkDebugMarkerObjectTagInfoEXT)))) ;; :EXTERNSYNC "pTagInfo.object" (defvkinstextfun ("vkDebugReportMessageEXT" vkDebugReportMessageEXT) :void (instance VkInstance) (flags VkDebugReportFlagsEXT) (objectType VkDebugReportObjectTypeEXT) (object :uint64) (location size-t) (messageCode :int32) (pLayerPrefix (:pointer :char)) ;; :LEN "null-terminated" (pMessage (:pointer :char))) ;; :LEN "null-terminated" (cffi:defcfun ("vkDestroyBuffer" vkDestroyBuffer) :void (device VkDevice) (buffer VkBuffer) ;; :OPTIONAL "true" :EXTERNSYNC "true" (pAllocator (:pointer (:struct VkAllocationCallbacks)))) ;; :OPTIONAL "true" (cffi:defcfun ("vkDestroyBufferView" vkDestroyBufferView) :void (device VkDevice) (bufferView VkBufferView) ;; :OPTIONAL "true" :EXTERNSYNC "true" (pAllocator (:pointer (:struct VkAllocationCallbacks)))) ;; :OPTIONAL "true" (cffi:defcfun ("vkDestroyCommandPool" vkDestroyCommandPool) :void (device VkDevice) (commandPool VkCommandPool) ;; :OPTIONAL "true" :EXTERNSYNC "true" (pAllocator (:pointer (:struct VkAllocationCallbacks)))) ;; :OPTIONAL "true" (defvkinstextfun ("vkDestroyDebugReportCallbackEXT" vkDestroyDebugReportCallbackEXT) :void (instance VkInstance) (callback VkDebugReportCallbackEXT) ;; :EXTERNSYNC "true" (pAllocator (:pointer (:struct VkAllocationCallbacks)))) ;; :OPTIONAL "true" (cffi:defcfun ("vkDestroyDescriptorPool" vkDestroyDescriptorPool) :void (device VkDevice) (descriptorPool VkDescriptorPool) ;; :OPTIONAL "true" :EXTERNSYNC "true" (pAllocator (:pointer (:struct VkAllocationCallbacks)))) ;; :OPTIONAL "true" (cffi:defcfun ("vkDestroyDescriptorSetLayout" vkDestroyDescriptorSetLayout) :void (device VkDevice) (descriptorSetLayout VkDescriptorSetLayout) ;; :OPTIONAL "true" :EXTERNSYNC "true" (pAllocator (:pointer (:struct VkAllocationCallbacks)))) ;; :OPTIONAL "true" (defvkdevextfun ("vkDestroyDescriptorUpdateTemplateKHR" vkDestroyDescriptorUpdateTemplateKHR) :void (device VkDevice) (descriptorUpdateTemplate VkDescriptorUpdateTemplateKHR) ;; :OPTIONAL "true" :EXTERNSYNC "true" (pAllocator (:pointer (:struct VkAllocationCallbacks)))) ;; :OPTIONAL "true" (cffi:defcfun ("vkDestroyDevice" vkDestroyDevice) :void (device VkDevice) ;; :OPTIONAL "true" :EXTERNSYNC "true" (pAllocator (:pointer (:struct VkAllocationCallbacks)))) ;; :OPTIONAL "true" (cffi:defcfun ("vkDestroyEvent" vkDestroyEvent) :void (device VkDevice) (event VkEvent) ;; :OPTIONAL "true" :EXTERNSYNC "true" (pAllocator (:pointer (:struct VkAllocationCallbacks)))) ;; :OPTIONAL "true" (cffi:defcfun ("vkDestroyFence" vkDestroyFence) :void (device VkDevice) (fence VkFence) ;; :OPTIONAL "true" :EXTERNSYNC "true" (pAllocator (:pointer (:struct VkAllocationCallbacks)))) ;; :OPTIONAL "true" (cffi:defcfun ("vkDestroyFramebuffer" vkDestroyFramebuffer) :void (device VkDevice) (framebuffer VkFramebuffer) ;; :OPTIONAL "true" :EXTERNSYNC "true" (pAllocator (:pointer (:struct VkAllocationCallbacks)))) ;; :OPTIONAL "true" (cffi:defcfun ("vkDestroyImage" vkDestroyImage) :void (device VkDevice) (image VkImage) ;; :OPTIONAL "true" :EXTERNSYNC "true" (pAllocator (:pointer (:struct VkAllocationCallbacks)))) ;; :OPTIONAL "true" (cffi:defcfun ("vkDestroyImageView" vkDestroyImageView) :void (device VkDevice) (imageView VkImageView) ;; :OPTIONAL "true" :EXTERNSYNC "true" (pAllocator (:pointer (:struct VkAllocationCallbacks)))) ;; :OPTIONAL "true" (defvkdevextfun ("vkDestroyIndirectCommandsLayoutNVX" vkDestroyIndirectCommandsLayoutNVX) :void (device VkDevice) (indirectCommandsLayout VkIndirectCommandsLayoutNVX) (pAllocator (:pointer (:struct VkAllocationCallbacks)))) ;; :OPTIONAL "true" (cffi:defcfun ("vkDestroyInstance" vkDestroyInstance) :void (instance VkInstance) ;; :OPTIONAL "true" :EXTERNSYNC "true" (pAllocator (:pointer (:struct VkAllocationCallbacks)))) ;; :OPTIONAL "true" (defvkdevextfun ("vkDestroyObjectTableNVX" vkDestroyObjectTableNVX) :void (device VkDevice) (objectTable VkObjectTableNVX) ;; :EXTERNSYNC "true" (pAllocator (:pointer (:struct VkAllocationCallbacks)))) ;; :OPTIONAL "true" (cffi:defcfun ("vkDestroyPipeline" vkDestroyPipeline) :void (device VkDevice) (pipeline VkPipeline) ;; :OPTIONAL "true" :EXTERNSYNC "true" (pAllocator (:pointer (:struct VkAllocationCallbacks)))) ;; :OPTIONAL "true" (cffi:defcfun ("vkDestroyPipelineCache" vkDestroyPipelineCache) :void (device VkDevice) (pipelineCache VkPipelineCache) ;; :OPTIONAL "true" :EXTERNSYNC "true" (pAllocator (:pointer (:struct VkAllocationCallbacks)))) ;; :OPTIONAL "true" (cffi:defcfun ("vkDestroyPipelineLayout" vkDestroyPipelineLayout) :void (device VkDevice) (pipelineLayout VkPipelineLayout) ;; :OPTIONAL "true" :EXTERNSYNC "true" (pAllocator (:pointer (:struct VkAllocationCallbacks)))) ;; :OPTIONAL "true" (cffi:defcfun ("vkDestroyQueryPool" vkDestroyQueryPool) :void (device VkDevice) (queryPool VkQueryPool) ;; :OPTIONAL "true" :EXTERNSYNC "true" (pAllocator (:pointer (:struct VkAllocationCallbacks)))) ;; :OPTIONAL "true" (cffi:defcfun ("vkDestroyRenderPass" vkDestroyRenderPass) :void (device VkDevice) (renderPass VkRenderPass) ;; :OPTIONAL "true" :EXTERNSYNC "true" (pAllocator (:pointer (:struct VkAllocationCallbacks)))) ;; :OPTIONAL "true" (cffi:defcfun ("vkDestroySampler" vkDestroySampler) :void (device VkDevice) (sampler VkSampler) ;; :OPTIONAL "true" :EXTERNSYNC "true" (pAllocator (:pointer (:struct VkAllocationCallbacks)))) ;; :OPTIONAL "true" (cffi:defcfun ("vkDestroySemaphore" vkDestroySemaphore) :void (device VkDevice) (semaphore VkSemaphore) ;; :OPTIONAL "true" :EXTERNSYNC "true" (pAllocator (:pointer (:struct VkAllocationCallbacks)))) ;; :OPTIONAL "true" (cffi:defcfun ("vkDestroyShaderModule" vkDestroyShaderModule) :void (device VkDevice) (shaderModule VkShaderModule) ;; :OPTIONAL "true" :EXTERNSYNC "true" (pAllocator (:pointer (:struct VkAllocationCallbacks)))) ;; :OPTIONAL "true" (cffi:defcfun ("vkDestroySurfaceKHR" vkDestroySurfaceKHR) :void (instance VkInstance) (surface VkSurfaceKHR) ;; :OPTIONAL "true" :EXTERNSYNC "true" (pAllocator (:pointer (:struct VkAllocationCallbacks)))) ;; :OPTIONAL "true" (cffi:defcfun ("vkDestroySwapchainKHR" vkDestroySwapchainKHR) :void (device VkDevice) (swapchain VkSwapchainKHR) ;; :OPTIONAL "true" :EXTERNSYNC "true" (pAllocator (:pointer (:struct VkAllocationCallbacks)))) ;; :OPTIONAL "true" (cffi:defcfun ("vkDeviceWaitIdle" vkDeviceWaitIdle) VkResult (device VkDevice)) (defvkdevextfun ("vkDisplayPowerControlEXT" vkDisplayPowerControlEXT) VkResult (device VkDevice) (display VkDisplayKHR) (pDisplayPowerInfo (:pointer (:struct VkDisplayPowerInfoEXT)))) (cffi:defcfun ("vkEndCommandBuffer" vkEndCommandBuffer) VkResult (commandBuffer VkCommandBuffer)) ;; :EXTERNSYNC "true" (cffi:defcfun ("vkEnumerateDeviceExtensionProperties" vkEnumerateDeviceExtensionProperties) VkResult (physicalDevice VkPhysicalDevice) (pLayerName (:pointer :char)) ;; :OPTIONAL "true" :LEN "null-terminated" (pPropertyCount (:pointer :uint32)) ;; :OPTIONAL "false,true" (pProperties (:pointer (:struct VkExtensionProperties)))) ;; :OPTIONAL "true" :LEN "pPropertyCount" (cffi:defcfun ("vkEnumerateDeviceLayerProperties" vkEnumerateDeviceLayerProperties) VkResult (physicalDevice VkPhysicalDevice) (pPropertyCount (:pointer :uint32)) ;; :OPTIONAL "false,true" (pProperties (:pointer (:struct VkLayerProperties)))) ;; :OPTIONAL "true" :LEN "pPropertyCount" (cffi:defcfun ("vkEnumerateInstanceExtensionProperties" vkEnumerateInstanceExtensionProperties) VkResult (pLayerName (:pointer :char)) ;; :OPTIONAL "true" :LEN "null-terminated" (pPropertyCount (:pointer :uint32)) ;; :OPTIONAL "false,true" (pProperties (:pointer (:struct VkExtensionProperties)))) ;; :OPTIONAL "true" :LEN "pPropertyCount" (cffi:defcfun ("vkEnumerateInstanceLayerProperties" vkEnumerateInstanceLayerProperties) VkResult (pPropertyCount (:pointer :uint32)) ;; :OPTIONAL "false,true" (pProperties (:pointer (:struct VkLayerProperties)))) ;; :OPTIONAL "true" :LEN "pPropertyCount" (defvkinstextfun ("vkEnumeratePhysicalDeviceGroupsKHX" vkEnumeratePhysicalDeviceGroupsKHX) VkResult (instance VkInstance) (pPhysicalDeviceGroupCount (:pointer :uint32)) ;; :OPTIONAL "false,true" (pPhysicalDeviceGroupProperties (:pointer (:struct VkPhysicalDeviceGroupPropertiesKHX)))) ;; :OPTIONAL "true" :LEN "pPhysicalDeviceGroupCount" (cffi:defcfun ("vkEnumeratePhysicalDevices" vkEnumeratePhysicalDevices) VkResult (instance VkInstance) (pPhysicalDeviceCount (:pointer :uint32)) ;; :OPTIONAL "false,true" (pPhysicalDevices (:pointer VkPhysicalDevice))) ;; :OPTIONAL "true" :LEN "pPhysicalDeviceCount" (cffi:defcfun ("vkFlushMappedMemoryRanges" vkFlushMappedMemoryRanges) VkResult (device VkDevice) (memoryRangeCount :uint32) (pMemoryRanges (:pointer (:struct VkMappedMemoryRange)))) ;; :LEN "memoryRangeCount" (cffi:defcfun ("vkFreeCommandBuffers" vkFreeCommandBuffers) :void (device VkDevice) (commandPool VkCommandPool) ;; :EXTERNSYNC "true" (commandBufferCount :uint32) (pCommandBuffers (:pointer VkCommandBuffer))) ;; :LEN "commandBufferCount" :NOAUTOVALIDITY "true" :EXTERNSYNC "true" (cffi:defcfun ("vkFreeDescriptorSets" vkFreeDescriptorSets) VkResult (device VkDevice) (descriptorPool VkDescriptorPool) ;; :EXTERNSYNC "true" (descriptorSetCount :uint32) (pDescriptorSets (:pointer VkDescriptorSet))) ;; :LEN "descriptorSetCount" :NOAUTOVALIDITY "true" :EXTERNSYNC "true" (cffi:defcfun ("vkFreeMemory" vkFreeMemory) :void (device VkDevice) (memory VkDeviceMemory) ;; :OPTIONAL "true" :EXTERNSYNC "true" (pAllocator (:pointer (:struct VkAllocationCallbacks)))) ;; :OPTIONAL "true" (cffi:defcfun ("vkGetBufferMemoryRequirements" vkGetBufferMemoryRequirements) :void (device VkDevice) (buffer VkBuffer) (pMemoryRequirements (:pointer (:struct VkMemoryRequirements)))) (defvkdevextfun ("vkGetDeviceGroupPeerMemoryFeaturesKHX" vkGetDeviceGroupPeerMemoryFeaturesKHX) :void (device VkDevice) (heapIndex :uint32) (localDeviceIndex :uint32) (remoteDeviceIndex :uint32) (pPeerMemoryFeatures (:pointer VkPeerMemoryFeatureFlagsKHX))) (defvkdevextfun ("vkGetDeviceGroupPresentCapabilitiesKHX" vkGetDeviceGroupPresentCapabilitiesKHX) VkResult (device VkDevice) (pDeviceGroupPresentCapabilities (:pointer (:struct VkDeviceGroupPresentCapabilitiesKHX)))) (defvkdevextfun ("vkGetDeviceGroupSurfacePresentModesKHX" vkGetDeviceGroupSurfacePresentModesKHX) VkResult (device VkDevice) (surface VkSurfaceKHR) ;; :EXTERNSYNC "true" (pModes (:pointer VkDeviceGroupPresentModeFlagsKHX))) (cffi:defcfun ("vkGetDeviceMemoryCommitment" vkGetDeviceMemoryCommitment) :void (device VkDevice) (memory VkDeviceMemory) (pCommittedMemoryInBytes (:pointer VkDeviceSize))) (cffi:defcfun ("vkGetDeviceProcAddr" vkGetDeviceProcAddr) PFN_vkVoidFunction (device VkDevice) (pName (:pointer :char))) ;; :LEN "null-terminated" (cffi:defcfun ("vkGetDeviceQueue" vkGetDeviceQueue) :void (device VkDevice) (queueFamilyIndex :uint32) (queueIndex :uint32) (pQueue (:pointer VkQueue))) (cffi:defcfun ("vkGetDisplayModePropertiesKHR" vkGetDisplayModePropertiesKHR) VkResult (physicalDevice VkPhysicalDevice) (display VkDisplayKHR) (pPropertyCount (:pointer :uint32)) ;; :OPTIONAL "false,true" (pProperties (:pointer (:struct VkDisplayModePropertiesKHR)))) ;; :OPTIONAL "true" :LEN "pPropertyCount" (cffi:defcfun ("vkGetDisplayPlaneCapabilitiesKHR" vkGetDisplayPlaneCapabilitiesKHR) VkResult (physicalDevice VkPhysicalDevice) (mode VkDisplayModeKHR) ;; :EXTERNSYNC "true" (planeIndex :uint32) (pCapabilities (:pointer (:struct VkDisplayPlaneCapabilitiesKHR)))) (cffi:defcfun ("vkGetDisplayPlaneSupportedDisplaysKHR" vkGetDisplayPlaneSupportedDisplaysKHR) VkResult (physicalDevice VkPhysicalDevice) (planeIndex :uint32) (pDisplayCount (:pointer :uint32)) ;; :OPTIONAL "false,true" (pDisplays (:pointer VkDisplayKHR))) ;; :OPTIONAL "true" :LEN "pDisplayCount" (cffi:defcfun ("vkGetEventStatus" vkGetEventStatus) VkResult (device VkDevice) (event VkEvent)) (cffi:defcfun ("vkGetFenceStatus" vkGetFenceStatus) VkResult (device VkDevice) (fence VkFence)) (cffi:defcfun ("vkGetImageMemoryRequirements" vkGetImageMemoryRequirements) :void (device VkDevice) (image VkImage) (pMemoryRequirements (:pointer (:struct VkMemoryRequirements)))) (cffi:defcfun ("vkGetImageSparseMemoryRequirements" vkGetImageSparseMemoryRequirements) :void (device VkDevice) (image VkImage) (pSparseMemoryRequirementCount (:pointer :uint32)) ;; :OPTIONAL "false,true" (pSparseMemoryRequirements (:pointer (:struct VkSparseImageMemoryRequirements)))) ;; :OPTIONAL "true" :LEN "pSparseMemoryRequirementCount" (cffi:defcfun ("vkGetImageSubresourceLayout" vkGetImageSubresourceLayout) :void (device VkDevice) (image VkImage) (pSubresource (:pointer (:struct VkImageSubresource))) (pLayout (:pointer (:struct VkSubresourceLayout)))) (cffi:defcfun ("vkGetInstanceProcAddr" vkGetInstanceProcAddr) PFN_vkVoidFunction (instance VkInstance) ;; :OPTIONAL "true" (pName (:pointer :char))) ;; :LEN "null-terminated" (defvkdevextfun ("vkGetMemoryFdKHX" vkGetMemoryFdKHX) VkResult (device VkDevice) (memory VkDeviceMemory) (handleType VkExternalMemoryHandleTypeFlagBitsKHX) (pFd (:pointer :int))) (defvkdevextfun ("vkGetMemoryFdPropertiesKHX" vkGetMemoryFdPropertiesKHX) VkResult (device VkDevice) (handleType VkExternalMemoryHandleTypeFlagBitsKHX) (fd :int) (pMemoryFdProperties (:pointer (:struct VkMemoryFdPropertiesKHX)))) (defvkdevextfun ("vkGetMemoryWin32HandleKHX" vkGetMemoryWin32HandleKHX) VkResult (device VkDevice) (memory VkDeviceMemory) (handleType VkExternalMemoryHandleTypeFlagBitsKHX) (pHandle (:pointer HANDLE))) (defvkdevextfun ("vkGetMemoryWin32HandleNV" vkGetMemoryWin32HandleNV) VkResult (device VkDevice) (memory VkDeviceMemory) (handleType VkExternalMemoryHandleTypeFlagsNV) (pHandle (:pointer HANDLE))) (defvkdevextfun ("vkGetMemoryWin32HandlePropertiesKHX" vkGetMemoryWin32HandlePropertiesKHX) VkResult (device VkDevice) (handleType VkExternalMemoryHandleTypeFlagBitsKHX) (handle HANDLE) (pMemoryWin32HandleProperties (:pointer (:struct VkMemoryWin32HandlePropertiesKHX)))) (defvkdevextfun ("vkGetPastPresentationTimingGOOGLE" vkGetPastPresentationTimingGOOGLE) VkResult (device VkDevice) (swapchain VkSwapchainKHR) ;; :EXTERNSYNC "true" (pPresentationTimingCount (:pointer :uint32)) ;; :OPTIONAL "false,true" (pPresentationTimings (:pointer (:struct VkPastPresentationTimingGOOGLE)))) ;; :OPTIONAL "true" :LEN "pPresentationTimingCount" (cffi:defcfun ("vkGetPhysicalDeviceDisplayPlanePropertiesKHR" vkGetPhysicalDeviceDisplayPlanePropertiesKHR) VkResult (physicalDevice VkPhysicalDevice) (pPropertyCount (:pointer :uint32)) ;; :OPTIONAL "false,true" (pProperties (:pointer (:struct VkDisplayPlanePropertiesKHR)))) ;; :OPTIONAL "true" :LEN "pPropertyCount" (cffi:defcfun ("vkGetPhysicalDeviceDisplayPropertiesKHR" vkGetPhysicalDeviceDisplayPropertiesKHR) VkResult (physicalDevice VkPhysicalDevice) (pPropertyCount (:pointer :uint32)) ;; :OPTIONAL "false,true" (pProperties (:pointer (:struct VkDisplayPropertiesKHR)))) ;; :OPTIONAL "true" :LEN "pPropertyCount" (defvkinstextfun ("vkGetPhysicalDeviceExternalBufferPropertiesKHX" vkGetPhysicalDeviceExternalBufferPropertiesKHX) :void (physicalDevice VkPhysicalDevice) (pExternalBufferInfo (:pointer (:struct VkPhysicalDeviceExternalBufferInfoKHX))) (pExternalBufferProperties (:pointer (:struct VkExternalBufferPropertiesKHX)))) (defvkinstextfun ("vkGetPhysicalDeviceExternalImageFormatPropertiesNV" vkGetPhysicalDeviceExternalImageFormatPropertiesNV) VkResult (physicalDevice VkPhysicalDevice) (format VkFormat) (type VkImageType) (tiling VkImageTiling) (usage VkImageUsageFlags) (flags VkImageCreateFlags) ;; :OPTIONAL "true" (externalHandleType VkExternalMemoryHandleTypeFlagsNV) ;; :OPTIONAL "true" (pExternalImageFormatProperties (:pointer (:struct VkExternalImageFormatPropertiesNV)))) (defvkinstextfun ("vkGetPhysicalDeviceExternalSemaphorePropertiesKHX" vkGetPhysicalDeviceExternalSemaphorePropertiesKHX) :void (physicalDevice VkPhysicalDevice) (pExternalSemaphoreInfo (:pointer (:struct VkPhysicalDeviceExternalSemaphoreInfoKHX))) (pExternalSemaphoreProperties (:pointer (:struct VkExternalSemaphorePropertiesKHX)))) (cffi:defcfun ("vkGetPhysicalDeviceFeatures" vkGetPhysicalDeviceFeatures) :void (physicalDevice VkPhysicalDevice) (pFeatures (:pointer (:struct VkPhysicalDeviceFeatures)))) (defvkinstextfun ("vkGetPhysicalDeviceFeatures2KHR" vkGetPhysicalDeviceFeatures2KHR) :void (physicalDevice VkPhysicalDevice) (pFeatures (:pointer (:struct VkPhysicalDeviceFeatures2KHR)))) (cffi:defcfun ("vkGetPhysicalDeviceFormatProperties" vkGetPhysicalDeviceFormatProperties) :void (physicalDevice VkPhysicalDevice) (format VkFormat) (pFormatProperties (:pointer (:struct VkFormatProperties)))) (defvkinstextfun ("vkGetPhysicalDeviceFormatProperties2KHR" vkGetPhysicalDeviceFormatProperties2KHR) :void (physicalDevice VkPhysicalDevice) (format VkFormat) (pFormatProperties (:pointer (:struct VkFormatProperties2KHR)))) (defvkdevextfun ("vkGetPhysicalDeviceGeneratedCommandsPropertiesNVX" vkGetPhysicalDeviceGeneratedCommandsPropertiesNVX) :void (physicalDevice VkPhysicalDevice) (pFeatures (:pointer (:struct VkDeviceGeneratedCommandsFeaturesNVX))) (pLimits (:pointer (:struct VkDeviceGeneratedCommandsLimitsNVX)))) (cffi:defcfun ("vkGetPhysicalDeviceImageFormatProperties" vkGetPhysicalDeviceImageFormatProperties) VkResult (physicalDevice VkPhysicalDevice) (format VkFormat) (type VkImageType) (tiling VkImageTiling) (usage VkImageUsageFlags) (flags VkImageCreateFlags) ;; :OPTIONAL "true" (pImageFormatProperties (:pointer (:struct VkImageFormatProperties)))) (defvkinstextfun ("vkGetPhysicalDeviceImageFormatProperties2KHR" vkGetPhysicalDeviceImageFormatProperties2KHR) VkResult (physicalDevice VkPhysicalDevice) (pImageFormatInfo (:pointer (:struct VkPhysicalDeviceImageFormatInfo2KHR))) (pImageFormatProperties (:pointer (:struct VkImageFormatProperties2KHR)))) (cffi:defcfun ("vkGetPhysicalDeviceMemoryProperties" vkGetPhysicalDeviceMemoryProperties) :void (physicalDevice VkPhysicalDevice) (pMemoryProperties (:pointer (:struct VkPhysicalDeviceMemoryProperties)))) (defvkinstextfun ("vkGetPhysicalDeviceMemoryProperties2KHR" vkGetPhysicalDeviceMemoryProperties2KHR) :void (physicalDevice VkPhysicalDevice) (pMemoryProperties (:pointer (:struct VkPhysicalDeviceMemoryProperties2KHR)))) (defvkinstextfun ("vkGetPhysicalDeviceMirPresentationSupportKHR" vkGetPhysicalDeviceMirPresentationSupportKHR) VkBool32 (physicalDevice VkPhysicalDevice) (queueFamilyIndex :uint32) (connection (:pointer MirConnection))) (defvkdevextfun ("vkGetPhysicalDevicePresentRectanglesKHX" vkGetPhysicalDevicePresentRectanglesKHX) VkResult (physicalDevice VkPhysicalDevice) (surface VkSurfaceKHR) ;; :EXTERNSYNC "true" (pRectCount (:pointer :uint32)) ;; :OPTIONAL "false,true" (pRects (:pointer (:struct VkRect2D)))) ;; :OPTIONAL "true" :LEN "pRectCount" (cffi:defcfun ("vkGetPhysicalDeviceProperties" vkGetPhysicalDeviceProperties) :void (physicalDevice VkPhysicalDevice) (pProperties (:pointer (:struct VkPhysicalDeviceProperties)))) (defvkinstextfun ("vkGetPhysicalDeviceProperties2KHR" vkGetPhysicalDeviceProperties2KHR) :void (physicalDevice VkPhysicalDevice) (pProperties (:pointer (:struct VkPhysicalDeviceProperties2KHR)))) (cffi:defcfun ("vkGetPhysicalDeviceQueueFamilyProperties" vkGetPhysicalDeviceQueueFamilyProperties) :void (physicalDevice VkPhysicalDevice) (pQueueFamilyPropertyCount (:pointer :uint32)) ;; :OPTIONAL "false,true" (pQueueFamilyProperties (:pointer (:struct VkQueueFamilyProperties)))) ;; :OPTIONAL "true" :LEN "pQueueFamilyPropertyCount" (defvkinstextfun ("vkGetPhysicalDeviceQueueFamilyProperties2KHR" vkGetPhysicalDeviceQueueFamilyProperties2KHR) :void (physicalDevice VkPhysicalDevice) (pQueueFamilyPropertyCount (:pointer :uint32)) ;; :OPTIONAL "false,true" (pQueueFamilyProperties (:pointer (:struct VkQueueFamilyProperties2KHR)))) ;; :OPTIONAL "true" :LEN "pQueueFamilyPropertyCount" (cffi:defcfun ("vkGetPhysicalDeviceSparseImageFormatProperties" vkGetPhysicalDeviceSparseImageFormatProperties) :void (physicalDevice VkPhysicalDevice) (format VkFormat) (type VkImageType) (samples VkSampleCountFlagBits) (usage VkImageUsageFlags) (tiling VkImageTiling) (pPropertyCount (:pointer :uint32)) ;; :OPTIONAL "false,true" (pProperties (:pointer (:struct VkSparseImageFormatProperties)))) ;; :OPTIONAL "true" :LEN "pPropertyCount" (defvkinstextfun ("vkGetPhysicalDeviceSparseImageFormatProperties2KHR" vkGetPhysicalDeviceSparseImageFormatProperties2KHR) :void (physicalDevice VkPhysicalDevice) (pFormatInfo (:pointer (:struct VkPhysicalDeviceSparseImageFormatInfo2KHR))) (pPropertyCount (:pointer :uint32)) ;; :OPTIONAL "false,true" (pProperties (:pointer (:struct VkSparseImageFormatProperties2KHR)))) ;; :OPTIONAL "true" :LEN "pPropertyCount" (defvkinstextfun ("vkGetPhysicalDeviceSurfaceCapabilities2EXT" vkGetPhysicalDeviceSurfaceCapabilities2EXT) VkResult (physicalDevice VkPhysicalDevice) (surface VkSurfaceKHR) (pSurfaceCapabilities (:pointer (:struct VkSurfaceCapabilities2EXT)))) (defvkinstextfun ("vkGetPhysicalDeviceSurfaceCapabilities2KHR" vkGetPhysicalDeviceSurfaceCapabilities2KHR) VkResult (physicalDevice VkPhysicalDevice) (pSurfaceInfo (:pointer (:struct VkPhysicalDeviceSurfaceInfo2KHR))) (pSurfaceCapabilities (:pointer (:struct VkSurfaceCapabilities2KHR)))) (cffi:defcfun ("vkGetPhysicalDeviceSurfaceCapabilitiesKHR" vkGetPhysicalDeviceSurfaceCapabilitiesKHR) VkResult (physicalDevice VkPhysicalDevice) (surface VkSurfaceKHR) (pSurfaceCapabilities (:pointer (:struct VkSurfaceCapabilitiesKHR)))) (defvkinstextfun ("vkGetPhysicalDeviceSurfaceFormats2KHR" vkGetPhysicalDeviceSurfaceFormats2KHR) VkResult (physicalDevice VkPhysicalDevice) (pSurfaceInfo (:pointer (:struct VkPhysicalDeviceSurfaceInfo2KHR))) (pSurfaceFormatCount (:pointer :uint32)) ;; :OPTIONAL "false,true" (pSurfaceFormats (:pointer (:struct VkSurfaceFormat2KHR)))) ;; :OPTIONAL "true" :LEN "pSurfaceFormatCount" (cffi:defcfun ("vkGetPhysicalDeviceSurfaceFormatsKHR" vkGetPhysicalDeviceSurfaceFormatsKHR) VkResult (physicalDevice VkPhysicalDevice) (surface VkSurfaceKHR) (pSurfaceFormatCount (:pointer :uint32)) ;; :OPTIONAL "false,true" (pSurfaceFormats (:pointer (:struct VkSurfaceFormatKHR)))) ;; :OPTIONAL "true" :LEN "pSurfaceFormatCount" (cffi:defcfun ("vkGetPhysicalDeviceSurfacePresentModesKHR" vkGetPhysicalDeviceSurfacePresentModesKHR) VkResult (physicalDevice VkPhysicalDevice) (surface VkSurfaceKHR) (pPresentModeCount (:pointer :uint32)) ;; :OPTIONAL "false,true" (pPresentModes (:pointer VkPresentModeKHR))) ;; :OPTIONAL "true" :LEN "pPresentModeCount" (cffi:defcfun ("vkGetPhysicalDeviceSurfaceSupportKHR" vkGetPhysicalDeviceSurfaceSupportKHR) VkResult (physicalDevice VkPhysicalDevice) (queueFamilyIndex :uint32) (surface VkSurfaceKHR) (pSupported (:pointer VkBool32))) (defvkinstextfun ("vkGetPhysicalDeviceWaylandPresentationSupportKHR" vkGetPhysicalDeviceWaylandPresentationSupportKHR) VkBool32 (physicalDevice VkPhysicalDevice) (queueFamilyIndex :uint32) (display (:pointer (:struct wl_display)))) (cffi:defcfun ("vkGetPhysicalDeviceWin32PresentationSupportKHR" vkGetPhysicalDeviceWin32PresentationSupportKHR) VkBool32 (physicalDevice VkPhysicalDevice) (queueFamilyIndex :uint32)) (defvkinstextfun ("vkGetPhysicalDeviceXlibPresentationSupportKHR" vkGetPhysicalDeviceXlibPresentationSupportKHR) VkBool32 (physicalDevice VkPhysicalDevice) (queueFamilyIndex :uint32) (dpy (:pointer Display)) (visualID VisualID)) (cffi:defcfun ("vkGetPipelineCacheData" vkGetPipelineCacheData) VkResult (device VkDevice) (pipelineCache VkPipelineCache) (pDataSize (:pointer size-t)) ;; :OPTIONAL "false,true" (pData (:pointer :void))) ;; :OPTIONAL "true" :LEN "pDataSize" (cffi:defcfun ("vkGetQueryPoolResults" vkGetQueryPoolResults) VkResult (device VkDevice) (queryPool VkQueryPool) (firstQuery :uint32) (queryCount :uint32) (dataSize size-t) (pData (:pointer :void)) ;; :LEN "dataSize" (stride VkDeviceSize) (flags VkQueryResultFlags)) ;; :OPTIONAL "true" (defvkinstextfun ("vkGetRandROutputDisplayEXT" vkGetRandROutputDisplayEXT) VkResult (physicalDevice VkPhysicalDevice) (dpy (:pointer Display)) (rrOutput RROutput) (pDisplay (:pointer VkDisplayKHR))) (defvkdevextfun ("vkGetRefreshCycleDurationGOOGLE" vkGetRefreshCycleDurationGOOGLE) VkResult (device VkDevice) (swapchain VkSwapchainKHR) ;; :EXTERNSYNC "true" (pDisplayTimingProperties (:pointer (:struct VkRefreshCycleDurationGOOGLE)))) (cffi:defcfun ("vkGetRenderAreaGranularity" vkGetRenderAreaGranularity) :void (device VkDevice) (renderPass VkRenderPass) (pGranularity (:pointer (:struct VkExtent2D)))) (defvkdevextfun ("vkGetSemaphoreFdKHX" vkGetSemaphoreFdKHX) VkResult (device VkDevice) (semaphore VkSemaphore) (handleType VkExternalSemaphoreHandleTypeFlagBitsKHX) (pFd (:pointer :int))) (defvkdevextfun ("vkGetSemaphoreWin32HandleKHX" vkGetSemaphoreWin32HandleKHX) VkResult (device VkDevice) (semaphore VkSemaphore) (handleType VkExternalSemaphoreHandleTypeFlagBitsKHX) (pHandle (:pointer HANDLE))) (defvkdevextfun ("vkGetSwapchainCounterEXT" vkGetSwapchainCounterEXT) VkResult (device VkDevice) (swapchain VkSwapchainKHR) (counter VkSurfaceCounterFlagBitsEXT) (pCounterValue (:pointer :uint64))) (cffi:defcfun ("vkGetSwapchainImagesKHR" vkGetSwapchainImagesKHR) VkResult (device VkDevice) (swapchain VkSwapchainKHR) (pSwapchainImageCount (:pointer :uint32)) ;; :OPTIONAL "false,true" (pSwapchainImages (:pointer VkImage))) ;; :OPTIONAL "true" :LEN "pSwapchainImageCount" (defvkdevextfun ("vkGetSwapchainStatusKHR" vkGetSwapchainStatusKHR) VkResult (device VkDevice) (swapchain VkSwapchainKHR)) ;; :EXTERNSYNC "true" (defvkdevextfun ("vkImportSemaphoreFdKHX" vkImportSemaphoreFdKHX) VkResult (device VkDevice) (pImportSemaphoreFdInfo (:pointer (:struct VkImportSemaphoreFdInfoKHX)))) (defvkdevextfun ("vkImportSemaphoreWin32HandleKHX" vkImportSemaphoreWin32HandleKHX) VkResult (device VkDevice) (pImportSemaphoreWin32HandleInfo (:pointer (:struct VkImportSemaphoreWin32HandleInfoKHX)))) (cffi:defcfun ("vkInvalidateMappedMemoryRanges" vkInvalidateMappedMemoryRanges) VkResult (device VkDevice) (memoryRangeCount :uint32) (pMemoryRanges (:pointer (:struct VkMappedMemoryRange)))) ;; :LEN "memoryRangeCount" (cffi:defcfun ("vkMapMemory" vkMapMemory) VkResult (device VkDevice) (memory VkDeviceMemory) ;; :EXTERNSYNC "true" (offset VkDeviceSize) (size VkDeviceSize) (flags VkMemoryMapFlags) ;; :OPTIONAL "true" (ppData (:pointer (:pointer :void)))) (cffi:defcfun ("vkMergePipelineCaches" vkMergePipelineCaches) VkResult (device VkDevice) (dstCache VkPipelineCache) ;; :EXTERNSYNC "true" (srcCacheCount :uint32) (pSrcCaches (:pointer VkPipelineCache))) ;; :LEN "srcCacheCount" (cffi:defcfun ("vkQueueBindSparse" vkQueueBindSparse) VkResult (queue VkQueue) ;; :EXTERNSYNC "true" (bindInfoCount :uint32) ;; :OPTIONAL "true" (pBindInfo (:pointer (:struct VkBindSparseInfo))) ;; :LEN "bindInfoCount" :EXTERNSYNC "pBindInfo[].pWaitSemaphores[],pBindInfo[].pSignalSemaphores[],pBindInfo[].pBufferBinds[].buffer,pBindInfo[].pImageOpaqueBinds[].image,pBindInfo[].pImageBinds[].image" (fence VkFence)) ;; :OPTIONAL "true" :EXTERNSYNC "true" (cffi:defcfun ("vkQueuePresentKHR" vkQueuePresentKHR) VkResult (queue VkQueue) ;; :EXTERNSYNC "true" (pPresentInfo (:pointer (:struct VkPresentInfoKHR)))) ;; :EXTERNSYNC "pPresentInfo.pWaitSemaphores[],pPresentInfo.pSwapchains[]" (cffi:defcfun ("vkQueueSubmit" vkQueueSubmit) VkResult (queue VkQueue) ;; :EXTERNSYNC "true" (submitCount :uint32) ;; :OPTIONAL "true" (pSubmits (:pointer (:struct VkSubmitInfo))) ;; :LEN "submitCount" :EXTERNSYNC "pSubmits[].pWaitSemaphores[],pSubmits[].pSignalSemaphores[]" (fence VkFence)) ;; :OPTIONAL "true" :EXTERNSYNC "true" (cffi:defcfun ("vkQueueWaitIdle" vkQueueWaitIdle) VkResult (queue VkQueue)) (defvkdevextfun ("vkRegisterDeviceEventEXT" vkRegisterDeviceEventEXT) VkResult (device VkDevice) (pDeviceEventInfo (:pointer (:struct VkDeviceEventInfoEXT))) (pAllocator (:pointer (:struct VkAllocationCallbacks))) (pFence (:pointer VkFence))) (defvkdevextfun ("vkRegisterDisplayEventEXT" vkRegisterDisplayEventEXT) VkResult (device VkDevice) (display VkDisplayKHR) (pDisplayEventInfo (:pointer (:struct VkDisplayEventInfoEXT))) (pAllocator (:pointer (:struct VkAllocationCallbacks))) (pFence (:pointer VkFence))) (defvkdevextfun ("vkRegisterObjectsNVX" vkRegisterObjectsNVX) VkResult (device VkDevice) (objectTable VkObjectTableNVX) ;; :EXTERNSYNC "true" (objectCount :uint32) (ppObjectTableEntries (:pointer (:pointer (:struct VkObjectTableEntryNVX)))) ;; :LEN "objectCount" (pObjectIndices (:pointer :uint32))) ;; :LEN "objectCount" (defvkinstextfun ("vkReleaseDisplayEXT" vkReleaseDisplayEXT) VkResult (physicalDevice VkPhysicalDevice) (display VkDisplayKHR)) (cffi:defcfun ("vkResetCommandBuffer" vkResetCommandBuffer) VkResult (commandBuffer VkCommandBuffer) ;; :EXTERNSYNC "true" (flags VkCommandBufferResetFlags)) ;; :OPTIONAL "true" (cffi:defcfun ("vkResetCommandPool" vkResetCommandPool) VkResult (device VkDevice) (commandPool VkCommandPool) ;; :EXTERNSYNC "true" (flags VkCommandPoolResetFlags)) ;; :OPTIONAL "true" (cffi:defcfun ("vkResetDescriptorPool" vkResetDescriptorPool) VkResult (device VkDevice) (descriptorPool VkDescriptorPool) ;; :EXTERNSYNC "true" (flags VkDescriptorPoolResetFlags)) ;; :OPTIONAL "true" (cffi:defcfun ("vkResetEvent" vkResetEvent) VkResult (device VkDevice) (event VkEvent)) ;; :EXTERNSYNC "true" (cffi:defcfun ("vkResetFences" vkResetFences) VkResult (device VkDevice) (fenceCount :uint32) (pFences (:pointer VkFence))) ;; :LEN "fenceCount" :EXTERNSYNC "true" (cffi:defcfun ("vkSetEvent" vkSetEvent) VkResult (device VkDevice) (event VkEvent)) ;; :EXTERNSYNC "true" (defvkdevextfun ("vkSetHdrMetadataEXT" vkSetHdrMetadataEXT) :void (device VkDevice) (swapchainCount :uint32) (pSwapchains (:pointer VkSwapchainKHR)) ;; :LEN "swapchainCount" (pMetadata (:pointer (:struct VkHdrMetadataEXT)))) ;; :LEN "swapchainCount" (defvkdevextfun ("vkTrimCommandPoolKHR" vkTrimCommandPoolKHR) :void (device VkDevice) (commandPool VkCommandPool) ;; :EXTERNSYNC "true" (flags VkCommandPoolTrimFlagsKHR)) ;; :OPTIONAL "true" (cffi:defcfun ("vkUnmapMemory" vkUnmapMemory) :void (device VkDevice) (memory VkDeviceMemory)) ;; :EXTERNSYNC "true" (defvkdevextfun ("vkUnregisterObjectsNVX" vkUnregisterObjectsNVX) VkResult (device VkDevice) (objectTable VkObjectTableNVX) ;; :EXTERNSYNC "true" (objectCount :uint32) (pObjectEntryTypes (:pointer VkObjectEntryTypeNVX)) ;; :LEN "objectCount" (pObjectIndices (:pointer :uint32))) ;; :LEN "objectCount" (defvkdevextfun ("vkUpdateDescriptorSetWithTemplateKHR" vkUpdateDescriptorSetWithTemplateKHR) :void (device VkDevice) (descriptorSet VkDescriptorSet) ;; :EXTERNSYNC "true" (descriptorUpdateTemplate VkDescriptorUpdateTemplateKHR) (pData (:pointer :void))) (cffi:defcfun ("vkUpdateDescriptorSets" vkUpdateDescriptorSets) :void (device VkDevice) (descriptorWriteCount :uint32) ;; :OPTIONAL "true" (pDescriptorWrites (:pointer (:struct VkWriteDescriptorSet))) ;; :LEN "descriptorWriteCount" :EXTERNSYNC "pDescriptorWrites[].dstSet" (descriptorCopyCount :uint32) ;; :OPTIONAL "true" (pDescriptorCopies (:pointer (:struct VkCopyDescriptorSet)))) ;; :LEN "descriptorCopyCount" :EXTERNSYNC "pDescriptorCopies[].dstSet" (cffi:defcfun ("vkWaitForFences" vkWaitForFences) VkResult (device VkDevice) (fenceCount :uint32) (pFences (:pointer VkFence)) ;; :LEN "fenceCount" (waitAll VkBool32) (timeout :uint64))
[ { "context": "mon-Lisp; Base: 10 -*-\n\n;;;. Copyright (c) 1991 by Venue\n(in-package \"CLOS\")\n\n;;; ************************", "end": 89, "score": 0.9988239407539368, "start": 84, "tag": "NAME", "value": "Venue" } ]
obsolete/clos/2.0/defclass.lisp
FultonBrowne/medley
152
;;;-*- Package: CLOS; Syntax: Common-Lisp; Base: 10 -*- ;;;. Copyright (c) 1991 by Venue (in-package "CLOS") ;;; ************************************************************************* ;;; MAKE-TOP-LEVEL-FORM is used by all PCL macros that appear `at top-level'. The original ;;; motiviation for this function was to deal with the bug in the Genera compiler that prevents ;;; lambda expressions in top-level forms other than DEFUN from being compiled. Now this function is ;;; used to grab other functionality as well. This includes: - Preventing the grouping of top-level ;;; forms. For example, a DEFCLASS followed by a DEFMETHOD may not want to be grouped into the same ;;; top-level form. - Telling the programming environment what the pretty version of the name of ;;; this form is. This is used by WARN. (defun make-top-level-form (name times form) (flet ((definition-name nil (if (and (listp name) (memq (car name) '(defmethod defclass class method method-combination))) (format nil "~A~{ ~S~}" (capitalize-words (car name) nil) (cdr name)) (format nil "~S" name)))) (definition-name) (make-progn `',name `(eval-when ,times ,form)))) (defun make-progn (&rest forms) (let ((progn-form nil)) (labels ((collect-forms (forms) (unless (null forms) (collect-forms (cdr forms)) (if (and (listp (car forms)) (eq (caar forms) 'progn)) (collect-forms (cdar forms)) (push (car forms) progn-form))))) (collect-forms forms) (cons 'progn progn-form)))) ;;; Like the DEFMETHOD macro, the expansion of the DEFCLASS macro is fixed. DEFCLASS always expands ;;; into a call to LOAD-DEFCLASS. Until the meta- braid is set up, LOAD-DEFCLASS has a special ;;; definition which simply collects all class definitions up, when the metabraid is initialized it ;;; is done from those class definitions. After the metabraid has been setup, and the protocol for ;;; defining classes has been defined, the real definition of LOAD-DEFCLASS is installed by the file ;;; defclass.lisp (defmacro defclass (name direct-superclasses direct-slots &rest options) (declare (indentation 2 4 3 1)) (expand-defclass name direct-superclasses direct-slots options)) (defun expand-defclass (name supers slots options) (setq supers (copy-tree supers) slots (copy-tree slots) options (copy-tree options)) (let ((metaclass 'standard-class)) (dolist (option options) (if (not (listp option)) (error "~S is not a legal defclass option." option) (when (eq (car option) ':metaclass) (unless (legal-class-name-p (cadr option)) (error "The value of the :metaclass option (~S) is not a~%~ legal class name." (cadr option))) (setq metaclass (cadr option)) (setf options (remove option options)) (return t)))) (let ((*initfunctions* nil) (*accessors* nil)) ; Truly a crock, but we got to have it ; to live nicely. (declare (special *initfunctions* *accessors*)) (let ((canonical-slots (mapcar #'(lambda (spec) (canonicalize-slot-specification name spec)) slots)) (other-initargs (mapcar #'(lambda (option) (canonicalize-defclass-option name option)) options))) (do-standard-defsetfs-for-defclass *accessors*) ; (load-defclass name metaclass supers ; canonical-slots (apply #'append ; other-initargs) *accessors*))))) (make-top-level-form `(defclass ,name nil nil) *defclass-times* `(let ,(mapcar #'cdr *initfunctions*) (load-defclass ',name ',metaclass ',supers (list ,@canonical-slots ) (list ,@(apply #'append other-initargs)) ',*accessors*))))))) (defun make-initfunction (initform) (declare (special *initfunctions*)) (cond ((or (eq initform 't) (equal initform ''t)) '#'true) ((or (eq initform 'nil) (equal initform ''nil)) '#'false) ((or (eql initform '0) (equal initform ''0)) '#'zero) (t (let ((entry (assoc initform *initfunctions* :test #'equal))) (unless entry (setq entry (list initform (gensym) `#'(lambda nil ,initform))) (push entry *initfunctions*)) (cadr entry))))) (defun canonicalize-slot-specification (class-name spec) (declare (special *accessors*)) (cond ((and (symbolp spec) (not (keywordp spec)) (not (memq spec '(t nil)))) `'(:name ,spec)) ((not (consp spec)) (error "~S is not a legal slot specification." spec)) ((null (cdr spec)) `'(:name ,(car spec))) ((null (cddr spec)) (error "In DEFCLASS ~S, the slot specification ~S is obsolete.~%~ Convert it to ~S" class-name spec (list (car spec) :initform (cadr spec)))) (t (let* ((name (pop spec)) (readers nil) (writers nil) (initargs nil) (unsupplied (list nil)) (initform (getf spec :initform unsupplied))) (doplist (key val) spec (case key (:accessor (push val *accessors*) (push val readers) (push `(setf ,val) writers)) (:reader (push val readers)) (:writer (push val writers)) (:initarg (push val initargs)))) (loop (unless (remf spec :accessor) (return))) (loop (unless (remf spec :reader) (return))) (loop (unless (remf spec :writer) (return))) (loop (unless (remf spec :initarg) (return))) (setq spec `(:name ',name :readers ',readers :writers ',writers :initargs ',initargs ',spec)) (if (eq initform unsupplied) `(list* ,@spec) `(list* :initfunction ,(make-initfunction initform) ,@spec)))))) (defun canonicalize-defclass-option (class-name option) (declare (ignore class-name)) (case (car option) (:default-initargs (let ((canonical nil)) (let (key val (tail (cdr option))) (loop (when (null tail) (return nil)) (setq key (pop tail) val (pop tail)) (push ``(,',key ,,(make-initfunction val) ,',val) canonical)) `(':direct-default-initargs (list ,@(nreverse canonical)))))) (otherwise `(',(car option) ',(cdr option))))) ;;; This is the early definition of load-defclass. It just collects up all the class definitions in ;;; a list. Later, in the file braid1.lisp, these are actually defined. Each entry in ;;; *early-class-definitions* is an early-class-definition. (defparameter *early-class-definitions* nil) (defun make-early-class-definition (name source metaclass superclass-names canonical-slots other-initargs) (list 'early-class-definition name source metaclass superclass-names canonical-slots other-initargs)) (defun ecd-class-name (ecd) (nth 1 ecd)) (defun ecd-source (ecd) (nth 2 ecd)) (defun ecd-metaclass (ecd) (nth 3 ecd)) (defun ecd-superclass-names (ecd) (nth 4 ecd)) (defun ecd-canonical-slots (ecd) (nth 5 ecd)) (defun ecd-other-initargs (ecd) (nth 6 ecd)) (proclaim '(notinline load-defclass)) (defun load-defclass (name metaclass supers canonical-slots canonical-options accessor-names) (setq supers (copy-tree supers) canonical-slots (copy-tree canonical-slots) canonical-options (copy-tree canonical-options)) (do-standard-defsetfs-for-defclass accessor-names) (let ((ecd (make-early-class-definition name (load-truename) metaclass supers canonical-slots (apply #'append canonical-options))) (existing (find name *early-class-definitions* :key #'ecd-class-name))) (setq *early-class-definitions* (cons ecd (remove existing *early-class-definitions*))) ecd))
84755
;;;-*- Package: CLOS; Syntax: Common-Lisp; Base: 10 -*- ;;;. Copyright (c) 1991 by <NAME> (in-package "CLOS") ;;; ************************************************************************* ;;; MAKE-TOP-LEVEL-FORM is used by all PCL macros that appear `at top-level'. The original ;;; motiviation for this function was to deal with the bug in the Genera compiler that prevents ;;; lambda expressions in top-level forms other than DEFUN from being compiled. Now this function is ;;; used to grab other functionality as well. This includes: - Preventing the grouping of top-level ;;; forms. For example, a DEFCLASS followed by a DEFMETHOD may not want to be grouped into the same ;;; top-level form. - Telling the programming environment what the pretty version of the name of ;;; this form is. This is used by WARN. (defun make-top-level-form (name times form) (flet ((definition-name nil (if (and (listp name) (memq (car name) '(defmethod defclass class method method-combination))) (format nil "~A~{ ~S~}" (capitalize-words (car name) nil) (cdr name)) (format nil "~S" name)))) (definition-name) (make-progn `',name `(eval-when ,times ,form)))) (defun make-progn (&rest forms) (let ((progn-form nil)) (labels ((collect-forms (forms) (unless (null forms) (collect-forms (cdr forms)) (if (and (listp (car forms)) (eq (caar forms) 'progn)) (collect-forms (cdar forms)) (push (car forms) progn-form))))) (collect-forms forms) (cons 'progn progn-form)))) ;;; Like the DEFMETHOD macro, the expansion of the DEFCLASS macro is fixed. DEFCLASS always expands ;;; into a call to LOAD-DEFCLASS. Until the meta- braid is set up, LOAD-DEFCLASS has a special ;;; definition which simply collects all class definitions up, when the metabraid is initialized it ;;; is done from those class definitions. After the metabraid has been setup, and the protocol for ;;; defining classes has been defined, the real definition of LOAD-DEFCLASS is installed by the file ;;; defclass.lisp (defmacro defclass (name direct-superclasses direct-slots &rest options) (declare (indentation 2 4 3 1)) (expand-defclass name direct-superclasses direct-slots options)) (defun expand-defclass (name supers slots options) (setq supers (copy-tree supers) slots (copy-tree slots) options (copy-tree options)) (let ((metaclass 'standard-class)) (dolist (option options) (if (not (listp option)) (error "~S is not a legal defclass option." option) (when (eq (car option) ':metaclass) (unless (legal-class-name-p (cadr option)) (error "The value of the :metaclass option (~S) is not a~%~ legal class name." (cadr option))) (setq metaclass (cadr option)) (setf options (remove option options)) (return t)))) (let ((*initfunctions* nil) (*accessors* nil)) ; Truly a crock, but we got to have it ; to live nicely. (declare (special *initfunctions* *accessors*)) (let ((canonical-slots (mapcar #'(lambda (spec) (canonicalize-slot-specification name spec)) slots)) (other-initargs (mapcar #'(lambda (option) (canonicalize-defclass-option name option)) options))) (do-standard-defsetfs-for-defclass *accessors*) ; (load-defclass name metaclass supers ; canonical-slots (apply #'append ; other-initargs) *accessors*))))) (make-top-level-form `(defclass ,name nil nil) *defclass-times* `(let ,(mapcar #'cdr *initfunctions*) (load-defclass ',name ',metaclass ',supers (list ,@canonical-slots ) (list ,@(apply #'append other-initargs)) ',*accessors*))))))) (defun make-initfunction (initform) (declare (special *initfunctions*)) (cond ((or (eq initform 't) (equal initform ''t)) '#'true) ((or (eq initform 'nil) (equal initform ''nil)) '#'false) ((or (eql initform '0) (equal initform ''0)) '#'zero) (t (let ((entry (assoc initform *initfunctions* :test #'equal))) (unless entry (setq entry (list initform (gensym) `#'(lambda nil ,initform))) (push entry *initfunctions*)) (cadr entry))))) (defun canonicalize-slot-specification (class-name spec) (declare (special *accessors*)) (cond ((and (symbolp spec) (not (keywordp spec)) (not (memq spec '(t nil)))) `'(:name ,spec)) ((not (consp spec)) (error "~S is not a legal slot specification." spec)) ((null (cdr spec)) `'(:name ,(car spec))) ((null (cddr spec)) (error "In DEFCLASS ~S, the slot specification ~S is obsolete.~%~ Convert it to ~S" class-name spec (list (car spec) :initform (cadr spec)))) (t (let* ((name (pop spec)) (readers nil) (writers nil) (initargs nil) (unsupplied (list nil)) (initform (getf spec :initform unsupplied))) (doplist (key val) spec (case key (:accessor (push val *accessors*) (push val readers) (push `(setf ,val) writers)) (:reader (push val readers)) (:writer (push val writers)) (:initarg (push val initargs)))) (loop (unless (remf spec :accessor) (return))) (loop (unless (remf spec :reader) (return))) (loop (unless (remf spec :writer) (return))) (loop (unless (remf spec :initarg) (return))) (setq spec `(:name ',name :readers ',readers :writers ',writers :initargs ',initargs ',spec)) (if (eq initform unsupplied) `(list* ,@spec) `(list* :initfunction ,(make-initfunction initform) ,@spec)))))) (defun canonicalize-defclass-option (class-name option) (declare (ignore class-name)) (case (car option) (:default-initargs (let ((canonical nil)) (let (key val (tail (cdr option))) (loop (when (null tail) (return nil)) (setq key (pop tail) val (pop tail)) (push ``(,',key ,,(make-initfunction val) ,',val) canonical)) `(':direct-default-initargs (list ,@(nreverse canonical)))))) (otherwise `(',(car option) ',(cdr option))))) ;;; This is the early definition of load-defclass. It just collects up all the class definitions in ;;; a list. Later, in the file braid1.lisp, these are actually defined. Each entry in ;;; *early-class-definitions* is an early-class-definition. (defparameter *early-class-definitions* nil) (defun make-early-class-definition (name source metaclass superclass-names canonical-slots other-initargs) (list 'early-class-definition name source metaclass superclass-names canonical-slots other-initargs)) (defun ecd-class-name (ecd) (nth 1 ecd)) (defun ecd-source (ecd) (nth 2 ecd)) (defun ecd-metaclass (ecd) (nth 3 ecd)) (defun ecd-superclass-names (ecd) (nth 4 ecd)) (defun ecd-canonical-slots (ecd) (nth 5 ecd)) (defun ecd-other-initargs (ecd) (nth 6 ecd)) (proclaim '(notinline load-defclass)) (defun load-defclass (name metaclass supers canonical-slots canonical-options accessor-names) (setq supers (copy-tree supers) canonical-slots (copy-tree canonical-slots) canonical-options (copy-tree canonical-options)) (do-standard-defsetfs-for-defclass accessor-names) (let ((ecd (make-early-class-definition name (load-truename) metaclass supers canonical-slots (apply #'append canonical-options))) (existing (find name *early-class-definitions* :key #'ecd-class-name))) (setq *early-class-definitions* (cons ecd (remove existing *early-class-definitions*))) ecd))
true
;;;-*- Package: CLOS; Syntax: Common-Lisp; Base: 10 -*- ;;;. Copyright (c) 1991 by PI:NAME:<NAME>END_PI (in-package "CLOS") ;;; ************************************************************************* ;;; MAKE-TOP-LEVEL-FORM is used by all PCL macros that appear `at top-level'. The original ;;; motiviation for this function was to deal with the bug in the Genera compiler that prevents ;;; lambda expressions in top-level forms other than DEFUN from being compiled. Now this function is ;;; used to grab other functionality as well. This includes: - Preventing the grouping of top-level ;;; forms. For example, a DEFCLASS followed by a DEFMETHOD may not want to be grouped into the same ;;; top-level form. - Telling the programming environment what the pretty version of the name of ;;; this form is. This is used by WARN. (defun make-top-level-form (name times form) (flet ((definition-name nil (if (and (listp name) (memq (car name) '(defmethod defclass class method method-combination))) (format nil "~A~{ ~S~}" (capitalize-words (car name) nil) (cdr name)) (format nil "~S" name)))) (definition-name) (make-progn `',name `(eval-when ,times ,form)))) (defun make-progn (&rest forms) (let ((progn-form nil)) (labels ((collect-forms (forms) (unless (null forms) (collect-forms (cdr forms)) (if (and (listp (car forms)) (eq (caar forms) 'progn)) (collect-forms (cdar forms)) (push (car forms) progn-form))))) (collect-forms forms) (cons 'progn progn-form)))) ;;; Like the DEFMETHOD macro, the expansion of the DEFCLASS macro is fixed. DEFCLASS always expands ;;; into a call to LOAD-DEFCLASS. Until the meta- braid is set up, LOAD-DEFCLASS has a special ;;; definition which simply collects all class definitions up, when the metabraid is initialized it ;;; is done from those class definitions. After the metabraid has been setup, and the protocol for ;;; defining classes has been defined, the real definition of LOAD-DEFCLASS is installed by the file ;;; defclass.lisp (defmacro defclass (name direct-superclasses direct-slots &rest options) (declare (indentation 2 4 3 1)) (expand-defclass name direct-superclasses direct-slots options)) (defun expand-defclass (name supers slots options) (setq supers (copy-tree supers) slots (copy-tree slots) options (copy-tree options)) (let ((metaclass 'standard-class)) (dolist (option options) (if (not (listp option)) (error "~S is not a legal defclass option." option) (when (eq (car option) ':metaclass) (unless (legal-class-name-p (cadr option)) (error "The value of the :metaclass option (~S) is not a~%~ legal class name." (cadr option))) (setq metaclass (cadr option)) (setf options (remove option options)) (return t)))) (let ((*initfunctions* nil) (*accessors* nil)) ; Truly a crock, but we got to have it ; to live nicely. (declare (special *initfunctions* *accessors*)) (let ((canonical-slots (mapcar #'(lambda (spec) (canonicalize-slot-specification name spec)) slots)) (other-initargs (mapcar #'(lambda (option) (canonicalize-defclass-option name option)) options))) (do-standard-defsetfs-for-defclass *accessors*) ; (load-defclass name metaclass supers ; canonical-slots (apply #'append ; other-initargs) *accessors*))))) (make-top-level-form `(defclass ,name nil nil) *defclass-times* `(let ,(mapcar #'cdr *initfunctions*) (load-defclass ',name ',metaclass ',supers (list ,@canonical-slots ) (list ,@(apply #'append other-initargs)) ',*accessors*))))))) (defun make-initfunction (initform) (declare (special *initfunctions*)) (cond ((or (eq initform 't) (equal initform ''t)) '#'true) ((or (eq initform 'nil) (equal initform ''nil)) '#'false) ((or (eql initform '0) (equal initform ''0)) '#'zero) (t (let ((entry (assoc initform *initfunctions* :test #'equal))) (unless entry (setq entry (list initform (gensym) `#'(lambda nil ,initform))) (push entry *initfunctions*)) (cadr entry))))) (defun canonicalize-slot-specification (class-name spec) (declare (special *accessors*)) (cond ((and (symbolp spec) (not (keywordp spec)) (not (memq spec '(t nil)))) `'(:name ,spec)) ((not (consp spec)) (error "~S is not a legal slot specification." spec)) ((null (cdr spec)) `'(:name ,(car spec))) ((null (cddr spec)) (error "In DEFCLASS ~S, the slot specification ~S is obsolete.~%~ Convert it to ~S" class-name spec (list (car spec) :initform (cadr spec)))) (t (let* ((name (pop spec)) (readers nil) (writers nil) (initargs nil) (unsupplied (list nil)) (initform (getf spec :initform unsupplied))) (doplist (key val) spec (case key (:accessor (push val *accessors*) (push val readers) (push `(setf ,val) writers)) (:reader (push val readers)) (:writer (push val writers)) (:initarg (push val initargs)))) (loop (unless (remf spec :accessor) (return))) (loop (unless (remf spec :reader) (return))) (loop (unless (remf spec :writer) (return))) (loop (unless (remf spec :initarg) (return))) (setq spec `(:name ',name :readers ',readers :writers ',writers :initargs ',initargs ',spec)) (if (eq initform unsupplied) `(list* ,@spec) `(list* :initfunction ,(make-initfunction initform) ,@spec)))))) (defun canonicalize-defclass-option (class-name option) (declare (ignore class-name)) (case (car option) (:default-initargs (let ((canonical nil)) (let (key val (tail (cdr option))) (loop (when (null tail) (return nil)) (setq key (pop tail) val (pop tail)) (push ``(,',key ,,(make-initfunction val) ,',val) canonical)) `(':direct-default-initargs (list ,@(nreverse canonical)))))) (otherwise `(',(car option) ',(cdr option))))) ;;; This is the early definition of load-defclass. It just collects up all the class definitions in ;;; a list. Later, in the file braid1.lisp, these are actually defined. Each entry in ;;; *early-class-definitions* is an early-class-definition. (defparameter *early-class-definitions* nil) (defun make-early-class-definition (name source metaclass superclass-names canonical-slots other-initargs) (list 'early-class-definition name source metaclass superclass-names canonical-slots other-initargs)) (defun ecd-class-name (ecd) (nth 1 ecd)) (defun ecd-source (ecd) (nth 2 ecd)) (defun ecd-metaclass (ecd) (nth 3 ecd)) (defun ecd-superclass-names (ecd) (nth 4 ecd)) (defun ecd-canonical-slots (ecd) (nth 5 ecd)) (defun ecd-other-initargs (ecd) (nth 6 ecd)) (proclaim '(notinline load-defclass)) (defun load-defclass (name metaclass supers canonical-slots canonical-options accessor-names) (setq supers (copy-tree supers) canonical-slots (copy-tree canonical-slots) canonical-options (copy-tree canonical-options)) (do-standard-defsetfs-for-defclass accessor-names) (let ((ecd (make-early-class-definition name (load-truename) metaclass supers canonical-slots (apply #'append canonical-options))) (existing (find name *early-class-definitions* :key #'ecd-class-name))) (setq *early-class-definitions* (cons ecd (remove existing *early-class-definitions*))) ecd))
[ { "context": "; DEALINGS IN THE SOFTWARE.\n;\n; Original author: Sol Swords <[email protected]>\n\n\n(in-package \"AIGNET\")\n\n(", "end": 1402, "score": 0.9998686909675598, "start": 1392, "tag": "NAME", "value": "Sol Swords" }, { "context": "IN THE SOFTWARE.\n;\n; Original author: Sol Swords <[email protected]>\n\n\n(in-package \"AIGNET\")\n\n(include-book \"aignet-a", "end": 1424, "score": 0.9999305605888367, "start": 1404, "tag": "EMAIL", "value": "[email protected]" } ]
books/centaur/aignet/stats.lisp
mayankmanj/acl2
305
; AIGNET - And-Inverter Graph Networks ; Copyright (C) 2017 Centaur Technology ; ; Contact: ; Centaur Technology Formal Verification Group ; 7600-C N. Capital of Texas Highway, Suite 300, Austin, TX 78731, USA. ; http://www.centtech.com/ ; ; License: (An MIT/X11-style license) ; ; Permission is hereby granted, free of charge, to any person obtaining a ; copy of this software and associated documentation files (the "Software"), ; to deal in the Software without restriction, including without limitation ; the rights to use, copy, modify, merge, publish, distribute, sublicense, ; and/or sell copies of the Software, and to permit persons to whom the ; Software is furnished to do so, subject to the following conditions: ; ; The above copyright notice and this permission notice shall be included in ; all copies or substantial portions of the Software. ; ; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR ; IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, ; FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE ; AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER ; LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING ; FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER ; DEALINGS IN THE SOFTWARE. ; ; Original author: Sol Swords <[email protected]> (in-package "AIGNET") (include-book "aignet-absstobj") (define count-xors-rec ((start natp) aignet (acc natp)) :guard (<= start (num-fanins aignet)) :guard-hints (("goal" :in-theory (enable aignet-idp))) :measure (nfix (- (num-fanins aignet) (nfix start))) :returns (count natp :rule-classes :type-prescription) (b* (((when (mbe :logic (zp (- (num-fanins aignet) (nfix start))) :exec (eql start (num-fanins aignet)))) (lnfix acc)) (acc (if (and (eql (id->type start aignet) (gate-type)) (eql (id->regp start aignet) 1)) (+ 1 (lnfix acc)) (lnfix acc)))) (count-xors-rec (+ 1 (lnfix start)) aignet acc)) /// (local (defthm stype-count-of-lookup-fanin-count (implies (not (equal (ctype stype) (out-ctype))) (equal (stype-count stype (lookup-id (fanin-count aignet) aignet)) (stype-count stype aignet))) :hints(("Goal" :in-theory (enable lookup-id fanin-count fanin-node-p))))) (local (defthm cdr-of-lookup-id (implies (and (posp n) (< n (num-fanins aignet)) (not (equal (ctype stype) (out-ctype)))) (equal (stype-count stype (cdr (lookup-id n aignet))) (stype-count stype (lookup-id (+ -1 n) aignet)))) :hints(("Goal" :in-theory (e/d (lookup-id node-list-fix fanin-node-p) (lookup-id-in-extension-inverse)) :induct t) (and stable-under-simplificationp '(:expand ((lookup-id (+ -1 (fanin-count aignet)) aignet))))))) (defret count-xors-rec-value (implies (<= (nfix start) (num-fanins aignet)) (equal count (+ (nfix acc) (- (stype-count :xor aignet) (stype-count :xor (lookup-id (- (nfix start) 1) aignet)))))) :hints(("Goal" :in-theory (e/d (stype-count lookup-id lookup-id-in-bounds)) :induct (count-xors-rec start aignet acc) :expand ((stype-count :xor (lookup-id start aignet)))) (and stable-under-simplificationp '(:cases ((natp start))))))) (define count-xors (aignet) :returns (count natp :rule-classes :type-prescription) (count-xors-rec 0 aignet 0) /// (defret count-xors-value (equal (count-xors aignet) (stype-count :xor aignet)))) (define print-aignet-stats ((name stringp) aignet) (b* ((xors (count-xors aignet)) (gates (num-gates aignet))) (cw "~s0 network: Nodes: ~x8 ~ PIs ~x1 regs ~x2~% ~ gates ~x3 (ands ~x4 xors ~x5)~% ~ nxsts ~x6 POs ~x7~%" (mbe :logic (acl2::str-fix name) :exec name) (num-ins aignet) (num-regs aignet) gates (- gates xors) xors (num-nxsts aignet) (num-outs aignet) (num-fanins aignet))))
63907
; AIGNET - And-Inverter Graph Networks ; Copyright (C) 2017 Centaur Technology ; ; Contact: ; Centaur Technology Formal Verification Group ; 7600-C N. Capital of Texas Highway, Suite 300, Austin, TX 78731, USA. ; http://www.centtech.com/ ; ; License: (An MIT/X11-style license) ; ; Permission is hereby granted, free of charge, to any person obtaining a ; copy of this software and associated documentation files (the "Software"), ; to deal in the Software without restriction, including without limitation ; the rights to use, copy, modify, merge, publish, distribute, sublicense, ; and/or sell copies of the Software, and to permit persons to whom the ; Software is furnished to do so, subject to the following conditions: ; ; The above copyright notice and this permission notice shall be included in ; all copies or substantial portions of the Software. ; ; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR ; IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, ; FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE ; AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER ; LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING ; FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER ; DEALINGS IN THE SOFTWARE. ; ; Original author: <NAME> <<EMAIL>> (in-package "AIGNET") (include-book "aignet-absstobj") (define count-xors-rec ((start natp) aignet (acc natp)) :guard (<= start (num-fanins aignet)) :guard-hints (("goal" :in-theory (enable aignet-idp))) :measure (nfix (- (num-fanins aignet) (nfix start))) :returns (count natp :rule-classes :type-prescription) (b* (((when (mbe :logic (zp (- (num-fanins aignet) (nfix start))) :exec (eql start (num-fanins aignet)))) (lnfix acc)) (acc (if (and (eql (id->type start aignet) (gate-type)) (eql (id->regp start aignet) 1)) (+ 1 (lnfix acc)) (lnfix acc)))) (count-xors-rec (+ 1 (lnfix start)) aignet acc)) /// (local (defthm stype-count-of-lookup-fanin-count (implies (not (equal (ctype stype) (out-ctype))) (equal (stype-count stype (lookup-id (fanin-count aignet) aignet)) (stype-count stype aignet))) :hints(("Goal" :in-theory (enable lookup-id fanin-count fanin-node-p))))) (local (defthm cdr-of-lookup-id (implies (and (posp n) (< n (num-fanins aignet)) (not (equal (ctype stype) (out-ctype)))) (equal (stype-count stype (cdr (lookup-id n aignet))) (stype-count stype (lookup-id (+ -1 n) aignet)))) :hints(("Goal" :in-theory (e/d (lookup-id node-list-fix fanin-node-p) (lookup-id-in-extension-inverse)) :induct t) (and stable-under-simplificationp '(:expand ((lookup-id (+ -1 (fanin-count aignet)) aignet))))))) (defret count-xors-rec-value (implies (<= (nfix start) (num-fanins aignet)) (equal count (+ (nfix acc) (- (stype-count :xor aignet) (stype-count :xor (lookup-id (- (nfix start) 1) aignet)))))) :hints(("Goal" :in-theory (e/d (stype-count lookup-id lookup-id-in-bounds)) :induct (count-xors-rec start aignet acc) :expand ((stype-count :xor (lookup-id start aignet)))) (and stable-under-simplificationp '(:cases ((natp start))))))) (define count-xors (aignet) :returns (count natp :rule-classes :type-prescription) (count-xors-rec 0 aignet 0) /// (defret count-xors-value (equal (count-xors aignet) (stype-count :xor aignet)))) (define print-aignet-stats ((name stringp) aignet) (b* ((xors (count-xors aignet)) (gates (num-gates aignet))) (cw "~s0 network: Nodes: ~x8 ~ PIs ~x1 regs ~x2~% ~ gates ~x3 (ands ~x4 xors ~x5)~% ~ nxsts ~x6 POs ~x7~%" (mbe :logic (acl2::str-fix name) :exec name) (num-ins aignet) (num-regs aignet) gates (- gates xors) xors (num-nxsts aignet) (num-outs aignet) (num-fanins aignet))))
true
; AIGNET - And-Inverter Graph Networks ; Copyright (C) 2017 Centaur Technology ; ; Contact: ; Centaur Technology Formal Verification Group ; 7600-C N. Capital of Texas Highway, Suite 300, Austin, TX 78731, USA. ; http://www.centtech.com/ ; ; License: (An MIT/X11-style license) ; ; Permission is hereby granted, free of charge, to any person obtaining a ; copy of this software and associated documentation files (the "Software"), ; to deal in the Software without restriction, including without limitation ; the rights to use, copy, modify, merge, publish, distribute, sublicense, ; and/or sell copies of the Software, and to permit persons to whom the ; Software is furnished to do so, subject to the following conditions: ; ; The above copyright notice and this permission notice shall be included in ; all copies or substantial portions of the Software. ; ; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR ; IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, ; FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE ; AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER ; LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING ; FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER ; DEALINGS IN THE SOFTWARE. ; ; Original author: PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> (in-package "AIGNET") (include-book "aignet-absstobj") (define count-xors-rec ((start natp) aignet (acc natp)) :guard (<= start (num-fanins aignet)) :guard-hints (("goal" :in-theory (enable aignet-idp))) :measure (nfix (- (num-fanins aignet) (nfix start))) :returns (count natp :rule-classes :type-prescription) (b* (((when (mbe :logic (zp (- (num-fanins aignet) (nfix start))) :exec (eql start (num-fanins aignet)))) (lnfix acc)) (acc (if (and (eql (id->type start aignet) (gate-type)) (eql (id->regp start aignet) 1)) (+ 1 (lnfix acc)) (lnfix acc)))) (count-xors-rec (+ 1 (lnfix start)) aignet acc)) /// (local (defthm stype-count-of-lookup-fanin-count (implies (not (equal (ctype stype) (out-ctype))) (equal (stype-count stype (lookup-id (fanin-count aignet) aignet)) (stype-count stype aignet))) :hints(("Goal" :in-theory (enable lookup-id fanin-count fanin-node-p))))) (local (defthm cdr-of-lookup-id (implies (and (posp n) (< n (num-fanins aignet)) (not (equal (ctype stype) (out-ctype)))) (equal (stype-count stype (cdr (lookup-id n aignet))) (stype-count stype (lookup-id (+ -1 n) aignet)))) :hints(("Goal" :in-theory (e/d (lookup-id node-list-fix fanin-node-p) (lookup-id-in-extension-inverse)) :induct t) (and stable-under-simplificationp '(:expand ((lookup-id (+ -1 (fanin-count aignet)) aignet))))))) (defret count-xors-rec-value (implies (<= (nfix start) (num-fanins aignet)) (equal count (+ (nfix acc) (- (stype-count :xor aignet) (stype-count :xor (lookup-id (- (nfix start) 1) aignet)))))) :hints(("Goal" :in-theory (e/d (stype-count lookup-id lookup-id-in-bounds)) :induct (count-xors-rec start aignet acc) :expand ((stype-count :xor (lookup-id start aignet)))) (and stable-under-simplificationp '(:cases ((natp start))))))) (define count-xors (aignet) :returns (count natp :rule-classes :type-prescription) (count-xors-rec 0 aignet 0) /// (defret count-xors-value (equal (count-xors aignet) (stype-count :xor aignet)))) (define print-aignet-stats ((name stringp) aignet) (b* ((xors (count-xors aignet)) (gates (num-gates aignet))) (cw "~s0 network: Nodes: ~x8 ~ PIs ~x1 regs ~x2~% ~ gates ~x3 (ands ~x4 xors ~x5)~% ~ nxsts ~x6 POs ~x7~%" (mbe :logic (acl2::str-fix name) :exec name) (num-ins aignet) (num-regs aignet) gates (- gates xors) xors (num-nxsts aignet) (num-outs aignet) (num-fanins aignet))))
[ { "context": ":asdf-user)\r\n(defsystem \"step7_quote\"\r\n :author \"Aratrik Pal\"\r\n :serial t\r\n :depends-on (\"cl-ppcre\" \"unix-op", "end": 75, "score": 0.9998540282249451, "start": 64, "tag": "NAME", "value": "Aratrik Pal" } ]
step7_quote.asd
AP2008/mal-cl
0
(in-package :asdf-user) (defsystem "step7_quote" :author "Aratrik Pal" :serial t :depends-on ("cl-ppcre" "unix-opts") :components ((:file "errors") (:file "types") (:file "env") (:file "reader") (:file "printer") (:file "core") (:file "step7_quote")) :pathname "src/" :build-operation "asdf:program-op" :build-pathname "../step7_quote" :entry-point "step7_quote:main")
37104
(in-package :asdf-user) (defsystem "step7_quote" :author "<NAME>" :serial t :depends-on ("cl-ppcre" "unix-opts") :components ((:file "errors") (:file "types") (:file "env") (:file "reader") (:file "printer") (:file "core") (:file "step7_quote")) :pathname "src/" :build-operation "asdf:program-op" :build-pathname "../step7_quote" :entry-point "step7_quote:main")
true
(in-package :asdf-user) (defsystem "step7_quote" :author "PI:NAME:<NAME>END_PI" :serial t :depends-on ("cl-ppcre" "unix-opts") :components ((:file "errors") (:file "types") (:file "env") (:file "reader") (:file "printer") (:file "core") (:file "step7_quote")) :pathname "src/" :build-operation "asdf:program-op" :build-pathname "../step7_quote" :entry-point "step7_quote:main")
[ { "context": "- Parsnip example JSON decoder\n\n;;; Copyright 2021 Samuel Hunter <samuel (at) shunter (dot) xyz>\n;;; BSD-3-Clause\n", "end": 78, "score": 0.9998773336410522, "start": 65, "tag": "NAME", "value": "Samuel Hunter" }, { "context": "e JSON decoder\n\n;;; Copyright 2021 Samuel Hunter <samuel (at) shunter (dot) xyz>\n;;; BSD-3-Clause\n\n(def", "end": 83, "score": 0.4658123850822449, "start": 80, "tag": "USERNAME", "value": "sam" } ]
examples/json.lisp
samuel-hunter/parsnip
0
;;; json.lisp - Parsnip example JSON decoder ;;; Copyright 2021 Samuel Hunter <samuel (at) shunter (dot) xyz> ;;; BSD-3-Clause (defpackage #:xyz.shunter.parsnip.examples.json (:documentation "Parsnip example JSON decoder") (:use #:cl #:xyz.shunter.parsnip) (:import-from #:alexandria #:eswitch) (:export #:decode-json #:decode-json-from-string)) (in-package #:xyz.shunter.parsnip.examples.json) (defun charbag-parser (charbag) (predicate-parser (lambda (c) (position c charbag)))) ;;; RFC 8259 § 2. JSON Grammar ;; whitespace := ( space | tab | newline | return )* (defparameter *whitespace* (parse-skip-many (charbag-parser '(#\Space #\Tab #\Newline #\Return)))) (defun trim-ws (parser) (parse-prog2 *whitespace* parser *whitespace*)) ;; begin-array := ws '[' ws (defparameter *begin-array* (trim-ws (char-parser #\[))) ;; begin-object := ws '{' ws (defparameter *begin-object* (trim-ws (char-parser #\{))) ;; end-array := ws ']' ws (defparameter *end-array* (trim-ws (char-parser #\]))) ;; end-object := ws '}' ws (defparameter *end-object* (trim-ws (char-parser #\}))) ;; name-separator := ws ':' ws (defparameter *name-separator* (trim-ws (char-parser #\:))) ;; value-separator := ws ',' ws (defparameter *value-separator* (trim-ws (char-parser #\,))) ;; RFC 8259 § 7. Strings (defparameter *char-code* (parse-let ((char (charbag-parser "\"\\/bfnrt"))) (eswitch (char :test char=) (#\" #\") ;; " => " quotation mark (#\\ #\\) ;; \ => \ reverse solidus (#\/ #\/) ;; / => / solidus (#\b #\Backspace) ;; b => Backspace (#\f #\Page) ;; f => Form feed / New page (#\n #\Newline) ;; n => Line feed / New line (#\r #\Return) ;; r => Carriage return (#\t #\Tab)))) ;; t => Horizontal tab (defparameter *unicode-char* (parse-progn (char-parser #\u) (parse-map (lambda (digits) (code-char (reduce (lambda (num dig) (+ (* 16 num) dig)) digits))) (parse-take 4 (digit-parser 16))))) ;; char := unescaped | '\' char-code (defparameter *char* (parse-or (parse-progn (char-parser #\\) (parse-or *char-code* *unicode-char*)) (predicate-parser (lambda (c) (not (char= c #\")))))) ;; string := quotation char+ quotation (defparser json-string () (parse-prog2 (char-parser #\") (parse-collect-string *char*) (char-parser #\"))) ;;; RFC 8259 § 4. Objects ;; member := string name-separator value (defparameter *member* (parse-let ((name 'json-string) (separator *name-separator*) (value 'value)) (declare (ignore separator)) (cons name value))) ;; object := begin-object [ member ( value-separator member ) + ] end-object (defparser json-object () (parse-prog2 *begin-object* (parse-optional (parse-map #'cons *member* (parse-collect (parse-progn *value-separator* *member*))) ()) *end-object*)) ;;; RFC 8259 § 5. Arrays ;; array := begin-array [ value ( value-separator value )+ ] end-array (defparser json-array () (parse-prog2 *begin-array* (parse-optional (parse-map #'cons 'value (parse-collect (parse-progn *value-separator* 'value))) ()) *end-array*)) ;; RFC 8259 § 6. Numbers ;; frac := '.' int (defparameter *frac* (parse-progn (char-parser #\.) (parse-let ((digits (parse-collect1 (digit-parser)))) (/ (reduce (lambda (num dig) (+ (* num 10) dig)) digits) (expt 10 (length digits)))))) ;; exp := 'e' ['+' | '-'] int (defparameter *exp* (parse-progn (char-parser #\e) (parse-let ((sign (parse-optional (charbag-parser "+-") #\+)) (num (integer-parser))) (* (if (char= sign #\+) 1 -1) num)))) ;; number := [minus] int [frac] [exp] (defparser json-number () (parse-let ((sign (parse-optional (char-parser #\-))) (whole-part (integer-parser)) (frac-part (parse-optional *frac* 0)) (exp-part (parse-optional *exp* 0))) (setf sign (if sign -1 1)) (if (and (zerop frac-part) (zerop exp-part)) (* sign whole-part) (float (* sign (+ whole-part frac-part) (expt 10 exp-part)))))) ;; RFC 8259 § 3. Values (defun literal-parser (start remaining-name value) ;; Separate the starting char and remaining name so that the parser can peek ;; at a single char before reading the rest of the name. Possible since every ;; literal has a unique character (f, n, t). (parse-map (constantly value) (parse-progn (char-parser start) (string-parser remaining-name)))) ;; value := 'false' | 'null' | 'true' | object | array | number | string (defparser value () (parse-or (literal-parser #\f "alse" :false) (literal-parser #\n "ull" :null) (literal-parser #\t "rue" :true) 'json-object 'json-array 'json-number 'json-string)) ;; text := ws value ws EOF (defparameter *text* (prog2 *whitespace* #'value *whitespace* (eof-parser))) (defun decode-json (&optional (stream *standard-input*)) (parse *text* stream)) (defun decode-json-from-string (string) (with-input-from-string (stream string) (decode-json stream)))
27410
;;; json.lisp - Parsnip example JSON decoder ;;; Copyright 2021 <NAME> <samuel (at) shunter (dot) xyz> ;;; BSD-3-Clause (defpackage #:xyz.shunter.parsnip.examples.json (:documentation "Parsnip example JSON decoder") (:use #:cl #:xyz.shunter.parsnip) (:import-from #:alexandria #:eswitch) (:export #:decode-json #:decode-json-from-string)) (in-package #:xyz.shunter.parsnip.examples.json) (defun charbag-parser (charbag) (predicate-parser (lambda (c) (position c charbag)))) ;;; RFC 8259 § 2. JSON Grammar ;; whitespace := ( space | tab | newline | return )* (defparameter *whitespace* (parse-skip-many (charbag-parser '(#\Space #\Tab #\Newline #\Return)))) (defun trim-ws (parser) (parse-prog2 *whitespace* parser *whitespace*)) ;; begin-array := ws '[' ws (defparameter *begin-array* (trim-ws (char-parser #\[))) ;; begin-object := ws '{' ws (defparameter *begin-object* (trim-ws (char-parser #\{))) ;; end-array := ws ']' ws (defparameter *end-array* (trim-ws (char-parser #\]))) ;; end-object := ws '}' ws (defparameter *end-object* (trim-ws (char-parser #\}))) ;; name-separator := ws ':' ws (defparameter *name-separator* (trim-ws (char-parser #\:))) ;; value-separator := ws ',' ws (defparameter *value-separator* (trim-ws (char-parser #\,))) ;; RFC 8259 § 7. Strings (defparameter *char-code* (parse-let ((char (charbag-parser "\"\\/bfnrt"))) (eswitch (char :test char=) (#\" #\") ;; " => " quotation mark (#\\ #\\) ;; \ => \ reverse solidus (#\/ #\/) ;; / => / solidus (#\b #\Backspace) ;; b => Backspace (#\f #\Page) ;; f => Form feed / New page (#\n #\Newline) ;; n => Line feed / New line (#\r #\Return) ;; r => Carriage return (#\t #\Tab)))) ;; t => Horizontal tab (defparameter *unicode-char* (parse-progn (char-parser #\u) (parse-map (lambda (digits) (code-char (reduce (lambda (num dig) (+ (* 16 num) dig)) digits))) (parse-take 4 (digit-parser 16))))) ;; char := unescaped | '\' char-code (defparameter *char* (parse-or (parse-progn (char-parser #\\) (parse-or *char-code* *unicode-char*)) (predicate-parser (lambda (c) (not (char= c #\")))))) ;; string := quotation char+ quotation (defparser json-string () (parse-prog2 (char-parser #\") (parse-collect-string *char*) (char-parser #\"))) ;;; RFC 8259 § 4. Objects ;; member := string name-separator value (defparameter *member* (parse-let ((name 'json-string) (separator *name-separator*) (value 'value)) (declare (ignore separator)) (cons name value))) ;; object := begin-object [ member ( value-separator member ) + ] end-object (defparser json-object () (parse-prog2 *begin-object* (parse-optional (parse-map #'cons *member* (parse-collect (parse-progn *value-separator* *member*))) ()) *end-object*)) ;;; RFC 8259 § 5. Arrays ;; array := begin-array [ value ( value-separator value )+ ] end-array (defparser json-array () (parse-prog2 *begin-array* (parse-optional (parse-map #'cons 'value (parse-collect (parse-progn *value-separator* 'value))) ()) *end-array*)) ;; RFC 8259 § 6. Numbers ;; frac := '.' int (defparameter *frac* (parse-progn (char-parser #\.) (parse-let ((digits (parse-collect1 (digit-parser)))) (/ (reduce (lambda (num dig) (+ (* num 10) dig)) digits) (expt 10 (length digits)))))) ;; exp := 'e' ['+' | '-'] int (defparameter *exp* (parse-progn (char-parser #\e) (parse-let ((sign (parse-optional (charbag-parser "+-") #\+)) (num (integer-parser))) (* (if (char= sign #\+) 1 -1) num)))) ;; number := [minus] int [frac] [exp] (defparser json-number () (parse-let ((sign (parse-optional (char-parser #\-))) (whole-part (integer-parser)) (frac-part (parse-optional *frac* 0)) (exp-part (parse-optional *exp* 0))) (setf sign (if sign -1 1)) (if (and (zerop frac-part) (zerop exp-part)) (* sign whole-part) (float (* sign (+ whole-part frac-part) (expt 10 exp-part)))))) ;; RFC 8259 § 3. Values (defun literal-parser (start remaining-name value) ;; Separate the starting char and remaining name so that the parser can peek ;; at a single char before reading the rest of the name. Possible since every ;; literal has a unique character (f, n, t). (parse-map (constantly value) (parse-progn (char-parser start) (string-parser remaining-name)))) ;; value := 'false' | 'null' | 'true' | object | array | number | string (defparser value () (parse-or (literal-parser #\f "alse" :false) (literal-parser #\n "ull" :null) (literal-parser #\t "rue" :true) 'json-object 'json-array 'json-number 'json-string)) ;; text := ws value ws EOF (defparameter *text* (prog2 *whitespace* #'value *whitespace* (eof-parser))) (defun decode-json (&optional (stream *standard-input*)) (parse *text* stream)) (defun decode-json-from-string (string) (with-input-from-string (stream string) (decode-json stream)))
true
;;; json.lisp - Parsnip example JSON decoder ;;; Copyright 2021 PI:NAME:<NAME>END_PI <samuel (at) shunter (dot) xyz> ;;; BSD-3-Clause (defpackage #:xyz.shunter.parsnip.examples.json (:documentation "Parsnip example JSON decoder") (:use #:cl #:xyz.shunter.parsnip) (:import-from #:alexandria #:eswitch) (:export #:decode-json #:decode-json-from-string)) (in-package #:xyz.shunter.parsnip.examples.json) (defun charbag-parser (charbag) (predicate-parser (lambda (c) (position c charbag)))) ;;; RFC 8259 § 2. JSON Grammar ;; whitespace := ( space | tab | newline | return )* (defparameter *whitespace* (parse-skip-many (charbag-parser '(#\Space #\Tab #\Newline #\Return)))) (defun trim-ws (parser) (parse-prog2 *whitespace* parser *whitespace*)) ;; begin-array := ws '[' ws (defparameter *begin-array* (trim-ws (char-parser #\[))) ;; begin-object := ws '{' ws (defparameter *begin-object* (trim-ws (char-parser #\{))) ;; end-array := ws ']' ws (defparameter *end-array* (trim-ws (char-parser #\]))) ;; end-object := ws '}' ws (defparameter *end-object* (trim-ws (char-parser #\}))) ;; name-separator := ws ':' ws (defparameter *name-separator* (trim-ws (char-parser #\:))) ;; value-separator := ws ',' ws (defparameter *value-separator* (trim-ws (char-parser #\,))) ;; RFC 8259 § 7. Strings (defparameter *char-code* (parse-let ((char (charbag-parser "\"\\/bfnrt"))) (eswitch (char :test char=) (#\" #\") ;; " => " quotation mark (#\\ #\\) ;; \ => \ reverse solidus (#\/ #\/) ;; / => / solidus (#\b #\Backspace) ;; b => Backspace (#\f #\Page) ;; f => Form feed / New page (#\n #\Newline) ;; n => Line feed / New line (#\r #\Return) ;; r => Carriage return (#\t #\Tab)))) ;; t => Horizontal tab (defparameter *unicode-char* (parse-progn (char-parser #\u) (parse-map (lambda (digits) (code-char (reduce (lambda (num dig) (+ (* 16 num) dig)) digits))) (parse-take 4 (digit-parser 16))))) ;; char := unescaped | '\' char-code (defparameter *char* (parse-or (parse-progn (char-parser #\\) (parse-or *char-code* *unicode-char*)) (predicate-parser (lambda (c) (not (char= c #\")))))) ;; string := quotation char+ quotation (defparser json-string () (parse-prog2 (char-parser #\") (parse-collect-string *char*) (char-parser #\"))) ;;; RFC 8259 § 4. Objects ;; member := string name-separator value (defparameter *member* (parse-let ((name 'json-string) (separator *name-separator*) (value 'value)) (declare (ignore separator)) (cons name value))) ;; object := begin-object [ member ( value-separator member ) + ] end-object (defparser json-object () (parse-prog2 *begin-object* (parse-optional (parse-map #'cons *member* (parse-collect (parse-progn *value-separator* *member*))) ()) *end-object*)) ;;; RFC 8259 § 5. Arrays ;; array := begin-array [ value ( value-separator value )+ ] end-array (defparser json-array () (parse-prog2 *begin-array* (parse-optional (parse-map #'cons 'value (parse-collect (parse-progn *value-separator* 'value))) ()) *end-array*)) ;; RFC 8259 § 6. Numbers ;; frac := '.' int (defparameter *frac* (parse-progn (char-parser #\.) (parse-let ((digits (parse-collect1 (digit-parser)))) (/ (reduce (lambda (num dig) (+ (* num 10) dig)) digits) (expt 10 (length digits)))))) ;; exp := 'e' ['+' | '-'] int (defparameter *exp* (parse-progn (char-parser #\e) (parse-let ((sign (parse-optional (charbag-parser "+-") #\+)) (num (integer-parser))) (* (if (char= sign #\+) 1 -1) num)))) ;; number := [minus] int [frac] [exp] (defparser json-number () (parse-let ((sign (parse-optional (char-parser #\-))) (whole-part (integer-parser)) (frac-part (parse-optional *frac* 0)) (exp-part (parse-optional *exp* 0))) (setf sign (if sign -1 1)) (if (and (zerop frac-part) (zerop exp-part)) (* sign whole-part) (float (* sign (+ whole-part frac-part) (expt 10 exp-part)))))) ;; RFC 8259 § 3. Values (defun literal-parser (start remaining-name value) ;; Separate the starting char and remaining name so that the parser can peek ;; at a single char before reading the rest of the name. Possible since every ;; literal has a unique character (f, n, t). (parse-map (constantly value) (parse-progn (char-parser start) (string-parser remaining-name)))) ;; value := 'false' | 'null' | 'true' | object | array | number | string (defparser value () (parse-or (literal-parser #\f "alse" :false) (literal-parser #\n "ull" :null) (literal-parser #\t "rue" :true) 'json-object 'json-array 'json-number 'json-string)) ;; text := ws value ws EOF (defparameter *text* (prog2 *whitespace* #'value *whitespace* (eof-parser))) (defun decode-json (&optional (stream *standard-input*)) (parse *text* stream)) (defun decode-json-from-string (string) (with-input-from-string (stream string) (decode-json stream)))
[ { "context": "art of mmap\n (c) 2017 Shirakumo http://tymoon.eu (shinmera@tymoon .eu)\n Author: Nicolas Hafner <[email protected]>\n|#\n", "end": 89, "score": 0.9992203116416931, "start": 70, "tag": "EMAIL", "value": "shinmera@tymoon .eu" }, { "context": "mo http://tymoon.eu (shinmera@tymoon .eu)\n Author: Nicolas Hafner <[email protected]>\n|#\n\n(asdf:defsystem mmap-tes", "end": 114, "score": 0.9998864531517029, "start": 100, "tag": "NAME", "value": "Nicolas Hafner" }, { "context": "eu (shinmera@tymoon .eu)\n Author: Nicolas Hafner <[email protected]>\n|#\n\n(asdf:defsystem mmap-test\n :version \"1.0.0\"", "end": 134, "score": 0.9998689293861389, "start": 116, "tag": "EMAIL", "value": "[email protected]" }, { "context": "t\n :version \"1.0.0\"\n :license \"zlib\"\n :author \"Nicolas Hafner <[email protected]>\"\n :maintainer \"Nicolas Hafn", "end": 228, "score": 0.999884307384491, "start": 214, "tag": "NAME", "value": "Nicolas Hafner" }, { "context": "0.0\"\n :license \"zlib\"\n :author \"Nicolas Hafner <[email protected]>\"\n :maintainer \"Nicolas Hafner <shinmera@tymoon.", "end": 248, "score": 0.9998283386230469, "start": 230, "tag": "EMAIL", "value": "[email protected]" }, { "context": "colas Hafner <[email protected]>\"\n :maintainer \"Nicolas Hafner <[email protected]>\"\n :description \"Tests for t", "end": 280, "score": 0.9998845458030701, "start": 266, "tag": "NAME", "value": "Nicolas Hafner" }, { "context": "[email protected]>\"\n :maintainer \"Nicolas Hafner <[email protected]>\"\n :description \"Tests for the mmap system.\"\n :", "end": 300, "score": 0.9997971057891846, "start": 282, "tag": "EMAIL", "value": "[email protected]" }, { "context": "ub.io/mmap/\"\n :bug-tracker \"https://github.com/Shinmera/mmap/issues\"\n :source-control (:git \"https://git", "end": 437, "score": 0.8228691220283508, "start": 431, "tag": "USERNAME", "value": "inmera" }, { "context": "es\"\n :source-control (:git \"https://github.com/Shinmera/mmap.git\")\n :serial T\n :components ((:file \"tes", "end": 503, "score": 0.7297059893608093, "start": 497, "tag": "USERNAME", "value": "inmera" } ]
mmap-test.asd
jathd/mmap
28
#| This file is a part of mmap (c) 2017 Shirakumo http://tymoon.eu (shinmera@tymoon .eu) Author: Nicolas Hafner <[email protected]> |# (asdf:defsystem mmap-test :version "1.0.0" :license "zlib" :author "Nicolas Hafner <[email protected]>" :maintainer "Nicolas Hafner <[email protected]>" :description "Tests for the mmap system." :homepage "https://shinmera.github.io/mmap/" :bug-tracker "https://github.com/Shinmera/mmap/issues" :source-control (:git "https://github.com/Shinmera/mmap.git") :serial T :components ((:file "test")) :depends-on (:mmap :cffi :alexandria :parachute) :perform (asdf:test-op (op c) (uiop:symbol-call :parachute :test :mmap-test)))
9615
#| This file is a part of mmap (c) 2017 Shirakumo http://tymoon.eu (<EMAIL>) Author: <NAME> <<EMAIL>> |# (asdf:defsystem mmap-test :version "1.0.0" :license "zlib" :author "<NAME> <<EMAIL>>" :maintainer "<NAME> <<EMAIL>>" :description "Tests for the mmap system." :homepage "https://shinmera.github.io/mmap/" :bug-tracker "https://github.com/Shinmera/mmap/issues" :source-control (:git "https://github.com/Shinmera/mmap.git") :serial T :components ((:file "test")) :depends-on (:mmap :cffi :alexandria :parachute) :perform (asdf:test-op (op c) (uiop:symbol-call :parachute :test :mmap-test)))
true
#| This file is a part of mmap (c) 2017 Shirakumo http://tymoon.eu (PI:EMAIL:<EMAIL>END_PI) Author: PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> |# (asdf:defsystem mmap-test :version "1.0.0" :license "zlib" :author "PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>" :maintainer "PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>" :description "Tests for the mmap system." :homepage "https://shinmera.github.io/mmap/" :bug-tracker "https://github.com/Shinmera/mmap/issues" :source-control (:git "https://github.com/Shinmera/mmap.git") :serial T :components ((:file "test")) :depends-on (:mmap :cffi :alexandria :parachute) :perform (asdf:test-op (op c) (uiop:symbol-call :parachute :test :mmap-test)))
[ { "context": "\n% RLISP to LISP converter. A C Norman 2004-2020\n\n\n%%\n%% Copyright (C) 2020, following t", "end": 38, "score": 0.6931051015853882, "start": 32, "tag": "NAME", "value": "Norman" } ]
csl/cslbase/compiler-for-jlisp.lsp
arthurcnorman/general
0
% RLISP to LISP converter. A C Norman 2004-2020 %% %% Copyright (C) 2020, following the master REDUCE source files. * %% * %% 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 relevant * %% copyright notice, this list of conditions and the following * %% disclaimer. * %% * Redistributions in binary form must reproduce the above * %% copyright notice, this list of conditions and the following * %% disclaimer in the documentation and/or other materials provided * %% with the distribution. * %% * %% THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * %% "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * %% LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * %% FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * %% COPYRIGHT OWNERS 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. * %% (global (quote (s!:opcodelist))) (setq s!:opcodelist (quote (LOADLOC LOADLOC0 LOADLOC1 LOADLOC2 LOADLOC3 LOADLOC4 LOADLOC5 LOADLOC6 LOADLOC7 LOADLOC8 LOADLOC9 LOADLOC10 LOADLOC11 LOC0LOC1 LOC1LOC2 LOC2LOC3 LOC1LOC0 LOC2LOC1 LOC3LOC2 VNIL LOADLIT LOADLIT1 LOADLIT2 LOADLIT3 LOADLIT4 LOADLIT5 LOADLIT6 LOADLIT7 LOADFREE LOADFREE1 LOADFREE2 LOADFREE3 LOADFREE4 STORELOC STORELOC0 STORELOC1 STORELOC2 STORELOC3 STORELOC4 STORELOC5 STORELOC6 STORELOC7 STOREFREE STOREFREE1 STOREFREE2 STOREFREE3 LOADLEX STORELEX CLOSURE CARLOC0 CARLOC1 CARLOC2 CARLOC3 CARLOC4 CARLOC5 CARLOC6 CARLOC7 CARLOC8 CARLOC9 CARLOC10 CARLOC11 CDRLOC0 CDRLOC1 CDRLOC2 CDRLOC3 CDRLOC4 CDRLOC5 CAARLOC0 CAARLOC1 CAARLOC2 CAARLOC3 CALL0 CALL1 CALL2 CALL2R CALL3 CALLN CALL0_0 CALL0_1 CALL0_2 CALL0_3 CALL1_0 CALL1_1 CALL1_2 CALL1_3 CALL1_4 CALL1_5 CALL2_0 CALL2_1 CALL2_2 CALL2_3 CALL2_4 BUILTIN0 BUILTIN1 BUILTIN2 BUILTIN2R BUILTIN3 APPLY1 APPLY2 APPLY3 APPLY4 JCALL JCALLN JUMP JUMP_B JUMP_L JUMP_BL JUMPNIL JUMPNIL_B JUMPNIL_L JUMPNIL_BL JUMPT JUMPT_B JUMPT_L JUMPT_BL JUMPATOM JUMPATOM_B JUMPATOM_L JUMPATOM_BL JUMPNATOM JUMPNATOM_B JUMPNATOM_L JUMPNATOM_BL JUMPEQ JUMPEQ_B JUMPEQ_L JUMPEQ_BL JUMPNE JUMPNE_B JUMPNE_L JUMPNE_BL JUMPEQUAL JUMPEQUAL_B JUMPEQUAL_L JUMPEQUAL_BL JUMPNEQUAL JUMPNEQUAL_B JUMPNEQUAL_L JUMPNEQUAL_BL JUMPL0NIL JUMPL0T JUMPL1NIL JUMPL1T JUMPL2NIL JUMPL2T JUMPL3NIL JUMPL3T JUMPL4NIL JUMPL4T JUMPST0NIL JUMPST0T JUMPST1NIL JUMPST1T JUMPST2NIL JUMPST2T JUMPL0ATOM JUMPL0NATOM JUMPL1ATOM JUMPL1NATOM JUMPL2ATOM JUMPL2NATOM JUMPL3ATOM JUMPL3NATOM JUMPFREE1NIL JUMPFREE1T JUMPFREE2NIL JUMPFREE2T JUMPFREE3NIL JUMPFREE3T JUMPFREE4NIL JUMPFREE4T JUMPFREENIL JUMPFREET JUMPLIT1EQ JUMPLIT1NE JUMPLIT2EQ JUMPLIT2NE JUMPLIT3EQ JUMPLIT3NE JUMPLIT4EQ JUMPLIT4NE JUMPLITEQ JUMPLITNE JUMPB1NIL JUMPB1T JUMPB2NIL JUMPB2T JUMPFLAGP JUMPNFLAGP JUMPEQCAR JUMPNEQCAR CATCH CATCH_B CATCH_L CATCH_BL UNCATCH THROW PROTECT UNPROTECT PVBIND PVRESTORE FREEBIND FREERSTR EXIT NILEXIT LOC0EXIT LOC1EXIT LOC2EXIT PUSH PUSHNIL PUSHNIL2 PUSHNIL3 PUSHNILS POP LOSE LOSE2 LOSE3 LOSES SWOP EQ EQCAR EQUAL NUMBERP CAR CDR CAAR CADR CDAR CDDR CONS NCONS XCONS ACONS LENGTH LIST2 LIST2STAR LIST3 PLUS2 ADD1 DIFFERENCE SUB1 TIMES2 GREATERP LESSP FLAGP GET LITGET GETV QGETV QGETVN BIGSTACK BIGCALL ICASE FASTGET ONEVALUE SPARE))) (prog (n) (setq n 0) (prog (var1001) (setq var1001 s!:opcodelist) lab1000 ( cond ((null var1001) (return nil))) (prog (v) (setq v (car var1001)) (progn ( put v (quote s!:opcode) n) (setq n (plus n 1)))) (setq var1001 (cdr var1001)) (go lab1000)) (return (list n (quote opcodes) (quote allocated)))) (setq s!:opcodelist nil) (fluid (quote (s!:env_alist))) (de s!:vecof (l) (prog (w) (setq w (assoc l s!:env_alist)) (cond (w (return ( cdr w)))) (setq w (s!:vecof1 l)) (setq s!:env_alist (cons (cons l w) s!:env_alist)) (return w))) (de s!:vecof1 (l) (prog (v n) (setq v (mkvect (sub1 (length l)))) (setq n 0) (prog (var1003) (setq var1003 l) lab1002 (cond ((null var1003) (return nil))) (prog (x) (setq x (car var1003)) (progn (putv v n x) (setq n (plus n 1)))) ( setq var1003 (cdr var1003)) (go lab1002)) (return v))) (progn (put (quote batchp) (quote s!:builtin0) 0) (put (quote date) (quote s!:builtin0) 1) (put (quote eject) (quote s!:builtin0) 2) (put (quote error1) (quote s!:builtin0) 3) (put (quote gctime) (quote s!:builtin0) 4) (put ( quote lposn) (quote s!:builtin0) 6) (put (quote posn) (quote s!:builtin0) 8) (put (quote read) (quote s!:builtin0) 9) (put (quote readch) (quote s!:builtin0) 10) (put (quote terpri) (quote s!:builtin0) 11) (put (quote time ) (quote s!:builtin0) 12) (put (quote tyi) (quote s!:builtin0) 13) (put ( quote load!-spid) (quote s!:builtin0) 14) (put (quote abs) (quote s!:builtin1 ) 0) (put (quote add1) (quote s!:builtin1) 1) (put (quote atan) (quote s!:builtin1) 2) (put (quote apply0) (quote s!:builtin1) 3) (put (quote atom) (quote s!:builtin1) 4) (put (quote boundp) (quote s!:builtin1) 5) (put (quote char!-code) (quote s!:builtin1) 6) (put (quote close) (quote s!:builtin1) 7) (put (quote codep) (quote s!:builtin1) 8) (put (quote compress) (quote s!:builtin1) 9) (put (quote constantp) (quote s!:builtin1) 10) (put (quote digit) (quote s!:builtin1) 11) (put (quote endp) (quote s!:builtin1) 12) (put (quote eval) (quote s!:builtin1) 13) (put (quote evenp) (quote s!:builtin1) 14) (put (quote evlis) (quote s!:builtin1) 15) (put (quote explode) (quote s!:builtin1) 16) (put (quote explode2lc) (quote s!:builtin1) 17) (put (quote explode2) (quote s!:builtin1) 18) (put (quote explodec) (quote s!:builtin1) 18) (put (quote fixp) (quote s!:builtin1) 19) (put (quote float) (quote s!:builtin1) 20) (put (quote floatp) (quote s!:builtin1) 21) (put (quote symbol!-specialp) (quote s!:builtin1) 22) (put (quote gc) (quote s!:builtin1) 23) (put (quote gensym1) (quote s!:builtin1) 24) (put (quote getenv) (quote s!:builtin1) 25) (put (quote symbol!-globalp) (quote s!:builtin1) 26) (put ( quote iadd1) (quote s!:builtin1) 27) (put (quote symbolp) (quote s!:builtin1) 28) (put (quote iminus) (quote s!:builtin1) 29) (put (quote iminusp) (quote s!:builtin1) 30) (put (quote indirect) (quote s!:builtin1) 31) (put (quote integerp) (quote s!:builtin1) 32) (put (quote intern) (quote s!:builtin1) 33) (put (quote isub1) (quote s!:builtin1) 34) (put (quote length) (quote s!:builtin1) 35) (put (quote lengthc) (quote s!:builtin1) 36) (put (quote linelength) (quote s!:builtin1) 37) (put (quote liter) (quote s!:builtin1) 38 ) (put (quote load!-module) (quote s!:builtin1) 39) (put (quote lognot) ( quote s!:builtin1) 40) (put (quote macroexpand) (quote s!:builtin1) 41) (put (quote macroexpand!-1) (quote s!:builtin1) 42) (put (quote macro!-function) ( quote s!:builtin1) 43) (put (quote make!-bps) (quote s!:builtin1) 44) (put ( quote make!-global) (quote s!:builtin1) 45) (put (quote make!-simple!-string) (quote s!:builtin1) 46) (put (quote make!-special) (quote s!:builtin1) 47) ( put (quote minus) (quote s!:builtin1) 48) (put (quote minusp) (quote s!:builtin1) 49) (put (quote mkvect) (quote s!:builtin1) 50) (put (quote modular!-minus) (quote s!:builtin1) 51) (put (quote modular!-number) (quote s!:builtin1) 52) (put (quote modular!-reciprocal) (quote s!:builtin1) 53) ( put (quote null) (quote s!:builtin1) 54) (put (quote oddp) (quote s!:builtin1 ) 55) (put (quote onep) (quote s!:builtin1) 56) (put (quote pagelength) ( quote s!:builtin1) 57) (put (quote pairp) (quote s!:builtin1) 58) (put (quote plist) (quote s!:builtin1) 59) (put (quote plusp) (quote s!:builtin1) 60) ( put (quote prin) (quote s!:builtin1) 61) (put (quote princ) (quote s!:builtin1) 62) (put (quote print) (quote s!:builtin1) 63) (put (quote printc) (quote s!:builtin1) 64) (put (quote rds) (quote s!:builtin1) 68) (put (quote remd) (quote s!:builtin1) 69) (put (quote reverse) (quote s!:builtin1 ) 70) (put (quote reversip) (quote s!:builtin1) 71) (put (quote seprp) (quote s!:builtin1) 72) (put (quote set!-small!-modulus) (quote s!:builtin1) 73) ( put (quote spaces) (quote s!:builtin1) 74) (put (quote xtab) (quote s!:builtin1) 74) (put (quote special!-char) (quote s!:builtin1) 75) (put ( quote special!-form!-p) (quote s!:builtin1) 76) (put (quote spool) (quote s!:builtin1) 77) (put (quote stop) (quote s!:builtin1) 78) (put (quote stringp) (quote s!:builtin1) 79) (put (quote sub1) (quote s!:builtin1) 80) ( put (quote symbol!-env) (quote s!:builtin1) 81) (put (quote symbol!-function) (quote s!:builtin1) 82) (put (quote symbol!-name) (quote s!:builtin1) 83) ( put (quote symbol!-value) (quote s!:builtin1) 84) (put (quote system) (quote s!:builtin1) 85) (put (quote fix) (quote s!:builtin1) 86) (put (quote ttab) ( quote s!:builtin1) 87) (put (quote tyo) (quote s!:builtin1) 88) (put (quote remob) (quote s!:builtin1) 89) (put (quote unmake!-global) (quote s!:builtin1 ) 90) (put (quote unmake!-special) (quote s!:builtin1) 91) (put (quote upbv) (quote s!:builtin1) 92) (put (quote vectorp) (quote s!:builtin1) 93) (put ( quote verbos) (quote s!:builtin1) 94) (put (quote wrs) (quote s!:builtin1) 95 ) (put (quote zerop) (quote s!:builtin1) 96) (put (quote car) (quote s!:builtin1) 97) (put (quote cdr) (quote s!:builtin1) 98) (put (quote caar) ( quote s!:builtin1) 99) (put (quote cadr) (quote s!:builtin1) 100) (put (quote cdar) (quote s!:builtin1) 101) (put (quote cddr) (quote s!:builtin1) 102) ( put (quote qcar) (quote s!:builtin1) 103) (put (quote qcdr) (quote s!:builtin1) 104) (put (quote qcaar) (quote s!:builtin1) 105) (put (quote qcadr) (quote s!:builtin1) 106) (put (quote qcdar) (quote s!:builtin1) 107) ( put (quote qcddr) (quote s!:builtin1) 108) (put (quote ncons) (quote s!:builtin1) 109) (put (quote numberp) (quote s!:builtin1) 110) (put (quote is!-spid) (quote s!:builtin1) 111) (put (quote spid!-to!-nil) (quote s!:builtin1) 112) (put (quote append) (quote s!:builtin2) 0) (put (quote ash) (quote s!:builtin2) 1) (put (quote assoc) (quote s!:builtin2) 2) (put (quote assoc!*!*) (quote s!:builtin2) 2) (put (quote atsoc) (quote s!:builtin2) 3) (put (quote deleq) (quote s!:builtin2) 4) (put (quote delete) (quote s!:builtin2) 5) (put (quote divide) (quote s!:builtin2) 6) (put (quote eqcar) (quote s!:builtin2) 7) (put (quote eql) (quote s!:builtin2) 8) (put (quote eqn) (quote s!:builtin2) 9) (put (quote expt) (quote s!:builtin2) 10) (put ( quote flag) (quote s!:builtin2) 11) (put (quote flagpcar) (quote s!:builtin2) 12) (put (quote gcdn) (quote s!:builtin2) 13) (put (quote geq) (quote s!:builtin2) 14) (put (quote getv) (quote s!:builtin2) 15) (put (quote greaterp) (quote s!:builtin2) 16) (put (quote idifference) (quote s!:builtin2 ) 17) (put (quote igreaterp) (quote s!:builtin2) 18) (put (quote ilessp) ( quote s!:builtin2) 19) (put (quote imax) (quote s!:builtin2) 20) (put (quote imin) (quote s!:builtin2) 21) (put (quote iplus2) (quote s!:builtin2) 22) ( put (quote iquotient) (quote s!:builtin2) 23) (put (quote iremainder) (quote s!:builtin2) 24) (put (quote irightshift) (quote s!:builtin2) 25) (put (quote itimes2) (quote s!:builtin2) 26) (put (quote leq) (quote s!:builtin2) 28) ( put (quote lessp) (quote s!:builtin2) 29) (put (quote max2) (quote s!:builtin2) 31) (put (quote member) (quote s!:builtin2) 32) (put (quote member!*!*) (quote s!:builtin2) 32) (put (quote memq) (quote s!:builtin2) 33) (put (quote min2) (quote s!:builtin2) 34) (put (quote mod) (quote s!:builtin2) 35) (put (quote modular!-difference) (quote s!:builtin2) 36) ( put (quote modular!-expt) (quote s!:builtin2) 37) (put (quote modular!-plus) (quote s!:builtin2) 38) (put (quote modular!-quotient) (quote s!:builtin2) 39 ) (put (quote modular!-times) (quote s!:builtin2) 40) (put (quote nconc) ( quote s!:builtin2) 41) (put (quote neq) (quote s!:builtin2) 42) (put (quote orderp) (quote s!:builtin2) 43) (put (quote quotient) (quote s!:builtin2) 44) (put (quote remainder) (quote s!:builtin2) 45) (put (quote remflag) (quote s!:builtin2) 46) (put (quote remprop) (quote s!:builtin2) 47) (put (quote rplaca) (quote s!:builtin2) 48) (put (quote rplacd) (quote s!:builtin2) 49) ( put (quote schar) (quote s!:builtin2) 50) (put (quote set) (quote s!:builtin2 ) 51) (put (quote smemq) (quote s!:builtin2) 52) (put (quote subla) (quote s!:builtin2) 53) (put (quote sublis) (quote s!:builtin2) 54) (put (quote symbol!-set!-definition) (quote s!:builtin2) 55) (put (quote symbol!-set!-env ) (quote s!:builtin2) 56) (put (quote times2) (quote s!:builtin2) 57) (put ( quote xcons) (quote s!:builtin2) 58) (put (quote equal) (quote s!:builtin2) 59) (put (quote eq) (quote s!:builtin2) 60) (put (quote cons) (quote s!:builtin2) 61) (put (quote list2) (quote s!:builtin2) 62) (put (quote get) (quote s!:builtin2) 63) (put (quote qgetv) (quote s!:builtin2) 64) (put ( quote flagp) (quote s!:builtin2) 65) (put (quote apply1) (quote s!:builtin2) 66) (put (quote difference) (quote s!:builtin2) 67) (put (quote plus2) (quote s!:builtin2) 68) (put (quote times2) (quote s!:builtin2) 69) (put (quote equalcar) (quote s!:builtin2) 70) (put (quote iequal) (quote s!:builtin2) 71) (put (quote nreverse) (quote s!:builtin2) 72) (put (quote bps!-putv) (quote s!:builtin3) 0) (put (quote errorset) (quote s!:builtin3) 1) (put (quote list2!*) (quote s!:builtin3) 2) (put (quote list3) (quote s!:builtin3) 3) ( put (quote putprop) (quote s!:builtin3) 4) (put (quote putv) (quote s!:builtin3) 5) (put (quote putv!-char) (quote s!:builtin3) 6) (put (quote subst) (quote s!:builtin3) 7) (put (quote apply2) (quote s!:builtin3) 8) (put (quote acons) (quote s!:builtin3) 9) nil) (de s!:prinhex1 (n) (princ (schar "0123456789abcdef" (logand n 15)))) (de s!:prinhex2 (n) (progn (s!:prinhex1 (truncate n 16)) (s!:prinhex1 n))) (de s!:prinhex4 (n) (progn (s!:prinhex2 (truncate n 256)) (s!:prinhex2 n))) (flag (quote (comp plap pgwd pwrds notailcall ord nocompile carcheckflag savedef r2i native_code save_native strip_native)) (quote switch)) (cond ((not (boundp (quote !*comp))) (progn (fluid (quote (!*comp))) (setq !*comp t)))) (cond ((not (boundp (quote !*nocompile))) (progn (fluid (quote (!*nocompile)) ) (setq !*nocompile nil)))) (cond ((not (boundp (quote !*plap))) (progn (fluid (quote (!*plap))) (setq !*plap nil)))) (cond ((not (boundp (quote !*pgwd))) (progn (fluid (quote (!*pgwd))) (setq !*pgwd nil)))) (cond ((not (boundp (quote !*pwrds))) (progn (fluid (quote (!*pwrds))) (setq !*pwrds t)))) (cond ((not (boundp (quote !*notailcall))) (progn (fluid (quote (!*notailcall ))) (setq !*notailcall nil)))) (cond ((not (boundp (quote !*ord))) (progn (fluid (quote (!*ord))) (setq !*ord t)))) (cond ((not (boundp (quote !*savedef))) (progn (fluid (quote (!*savedef))) ( setq !*savedef nil)))) (cond ((not (boundp (quote !*carcheckflag))) (progn (fluid (quote ( !*carcheckflag))) (setq !*carcheckflag t)))) (cond ((not (boundp (quote !*r2i))) (progn (fluid (quote (!*r2i))) (setq !*r2i t)))) (cond ((not (boundp (quote !*native_code))) (progn (fluid (quote ( !*native_code))) (setq !*native_code nil)))) (cond ((not (boundp (quote !*save_native))) (progn (fluid (quote ( !*save_native))) (setq !*save_native nil)))) (cond ((not (boundp (quote !*strip_native))) (progn (fluid (quote ( !*strip_native))) (setq !*strip_native t)))) (global (quote (s!:native_file))) (fluid (quote (s!:current_function s!:current_label s!:current_block s!:current_size s!:current_procedure s!:other_defs s!:lexical_env s!:has_closure s!:recent_literals s!:used_lexicals s!:a_reg_values s!:current_count s!:maybe_values))) (de s!:start_procedure (nargs nopts restarg) (progn (setq s!:current_procedure nil) (setq s!:current_label (gensym)) (setq s!:a_reg_values nil) (cond ((or (not (zerop nopts)) restarg) (progn (setq s!:current_block (list (list (quote OPTARGS) nopts) nopts (list (quote ARGCOUNT) nargs) nargs)) (setq s!:current_size 2))) (t (cond ((greaterp nargs 3) (progn (setq s!:current_block (list (list (quote ARGCOUNT) nargs) nargs)) (setq s!:current_size 1))) (t (progn (setq s!:current_block nil) (setq s!:current_size 0)))))))) (de s!:set_label (x) (progn (cond (s!:current_label (prog (w) (setq w (cons s!:current_size s!:current_block)) (prog (var1005) (setq var1005 s!:recent_literals) lab1004 (cond ((null var1005) (return nil))) (prog (x) ( setq x (car var1005)) (rplaca x w)) (setq var1005 (cdr var1005)) (go lab1004) ) (setq s!:recent_literals nil) (setq s!:current_procedure (cons (cons s!:current_label (cons (list (quote JUMP) x) w)) s!:current_procedure)) (setq s!:current_block nil) (setq s!:current_size 0)))) (setq s!:current_label x) (setq s!:a_reg_values nil))) (de s!:outjump (op lab) (prog (g w) (cond ((not (flagp op (quote s!:preserves_a))) (setq s!:a_reg_values nil))) (cond ((null s!:current_label) (return nil))) (cond ((equal op (quote JUMP)) (setq op (list op lab))) (t ( cond ((equal op (quote ICASE)) (setq op (cons op lab))) (t (setq op (list op lab (setq g (gensym)))))))) (setq w (cons s!:current_size s!:current_block)) (prog (var1007) (setq var1007 s!:recent_literals) lab1006 (cond ((null var1007) (return nil))) (prog (x) (setq x (car var1007)) (rplaca x w)) (setq var1007 (cdr var1007)) (go lab1006)) (setq s!:recent_literals nil) (setq s!:current_procedure (cons (cons s!:current_label (cons op w)) s!:current_procedure)) (setq s!:current_block nil) (setq s!:current_size 0) ( setq s!:current_label g) (return op))) (de s!:outexit nil (prog (w op) (setq op (quote (EXIT))) (cond ((null s!:current_label) (return nil))) (setq w (cons s!:current_size s!:current_block)) (prog (var1009) (setq var1009 s!:recent_literals) lab1008 (cond ((null var1009) (return nil))) (prog (x) (setq x (car var1009)) (rplaca x w)) (setq var1009 (cdr var1009)) (go lab1008)) (setq s!:recent_literals nil) (setq s!:current_procedure (cons (cons s!:current_label (cons op w)) s!:current_procedure)) (setq s!:current_block nil) (setq s!:current_size 0) ( setq s!:current_label nil))) (flag (quote (PUSH PUSHNIL PUSHNIL2 PUSHNIL3 LOSE LOSE2 LOSE3 LOSES STORELOC STORELOC0 STORELOC1 STORELOC2 STORELOC3 STORELOC4 STORELOC5 STORELOC6 STORELOC7 JUMP JUMPT JUMPNIL JUMPEQ JUMPEQUAL JUMPNE JUMPNEQUAL JUMPATOM JUMPNATOM)) (quote s!:preserves_a)) (de s!:outopcode0 (op doc) (prog nil (cond ((not (flagp op (quote s!:preserves_a))) (setq s!:a_reg_values nil))) (cond ((null s!:current_label) (return nil))) (setq s!:current_block (cons op s!:current_block)) (setq s!:current_size (plus s!:current_size 1)) (cond ((or !*plap !*pgwd) (setq s!:current_block (cons doc s!:current_block)))))) (de s!:outopcode1 (op arg doc) (prog nil (cond ((not (flagp op (quote s!:preserves_a))) (setq s!:a_reg_values nil))) (cond ((null s!:current_label) (return nil))) (setq s!:current_block (cons arg (cons op s!:current_block))) (setq s!:current_size (plus s!:current_size 2)) (cond ((or !*plap !*pgwd) ( setq s!:current_block (cons (list op doc) s!:current_block)))))) (deflist (quote ((LOADLIT 1) (LOADFREE 2) (CALL0 2) (CALL1 2) (LITGET 2) ( JUMPLITEQ 2) (JUMPLITNE 2) (JUMPLITEQ!* 2) (JUMPLITNE!* 2) (JUMPFREET 2) ( JUMPFREENIL 2))) (quote s!:short_form_bonus)) (de s!:record_literal (env) (prog (w extra) (setq w (gethash (car s!:current_block) (car env))) (cond ((null w) (setq w (cons 0 nil)))) (setq extra (get (cadr s!:current_block) (quote s!:short_form_bonus))) (cond ((null extra) (setq extra 10)) (t (setq extra (plus extra 10)))) (setq s!:recent_literals (cons (cons nil s!:current_block) s!:recent_literals)) ( puthash (car s!:current_block) (car env) (cons (plus (car w) extra) (cons ( car s!:recent_literals) (cdr w)))))) (de s!:record_literal_for_jump (x env lab) (prog (w extra) (cond ((null s!:current_label) (return nil))) (setq w (gethash (cadr x) (car env))) (cond ((null w) (setq w (cons 0 nil)))) (setq extra (get (car x) (quote s!:short_form_bonus))) (cond ((null extra) (setq extra 10)) (t (setq extra ( plus extra 10)))) (setq x (s!:outjump x lab)) (puthash (cadar x) (car env) ( cons (plus (car w) extra) (cons (cons nil x) (cdr w)))))) (de s!:outopcode1lit (op arg env) (prog nil (cond ((not (flagp op (quote s!:preserves_a))) (setq s!:a_reg_values nil))) (cond ((null s!:current_label) (return nil))) (setq s!:current_block (cons arg (cons op s!:current_block))) (s!:record_literal env) (setq s!:current_size (plus s!:current_size 2)) ( cond ((or !*plap !*pgwd) (setq s!:current_block (cons (list op arg) s!:current_block)))))) (de s!:outopcode2 (op arg1 arg2 doc) (prog nil (cond ((not (flagp op (quote s!:preserves_a))) (setq s!:a_reg_values nil))) (cond ((null s!:current_label) (return nil))) (setq s!:current_block (cons arg2 (cons arg1 (cons op s!:current_block)))) (setq s!:current_size (plus s!:current_size 3)) (cond (( or !*plap !*pgwd) (setq s!:current_block (cons (cons op doc) s!:current_block )))))) (de s!:outopcode2lit (op arg1 arg2 doc env) (prog nil (cond ((not (flagp op ( quote s!:preserves_a))) (setq s!:a_reg_values nil))) (cond ((null s!:current_label) (return nil))) (setq s!:current_block (cons arg1 (cons op s!:current_block))) (s!:record_literal env) (setq s!:current_block (cons arg2 s!:current_block)) (setq s!:current_size (plus s!:current_size 3)) (cond (( or !*plap !*pgwd) (setq s!:current_block (cons (cons op doc) s!:current_block )))))) (de s!:outlexref (op arg1 arg2 arg3 doc) (prog (arg4) (cond ((null s!:current_label) (return nil))) (cond ((or (greaterp arg1 255) (greaterp arg2 255) (greaterp arg3 255)) (progn (cond ((or (greaterp arg1 2047) ( greaterp arg2 31) (greaterp arg3 2047)) (error 0 "stack frame > 2047 or > 31 deep nesting"))) (setq doc (list op doc)) (setq arg4 (logand arg3 255)) (setq arg3 (plus (truncate arg3 256) (times 16 ( logand arg1 15)))) (cond ((equal op (quote LOADLEX)) (setq op (plus 192 arg2) )) (t (setq op (plus 224 arg2)))) (setq arg2 (truncate arg1 16)) (setq arg1 op) (setq op (quote BIGSTACK)))) (t (setq doc (list doc)))) (setq s!:current_block (cons arg3 (cons arg2 (cons arg1 (cons op s!:current_block)) ))) (setq s!:current_size (plus s!:current_size 4)) (cond (arg4 (progn (setq s!:current_block (cons arg4 s!:current_block)) (setq s!:current_size (plus s!:current_size 1))))) (cond ((or !*plap !*pgwd) (setq s!:current_block (cons (cons op doc) s!:current_block)))))) (put (quote LOADLIT) (quote s!:shortform) (cons (quote (1 . 7)) (s!:vecof ( quote (!- LOADLIT1 LOADLIT2 LOADLIT3 LOADLIT4 LOADLIT5 LOADLIT6 LOADLIT7))))) (put (quote LOADFREE) (quote s!:shortform) (cons (quote (1 . 4)) (s!:vecof ( quote (!- LOADFREE1 LOADFREE2 LOADFREE3 LOADFREE4))))) (put (quote STOREFREE) (quote s!:shortform) (cons (quote (1 . 3)) (s!:vecof ( quote (!- STOREFREE1 STOREFREE2 STOREFREE3))))) (put (quote CALL0) (quote s!:shortform) (cons (quote (0 . 3)) (s!:vecof ( quote (CALL0_0 CALL0_1 CALL0_2 CALL0_3))))) (put (quote CALL1) (quote s!:shortform) (cons (quote (0 . 5)) (s!:vecof ( quote (CALL1_0 CALL1_1 CALL1_2 CALL1_3 CALL1_4 CALL1_5))))) (put (quote CALL2) (quote s!:shortform) (cons (quote (0 . 4)) (s!:vecof ( quote (CALL2_0 CALL2_1 CALL2_2 CALL2_3 CALL2_4))))) (put (quote JUMPFREET) (quote s!:shortform) (cons (quote (1 . 4)) (s!:vecof ( quote (!- JUMPFREE1T JUMPFREE2T JUMPFREE3T JUMPFREE4T))))) (put (quote JUMPFREENIL) (quote s!:shortform) (cons (quote (1 . 4)) (s!:vecof (quote (!- JUMPFREE1NIL JUMPFREE2NIL JUMPFREE3NIL JUMPFREE4NIL))))) (put (quote JUMPLITEQ) (quote s!:shortform) (cons (quote (1 . 4)) (s!:vecof ( quote (!- JUMPLIT1EQ JUMPLIT2EQ JUMPLIT3EQ JUMPLIT4EQ))))) (put (quote JUMPLITNE) (quote s!:shortform) (cons (quote (1 . 4)) (s!:vecof ( quote (!- JUMPLIT1NE JUMPLIT2NE JUMPLIT3NE JUMPLIT4NE))))) (put (quote JUMPLITEQ!*) (quote s!:shortform) (get (quote JUMPLITEQ) (quote s!:shortform))) (put (quote JUMPLITNE!*) (quote s!:shortform) (get (quote JUMPLITNE) (quote s!:shortform))) (put (quote CALL0) (quote s!:longform) 0) (put (quote CALL1) (quote s!:longform) 16) (put (quote CALL2) (quote s!:longform) 32) (put (quote CALL3) (quote s!:longform) 48) (put (quote CALLN) (quote s!:longform) 64) (put (quote CALL2R) (quote s!:longform) 80) (put (quote LOADFREE) (quote s!:longform) 96) (put (quote STOREFREE) (quote s!:longform) 112) (put (quote JCALL0) (quote s!:longform) 128) (put (quote JCALL1) (quote s!:longform) 144) (put (quote JCALL2) (quote s!:longform) 160) (put (quote JCALL3) (quote s!:longform) 176) (put (quote JCALLN) (quote s!:longform) 192) (put (quote FREEBIND) (quote s!:longform) 208) (put (quote LITGET) (quote s!:longform) 224) (put (quote LOADLIT) (quote s!:longform) 240) (de s!:literal_order (a b) (cond ((equal (cadr a) (cadr b)) (orderp (car a) ( car b))) (t (greaterp (cadr a) (cadr b))))) (de s!:resolve_literals (env checksum) (prog (w op opspec n litbytes) (setq w (hashcontents (car env))) (setq w (sort w (function s!:literal_order))) ( setq w (append w (list (list checksum 0)))) (setq n (length w)) (setq litbytes (times 4 n)) (cond ((greaterp n 4096) (setq w (s!:too_many_literals w n)))) (setq n 0) (prog (var1011) (setq var1011 w) lab1010 (cond ((null var1011) (return nil))) (prog (x) (setq x (car var1011)) (progn (rplaca (cdr x) n) (setq n (plus n 1)))) (setq var1011 (cdr var1011)) (go lab1010)) (prog (var1015) (setq var1015 w) lab1014 (cond ((null var1015) (return nil))) (prog (x) (setq x (car var1015)) (progn (setq n (cadr x)) (prog (var1013) (setq var1013 (cddr x)) lab1012 (cond ((null var1013) (return nil))) (prog (y) ( setq y (car var1013)) (progn (cond ((null (car y)) (progn (setq op (caadr y)) (setq opspec (get op (quote s!:shortform))) (cond ((and opspec (leq (caar opspec) n) (leq n (cdar opspec))) (rplaca (cdr y) (getv (cdr opspec) n))) (t (rplaca (cdadr y) n))))) (t (progn (setq op (caddr y)) (cond ((greaterp n 255 ) (progn (rplaca (car y) (plus (caar y) 1)) (setq op (plus (get op (quote s!:longform)) (truncate n 256))) (rplaca (cdr y) (ilogand n 255)) (rplaca ( cddr y) (quote BIGCALL)) (rplacd (cdr y) (cons op (cddr y))))) (t (cond ((and (setq opspec (get op (quote s!:shortform))) (leq (caar opspec) n) (leq n ( cdar opspec))) (progn (rplaca (car y) (difference (caar y) 1)) (rplaca (cdr y ) (getv (cdr opspec) n)) (rplacd (cdr y) (cdddr y)))) (t (rplaca (cdr y) n))) ))))))) (setq var1013 (cdr var1013)) (go lab1012)))) (setq var1015 (cdr var1015)) (go lab1014)) (prog (var1017) (setq var1017 w) lab1016 (cond ((null var1017) (return nil))) (prog (x) (setq x (car var1017)) (rplacd x (cadr x)) ) (setq var1017 (cdr var1017)) (go lab1016)) (rplaca env (cons (reversip w) litbytes)))) (de s!:only_loadlit (l) (cond ((null l) t) (t (cond ((null (caar l)) nil) (t (cond ((not (eqcar (cddar l) (quote LOADLIT))) nil) (t (s!:only_loadlit (cdr l))))))))) (de s!:too_many_literals (w n) (prog (k xvecs l r newrefs uses z1) (setq k 0) (setq n (plus n 1)) (prog nil lab1018 (cond ((null (and (greaterp n 4096) ( not (null w)))) (return nil))) (progn (cond ((and (not (equal (cadar w) 10000000)) (s!:only_loadlit (cddar w))) (progn (setq l (cons (car w) l)) ( setq n (difference n 1)) (setq k (plus k 1)) (cond ((equal k 256) (progn ( setq xvecs (cons l xvecs)) (setq l nil) (setq k 0) (setq n (plus n 1))))))) ( t (setq r (cons (car w) r)))) (setq w (cdr w))) (go lab1018)) (cond (( greaterp n 4096) (error 0 "function uses too many literals (4096 is limit)")) ) (setq xvecs (cons l xvecs)) (prog nil lab1019 (cond ((null r) (return nil)) ) (progn (setq w (cons (car r) w)) (setq r (cdr r))) (go lab1019)) (prog ( var1025) (setq var1025 xvecs) lab1024 (cond ((null var1025) (return nil))) ( prog (v) (setq v (car var1025)) (progn (setq newrefs nil) (setq uses 0) (setq r nil) (setq k 0) (prog (var1023) (setq var1023 v) lab1022 (cond ((null var1023) (return nil))) (prog (q) (setq q (car var1023)) (progn (prog ( var1021) (setq var1021 (cddr q)) lab1020 (cond ((null var1021) (return nil))) (prog (z) (setq z (car var1021)) (progn (cond ((car z) (rplaca (car z) (plus (caar z) 2)))) (setq z1 (cons (quote QGETVN) (cons nil (cddr z)))) (rplaca ( cdr z) k) (rplacd (cdr z) z1) (rplacd z (cdr z1)) (setq newrefs (cons z newrefs)) (setq uses (plus uses 11)))) (setq var1021 (cdr var1021)) (go lab1020)) (setq r (cons (car q) r)) (setq k (plus k 1)))) (setq var1023 (cdr var1023)) (go lab1022)) (setq newrefs (cons uses newrefs)) (setq newrefs ( cons (s!:vecof (reversip r)) newrefs)) (setq w (cons newrefs w)))) (setq var1025 (cdr var1025)) (go lab1024)) (return (sort w (function s!:literal_order))))) (fluid (quote (s!:into_c))) (de s!:endprocedure (name env checksum) (prog (pc labelvals w vec) ( s!:outexit) (cond (s!:into_c (return (cons s!:current_procedure env)))) ( s!:resolve_literals env checksum) (setq s!:current_procedure ( s!:tidy_flowgraph s!:current_procedure)) (cond ((and (not !*notailcall) (not s!:has_closure)) (setq s!:current_procedure (s!:try_tailcall s!:current_procedure)))) (setq s!:current_procedure (s!:tidy_exits s!:current_procedure)) (setq labelvals (s!:resolve_labels)) (setq pc (car labelvals)) (setq labelvals (cdr labelvals)) (setq vec (make!-bps pc)) (setq pc 0) (cond ((or !*plap !*pgwd) (progn (terpri) (ttab 23) (princ "+++ ") ( prin name) (princ " +++") (terpri)))) (prog (var1027) (setq var1027 s!:current_procedure) lab1026 (cond ((null var1027) (return nil))) (prog (b) (setq b (car var1027)) (progn (cond ((and (car b) (flagp (car b) (quote used_label)) (or !*plap !*pgwd)) (progn (ttab 20) (prin (car b)) (princ ":") (terpri)))) (setq pc (s!:plant_basic_block vec pc (reverse (cdddr b)))) (setq b (cadr b)) (cond ((and b (neq (car b) (quote ICASE)) (cdr b) (cddr b)) ( setq b (list (car b) (cadr b))))) (setq pc (s!:plant_exit_code vec pc b labelvals)))) (setq var1027 (cdr var1027)) (go lab1026)) (cond (!*pwrds ( progn (cond ((neq (posn) 0) (terpri))) (princ "+++ ") (prin name) (princ " compiled, ") (princ pc) (princ " + ") (princ (cdar env)) (princ " bytes") ( terpri)))) (setq env (caar env)) (cond ((null env) (setq w nil)) (t (progn ( setq w (mkvect (cdar env))) (prog nil lab1028 (cond ((null env) (return nil)) ) (progn (putv w (cdar env) (caar env)) (setq env (cdr env))) (go lab1028)))) ) (return (cons vec w)))) (de s!:add_pending (lab pend blocks) (prog (w) (cond ((not (atom lab)) ( return (cons (list (gensym) lab 0) pend)))) (setq w (atsoc lab pend)) (cond ( w (return (cons w (deleq w pend)))) (t (return (cons (atsoc lab blocks) pend) ))))) (de s!:invent_exit (x blocks) (prog (w) (setq w blocks) scan (cond ((null w) (go not_found)) (t (cond ((and (eqcar (cadar w) x) (equal (caddar w) 0)) ( return (cons (caar w) blocks))) (t (setq w (cdr w)))))) (go scan) not_found ( setq w (gensym)) (return (cons w (cons (list w (list x) 0) blocks))))) (de s!:destination_label (lab blocks) (prog (n w x) (setq w (atsoc lab blocks )) (cond ((s!:is_lose_and_exit w blocks) (return (quote (EXIT))))) (setq x ( cadr w)) (setq n (caddr w)) (setq w (cdddr w)) (cond ((neq n 0) (return lab)) ) (cond ((or (null x) (null (cdr x))) (return x)) (t (cond ((equal (cadr x) lab) (return lab)) (t (cond ((null (cddr x)) (return (s!:destination_label ( cadr x) blocks))) (t (return lab))))))))) (de s!:remlose (b) (prog (w) (setq w b) (prog nil lab1029 (cond ((null (and w (not (atom (car w))))) (return nil))) (setq w (cdr w)) (go lab1029)) (cond ( (null w) (return (cons 0 b)))) (cond ((and (numberp (car w)) (eqcar (cdr w) ( quote LOSES))) (setq w (cons 2 (cddr w)))) (t (cond ((or (equal (car w) ( quote LOSE)) (equal (car w) (quote LOSE2)) (equal (car w) (quote LOSE3))) ( setq w (cons 1 (cdr w)))) (t (return (cons 0 b)))))) (setq b (s!:remlose (cdr w))) (return (cons (plus (car w) (car b)) (cdr b))))) (put (quote CALL0_0) (quote s!:shortcall) (quote (0 . 0))) (put (quote CALL0_1) (quote s!:shortcall) (quote (0 . 1))) (put (quote CALL0_2) (quote s!:shortcall) (quote (0 . 2))) (put (quote CALL0_3) (quote s!:shortcall) (quote (0 . 3))) (put (quote CALL1_0) (quote s!:shortcall) (quote (1 . 0))) (put (quote CALL1_1) (quote s!:shortcall) (quote (1 . 1))) (put (quote CALL1_2) (quote s!:shortcall) (quote (1 . 2))) (put (quote CALL1_3) (quote s!:shortcall) (quote (1 . 3))) (put (quote CALL1_4) (quote s!:shortcall) (quote (1 . 4))) (put (quote CALL1_5) (quote s!:shortcall) (quote (1 . 5))) (put (quote CALL2_0) (quote s!:shortcall) (quote (2 . 0))) (put (quote CALL2_1) (quote s!:shortcall) (quote (2 . 1))) (put (quote CALL2_2) (quote s!:shortcall) (quote (2 . 2))) (put (quote CALL2_3) (quote s!:shortcall) (quote (2 . 3))) (put (quote CALL2_4) (quote s!:shortcall) (quote (2 . 4))) (de s!:remcall (b) (prog (w p q r s) (prog nil lab1030 (cond ((null (and b ( not (atom (car b))))) (return nil))) (progn (setq p (car b)) (setq b (cdr b)) ) (go lab1030)) (cond ((null b) (return nil)) (t (cond ((numberp (car b)) ( progn (setq r (car b)) (setq s 2) (setq b (cdr b)) (cond ((null b) (return nil)) (t (cond ((numberp (car b)) (progn (setq q r) (setq r (car b)) (setq s 3) (setq b (cdr b)) (cond ((and b (numberp (setq w (car b))) (eqcar (cdr b) ( quote BIGCALL)) (equal (truncate w 16) 4)) (progn (setq r (plus (times 256 ( logand w 15)) r)) (setq s 4) (setq b (cdr b)))) (t (cond ((eqcar b (quote BIGCALL)) (progn (setq w (truncate r 16)) (setq r (plus (times 256 (logand r 15)) q)) (setq q w) (cond ((equal q 5) (progn (setq q 2) (setq s (difference s 1)) (setq b (cons (quote BIGCALL) (cons (quote SWOP) (cdr b))))))) (cond (( greaterp q 4) (return nil))))) (t (cond ((not (eqcar b (quote CALLN))) ( return nil))))))))) (t (cond ((equal (car b) (quote CALL0)) (setq q 0)) (t ( cond ((equal (car b) (quote CALL1)) (setq q 1)) (t (cond ((equal (car b) ( quote CALL2)) (setq q 2)) (t (cond ((equal (car b) (quote CALL2R)) (progn ( setq q 2) (setq s (difference s 1)) (setq b (cons (quote CALL2) (cons (quote SWOP) (cdr b)))))) (t (cond ((equal (car b) (quote CALL3)) (setq q 3)) (t ( return nil))))))))))))))) (setq b (cdr b)))) (t (cond ((setq q (get (car b) ( quote s!:shortcall))) (progn (setq r (cdr q)) (setq q (car q)) (setq s 1) ( setq b (cdr b)))) (t (return nil))))))) (return (cons p (cons q (cons r (cons s b))))))) (de s!:is_lose_and_exit (b blocks) (prog (lab exit) (setq lab (car b)) (setq exit (cadr b)) (setq b (cdddr b)) (cond ((null exit) (return nil))) (setq b ( s!:remlose b)) (setq b (cdr b)) (prog nil lab1031 (cond ((null (and b (not ( atom (car b))))) (return nil))) (setq b (cdr b)) (go lab1031)) (cond (b ( return nil)) (t (cond ((equal (car exit) (quote EXIT)) (return t)) (t (cond ( (equal (car exit) (quote JUMP)) (progn (cond ((equal (cadr exit) lab) nil) (t (return (s!:is_lose_and_exit (atsoc (cadr exit) blocks) blocks)))))) (t ( return nil))))))))) (de s!:try_tail_1 (b blocks) (prog (exit size body w w0 w1 w2 op) (setq exit (cadr b)) (cond ((null exit) (return b)) (t (cond ((not (equal (car exit) ( quote EXIT))) (progn (cond ((equal (car exit) (quote JUMP)) (progn (cond (( not (s!:is_lose_and_exit (atsoc (cadr exit) blocks) blocks)) (return b))))) ( t (return b)))))))) (setq size (caddr b)) (setq body (cdddr b)) (setq body ( s!:remlose body)) (setq size (difference size (car body))) (setq body (cdr body)) (setq w (s!:remcall body)) (cond ((null w) (return b))) (setq w0 (cadr w)) (setq w1 (caddr w)) (setq body (cddddr w)) (cond ((and (leq w0 7) (leq w1 31)) (progn (setq body (cons (quote JCALL) body)) (setq body (cons (plus ( times 32 w0) w1) body)) (setq size (difference size 1)))) (t (cond ((lessp w1 256) (setq body (cons w0 (cons w1 (cons (quote JCALLN) body))))) (t (progn ( setq body (cons (quote BIGCALL) body)) (setq w2 (logand w1 255)) (setq w1 ( truncate w1 256)) (cond ((lessp w0 4) (setq body (cons w2 (cons (plus w1 ( times 16 w0) 128) body)))) (t (progn (setq body (cons w0 (cons w2 (cons (plus w1 (plus (times 16 4) 128)) body)))) (setq size (plus size 1)))))))))) (cond ((car w) (setq body (cons (append (car w) (list (quote TAIL))) body)))) ( rplaca (cdr b) nil) (rplaca (cddr b) (plus (difference size (cadddr w)) 3)) ( rplacd (cddr b) body) (return b))) (de s!:try_tailcall (b) (prog (var1033 var1034) (setq var1033 b) lab1032 ( cond ((null var1033) (return (reversip var1034)))) (prog (v) (setq v (car var1033)) (setq var1034 (cons (s!:try_tail_1 v b) var1034))) (setq var1033 ( cdr var1033)) (go lab1032))) (de s!:tidy_exits_1 (b blocks) (prog (exit size body comm w w0 w1 w2 op) ( setq exit (cadr b)) (cond ((null exit) (return b)) (t (cond ((not (equal (car exit) (quote EXIT))) (progn (cond ((equal (car exit) (quote JUMP)) (progn ( cond ((not (s!:is_lose_and_exit (atsoc (cadr exit) blocks) blocks)) (return b ))))) (t (return b)))))))) (setq size (caddr b)) (setq body (cdddr b)) (setq body (s!:remlose body)) (setq size (difference size (car body))) (setq body ( cdr body)) (prog nil lab1035 (cond ((null (and body (not (atom (car body))))) (return nil))) (progn (setq comm (car body)) (setq body (cdr body))) (go lab1035)) (cond ((eqcar body (quote VNIL)) (setq w (quote NILEXIT))) (t (cond ((eqcar body (quote LOADLOC0)) (setq w (quote LOC0EXIT))) (t (cond ((eqcar body (quote LOADLOC1)) (setq w (quote LOC1EXIT))) (t (cond ((eqcar body ( quote LOADLOC2)) (setq w (quote LOC2EXIT))) (t (setq w nil))))))))) (cond (w (progn (rplaca (cdr b) (list w)) (setq body (cdr body)) (setq size ( difference size 1)))) (t (cond (comm (setq body (cons comm body)))))) (rplaca (cddr b) size) (rplacd (cddr b) body) (return b))) (de s!:tidy_exits (b) (prog (var1037 var1038) (setq var1037 b) lab1036 (cond ((null var1037) (return (reversip var1038)))) (prog (v) (setq v (car var1037) ) (setq var1038 (cons (s!:tidy_exits_1 v b) var1038))) (setq var1037 (cdr var1037)) (go lab1036))) (de s!:tidy_flowgraph (b) (prog (r pending) (setq b (reverse b)) (setq pending (list (car b))) (prog nil lab1040 (cond ((null pending) (return nil)) ) (prog (c x l1 l2 done1 done2) (setq c (car pending)) (setq pending (cdr pending)) (flag (list (car c)) (quote coded)) (setq x (cadr c)) (cond ((or ( null x) (null (cdr x))) (setq r (cons c r))) (t (cond ((equal (car x) (quote ICASE)) (progn (rplacd x (reversip (cdr x))) (prog (ll) (setq ll (cdr x)) lab1039 (cond ((null ll) (return nil))) (progn (setq l1 (s!:destination_label (car ll) b)) (cond ((not (atom l1)) (progn (setq l1 (s!:invent_exit (car l1) b)) (setq b (cdr l1)) (setq l1 (cadr l1))))) (rplaca ll l1) (setq done1 ( flagp l1 (quote coded))) (flag (list l1) (quote used_label)) (cond ((not done1) (setq pending (s!:add_pending l1 pending b))))) (setq ll (cdr ll)) (go lab1039)) (rplacd x (reversip (cdr x))) (setq r (cons c r)))) (t (cond (( null (cddr x)) (progn (setq l1 (s!:destination_label (cadr x) b)) (cond ((not (atom l1)) (setq c (cons (car c) (cons l1 (cddr c))))) (t (cond ((flagp l1 ( quote coded)) (progn (flag (list l1) (quote used_label)) (setq c (cons (car c ) (cons (list (car x) l1) (cddr c)))))) (t (progn (setq c (cons (car c) (cons nil (cddr c)))) (setq pending (s!:add_pending l1 pending b))))))) (setq r ( cons c r)))) (t (progn (setq l1 (s!:destination_label (cadr x) b)) (setq l2 ( s!:destination_label (caddr x) b)) (setq done1 (and (atom l1) (flagp l1 ( quote coded)))) (setq done2 (and (atom l2) (flagp l2 (quote coded)))) (cond ( done1 (progn (cond (done2 (progn (flag (list l1) (quote used_label)) (rplaca (cdadr c) l1) (setq pending (cons (list (gensym) (list (quote JUMP) l2) 0) pending)))) (t (progn (flag (list l1) (quote used_label)) (rplaca (cdadr c) l1) (setq pending (s!:add_pending l2 pending b))))))) (t (progn (cond (done2 (progn (flag (list l2) (quote used_label)) (rplaca (cadr c) (s!:negate_jump ( car x))) (rplaca (cdadr c) l2) (setq pending (s!:add_pending l1 pending b)))) (t (progn (cond ((not (atom l1)) (progn (setq l1 (s!:invent_exit (car l1) b) ) (setq b (cdr l1)) (setq l1 (car l1))))) (flag (list l1) (quote used_label)) (rplaca (cdadr c) l1) (cond ((not (flagp l1 (quote coded))) (setq pending ( s!:add_pending l1 pending b)))) (setq pending (s!:add_pending l2 pending b))) ))))) (setq r (cons c r)))))))))) (go lab1040)) (return (reverse r)))) (deflist (quote ((JUMPNIL JUMPT) (JUMPT JUMPNIL) (JUMPATOM JUMPNATOM) ( JUMPNATOM JUMPATOM) (JUMPEQ JUMPNE) (JUMPNE JUMPEQ) (JUMPEQUAL JUMPNEQUAL) ( JUMPNEQUAL JUMPEQUAL) (JUMPL0NIL JUMPL0T) (JUMPL0T JUMPL0NIL) (JUMPL1NIL JUMPL1T) (JUMPL1T JUMPL1NIL) (JUMPL2NIL JUMPL2T) (JUMPL2T JUMPL2NIL) ( JUMPL3NIL JUMPL3T) (JUMPL3T JUMPL3NIL) (JUMPL4NIL JUMPL4T) (JUMPL4T JUMPL4NIL ) (JUMPL0ATOM JUMPL0NATOM) (JUMPL0NATOM JUMPL0ATOM) (JUMPL1ATOM JUMPL1NATOM) (JUMPL1NATOM JUMPL1ATOM) (JUMPL2ATOM JUMPL2NATOM) (JUMPL2NATOM JUMPL2ATOM) ( JUMPL3ATOM JUMPL3NATOM) (JUMPL3NATOM JUMPL3ATOM) (JUMPST0NIL JUMPST0T) ( JUMPST0T JUMPST0NIL) (JUMPST1NIL JUMPST1T) (JUMPST1T JUMPST1NIL) (JUMPST2NIL JUMPST2T) (JUMPST2T JUMPST2NIL) (JUMPFREE1NIL JUMPFREE1T) (JUMPFREE1T JUMPFREE1NIL) (JUMPFREE2NIL JUMPFREE2T) (JUMPFREE2T JUMPFREE2NIL) ( JUMPFREE3NIL JUMPFREE3T) (JUMPFREE3T JUMPFREE3NIL) (JUMPFREE4NIL JUMPFREE4T) (JUMPFREE4T JUMPFREE4NIL) (JUMPFREENIL JUMPFREET) (JUMPFREET JUMPFREENIL) ( JUMPLIT1EQ JUMPLIT1NE) (JUMPLIT1NE JUMPLIT1EQ) (JUMPLIT2EQ JUMPLIT2NE) ( JUMPLIT2NE JUMPLIT2EQ) (JUMPLIT3EQ JUMPLIT3NE) (JUMPLIT3NE JUMPLIT3EQ) ( JUMPLIT4EQ JUMPLIT4NE) (JUMPLIT4NE JUMPLIT4EQ) (JUMPLITEQ JUMPLITNE) ( JUMPLITNE JUMPLITEQ) (JUMPLITEQ!* JUMPLITNE!*) (JUMPLITNE!* JUMPLITEQ!*) ( JUMPB1NIL JUMPB1T) (JUMPB1T JUMPB1NIL) (JUMPB2NIL JUMPB2T) (JUMPB2T JUMPB2NIL ) (JUMPFLAGP JUMPNFLAGP) (JUMPNFLAGP JUMPFLAGP) (JUMPEQCAR JUMPNEQCAR) ( JUMPNEQCAR JUMPEQCAR))) (quote negjump)) (de s!:negate_jump (x) (cond ((atom x) (get x (quote negjump))) (t (rplaca x (get (car x) (quote negjump)))))) (de s!:resolve_labels nil (prog (w labelvals converged pc x) (prog nil lab1043 (progn (setq converged t) (setq pc 0) (prog (var1042) (setq var1042 s!:current_procedure) lab1041 (cond ((null var1042) (return nil))) (prog (b) (setq b (car var1042)) (progn (setq w (assoc!*!* (car b) labelvals)) (cond (( null w) (progn (setq converged nil) (setq w (cons (car b) pc)) (setq labelvals (cons w labelvals)))) (t (cond ((neq (cdr w) pc) (progn (rplacd w pc) (setq converged nil)))))) (setq pc (plus pc (caddr b))) (setq x (cadr b)) (cond ((null x) nil) (t (cond ((null (cdr x)) (setq pc (plus pc 1))) (t ( cond ((equal (car x) (quote ICASE)) (setq pc (plus pc (times 2 (length x))))) (t (progn (setq w (assoc!*!* (cadr x) labelvals)) (cond ((null w) (progn ( setq w 128) (setq converged nil))) (t (setq w (difference (cdr w) pc)))) ( setq w (s!:expand_jump (car x) w)) (setq pc (plus pc (length w)))))))))))) ( setq var1042 (cdr var1042)) (go lab1041))) (cond ((null converged) (go lab1043)))) (return (cons pc labelvals)))) (de s!:plant_basic_block (vec pc b) (prog (tagged) (prog (var1047) (setq var1047 b) lab1046 (cond ((null var1047) (return nil))) (prog (i) (setq i ( car var1047)) (progn (cond ((atom i) (progn (cond ((symbolp i) (setq i (get i (quote s!:opcode))))) (cond ((and (not tagged) (or !*plap !*pgwd)) (progn ( s!:prinhex4 pc) (princ ":") (ttab 8) (setq tagged t)))) (cond ((or (not (fixp i)) (lessp i 0) (greaterp i 255)) (error "bad byte to put" i))) (bps!-putv vec pc i) (cond ((or !*plap !*pgwd) (progn (s!:prinhex2 i) (princ " ")))) ( setq pc (plus pc 1)))) (t (cond ((or !*plap !*pgwd) (progn (ttab 23) (princ ( car i)) (prog (var1045) (setq var1045 (cdr i)) lab1044 (cond ((null var1045) (return nil))) (prog (w) (setq w (car var1045)) (progn (princ " ") (prin w))) (setq var1045 (cdr var1045)) (go lab1044)) (terpri) (setq tagged nil)))))))) (setq var1047 (cdr var1047)) (go lab1046)) (return pc))) (de s!:plant_bytes (vec pc bytelist doc) (prog nil (cond ((or !*plap !*pgwd) (progn (s!:prinhex4 pc) (princ ":") (ttab 8)))) (prog (var1049) (setq var1049 bytelist) lab1048 (cond ((null var1049) (return nil))) (prog (v) (setq v ( car var1049)) (progn (cond ((symbolp v) (setq v (get v (quote s!:opcode))))) (cond ((or (not (fixp v)) (lessp v 0) (greaterp v 255)) (error "bad byte to put" v))) (bps!-putv vec pc v) (cond ((or !*plap !*pgwd) (progn (cond ((greaterp (posn) 50) (progn (terpri) (ttab 8)))) (s!:prinhex2 v) ( princ " ")))) (setq pc (plus pc 1)))) (setq var1049 (cdr var1049)) (go lab1048)) (cond ((or !*plap !*pgwd) (progn (cond ((greaterp (posn) 23) ( terpri))) (ttab 23) (princ (car doc)) (prog (var1051) (setq var1051 (cdr doc) ) lab1050 (cond ((null var1051) (return nil))) (prog (w) (setq w (car var1051 )) (progn (cond ((greaterp (posn) 65) (progn (terpri) (ttab 23)))) (princ " " ) (prin w))) (setq var1051 (cdr var1051)) (go lab1050)) (terpri)))) (return pc))) (de s!:plant_exit_code (vec pc b labelvals) (prog (w loc low high r) (cond (( null b) (return pc)) (t (cond ((null (cdr b)) (return (s!:plant_bytes vec pc (list (get (car b) (quote s!:opcode))) b))) (t (cond ((equal (car b) (quote ICASE)) (progn (setq loc (plus pc 3)) (prog (var1053) (setq var1053 (cdr b)) lab1052 (cond ((null var1053) (return nil))) (prog (ll) (setq ll (car var1053 )) (progn (setq w (difference (cdr (assoc!*!* ll labelvals)) loc)) (setq loc (plus loc 2)) (cond ((lessp w 0) (progn (setq w (minus w)) (setq low (ilogand w 255)) (setq high (plus 128 (truncate (difference w low) 256))))) (t (progn (setq low (ilogand w 255)) (setq high (truncate (difference w low) 256))))) (setq r (cons low (cons high r))))) (setq var1053 (cdr var1053)) (go lab1052) ) (setq r (cons (get (quote ICASE) (quote s!:opcode)) (cons (length (cddr b)) (reversip r)))) (return (s!:plant_bytes vec pc r b))))))))) (setq w ( difference (cdr (assoc!*!* (cadr b) labelvals)) pc)) (setq w (s!:expand_jump (car b) w)) (return (s!:plant_bytes vec pc w b)))) (deflist (quote ((JUMPL0NIL ((LOADLOC0) JUMPNIL)) (JUMPL0T ((LOADLOC0) JUMPT) ) (JUMPL1NIL ((LOADLOC1) JUMPNIL)) (JUMPL1T ((LOADLOC1) JUMPT)) (JUMPL2NIL (( LOADLOC2) JUMPNIL)) (JUMPL2T ((LOADLOC2) JUMPT)) (JUMPL3NIL ((LOADLOC3) JUMPNIL)) (JUMPL3T ((LOADLOC3) JUMPT)) (JUMPL4NIL ((LOADLOC4) JUMPNIL)) ( JUMPL4T ((LOADLOC4) JUMPT)) (JUMPL0ATOM ((LOADLOC0) JUMPATOM)) (JUMPL0NATOM ( (LOADLOC0) JUMPNATOM)) (JUMPL1ATOM ((LOADLOC1) JUMPATOM)) (JUMPL1NATOM (( LOADLOC1) JUMPNATOM)) (JUMPL2ATOM ((LOADLOC2) JUMPATOM)) (JUMPL2NATOM (( LOADLOC2) JUMPNATOM)) (JUMPL3ATOM ((LOADLOC3) JUMPATOM)) (JUMPL3NATOM (( LOADLOC3) JUMPNATOM)) (JUMPST0NIL ((STORELOC0) JUMPNIL)) (JUMPST0T (( STORELOC0) JUMPT)) (JUMPST1NIL ((STORELOC1) JUMPNIL)) (JUMPST1T ((STORELOC1) JUMPT)) (JUMPST2NIL ((STORELOC2) JUMPNIL)) (JUMPST2T ((STORELOC2) JUMPT)) ( JUMPFREE1NIL ((LOADFREE1) JUMPNIL)) (JUMPFREE1T ((LOADFREE1) JUMPT)) ( JUMPFREE2NIL ((LOADFREE2) JUMPNIL)) (JUMPFREE2T ((LOADFREE2) JUMPT)) ( JUMPFREE3NIL ((LOADFREE3) JUMPNIL)) (JUMPFREE3T ((LOADFREE3) JUMPT)) ( JUMPFREE4NIL ((LOADFREE4) JUMPNIL)) (JUMPFREE4T ((LOADFREE4) JUMPT)) ( JUMPFREENIL ((LOADFREE !*) JUMPNIL)) (JUMPFREET ((LOADFREE !*) JUMPT)) ( JUMPLIT1EQ ((LOADLIT1) JUMPEQ)) (JUMPLIT1NE ((LOADLIT1) JUMPNE)) (JUMPLIT2EQ ((LOADLIT2) JUMPEQ)) (JUMPLIT2NE ((LOADLIT2) JUMPNE)) (JUMPLIT3EQ ((LOADLIT3) JUMPEQ)) (JUMPLIT3NE ((LOADLIT3) JUMPNE)) (JUMPLIT4EQ ((LOADLIT4) JUMPEQ)) ( JUMPLIT4NE ((LOADLIT4) JUMPNE)) (JUMPLITEQ ((LOADLIT !*) JUMPEQ)) (JUMPLITNE ((LOADLIT !*) JUMPNE)) (JUMPLITEQ!* ((LOADLIT !* SWOP) JUMPEQ)) (JUMPLITNE!* ((LOADLIT !* SWOP) JUMPNE)) (JUMPB1NIL ((BUILTIN1 !*) JUMPNIL)) (JUMPB1T (( BUILTIN1 !*) JUMPT)) (JUMPB2NIL ((BUILTIN2 !*) JUMPNIL)) (JUMPB2T ((BUILTIN2 !*) JUMPT)) (JUMPFLAGP ((LOADLIT !* FLAGP) JUMPT)) (JUMPNFLAGP ((LOADLIT !* FLAGP) JUMPNIL)) (JUMPEQCAR ((LOADLIT !* EQCAR) JUMPT)) (JUMPNEQCAR ((LOADLIT !* EQCAR) JUMPNIL)))) (quote s!:expand_jump)) (fluid (quote (s!:backwards_jump s!:longer_jump))) (progn (setq s!:backwards_jump (make!-simple!-string 256)) (setq s!:longer_jump (make!-simple!-string 256)) nil) (prog (var1055) (setq var1055 (quote ((JUMP JUMP_B JUMP_L JUMP_BL) (JUMPNIL JUMPNIL_B JUMPNIL_L JUMPNIL_BL) (JUMPT JUMPT_B JUMPT_L JUMPT_BL) (JUMPATOM JUMPATOM_B JUMPATOM_L JUMPATOM_BL) (JUMPNATOM JUMPNATOM_B JUMPNATOM_L JUMPNATOM_BL) (JUMPEQ JUMPEQ_B JUMPEQ_L JUMPEQ_BL) (JUMPNE JUMPNE_B JUMPNE_L JUMPNE_BL) (JUMPEQUAL JUMPEQUAL_B JUMPEQUAL_L JUMPEQUAL_BL) (JUMPNEQUAL JUMPNEQUAL_B JUMPNEQUAL_L JUMPNEQUAL_BL) (CATCH CATCH_B CATCH_L CATCH_BL)))) lab1054 (cond ((null var1055) (return nil))) (prog (op) (setq op (car var1055 )) (progn (putv!-char s!:backwards_jump (get (car op) (quote s!:opcode)) (get (cadr op) (quote s!:opcode))) (putv!-char s!:backwards_jump (get (caddr op) (quote s!:opcode)) (get (cadddr op) (quote s!:opcode))) (putv!-char s!:longer_jump (get (car op) (quote s!:opcode)) (get (caddr op) (quote s!:opcode))) (putv!-char s!:longer_jump (get (cadr op) (quote s!:opcode)) ( get (cadddr op) (quote s!:opcode))))) (setq var1055 (cdr var1055)) (go lab1054)) (de s!:expand_jump (op offset) (prog (arg low high opcode expanded) (cond (( not (atom op)) (progn (setq arg (cadr op)) (setq op (car op)) (setq offset ( difference offset 1))))) (setq expanded (get op (quote s!:expand_jump))) ( cond ((and expanded (not (and (leq 2 offset) (lessp offset (plus 256 2)) (or (null arg) (lessp arg 256))))) (progn (setq op (cadr expanded)) (setq expanded (car expanded)) (cond (arg (progn (cond ((greaterp arg 2047) (error 0 "function uses too many literals (2048 limit)")) (t (cond ((greaterp arg 255) (prog (high low) (setq low (ilogand arg 255)) (setq high (truncate ( difference arg low) 256)) (setq expanded (cons (quote BIGCALL) (cons (plus ( get (car expanded) (quote s!:longform)) high) (cons low (cddr expanded))))))) (t (setq expanded (subst arg (quote !*) expanded)))))) (setq offset (plus offset 1))))) (setq offset (difference offset (length expanded))) (setq arg nil))) (t (setq expanded nil))) (setq opcode (get op (quote s!:opcode))) ( cond ((null opcode) (error 0 (list op offset "invalid block exit")))) (cond ( (and (lessp (plus (minus 256) 2) offset) (lessp offset (plus 256 2))) (setq offset (difference offset 2))) (t (progn (setq high t) (setq offset ( difference offset 3))))) (cond ((lessp offset 0) (progn (setq opcode ( byte!-getv s!:backwards_jump opcode)) (setq offset (minus offset))))) (cond ( high (progn (setq low (logand offset 255)) (setq high (truncate (difference offset low) 256)))) (t (cond ((greaterp (setq low offset) 255) (error 0 "Bad offset in expand_jump"))))) (cond (arg (return (list opcode arg low))) ( t (cond ((not high) (return (append expanded (list opcode low)))) (t (return (append expanded (list (byte!-getv s!:longer_jump opcode) high low))))))))) (de s!:comval (x env context) (prog (helper) (setq x (s!:improve x)) (cond (( atom x) (return (s!:comatom x env context))) (t (cond ((eqcar (car x) (quote lambda)) (return (s!:comlambda (cadar x) (cddar x) (cdr x) env context))) (t (cond ((eq (car x) s!:current_function) (s!:comcall x env context)) (t (cond ((and (setq helper (get (car x) (quote s!:compilermacro))) (setq helper ( funcall helper x env context))) (return (s!:comval helper env context))) (t ( cond ((setq helper (get (car x) (quote s!:newname))) (return (s!:comval (cons helper (cdr x)) env context))) (t (cond ((setq helper (get (car x) (quote s!:compfn))) (return (funcall helper x env context))) (t (cond ((setq helper (macro!-function (car x))) (return (s!:comval (funcall helper x) env context) )) (t (return (s!:comcall x env context)))))))))))))))))) (de s!:comspecform (x env context) (error 0 (list "special form" x))) (cond ((null (get (quote and) (quote s!:compfn))) (progn (put (quote compiler!-let) (quote s!:compfn) (function s!:comspecform)) (put (quote de) ( quote s!:compfn) (function s!:comspecform)) (put (quote defun) (quote s!:compfn) (function s!:comspecform)) (put (quote eval!-when) (quote s!:compfn) (function s!:comspecform)) (put (quote flet) (quote s!:compfn) ( function s!:comspecform)) (put (quote labels) (quote s!:compfn) (function s!:comspecform)) (put (quote macrolet) (quote s!:compfn) (function s!:comspecform)) (put (quote multiple!-value!-call) (quote s!:compfn) ( function s!:comspecform)) (put (quote multiple!-value!-prog1) (quote s!:compfn) (function s!:comspecform)) (put (quote prog!*) (quote s!:compfn) ( function s!:comspecform)) (put (quote progv) (quote s!:compfn) (function s!:comspecform)) nil))) (de s!:improve (u) (prog (w) (cond ((atom u) (return u)) (t (cond ((setq w ( get (car u) (quote s!:tidy_fn))) (return (funcall w u))) (t (cond ((setq w ( get (car u) (quote s!:newname))) (return (s!:improve (cons w (cdr u))))) (t ( return u))))))))) (de s!:imp_minus (u) (prog (a) (setq a (s!:improve (cadr u))) (return (cond ( (numberp a) (minus a)) (t (cond ((or (eqcar a (quote minus)) (eqcar a (quote iminus))) (cadr a)) (t (cond ((eqcar a (quote difference)) (s!:improve (list (quote difference) (caddr a) (cadr a)))) (t (cond ((eqcar a (quote idifference)) (s!:improve (list (quote idifference) (caddr a) (cadr a)))) (t (list (car u) a)))))))))))) (put (quote minus) (quote s!:tidy_fn) (quote s!:imp_minus)) (put (quote iminus) (quote s!:tidy_fn) (quote s!:imp_minus)) (de s!:imp_times (u) (prog (a b) (cond ((not (equal (length u) 3)) (return ( cons (car u) (prog (var1057 var1058) (setq var1057 (cdr u)) lab1056 (cond (( null var1057) (return (reversip var1058)))) (prog (v) (setq v (car var1057)) (setq var1058 (cons (s!:improve v) var1058))) (setq var1057 (cdr var1057)) ( go lab1056)))))) (setq a (s!:improve (cadr u))) (setq b (s!:improve (caddr u) )) (return (cond ((equal a 1) b) (t (cond ((equal b 1) a) (t (cond ((equal a (minus 1)) (s!:imp_minus (list (quote minus) b))) (t (cond ((equal b (minus 1 )) (s!:imp_minus (list (quote minus) a))) (t (list (car u) a b)))))))))))) (put (quote times) (quote s!:tidy_fn) (quote s!:imp_times)) (de s!:imp_itimes (u) (prog (a b) (cond ((not (equal (length u) 3)) (return ( cons (car u) (prog (var1060 var1061) (setq var1060 (cdr u)) lab1059 (cond (( null var1060) (return (reversip var1061)))) (prog (v) (setq v (car var1060)) (setq var1061 (cons (s!:improve v) var1061))) (setq var1060 (cdr var1060)) ( go lab1059)))))) (setq a (s!:improve (cadr u))) (setq b (s!:improve (caddr u) )) (return (cond ((equal a 1) b) (t (cond ((equal b 1) a) (t (cond ((equal a (minus 1)) (s!:imp_minus (list (quote iminus) b))) (t (cond ((equal b (minus 1)) (s!:imp_minus (list (quote iminus) a))) (t (list (car u) a b)))))))))))) (put (quote itimes) (quote s!:tidy_fn) (quote s!:imp_itimes)) (de s!:imp_difference (u) (prog (a b) (setq a (s!:improve (cadr u))) (setq b (s!:improve (caddr u))) (return (cond ((equal a 0) (s!:imp_minus (list (quote minus) b))) (t (cond ((equal b 0) a) (t (list (car u) a b)))))))) (put (quote difference) (quote s!:tidy_fn) (quote s!:imp_difference)) (de s!:imp_idifference (u) (prog (a b) (setq a (s!:improve (cadr u))) (setq b (s!:improve (caddr u))) (return (cond ((equal a 0) (s!:imp_minus (list ( quote iminus) b))) (t (cond ((equal b 0) a) (t (list (car u) a b)))))))) (put (quote idifference) (quote s!:tidy_fn) (quote s!:imp_idifference)) (de s!:boolean_jumpable (u) (or (null u) (equal u t) (and (not (atom u)) ( atom (car u)) (or (flagp (car u) (quote s!:bool_opcode)) (and (or (equal (car u) (quote and)) (equal (car u) (quote or))) (s!:boolean_jumpable_list (cdr u ))))))) (de s!:boolean_jumpable_list (u) (or (atom u) (and (s!:boolean_jumpable (car u)) (s!:boolean_jumpable_list (cdr u))))) (flag (quote (null not eq equal neq eqcar atom flagp)) (quote s!:bool_opcode) ) (de s!:imp_or (u) (prog (w x) (setq w (cdr u)) (cond ((atom w) (return nil))) (setq x (car w)) (cond ((atom (cdr w)) (return (s!:improve x))) (t (cond (( s!:boolean_jumpable x) (return (list (quote cond) (list x t) (list t ( s!:imp_or (cons (quote or) (cdr w))))))) (t (return (list (quote or) ( s!:improve x) (s!:imp_or (cons (quote or) (cdr w))))))))))) (put (quote or) (quote s!:tidy_fn) (quote s!:imp_or)) (de s!:imp_and (u) (prog (w x) (setq w (cdr u)) (cond ((atom w) (return t))) (setq x (car w)) (cond ((atom (cdr w)) (return x)) (t (cond (( s!:boolean_jumpable x) (return (list (quote cond) (list x (s!:imp_and (cons ( quote and) (cdr w)))) (list t nil)))) (t (return (list (quote and) ( s!:improve x) (s!:imp_and (cons (quote and) (cdr w))))))))))) (put (quote and) (quote s!:tidy_fn) (quote s!:imp_and)) (de s!:alwayseasy (x) t) (put (quote quote) (quote s!:helpeasy) (function s!:alwayseasy)) (put (quote function) (quote s!:helpeasy) (function s!:alwayseasy)) (de s!:easyifarg (x) (or (null (cdr x)) (and (null (cddr x)) (s!:iseasy (cadr x))))) (put (quote ncons) (quote s!:helpeasy) (function s!:easyifarg)) (put (quote car) (quote s!:helpeasy) (function s!:easyifarg)) (put (quote cdr) (quote s!:helpeasy) (function s!:easyifarg)) (put (quote caar) (quote s!:helpeasy) (function s!:easyifarg)) (put (quote cadr) (quote s!:helpeasy) (function s!:easyifarg)) (put (quote cdar) (quote s!:helpeasy) (function s!:easyifarg)) (put (quote cddr) (quote s!:helpeasy) (function s!:easyifarg)) (put (quote caaar) (quote s!:helpeasy) (function s!:easyifarg)) (put (quote caadr) (quote s!:helpeasy) (function s!:easyifarg)) (put (quote cadar) (quote s!:helpeasy) (function s!:easyifarg)) (put (quote caddr) (quote s!:helpeasy) (function s!:easyifarg)) (put (quote cdaar) (quote s!:helpeasy) (function s!:easyifarg)) (put (quote cdadr) (quote s!:helpeasy) (function s!:easyifarg)) (put (quote cddar) (quote s!:helpeasy) (function s!:easyifarg)) (put (quote cdddr) (quote s!:helpeasy) (function s!:easyifarg)) (put (quote caaaar) (quote s!:helpeasy) (function s!:easyifarg)) (put (quote caaadr) (quote s!:helpeasy) (function s!:easyifarg)) (put (quote caadar) (quote s!:helpeasy) (function s!:easyifarg)) (put (quote caaddr) (quote s!:helpeasy) (function s!:easyifarg)) (put (quote cadaar) (quote s!:helpeasy) (function s!:easyifarg)) (put (quote cadadr) (quote s!:helpeasy) (function s!:easyifarg)) (put (quote caddar) (quote s!:helpeasy) (function s!:easyifarg)) (put (quote cadddr) (quote s!:helpeasy) (function s!:easyifarg)) (put (quote cdaaar) (quote s!:helpeasy) (function s!:easyifarg)) (put (quote cdaadr) (quote s!:helpeasy) (function s!:easyifarg)) (put (quote cdadar) (quote s!:helpeasy) (function s!:easyifarg)) (put (quote cdaddr) (quote s!:helpeasy) (function s!:easyifarg)) (put (quote cddaar) (quote s!:helpeasy) (function s!:easyifarg)) (put (quote cddadr) (quote s!:helpeasy) (function s!:easyifarg)) (put (quote cdddar) (quote s!:helpeasy) (function s!:easyifarg)) (put (quote cddddr) (quote s!:helpeasy) (function s!:easyifarg)) (de s!:easygetv (x) (prog (a2) (setq a2 (caddr x)) (cond ((and (null !*carcheckflag) (fixp a2) (geq a2 0) (lessp a2 256)) (return (s!:iseasy (cadr x)))) (t (return nil))))) (put (quote getv) (quote s!:helpeasy) (function s!:easygetv)) (de s!:easyqgetv (x) (prog (a2) (setq a2 (caddr x)) (cond ((and (fixp a2) ( geq a2 0) (lessp a2 256)) (return (s!:iseasy (cadr x)))) (t (return nil))))) (put (quote qgetv) (quote s!:helpeasy) (function s!:easyqgetv)) (de s!:iseasy (x) (prog (h) (cond ((atom x) (return t))) (cond ((not (atom ( car x))) (return nil))) (cond ((setq h (get (car x) (quote s!:helpeasy))) ( return (funcall h x))) (t (return nil))))) (de s!:instate_local_decs (v d w) (prog (fg) (cond ((fluidp v) (return w))) ( prog (var1063) (setq var1063 d) lab1062 (cond ((null var1063) (return nil))) (prog (z) (setq z (car var1063)) (cond ((and (eqcar z (quote special)) (memq v (cdr z))) (setq fg t)))) (setq var1063 (cdr var1063)) (go lab1062)) (cond ( fg (progn (make!-special v) (setq w (cons v w))))) (return w))) (de s!:residual_local_decs (d w) (prog nil (prog (var1067) (setq var1067 d) lab1066 (cond ((null var1067) (return nil))) (prog (z) (setq z (car var1067)) (cond ((eqcar z (quote special)) (prog (var1065) (setq var1065 (cdr z)) lab1064 (cond ((null var1065) (return nil))) (prog (v) (setq v (car var1065)) (cond ((and (not (fluidp v)) (not (globalp v))) (progn (make!-special v) ( setq w (cons v w)))))) (setq var1065 (cdr var1065)) (go lab1064))))) (setq var1067 (cdr var1067)) (go lab1066)) (return w))) (de s!:cancel_local_decs (w) (unfluid w)) (de s!:find_local_decs (body isprog) (prog (w local_decs) (cond ((and (not isprog) body (null (cdr body)) (eqcar (car body) (quote progn))) (setq body ( cdar body)))) (prog nil lab1068 (cond ((null (and body (or (eqcar (car body) (quote declare)) (stringp (car body))))) (return nil))) (progn (cond (( stringp (car body)) (setq w (cons (car body) w))) (t (setq local_decs (append local_decs (cdar body))))) (setq body (cdr body))) (go lab1068)) (prog nil lab1069 (cond ((null w) (return nil))) (progn (setq body (cons (car w) body)) (setq w (cdr w))) (go lab1069)) (return (cons local_decs body)))) (de s!:comlambda (bvl body args env context) (prog (s nbvl fluids fl1 w local_decs) (cond ((and (equal context 0) s!:maybe_values) (s!:outopcode0 ( quote ONEVALUE) (quote (onevalue))))) (setq nbvl (setq s (cdr env))) (setq body (s!:find_local_decs body nil)) (setq local_decs (car body)) (setq body ( cdr body)) (cond ((atom body) (setq body nil)) (t (cond ((atom (cdr body)) ( setq body (car body))) (t (setq body (cons (quote progn) body)))))) (setq w nil) (prog (var1071) (setq var1071 bvl) lab1070 (cond ((null var1071) (return nil))) (prog (v) (setq v (car var1071)) (setq w (s!:instate_local_decs v local_decs w))) (setq var1071 (cdr var1071)) (go lab1070)) (prog (var1073) ( setq var1073 bvl) lab1072 (cond ((null var1073) (return nil))) (prog (v) ( setq v (car var1073)) (progn (cond ((or (fluidp v) (globalp v)) (prog (g) ( setq g (gensym)) (setq nbvl (cons g nbvl)) (setq fl1 (cons v fl1)) (setq fluids (cons (cons v g) fluids)))) (t (setq nbvl (cons v nbvl)))) (cond (( equal (car args) nil) (s!:outstack 1)) (t (progn (s!:comval (car args) env 1) (s!:outopcode0 (quote PUSH) (quote (PUSH)))))) (rplacd env (cons 0 (cdr env) )) (setq args (cdr args)))) (setq var1073 (cdr var1073)) (go lab1072)) ( rplacd env nbvl) (cond (fluids (progn (setq fl1 (s!:vecof fl1)) ( s!:outopcode1lit (quote FREEBIND) fl1 env) (prog (var1075) (setq var1075 ( cons nil fluids)) lab1074 (cond ((null var1075) (return nil))) (prog (v) ( setq v (car var1075)) (rplacd env (cons 0 (cdr env)))) (setq var1075 (cdr var1075)) (go lab1074)) (rplacd env (cons (plus 2 (length fluids)) (cdr env)) ) (prog (var1077) (setq var1077 fluids) lab1076 (cond ((null var1077) (return nil))) (prog (v) (setq v (car var1077)) (s!:comval (list (quote setq) (car v ) (cdr v)) env 2)) (setq var1077 (cdr var1077)) (go lab1076))))) (setq w ( s!:residual_local_decs local_decs w)) (s!:comval body env 1) ( s!:cancel_local_decs w) (cond (fluids (s!:outopcode0 (quote FREERSTR) (quote (FREERSTR))))) (s!:outlose (length bvl)) (rplacd env s))) (de s!:loadliteral (x env) (cond ((member!*!* (list (quote quote) x) s!:a_reg_values) nil) (t (progn (cond ((equal x nil) (s!:outopcode0 (quote VNIL) (quote (loadlit nil)))) (t (s!:outopcode1lit (quote LOADLIT) x env))) ( setq s!:a_reg_values (list (list (quote quote) x))))))) (de s!:comquote (x env context) (progn (cond ((and (equal context 0) s!:maybe_values) (s!:outopcode0 (quote ONEVALUE) (quote (onevalue))))) (cond ((leq context 1) (s!:loadliteral (cadr x) env))))) (put (quote quote) (quote s!:compfn) (function s!:comquote)) (fluid (quote (s!:current_exitlab s!:current_proglabels s!:local_macros))) (de s!:comfunction (x env context) (progn (cond ((and (equal context 0) s!:maybe_values) (s!:outopcode0 (quote ONEVALUE) (quote (onevalue))))) (cond ((leq context 1) (progn (setq x (cadr x)) (cond ((eqcar x (quote lambda)) ( prog (g w s!:used_lexicals) (setq s!:has_closure t) (setq g (hashtagged!-name (quote lambda) (cdr x))) (setq w (s!:compile1 g (cadr x) (cddr x) (cons ( list (cdr env) s!:current_exitlab s!:current_proglabels s!:local_macros) s!:lexical_env))) (cond (s!:used_lexicals (setq w (s!:compile1 g (cons ( gensym) (cadr x)) (cddr x) (cons (list (cdr env) s!:current_exitlab s!:current_proglabels s!:local_macros) s!:lexical_env))))) (setq s!:other_defs (append w s!:other_defs)) (s!:loadliteral g env) (setq w ( length (cdr env))) (cond (s!:used_lexicals (progn (setq s!:has_closure t) ( cond ((greaterp w 4095) (error 0 "stack frame > 4095")) (t (cond ((greaterp w 255) (s!:outopcode2 (quote BIGSTACK) (plus 128 (truncate w 256)) (logand w 255) (list (quote CLOSURE) w))) (t (s!:outopcode1 (quote CLOSURE) w x)))))))) )) (t (s!:loadliteral x env)))))))) (put (quote function) (quote s!:compfn) (function s!:comfunction)) (de s!:should_be_fluid (x) (cond ((not (or (fluidp x) (globalp x))) (progn ( cond (!*pwrds (progn (cond ((neq (posn) 0) (terpri))) (princ "+++ ") (prin x) (princ " declared fluid") (terpri)))) (fluid (list x)) nil)))) (de s!:find_lexical (x lex n) (prog (p) (cond ((null lex) (return nil))) ( setq p (memq x (caar lex))) (cond (p (progn (cond ((not (memq x s!:used_lexicals)) (setq s!:used_lexicals (cons x s!:used_lexicals)))) ( return (list n (length p))))) (t (return (s!:find_lexical x (cdr lex) (plus n 1))))))) (global (quote (s!:loadlocs))) (setq s!:loadlocs (s!:vecof (quote (LOADLOC0 LOADLOC1 LOADLOC2 LOADLOC3 LOADLOC4 LOADLOC5 LOADLOC6 LOADLOC7 LOADLOC8 LOADLOC9 LOADLOC10 LOADLOC11)))) (de s!:comatom (x env context) (prog (n w) (cond ((and (equal context 0) s!:maybe_values) (s!:outopcode0 (quote ONEVALUE) (quote (onevalue))))) (cond ((greaterp context 1) (return nil)) (t (cond ((or (null x) (not (symbolp x))) (return (s!:loadliteral x env)))))) (setq n 0) (setq w (cdr env)) (prog nil lab1078 (cond ((null (and w (not (eqcar w x)))) (return nil))) (progn (setq n (add1 n)) (setq w (cdr w))) (go lab1078)) (cond (w (progn (setq w (cons ( quote loc) w)) (cond ((member!*!* w s!:a_reg_values) (return nil)) (t (progn (cond ((lessp n 12) (s!:outopcode0 (getv s!:loadlocs n) (list (quote LOADLOC) x))) (t (cond ((greaterp n 4095) (error 0 "stack frame > 4095")) (t (cond (( greaterp n 255) (s!:outopcode2 (quote BIGSTACK) (truncate n 256) (logand n 255) (list (quote LOADLOC) x))) (t (s!:outopcode1 (quote LOADLOC) n x))))))) (setq s!:a_reg_values (list w)) (return nil))))))) (cond ((setq w ( s!:find_lexical x s!:lexical_env 0)) (progn (cond ((member!*!* (cons (quote lex) w) s!:a_reg_values) (return nil))) (s!:outlexref (quote LOADLEX) (length (cdr env)) (car w) (cadr w) x) (setq s!:a_reg_values (list (cons (quote lex) w))) (return nil)))) (s!:should_be_fluid x) (cond ((flagp x (quote constant!?)) (return (s!:loadliteral (eval x) env)))) (setq w (cons (quote free) x)) (cond ((member!*!* w s!:a_reg_values) (return nil))) ( s!:outopcode1lit (quote LOADFREE) x env) (setq s!:a_reg_values (list w)))) (flag (quote (t !$EOL!$ !$EOF!$)) (quote constant!?)) (de s!:islocal (x env) (prog (n w) (cond ((or (null x) (not (symbolp x)) (eq x t)) (return 99999))) (setq n 0) (setq w (cdr env)) (prog nil lab1079 (cond ((null (and w (not (eqcar w x)))) (return nil))) (progn (setq n (add1 n)) ( setq w (cdr w))) (go lab1079)) (cond (w (return n)) (t (return 99999))))) (de s!:load2 (a b env) (progn (cond ((s!:iseasy b) (prog (wa wb w) (setq wa ( s!:islocal a env)) (setq wb (s!:islocal b env)) (cond ((and (lessp wa 4) ( lessp wb 4)) (progn (cond ((and (equal wa 0) (equal wb 1)) (setq w (quote LOC0LOC1))) (t (cond ((and (equal wa 1) (equal wb 2)) (setq w (quote LOC1LOC2 ))) (t (cond ((and (equal wa 2) (equal wb 3)) (setq w (quote LOC2LOC3))) (t ( cond ((and (equal wa 1) (equal wb 0)) (setq w (quote LOC1LOC0))) (t (cond (( and (equal wa 2) (equal wb 1)) (setq w (quote LOC2LOC1))) (t (cond ((and ( equal wa 3) (equal wb 2)) (setq w (quote LOC3LOC2)))))))))))))) (cond (w ( progn (s!:outopcode0 w (list (quote LOCLOC) a b)) (return nil))))))) ( s!:comval a env 1) (setq s!:a_reg_values nil) (s!:comval b env 1) (return nil ))) (t (cond (!*ord (progn (s!:comval a env 1) (s!:outopcode0 (quote PUSH) ( quote (PUSH))) (rplacd env (cons 0 (cdr env))) (setq s!:a_reg_values nil) ( s!:comval b env 1) (s!:outopcode0 (quote POP) (quote (POP))) (rplacd env ( cddr env)) t)) (t (cond ((s!:iseasy a) (progn (s!:comval b env 1) (setq s!:a_reg_values nil) (s!:comval a env 1) t)) (t (progn (s!:comval b env 1) ( s!:outopcode0 (quote PUSH) (quote (PUSH))) (rplacd env (cons 0 (cdr env))) ( setq s!:a_reg_values nil) (s!:comval a env 1) (s!:outopcode0 (quote POP) ( quote (POP))) (rplacd env (cddr env)) nil))))))))) (global (quote (s!:carlocs s!:cdrlocs s!:caarlocs))) (setq s!:carlocs (s!:vecof (quote (CARLOC0 CARLOC1 CARLOC2 CARLOC3 CARLOC4 CARLOC5 CARLOC6 CARLOC7 CARLOC8 CARLOC9 CARLOC10 CARLOC11)))) (setq s!:cdrlocs (s!:vecof (quote (CDRLOC0 CDRLOC1 CDRLOC2 CDRLOC3 CDRLOC4 CDRLOC5)))) (setq s!:caarlocs (s!:vecof (quote (CAARLOC0 CAARLOC1 CAARLOC2 CAARLOC3)))) (flag (quote (plus2 times2 eq equal)) (quote s!:symmetric)) (flag (quote (car cdr caar cadr cdar cddr ncons add1 sub1 numberp length)) ( quote s!:onearg)) (flag (quote (cons xcons list2 get flagp plus2 difference times2 greaterp lessp apply1 eq equal getv qgetv eqcar)) (quote s!:twoarg)) (flag (quote (apply2 list2!* list3 acons)) (quote s!:threearg)) (de s!:comcall (x env context) (prog (fn args nargs op s w1 w2 w3 sw) (setq fn (car x)) (cond ((not (symbolp fn)) (error 0 "non-symbol used in function position"))) (setq args (prog (var1081 var1082) (setq var1081 (cdr x)) lab1080 (cond ((null var1081) (return (reversip var1082)))) (prog (v) (setq v (car var1081)) (setq var1082 (cons (s!:improve v) var1082))) (setq var1081 (cdr var1081)) (go lab1080))) (setq nargs (length args)) (cond ((and (greaterp nargs 15) !*pwrds) (progn (cond ((neq (posn) 0) (terpri))) (princ "+++ ") (prin fn) (princ " called with ") (prin nargs) ( princ " from function ") (prin s!:current_function) (terpri)))) (setq s (cdr env)) (cond ((and (equal context 0) s!:maybe_values) (s!:outopcode0 (quote ONEVALUE) (quote (onevalue))))) (cond ((equal nargs 0) (cond ((setq w2 (get fn (quote s!:builtin0))) (s!:outopcode1 (quote BUILTIN0) w2 fn)) (t (progn ( s!:outopcode1lit (quote CALL0) fn env) (cond ((neq fn s!:current_function) ( setq s!:maybe_values t))))))) (t (cond ((equal nargs 1) (progn (cond ((and ( equal fn (quote car)) (lessp (setq w2 (s!:islocal (car args) env)) 12)) ( s!:outopcode0 (getv s!:carlocs w2) (list (quote carloc) (car args)))) (t ( cond ((and (equal fn (quote cdr)) (lessp (setq w2 (s!:islocal (car args) env) ) 6)) (s!:outopcode0 (getv s!:cdrlocs w2) (list (quote cdrloc) (car args)))) (t (cond ((and (equal fn (quote caar)) (lessp (setq w2 (s!:islocal (car args) env)) 4)) (s!:outopcode0 (getv s!:caarlocs w2) (list (quote caarloc) (car args)))) (t (progn (s!:comval (car args) env 1) (cond ((flagp fn (quote s!:onearg)) (s!:outopcode0 fn (list fn))) (t (cond ((setq w2 (get fn (quote s!:builtin1))) (s!:outopcode1 (quote BUILTIN1) w2 fn)) (t (progn (cond ((and (equal context 0) s!:maybe_values) (s!:outopcode0 (quote ONEVALUE) (quote ( onevalue))))) (s!:outopcode1lit (quote CALL1) fn env) (cond ((neq fn s!:current_function) (setq s!:maybe_values t))))))))))))))))) (t (cond (( equal nargs 2) (progn (setq sw (s!:load2 (car args) (cadr args) env)) (cond ( (flagp fn (quote s!:symmetric)) (setq sw nil))) (cond ((flagp fn (quote s!:twoarg)) (progn (cond (sw (s!:outopcode0 (quote SWOP) (quote (SWOP))))) ( s!:outopcode0 fn (list fn)))) (t (progn (setq w3 (get fn (quote s!:builtin2)) ) (cond (sw (progn (cond (w3 (s!:outopcode1 (quote BUILTIN2R) w3 fn)) (t ( s!:outopcode1lit (quote CALL2R) fn env))))) (t (cond (w3 (s!:outopcode1 ( quote BUILTIN2) w3 fn)) (t (progn (cond ((and (equal context 0) s!:maybe_values) (s!:outopcode0 (quote ONEVALUE) (quote (onevalue))))) ( s!:outopcode1lit (quote CALL2) fn env) (cond ((neq fn s!:current_function) ( setq s!:maybe_values t))))))))))))) (t (cond ((equal nargs 3) (progn (cond (( equal (car args) nil) (s!:outstack 1)) (t (progn (s!:comval (car args) env 1) (s!:outopcode0 (quote PUSH) (quote (PUSHA3)))))) (rplacd env (cons 0 (cdr env))) (setq s!:a_reg_values nil) (cond ((s!:load2 (cadr args) (caddr args) env) (s!:outopcode0 (quote SWOP) (quote (SWOP))))) (cond ((flagp fn (quote s!:threearg)) (s!:outopcode0 (cond ((equal fn (quote list2!*)) (quote list2star)) (t fn)) (list fn))) (t (cond ((setq w2 (get fn (quote s!:builtin3 ))) (s!:outopcode1 (quote BUILTIN3) w2 fn)) (t (progn (cond ((and (equal context 0) s!:maybe_values) (s!:outopcode0 (quote ONEVALUE) (quote (onevalue) )))) (s!:outopcode1lit (quote CALL3) fn env) (cond ((neq fn s!:current_function) (setq s!:maybe_values t)))))))) (rplacd env (cddr env))) ) (t (prog (largs) (setq largs (reverse args)) (prog (var1084) (setq var1084 (reverse (cddr largs))) lab1083 (cond ((null var1084) (return nil))) (prog (a ) (setq a (car var1084)) (progn (cond ((null a) (s!:outstack 1)) (t (progn ( s!:comval a env 1) (cond ((equal nargs 4) (s!:outopcode0 (quote PUSH) (quote (PUSHA4)))) (t (s!:outopcode0 (quote PUSH) (quote (PUSHARG)))))))) (rplacd env (cons 0 (cdr env))) (setq s!:a_reg_values nil))) (setq var1084 (cdr var1084)) (go lab1083)) (cond ((s!:load2 (cadr largs) (car largs) env) ( s!:outopcode0 (quote SWOP) (quote (SWOP))))) (cond ((and (equal fn (quote apply3)) (equal nargs 4)) (s!:outopcode0 (quote APPLY3) (quote (APPLY3)))) (t (cond ((greaterp nargs 255) (error 0 "Over 255 args in a function call")) (t (progn (cond ((and (equal context 0) s!:maybe_values) (s!:outopcode0 (quote ONEVALUE) (quote (onevalue))))) (s!:outopcode2lit (quote CALLN) fn nargs ( list nargs fn) env) (cond ((neq fn s!:current_function) (setq s!:maybe_values t)))))))) (rplacd env s)))))))))))) (de s!:ad_name (l) (cond ((equal (car l) (quote a)) (cond ((equal (cadr l) ( quote a)) (quote caar)) (t (quote cadr)))) (t (cond ((equal (cadr l) (quote a )) (quote cdar)) (t (quote cddr)))))) (de s!:comcarcdr3 (x env context) (prog (name outer c1 c2) (setq name (cdr ( explode2 (car x)))) (setq x (list (s!:ad_name name) (list (cond ((equal ( caddr name) (quote a)) (quote car)) (t (quote cdr))) (cadr x)))) (return ( s!:comval x env context)))) (put (quote caaar) (quote s!:compfn) (function s!:comcarcdr3)) (put (quote caadr) (quote s!:compfn) (function s!:comcarcdr3)) (put (quote cadar) (quote s!:compfn) (function s!:comcarcdr3)) (put (quote caddr) (quote s!:compfn) (function s!:comcarcdr3)) (put (quote cdaar) (quote s!:compfn) (function s!:comcarcdr3)) (put (quote cdadr) (quote s!:compfn) (function s!:comcarcdr3)) (put (quote cddar) (quote s!:compfn) (function s!:comcarcdr3)) (put (quote cdddr) (quote s!:compfn) (function s!:comcarcdr3)) (de s!:comcarcdr4 (x env context) (prog (name outer c1 c2) (setq name (cdr ( explode2 (car x)))) (setq x (list (s!:ad_name name) (list (s!:ad_name (cddr name)) (cadr x)))) (return (s!:comval x env context)))) (put (quote caaaar) (quote s!:compfn) (function s!:comcarcdr4)) (put (quote caaadr) (quote s!:compfn) (function s!:comcarcdr4)) (put (quote caadar) (quote s!:compfn) (function s!:comcarcdr4)) (put (quote caaddr) (quote s!:compfn) (function s!:comcarcdr4)) (put (quote cadaar) (quote s!:compfn) (function s!:comcarcdr4)) (put (quote cadadr) (quote s!:compfn) (function s!:comcarcdr4)) (put (quote caddar) (quote s!:compfn) (function s!:comcarcdr4)) (put (quote cadddr) (quote s!:compfn) (function s!:comcarcdr4)) (put (quote cdaaar) (quote s!:compfn) (function s!:comcarcdr4)) (put (quote cdaadr) (quote s!:compfn) (function s!:comcarcdr4)) (put (quote cdadar) (quote s!:compfn) (function s!:comcarcdr4)) (put (quote cdaddr) (quote s!:compfn) (function s!:comcarcdr4)) (put (quote cddaar) (quote s!:compfn) (function s!:comcarcdr4)) (put (quote cddadr) (quote s!:compfn) (function s!:comcarcdr4)) (put (quote cdddar) (quote s!:compfn) (function s!:comcarcdr4)) (put (quote cddddr) (quote s!:compfn) (function s!:comcarcdr4)) (de s!:comgetv (x env context) (cond (!*carcheckflag (s!:comcall x env context)) (t (s!:comval (cons (quote qgetv) (cdr x)) env context)))) (put (quote getv) (quote s!:compfn) (function s!:comgetv)) (de s!:comqgetv (x env context) (cond ((and (fixp (caddr x)) (geq (caddr x) 0 ) (lessp (caddr x) 256)) (progn (s!:comval (cadr x) env 1) (s!:outopcode1 ( quote QGETVN) (caddr x) (caddr x)))) (t (s!:comcall x env context)))) (put (quote qgetv) (quote s!:compfn) (function s!:comqgetv)) (de s!:comget (x env context) (prog (a b c w) (setq a (cadr x)) (setq b ( caddr x)) (setq c (cdddr x)) (cond ((eqcar b (quote quote)) (progn (setq b ( cadr b)) (setq w (symbol!-make!-fastget b nil)) (cond (c (progn (cond (w ( progn (cond ((s!:load2 a b env) (s!:outopcode0 (quote SWOP) (quote (SWOP))))) (s!:outopcode1 (quote FASTGET) (logor w 64) b))) (t (s!:comcall x env context))))) (t (progn (s!:comval a env 1) (cond (w (s!:outopcode1 (quote FASTGET) w b)) (t (s!:outopcode1lit (quote LITGET) b env)))))))) (t ( s!:comcall x env context))))) (put (quote get) (quote s!:compfn) (function s!:comget)) (de s!:comflagp (x env context) (prog (a b) (setq a (cadr x)) (setq b (caddr x)) (cond ((eqcar b (quote quote)) (progn (setq b (cadr b)) (s!:comval a env 1) (setq a (symbol!-make!-fastget b nil)) (cond (a (s!:outopcode1 (quote FASTGET) (logor a 128) b)) (t (s!:comcall x env context))))) (t (s!:comcall x env context))))) (put (quote flagp) (quote s!:compfn) (function s!:comflagp)) (de s!:complus (x env context) (s!:comval (expand (cdr x) (quote plus2)) env context)) (put (quote plus) (quote s!:compfn) (function s!:complus)) (de s!:comtimes (x env context) (s!:comval (expand (cdr x) (quote times2)) env context)) (put (quote times) (quote s!:compfn) (function s!:comtimes)) (de s!:comiplus (x env context) (s!:comval (expand (cdr x) (quote iplus2)) env context)) (put (quote iplus) (quote s!:compfn) (function s!:comiplus)) (de s!:comitimes (x env context) (s!:comval (expand (cdr x) (quote itimes2)) env context)) (put (quote itimes) (quote s!:compfn) (function s!:comitimes)) (de s!:complus2 (x env context) (prog (a b) (setq a (s!:improve (cadr x))) ( setq b (s!:improve (caddr x))) (return (cond ((and (numberp a) (numberp b)) ( s!:comval (plus a b) env context)) (t (cond ((equal a 0) (s!:comval b env context)) (t (cond ((equal a 1) (s!:comval (list (quote add1) b) env context) ) (t (cond ((equal b 0) (s!:comval a env context)) (t (cond ((equal b 1) ( s!:comval (list (quote add1) a) env context)) (t (cond ((equal b (minus 1)) ( s!:comval (list (quote sub1) a) env context)) (t (s!:comcall x env context))) ))))))))))))) (put (quote plus2) (quote s!:compfn) (function s!:complus2)) (de s!:comdifference (x env context) (prog (a b) (setq a (s!:improve (cadr x) )) (setq b (s!:improve (caddr x))) (return (cond ((and (numberp a) (numberp b )) (s!:comval (difference a b) env context)) (t (cond ((equal a 0) (s!:comval (list (quote minus) b) env context)) (t (cond ((equal b 0) (s!:comval a env context)) (t (cond ((equal b 1) (s!:comval (list (quote sub1) a) env context) ) (t (cond ((equal b (minus 1)) (s!:comval (list (quote add1) a) env context) ) (t (s!:comcall x env context)))))))))))))) (put (quote difference) (quote s!:compfn) (function s!:comdifference)) (de s!:comiplus2 (x env context) (prog (a b) (setq a (s!:improve (cadr x))) ( setq b (s!:improve (caddr x))) (return (cond ((and (numberp a) (numberp b)) ( s!:comval (plus a b) env context)) (t (cond ((equal a 1) (s!:comval (list ( quote iadd1) b) env context)) (t (cond ((equal b 1) (s!:comval (list (quote iadd1) a) env context)) (t (cond ((equal b (minus 1)) (s!:comval (list (quote isub1) a) env context)) (t (s!:comcall x env context)))))))))))) (put (quote iplus2) (quote s!:compfn) (function s!:comiplus2)) (de s!:comidifference (x env context) (prog (a b) (setq a (s!:improve (cadr x ))) (setq b (s!:improve (caddr x))) (return (cond ((and (numberp a) (numberp b)) (s!:comval (difference a b) env context)) (t (cond ((equal b 1) ( s!:comval (list (quote isub1) a) env context)) (t (cond ((equal b (minus 1)) (s!:comval (list (quote iadd1) a) env context)) (t (s!:comcall x env context) ))))))))) (put (quote idifference) (quote s!:compfn) (function s!:comidifference)) (de s!:comtimes2 (x env context) (prog (a b) (setq a (s!:improve (cadr x))) ( setq b (s!:improve (caddr x))) (return (cond ((and (numberp a) (numberp b)) ( s!:comval (times a b) env context)) (t (cond ((equal a 1) (s!:comval b env context)) (t (cond ((equal a (minus 1)) (s!:comval (list (quote minus) b) env context)) (t (cond ((equal b 1) (s!:comval a env context)) (t (cond ((equal b (minus 1)) (s!:comval (list (quote minus) a) env context)) (t (s!:comcall x env context)))))))))))))) (put (quote times2) (quote s!:compfn) (function s!:comtimes2)) (put (quote itimes2) (quote s!:compfn) (function s!:comtimes2)) (de s!:comminus (x env context) (prog (a b) (setq a (s!:improve (cadr x))) ( return (cond ((numberp a) (s!:comval (minus a) env context)) (t (cond ((eqcar a (quote minus)) (s!:comval (cadr a) env context)) (t (s!:comcall x env context)))))))) (put (quote minus) (quote s!:compfn) (function s!:comminus)) (de s!:comminusp (x env context) (prog (a) (setq a (s!:improve (cadr x))) ( cond ((eqcar a (quote difference)) (return (s!:comval (cons (quote lessp) ( cdr a)) env context))) (t (return (s!:comcall x env context)))))) (put (quote minusp) (quote s!:compfn) (function s!:comminusp)) (de s!:comlessp (x env context) (prog (a b) (setq a (s!:improve (cadr x))) ( setq b (s!:improve (caddr x))) (cond ((equal b 0) (return (s!:comval (list ( quote minusp) a) env context))) (t (return (s!:comcall x env context)))))) (put (quote lessp) (quote s!:compfn) (function s!:comlessp)) (de s!:comiminusp (x env context) (prog (a) (setq a (s!:improve (cadr x))) ( cond ((eqcar a (quote difference)) (return (s!:comval (cons (quote ilessp) ( cdr a)) env context))) (t (return (s!:comcall x env context)))))) (put (quote iminusp) (quote s!:compfn) (function s!:comiminusp)) (de s!:comilessp (x env context) (prog (a b) (setq a (s!:improve (cadr x))) ( setq b (s!:improve (caddr x))) (cond ((equal b 0) (return (s!:comval (list ( quote iminusp) a) env context))) (t (return (s!:comcall x env context)))))) (put (quote ilessp) (quote s!:compfn) (function s!:comilessp)) (de s!:comprogn (x env context) (progn (setq x (cdr x)) (cond ((null x) ( s!:comval nil env context)) (t (prog (a) (setq a (car x)) (prog nil lab1085 ( cond ((null (setq x (cdr x))) (return nil))) (progn (s!:comval a env (cond (( geq context 4) context) (t 2))) (setq a (car x))) (go lab1085)) (s!:comval a env context)))))) (put (quote progn) (quote s!:compfn) (function s!:comprogn)) (de s!:comprog1 (x env context) (prog nil (setq x (cdr x)) (cond ((null x) ( return (s!:comval nil env context)))) (s!:comval (car x) env context) (cond ( (null (setq x (cdr x))) (return nil))) (s!:outopcode0 (quote PUSH) (quote ( PUSH))) (rplacd env (cons 0 (cdr env))) (prog (var1087) (setq var1087 x) lab1086 (cond ((null var1087) (return nil))) (prog (a) (setq a (car var1087)) (s!:comval a env (cond ((geq context 4) context) (t 2)))) (setq var1087 (cdr var1087)) (go lab1086)) (s!:outopcode0 (quote POP) (quote (POP))) (rplacd env (cddr env)))) (put (quote prog1) (quote s!:compfn) (function s!:comprog1)) (de s!:comprog2 (x env context) (prog (a) (setq x (cdr x)) (cond ((null x) ( return (s!:comval nil env context)))) (setq a (car x)) (s!:comval a env (cond ((geq context 4) context) (t 2))) (s!:comprog1 x env context))) (put (quote prog2) (quote s!:compfn) (function s!:comprog2)) (de s!:outstack (n) (prog (w a) (setq w s!:current_block) (prog nil lab1088 ( cond ((null (and w (not (atom (car w))))) (return nil))) (setq w (cdr w)) (go lab1088)) (cond ((eqcar w (quote PUSHNIL)) (setq a 1)) (t (cond ((eqcar w ( quote PUSHNIL2)) (setq a 2)) (t (cond ((eqcar w (quote PUSHNIL3)) (setq a 3)) (t (cond ((and w (numberp (setq a (car w))) (not (equal a 255)) (eqcar (cdr w) (quote PUSHNILS))) (progn (setq w (cdr w)) (setq s!:current_size ( difference s!:current_size 1)))) (t (setq a nil))))))))) (cond (a (progn ( setq s!:current_block (cdr w)) (setq s!:current_size (difference s!:current_size 1)) (setq n (plus n a))))) (cond ((equal n 1) (s!:outopcode0 (quote PUSHNIL) (quote (PUSHNIL)))) (t (cond ((equal n 2) (s!:outopcode0 ( quote PUSHNIL2) (quote (PUSHNIL2)))) (t (cond ((equal n 3) (s!:outopcode0 ( quote PUSHNIL3) (quote (PUSHNIL3)))) (t (cond ((greaterp n 255) (progn ( s!:outopcode1 (quote PUSHNILS) 255 255) (s!:outstack (difference n 255)))) (t (cond ((greaterp n 3) (s!:outopcode1 (quote PUSHNILS) n n))))))))))))) (de s!:outlose (n) (prog (w a) (setq w s!:current_block) (prog nil lab1089 ( cond ((null (and w (not (atom (car w))))) (return nil))) (setq w (cdr w)) (go lab1089)) (cond ((eqcar w (quote LOSE)) (setq a 1)) (t (cond ((eqcar w ( quote LOSE2)) (setq a 2)) (t (cond ((eqcar w (quote LOSE3)) (setq a 3)) (t ( cond ((and w (numberp (setq a (car w))) (not (equal a 255)) (eqcar (cdr w) ( quote LOSES))) (progn (setq w (cdr w)) (setq s!:current_size (difference s!:current_size 1)))) (t (setq a nil))))))))) (cond (a (progn (setq s!:current_block (cdr w)) (setq s!:current_size (difference s!:current_size 1 )) (setq n (plus n a))))) (cond ((equal n 1) (s!:outopcode0 (quote LOSE) ( quote (LOSE)))) (t (cond ((equal n 2) (s!:outopcode0 (quote LOSE2) (quote ( LOSE2)))) (t (cond ((equal n 3) (s!:outopcode0 (quote LOSE3) (quote (LOSE3))) ) (t (cond ((greaterp n 255) (progn (s!:outopcode1 (quote LOSES) 255 255) ( s!:outlose (difference n 255)))) (t (cond ((greaterp n 3) (s!:outopcode1 ( quote LOSES) n n))))))))))))) (de s!:comprog (x env context) (prog (labs s bvl fluids n body local_decs w) (setq body (s!:find_local_decs (cddr x) t)) (setq local_decs (car body)) ( setq body (cdr body)) (setq n 0) (prog (var1091) (setq var1091 (cadr x)) lab1090 (cond ((null var1091) (return nil))) (prog (v) (setq v (car var1091)) (setq w (s!:instate_local_decs v local_decs w))) (setq var1091 (cdr var1091) ) (go lab1090)) (prog (var1093) (setq var1093 (cadr x)) lab1092 (cond ((null var1093) (return nil))) (prog (v) (setq v (car var1093)) (progn (cond (( globalp v) (progn (cond (!*pwrds (progn (cond ((neq (posn) 0) (terpri))) ( princ "+++++ global ") (prin v) (princ " converted to fluid") (terpri)))) ( unglobal (list v)) (fluid (list v))))) (cond ((fluidp v) (setq fluids (cons v fluids))) (t (progn (setq n (plus n 1)) (setq bvl (cons v bvl))))))) (setq var1093 (cdr var1093)) (go lab1092)) (setq s (cdr env)) (setq s!:current_exitlab (cons (cons nil (cons (gensym) s)) s!:current_exitlab)) ( s!:outstack n) (rplacd env (append bvl (cdr env))) (cond (fluids (prog (fl1) (setq fl1 (s!:vecof fluids)) (s!:outopcode1lit (quote FREEBIND) fl1 env) ( prog (var1095) (setq var1095 (cons nil fluids)) lab1094 (cond ((null var1095) (return nil))) (prog (v) (setq v (car var1095)) (rplacd env (cons 0 (cdr env )))) (setq var1095 (cdr var1095)) (go lab1094)) (rplacd env (cons (plus 2 ( length fluids)) (cdr env))) (cond ((equal context 0) (setq context 1)))))) ( prog (var1097) (setq var1097 body) lab1096 (cond ((null var1097) (return nil) )) (prog (a) (setq a (car var1097)) (cond ((atom a) (progn (cond ((atsoc a labs) (progn (cond ((not (null a)) (progn (cond ((neq (posn) 0) (terpri))) ( princ "+++++ label ") (prin a) (princ " multiply defined") (terpri)))))) (t ( setq labs (cons (cons a (cons (cons (gensym) (cdr env)) nil)) labs)))))))) ( setq var1097 (cdr var1097)) (go lab1096)) (setq s!:current_proglabels (cons labs s!:current_proglabels)) (setq w (s!:residual_local_decs local_decs w)) ( prog (var1099) (setq var1099 body) lab1098 (cond ((null var1099) (return nil) )) (prog (a) (setq a (car var1099)) (cond ((not (atom a)) (s!:comval a env ( plus context 4))) (t (prog (d) (setq d (atsoc a labs)) (cond ((null (cddr d)) (progn (rplacd (cdr d) t) (s!:set_label (caadr d))))))))) (setq var1099 (cdr var1099)) (go lab1098)) (s!:cancel_local_decs w) (s!:comval nil env context) (cond (fluids (s!:outopcode0 (quote FREERSTR) (quote (FREERSTR))))) ( s!:outlose n) (rplacd env s) (s!:set_label (cadar s!:current_exitlab)) (setq s!:current_exitlab (cdr s!:current_exitlab)) (setq s!:current_proglabels (cdr s!:current_proglabels)))) (put (quote prog) (quote s!:compfn) (function s!:comprog)) (de s!:comtagbody (x env context) (prog (labs) (prog (var1101) (setq var1101 (cdr x)) lab1100 (cond ((null var1101) (return nil))) (prog (a) (setq a (car var1101)) (cond ((atom a) (progn (cond ((atsoc a labs) (progn (cond ((not ( null a)) (progn (cond ((neq (posn) 0) (terpri))) (princ "+++++ label ") (prin a) (princ " multiply defined") (terpri)))))) (t (setq labs (cons (cons a ( cons (cons (gensym) (cdr env)) nil)) labs)))))))) (setq var1101 (cdr var1101) ) (go lab1100)) (setq s!:current_proglabels (cons labs s!:current_proglabels) ) (prog (var1103) (setq var1103 (cdr x)) lab1102 (cond ((null var1103) ( return nil))) (prog (a) (setq a (car var1103)) (cond ((not (atom a)) ( s!:comval a env (plus context 4))) (t (prog (d) (setq d (atsoc a labs)) (cond ((null (cddr d)) (progn (rplacd (cdr d) t) (s!:set_label (caadr d))))))))) ( setq var1103 (cdr var1103)) (go lab1102)) (s!:comval nil env context) (setq s!:current_proglabels (cdr s!:current_proglabels)))) (put (quote tagbody) (quote s!:compfn) (function s!:comtagbody)) (de s!:comblock (x env context) (prog nil (setq s!:current_exitlab (cons ( cons (cadr x) (cons (gensym) (cdr env))) s!:current_exitlab)) (s!:comval ( cons (quote progn) (cddr x)) env context) (s!:set_label (cadar s!:current_exitlab)) (setq s!:current_exitlab (cdr s!:current_exitlab)))) (put (quote !~block) (quote s!:compfn) (function s!:comblock)) (de s!:comcatch (x env context) (prog (g) (setq g (gensym)) (s!:comval (cadr x) env 1) (s!:outjump (quote CATCH) g) (rplacd env (cons (quote (catch)) ( cons 0 (cons 0 (cdr env))))) (s!:comval (cons (quote progn) (cddr x)) env context) (s!:outopcode0 (quote UNCATCH) (quote (UNCATCH))) (rplacd env ( cddddr env)) (s!:set_label g))) (put (quote catch) (quote s!:compfn) (quote s!:comcatch)) (de s!:comthrow (x env context) (prog nil (s!:comval (cadr x) env 1) ( s!:outopcode0 (quote PUSH) (quote (PUSH))) (rplacd env (cons 0 (cdr env))) ( s!:comval (caddr x) env 1) (s!:outopcode0 (quote THROW) (quote (THROW))) ( rplacd env (cddr env)))) (put (quote throw) (quote s!:compfn) (quote s!:comthrow)) (de s!:comunwind!-protect (x env context) (prog (g) (setq g (gensym)) ( s!:comval (quote (load!-spid)) env 1) (s!:outjump (quote CATCH) g) (rplacd env (cons (list (quote unwind!-protect) (cddr x)) (cons 0 (cons 0 (cdr env))) )) (s!:comval (cadr x) env context) (s!:outopcode0 (quote PROTECT) (quote ( PROTECT))) (s!:set_label g) (rplaca (cdr env) 0) (s!:comval (cons (quote progn) (cddr x)) env context) (s!:outopcode0 (quote UNPROTECT) (quote ( UNPROTECT))) (rplacd env (cddddr env)))) (put (quote unwind!-protect) (quote s!:compfn) (quote s!:comunwind!-protect)) (de s!:comdeclare (x env context) (prog nil (cond (!*pwrds (progn (princ "+++ ") (prin x) (princ " ignored") (terpri)))))) (put (quote declare) (quote s!:compfn) (function s!:comdeclare)) (de s!:expand_let (vl b) (prog (vars vals) (prog (var1105) (setq var1105 vl) lab1104 (cond ((null var1105) (return nil))) (prog (v) (setq v (car var1105)) (cond ((atom v) (progn (setq vars (cons v vars)) (setq vals (cons nil vals)) )) (t (cond ((atom (cdr v)) (progn (setq vars (cons (car v) vars)) (setq vals (cons nil vals)))) (t (progn (setq vars (cons (car v) vars)) (setq vals ( cons (cadr v) vals)))))))) (setq var1105 (cdr var1105)) (go lab1104)) (return (list (cons (cons (quote lambda) (cons vars b)) vals))))) (de s!:comlet (x env context) (s!:comval (cons (quote progn) (s!:expand_let ( cadr x) (cddr x))) env context)) (put (quote !~let) (quote s!:compfn) (function s!:comlet)) (de s!:expand_let!* (vl local_decs b) (prog (r var val) (setq r (cons (cons ( quote declare) local_decs) b)) (prog (var1109) (setq var1109 (reverse vl)) lab1108 (cond ((null var1109) (return nil))) (prog (x) (setq x (car var1109)) (progn (setq val nil) (cond ((atom x) (setq var x)) (t (cond ((atom (cdr x)) (setq var (car x))) (t (progn (setq var (car x)) (setq val (cadr x))))))) ( prog (var1107) (setq var1107 local_decs) lab1106 (cond ((null var1107) ( return nil))) (prog (z) (setq z (car var1107)) (cond ((eqcar z (quote special )) (cond ((memq var (cdr z)) (setq r (cons (list (quote declare) (list (quote special) var)) r))))))) (setq var1107 (cdr var1107)) (go lab1106)) (setq r ( list (list (cons (quote lambda) (cons (list var) r)) val))))) (setq var1109 ( cdr var1109)) (go lab1108)) (cond ((eqcar (car r) (quote declare)) (setq r ( list (cons (quote lambda) (cons nil r))))) (t (setq r (cons (quote progn) r)) )) (return r))) (de s!:comlet!* (x env context) (prog (b) (setq b (s!:find_local_decs (cddr x ) nil)) (return (s!:comval (s!:expand_let!* (cadr x) (car b) (cdr b)) env context)))) (put (quote let!*) (quote s!:compfn) (function s!:comlet!*)) (de s!:restore_stack (e1 e2) (prog (n) (setq n 0) (prog nil lab1111 (cond (( null (not (equal e1 e2))) (return nil))) (progn (cond ((null e1) (error 0 "bad block nesting with GO or RETURN-FROM"))) (cond ((and (numberp (car e1)) (greaterp (car e1) 2)) (progn (cond ((not (zerop n)) (s!:outlose n))) (setq n (car e1)) (s!:outopcode0 (quote FREERSTR) (quote (FREERSTR))) (prog (i) ( setq i 1) lab1110 (cond ((minusp (times 1 (difference n i))) (return nil))) ( setq e1 (cdr e1)) (setq i (plus i 1)) (go lab1110)) (setq n 0))) (t (cond (( equal (car e1) (quote (catch))) (progn (cond ((not (zerop n)) (s!:outlose n)) ) (s!:outopcode0 (quote UNCATCH) (quote (UNCATCH))) (setq e1 (cdddr e1)) ( setq n 0))) (t (cond ((eqcar (car e1) (quote unwind!-protect)) (progn (cond ( (not (zerop n)) (s!:outlose n))) (s!:outopcode0 (quote PROTECT) (quote ( PROTECT))) (s!:comval (cons (quote progn) (cadar e1)) e1 2) (s!:outopcode0 ( quote UNPROTECT) (quote (UNPROTECT))) (setq e1 (cdddr e1)) (setq n 0))) (t ( progn (setq e1 (cdr e1)) (setq n (plus n 1)))))))))) (go lab1111)) (cond (( not (zerop n)) (s!:outlose n))))) (de s!:comgo (x env context) (prog (pl d) (cond ((lessp context 4) (progn ( princ "go not in program context") (terpri)))) (setq pl s!:current_proglabels ) (prog nil lab1112 (cond ((null (and pl (null d))) (return nil))) (progn ( setq d (atsoc (cadr x) (car pl))) (cond ((null d) (setq pl (cdr pl))))) (go lab1112)) (cond ((null d) (progn (cond ((neq (posn) 0) (terpri))) (princ "+++++ label ") (prin (cadr x)) (princ " not set") (terpri) (return nil)))) ( setq d (cadr d)) (s!:restore_stack (cdr env) (cdr d)) (s!:outjump (quote JUMP ) (car d)))) (put (quote go) (quote s!:compfn) (function s!:comgo)) (de s!:comreturn!-from (x env context) (prog (tag) (cond ((lessp context 4) ( progn (princ "+++++ return or return-from not in prog context") (terpri)))) ( setq x (cdr x)) (setq tag (car x)) (cond ((cdr x) (setq x (cadr x))) (t (setq x nil))) (s!:comval x env (difference context 4)) (setq x (atsoc tag s!:current_exitlab)) (cond ((null x) (error 0 (list "invalid return-from" tag )))) (setq x (cdr x)) (s!:restore_stack (cdr env) (cdr x)) (s!:outjump (quote JUMP) (car x)))) (put (quote return!-from) (quote s!:compfn) (function s!:comreturn!-from)) (de s!:comreturn (x env context) (s!:comreturn!-from (cons (quote return!-from) (cons nil (cdr x))) env context)) (put (quote return) (quote s!:compfn) (function s!:comreturn)) (global (quote (s!:jumplts s!:jumplnils s!:jumpatoms s!:jumpnatoms))) (setq s!:jumplts (s!:vecof (quote (JUMPL0T JUMPL1T JUMPL2T JUMPL3T JUMPL4T))) ) (setq s!:jumplnils (s!:vecof (quote (JUMPL0NIL JUMPL1NIL JUMPL2NIL JUMPL3NIL JUMPL4NIL)))) (setq s!:jumpatoms (s!:vecof (quote (JUMPL0ATOM JUMPL1ATOM JUMPL2ATOM JUMPL3ATOM)))) (setq s!:jumpnatoms (s!:vecof (quote (JUMPL0NATOM JUMPL1NATOM JUMPL2NATOM JUMPL3NATOM)))) (de s!:jumpif (neg x env lab) (prog (w w1 j) top (cond ((null x) (progn (cond ((not neg) (s!:outjump (quote JUMP) lab))) (return nil))) (t (cond ((or (eq x t) (and (eqcar x (quote quote)) (cadr x)) (and (atom x) (not (symbolp x)))) (progn (cond (neg (s!:outjump (quote JUMP) lab))) (return nil))) (t (cond (( lessp (setq w (s!:islocal x env)) 5) (return (s!:outjump (getv (cond (neg s!:jumplts) (t s!:jumplnils)) w) lab))) (t (cond ((and (equal w 99999) ( symbolp x)) (progn (s!:should_be_fluid x) (setq w (list (cond (neg (quote JUMPFREET)) (t (quote JUMPFREENIL))) x x)) (return ( s!:record_literal_for_jump w env lab))))))))))) (cond ((and (not (atom x)) ( atom (car x)) (setq w (get (car x) (quote s!:testfn)))) (return (funcall w neg x env lab)))) (cond ((not (atom x)) (progn (setq w (s!:improve x)) (cond ((or (atom w) (not (eqcar x (car w)))) (progn (setq x w) (go top)))) (cond (( and (setq w1 (get (car w) (quote s!:compilermacro))) (setq w1 (funcall w1 w env 1))) (progn (setq x w1) (go top))))))) remacro (cond ((and (not (atom w)) (setq w1 (macro!-function (car w)))) (progn (setq w (funcall w1 w)) (cond (( or (atom w) (eqcar w (quote quote)) (get (car w) (quote s!:testfn)) (get (car w) (quote s!:compilermacro))) (progn (setq x w) (go top)))) (go remacro)))) (s!:comval x env 1) (setq w s!:current_block) (prog nil lab1113 (cond ((null (and w (not (atom (car w))))) (return nil))) (setq w (cdr w)) (go lab1113)) ( setq j (quote (JUMPNIL . JUMPT))) (cond (w (progn (setq w1 (car w)) (setq w ( cdr w)) (cond ((equal w1 (quote STORELOC0)) (progn (setq s!:current_block w) (setq s!:current_size (difference s!:current_size 1)) (setq j (quote ( JUMPST0NIL . JUMPST0T))))) (t (cond ((equal w1 (quote STORELOC1)) (progn ( setq s!:current_block w) (setq s!:current_size (difference s!:current_size 1) ) (setq j (quote (JUMPST1NIL . JUMPST1T))))) (t (cond ((equal w1 (quote STORELOC2)) (progn (setq s!:current_block w) (setq s!:current_size ( difference s!:current_size 1)) (setq j (quote (JUMPST2NIL . JUMPST2T))))) (t (cond ((eqcar w (quote BUILTIN1)) (progn (setq s!:current_block (cdr w)) ( setq s!:current_size (difference s!:current_size 2)) (setq j (cons (list ( quote JUMPB1NIL) w1) (list (quote JUMPB1T) w1))))) (t (cond ((eqcar w (quote BUILTIN2)) (progn (setq s!:current_block (cdr w)) (setq s!:current_size ( difference s!:current_size 2)) (setq j (cons (list (quote JUMPB2NIL) w1) ( list (quote JUMPB2T) w1))))))))))))))))) (return (s!:outjump (cond (neg (cdr j)) (t (car j))) lab)))) (de s!:testnot (neg x env lab) (s!:jumpif (not neg) (cadr x) env lab)) (put (quote null) (quote s!:testfn) (function s!:testnot)) (put (quote not) (quote s!:testfn) (function s!:testnot)) (de s!:testatom (neg x env lab) (prog (w) (cond ((lessp (setq w (s!:islocal ( cadr x) env)) 4) (return (s!:outjump (getv (cond (neg s!:jumpatoms) (t s!:jumpnatoms)) w) lab)))) (s!:comval (cadr x) env 1) (cond (neg (s!:outjump (quote JUMPATOM) lab)) (t (s!:outjump (quote JUMPNATOM) lab))))) (put (quote atom) (quote s!:testfn) (function s!:testatom)) (de s!:testconsp (neg x env lab) (prog (w) (cond ((lessp (setq w (s!:islocal (cadr x) env)) 4) (return (s!:outjump (getv (cond (neg s!:jumpnatoms) (t s!:jumpatoms)) w) lab)))) (s!:comval (cadr x) env 1) (cond (neg (s!:outjump ( quote JUMPNATOM) lab)) (t (s!:outjump (quote JUMPATOM) lab))))) (put (quote consp) (quote s!:testfn) (function s!:testconsp)) (de s!:comcond (x env context) (prog (l1 l2 w) (setq l1 (gensym)) (prog nil lab1114 (cond ((null (setq x (cdr x))) (return nil))) (progn (setq w (car x)) (cond ((atom (cdr w)) (progn (s!:comval (car w) env 1) (s!:outjump (quote JUMPT) l1) (setq l2 nil))) (t (progn (cond ((equal (car w) t) (setq l2 nil)) (t (progn (setq l2 (gensym)) (s!:jumpif nil (car w) env l2)))) (setq w (cdr w )) (cond ((null (cdr w)) (setq w (car w))) (t (setq w (cons (quote progn) w)) )) (s!:comval w env context) (cond (l2 (progn (s!:outjump (quote JUMP) l1) ( s!:set_label l2))) (t (setq x (quote (nil))))))))) (go lab1114)) (cond (l2 ( s!:comval nil env context))) (s!:set_label l1))) (put (quote cond) (quote s!:compfn) (function s!:comcond)) (de s!:comif (x env context) (prog (l1 l2) (setq l2 (gensym)) (s!:jumpif nil (cadr x) env l2) (setq x (cddr x)) (s!:comval (car x) env context) (setq x ( cdr x)) (cond ((or x (and (lessp context 2) (setq x (quote (nil))))) (progn ( setq l1 (gensym)) (s!:outjump (quote JUMP) l1) (s!:set_label l2) (s!:comval ( car x) env context) (s!:set_label l1))) (t (s!:set_label l2))))) (put (quote if) (quote s!:compfn) (function s!:comif)) (de s!:comwhen (x env context) (prog (l2) (setq l2 (gensym)) (cond ((lessp context 2) (progn (s!:comval (cadr x) env 1) (s!:outjump (quote JUMPNIL) l2)) ) (t (s!:jumpif nil (cadr x) env l2))) (s!:comval (cons (quote progn) (cddr x )) env context) (s!:set_label l2))) (put (quote when) (quote s!:compfn) (function s!:comwhen)) (de s!:comunless (x env context) (s!:comwhen (list!* (quote when) (list ( quote not) (cadr x)) (cddr x)) env context)) (put (quote unless) (quote s!:compfn) (function s!:comunless)) (de s!:comicase (x env context) (prog (l1 labs labassoc w) (setq x (cdr x)) ( prog (var1116) (setq var1116 (cdr x)) lab1115 (cond ((null var1116) (return nil))) (prog (v) (setq v (car var1116)) (progn (setq w (assoc!*!* v labassoc) ) (cond (w (setq l1 (cons (cdr w) l1))) (t (progn (setq l1 (gensym)) (setq labs (cons l1 labs)) (setq labassoc (cons (cons v l1) labassoc))))))) (setq var1116 (cdr var1116)) (go lab1115)) (s!:comval (car x) env 1) (s!:outjump ( quote ICASE) (reversip labs)) (setq l1 (gensym)) (prog (var1118) (setq var1118 labassoc) lab1117 (cond ((null var1118) (return nil))) (prog (v) ( setq v (car var1118)) (progn (s!:set_label (cdr v)) (s!:comval (car v) env context) (s!:outjump (quote JUMP) l1))) (setq var1118 (cdr var1118)) (go lab1117)) (s!:set_label l1))) (put (quote s!:icase) (quote s!:compfn) (function s!:comicase)) (put (quote JUMPLITEQ!*) (quote s!:opcode) (get (quote JUMPLITEQ) (quote s!:opcode))) (put (quote JUMPLITNE!*) (quote s!:opcode) (get (quote JUMPLITNE) (quote s!:opcode))) (de s!:jumpliteql (val lab env) (prog (w) (cond ((or (idp val) (eq!-safe val) ) (progn (setq w (list (quote JUMPLITEQ!*) val val)) ( s!:record_literal_for_jump w env lab))) (t (progn (s!:outopcode0 (quote PUSH) (quote (PUSH))) (s!:loadliteral val env) (s!:outopcode1 (quote BUILTIN2) ( get (quote eql) (quote s!:builtin2)) (quote eql)) (s!:outjump (quote JUMPT) lab) (flag (list lab) (quote s!:jumpliteql)) (s!:outopcode0 (quote POP) ( quote (POP)))))))) (de s!:casebranch (sw env dflt) (prog (size w w1 r g) (setq size (plus 4 ( truncate (length sw) 2))) (prog nil lab1119 (cond ((null (or (equal ( remainder size 2) 0) (equal (remainder size 3) 0) (equal (remainder size 5) 0 ) (equal (remainder size 13) 0))) (return nil))) (setq size (plus size 1)) ( go lab1119)) (prog (var1121) (setq var1121 sw) lab1120 (cond ((null var1121) (return nil))) (prog (p) (setq p (car var1121)) (progn (setq w (remainder ( eqlhash (car p)) size)) (setq w1 (assoc!*!* w r)) (cond (w1 (rplacd (cdr w1) (cons p (cddr w1)))) (t (setq r (cons (list w (gensym) p) r)))))) (setq var1121 (cdr var1121)) (go lab1120)) (s!:outopcode0 (quote PUSH) (quote (PUSH ))) (rplacd env (cons 0 (cdr env))) (s!:outopcode1lit (quote CALL1) (quote eqlhash) env) (s!:loadliteral size env) (setq g (gensym)) (s!:outopcode1 ( quote BUILTIN2) (get (quote iremainder) (quote s!:builtin2)) (quote iremainder)) (s!:outjump (quote ICASE) (cons g (prog (i var1123) (setq i 0) lab1122 (cond ((minusp (times 1 (difference (difference size 1) i))) (return (reversip var1123)))) (setq var1123 (cons (progn (setq w (assoc!*!* i r)) ( cond (w (cadr w)) (t g))) var1123)) (setq i (plus i 1)) (go lab1122)))) (prog (var1127) (setq var1127 r) lab1126 (cond ((null var1127) (return nil))) ( prog (p) (setq p (car var1127)) (progn (s!:set_label (cadr p)) (s!:outopcode0 (quote POP) (quote (POP))) (prog (var1125) (setq var1125 (cddr p)) lab1124 ( cond ((null var1125) (return nil))) (prog (q) (setq q (car var1125)) ( s!:jumpliteql (car q) (cdr q) env)) (setq var1125 (cdr var1125)) (go lab1124) ) (s!:outjump (quote JUMP) dflt))) (setq var1127 (cdr var1127)) (go lab1126)) (s!:set_label g) (s!:outopcode0 (quote POP) (quote (POP))) (s!:outjump ( quote JUMP) dflt) (rplacd env (cddr env)))) (de s!:comcase (x env context) (prog (keyform blocks v w g dflt sw keys nonnum) (setq x (cdr x)) (setq keyform (car x)) (prog (y) (setq y (cdr x)) lab1130 (cond ((null y) (return nil))) (progn (setq w (assoc!*!* (cdar y) blocks)) (cond (w (setq g (cdr w))) (t (progn (setq g (gensym)) (setq blocks (cons (cons (cdar y) g) blocks))))) (setq w (caar y)) (cond ((and (null (cdr y)) (or (equal w t) (equal w (quote otherwise)))) (setq dflt g)) (t (progn ( cond ((atom w) (setq w (list w)))) (prog (var1129) (setq var1129 w) lab1128 ( cond ((null var1129) (return nil))) (prog (n) (setq n (car var1129)) (progn ( cond ((or (idp n) (numberp n)) (progn (cond ((not (fixp n)) (setq nonnum t))) (setq keys (cons n keys)) (setq sw (cons (cons n g) sw)))) (t (error 0 (list "illegal case label" n)))))) (setq var1129 (cdr var1129)) (go lab1128)))))) (setq y (cdr y)) (go lab1130)) (cond ((null dflt) (progn (cond ((setq w ( assoc!*!* nil blocks)) (setq dflt (cdr w))) (t (setq blocks (cons (cons nil ( setq dflt (gensym))) blocks))))))) (cond ((not nonnum) (progn (setq keys ( sort keys (function lessp))) (setq nonnum (car keys)) (setq g (lastcar keys)) (cond ((lessp (difference g nonnum) (times 2 (length keys))) (progn (cond (( not (equal nonnum 0)) (progn (setq keyform (list (quote xdifference) keyform nonnum)) (setq sw (prog (var1132 var1133) (setq var1132 sw) lab1131 (cond (( null var1132) (return (reversip var1133)))) (prog (y) (setq y (car var1132)) (setq var1133 (cons (cons (difference (car y) nonnum) (cdr y)) var1133))) ( setq var1132 (cdr var1132)) (go lab1131)))))) (s!:comval keyform env 1) (setq w nil) (prog (i) (setq i 0) lab1134 (cond ((minusp (times 1 (difference g i) )) (return nil))) (cond ((setq v (assoc!*!* i sw)) (setq w (cons (cdr v) w))) (t (setq w (cons dflt w)))) (setq i (plus i 1)) (go lab1134)) (setq w (cons dflt (reversip w))) (s!:outjump (quote ICASE) w) (setq nonnum nil))) (t (setq nonnum t)))))) (cond (nonnum (progn (s!:comval keyform env 1) (cond ((lessp (length sw) 7) (progn (prog (var1136) (setq var1136 sw) lab1135 (cond ((null var1136) (return nil))) (prog (y) (setq y (car var1136)) (s!:jumpliteql (car y) (cdr y) env)) (setq var1136 (cdr var1136)) (go lab1135)) (s!:outjump ( quote JUMP) dflt))) (t (s!:casebranch sw env dflt)))))) (setq g (gensym)) ( prog (var1138) (setq var1138 blocks) lab1137 (cond ((null var1138) (return nil))) (prog (v) (setq v (car var1138)) (progn (s!:set_label (cdr v)) (cond ( (flagp (cdr v) (quote s!:jumpliteql)) (s!:outlose 1))) (s!:comval (cons ( quote progn) (car v)) env context) (s!:outjump (quote JUMP) g))) (setq var1138 (cdr var1138)) (go lab1137)) (s!:set_label g))) (put (quote case) (quote s!:compfn) (function s!:comcase)) (fluid (quote (!*defn dfprint!* s!:dfprintsave s!:faslmod_name))) (de s!:comeval!-when (x env context) (prog (y) (setq x (cdr x)) (setq y (car x)) (princ "COMPILING eval-when: ") (print y) (print x) (setq x (cons (quote progn) (cdr x))) (cond ((memq (quote compile) y) (eval x))) (cond ((memq ( quote load) y) (progn (cond (dfprint!* (apply1 dfprint!* x)))))) (cond ((memq (quote eval) y) (s!:comval x env context)) (t (s!:comval nil env context)))) ) (put (quote eval!-when) (quote s!:compfn) (function s!:comeval!-when)) (de s!:comthe (x env context) (s!:comval (caddr x) env context)) (put (quote the) (quote s!:compfn) (function s!:comthe)) (de s!:comand (x env context) (prog (l) (setq l (gensym)) (setq x (cdr x)) ( s!:comval (car x) env 1) (prog nil lab1139 (cond ((null (setq x (cdr x))) ( return nil))) (progn (s!:outjump (quote JUMPNIL) l) (s!:comval (car x) env 1) ) (go lab1139)) (s!:set_label l))) (put (quote and) (quote s!:compfn) (function s!:comand)) (de s!:comor (x env context) (prog (l) (setq l (gensym)) (setq x (cdr x)) ( s!:comval (car x) env 1) (prog nil lab1140 (cond ((null (setq x (cdr x))) ( return nil))) (progn (s!:outjump (quote JUMPT) l) (s!:comval (car x) env 1)) (go lab1140)) (s!:set_label l))) (put (quote or) (quote s!:compfn) (function s!:comor)) (de s!:combool (neg x env lab) (prog (fn) (setq fn (eqcar x (quote or))) ( cond ((eq fn neg) (prog nil lab1141 (cond ((null (setq x (cdr x))) (return nil))) (s!:jumpif fn (car x) env lab) (go lab1141))) (t (progn (setq neg ( gensym)) (prog nil lab1142 (cond ((null (setq x (cdr x))) (return nil))) ( s!:jumpif fn (car x) env neg) (go lab1142)) (s!:outjump (quote JUMP) lab) ( s!:set_label neg)))))) (put (quote and) (quote s!:testfn) (function s!:combool)) (put (quote or) (quote s!:testfn) (function s!:combool)) (de s!:testeq (neg x env lab) (prog (a b) (setq a (s!:improve (cadr x))) ( setq b (s!:improve (caddr x))) (cond ((or (s!:eval_to_eq_unsafe a) ( s!:eval_to_eq_unsafe b)) (progn (cond ((neq (posn) 0) (terpri))) (princ "++++ EQ on number upgraded to EQUAL in ") (prin s!:current_function) (princ " : ") (prin a) (princ " ") (print b) (return (s!:testequal neg (cons (quote equal) (cdr x)) env lab))))) (cond ((null a) (s!:jumpif (not neg) b env lab)) (t (cond ((null b) (s!:jumpif (not neg) a env lab)) (t (cond ((or (eqcar a ( quote quote)) (and (atom a) (not (symbolp a)))) (progn (s!:comval b env 1) ( cond ((eqcar a (quote quote)) (setq a (cadr a)))) (setq b (list (cond (neg ( quote JUMPLITEQ)) (t (quote JUMPLITNE))) a a)) (s!:record_literal_for_jump b env lab))) (t (cond ((or (eqcar b (quote quote)) (and (atom b) (not (symbolp b)))) (progn (s!:comval a env 1) (cond ((eqcar b (quote quote)) (setq b (cadr b)))) (setq a (list (cond (neg (quote JUMPLITEQ)) (t (quote JUMPLITNE))) b b )) (s!:record_literal_for_jump a env lab))) (t (progn (s!:load2 a b env) ( cond (neg (s!:outjump (quote JUMPEQ) lab)) (t (s!:outjump (quote JUMPNE) lab) ))))))))))))) (de s!:testeq1 (neg x env lab) (prog (a b) (setq a (s!:improve (cadr x))) ( setq b (s!:improve (caddr x))) (cond ((null a) (s!:jumpif (not neg) b env lab )) (t (cond ((null b) (s!:jumpif (not neg) a env lab)) (t (cond ((or (eqcar a (quote quote)) (and (atom a) (not (symbolp a)))) (progn (s!:comval b env 1) (cond ((eqcar a (quote quote)) (setq a (cadr a)))) (setq b (list (cond (neg ( quote JUMPLITEQ)) (t (quote JUMPLITNE))) a a)) (s!:record_literal_for_jump b env lab))) (t (cond ((or (eqcar b (quote quote)) (and (atom b) (not (symbolp b)))) (progn (s!:comval a env 1) (cond ((eqcar b (quote quote)) (setq b (cadr b)))) (setq a (list (cond (neg (quote JUMPLITEQ)) (t (quote JUMPLITNE))) b b )) (s!:record_literal_for_jump a env lab))) (t (progn (s!:load2 a b env) ( cond (neg (s!:outjump (quote JUMPEQ) lab)) (t (s!:outjump (quote JUMPNE) lab) ))))))))))))) (put (quote eq) (quote s!:testfn) (function s!:testeq)) (cond ((eq!-safe 0) (put (quote iequal) (quote s!:testfn) (function s!:testeq1))) (t (put (quote iequal) (quote s!:testfn) (function s!:testequal )))) (de s!:testequal (neg x env lab) (prog (a b) (setq a (cadr x)) (setq b (caddr x)) (cond ((null a) (s!:jumpif (not neg) b env lab)) (t (cond ((null b) ( s!:jumpif (not neg) a env lab)) (t (cond ((or (and (eqcar a (quote quote)) ( or (symbolp (cadr a)) (eq!-safe (cadr a)))) (and (eqcar b (quote quote)) (or (symbolp (cadr b)) (eq!-safe (cadr b)))) (and (not (idp a)) (eq!-safe a)) ( and (not (idp b)) (eq!-safe b))) (s!:testeq1 neg (cons (quote eq) (cdr x)) env lab)) (t (progn (s!:load2 a b env) (cond (neg (s!:outjump (quote JUMPEQUAL) lab)) (t (s!:outjump (quote JUMPNEQUAL) lab)))))))))))) (put (quote equal) (quote s!:testfn) (function s!:testequal)) (de s!:testneq (neg x env lab) (s!:testequal (not neg) (cons (quote equal) ( cdr x)) env lab)) (put (quote neq) (quote s!:testfn) (function s!:testneq)) (de s!:testeqcar (neg x env lab) (prog (a b sw promote) (setq a (cadr x)) ( setq b (s!:improve (caddr x))) (cond ((s!:eval_to_eq_unsafe b) (progn (cond ( (neq (posn) 0) (terpri))) (princ "++++ EQCAR on number upgraded to EQUALCAR in ") (prin s!:current_function) ( princ " : ") (print b) (setq promote t)))) (cond ((and (not promote) (eqcar b (quote quote))) (progn (s!:comval a env 1) (setq b (cadr b)) (setq a (list ( cond (neg (quote JUMPEQCAR)) (t (quote JUMPNEQCAR))) b b)) ( s!:record_literal_for_jump a env lab))) (t (cond ((or (equal b nil) (equal b t) (and (not (symbolp b)) (eq!-safe b))) (progn (s!:comval a env 1) (setq a ( list (cond (neg (quote JUMPEQCAR)) (t (quote JUMPNEQCAR))) b b)) ( s!:record_literal_for_jump a env lab))) (t (progn (setq sw (s!:load2 a b env) ) (cond (sw (s!:outopcode0 (quote SWOP) (quote (SWOP))))) (cond (promote ( s!:outopcode1 (quote BUILTIN2) (get (quote equalcar) (quote s!:builtin2)) ( quote equalcar))) (t (s!:outopcode0 (quote EQCAR) (quote (EQCAR))))) ( s!:outjump (cond (neg (quote JUMPT)) (t (quote JUMPNIL))) lab)))))))) (put (quote eqcar) (quote s!:testfn) (function s!:testeqcar)) (de s!:testflagp (neg x env lab) (prog (a b sw) (setq a (cadr x)) (setq b ( caddr x)) (cond ((eqcar b (quote quote)) (progn (s!:comval a env 1) (setq b ( cadr b)) (setq sw (symbol!-make!-fastget b nil)) (cond (sw (progn ( s!:outopcode1 (quote FASTGET) (logor sw 128) b) (s!:outjump (cond (neg (quote JUMPT)) (t (quote JUMPNIL))) lab))) (t (progn (setq a (list (cond (neg ( quote JUMPFLAGP)) (t (quote JUMPNFLAGP))) b b)) (s!:record_literal_for_jump a env lab)))))) (t (progn (setq sw (s!:load2 a b env)) (cond (sw ( s!:outopcode0 (quote SWOP) (quote (SWOP))))) (s!:outopcode0 (quote FLAGP) ( quote (FLAGP))) (s!:outjump (cond (neg (quote JUMPT)) (t (quote JUMPNIL))) lab)))))) (put (quote flagp) (quote s!:testfn) (function s!:testflagp)) (global (quote (s!:storelocs))) (setq s!:storelocs (s!:vecof (quote (STORELOC0 STORELOC1 STORELOC2 STORELOC3 STORELOC4 STORELOC5 STORELOC6 STORELOC7)))) (de s!:comsetq (x env context) (prog (n w var) (setq x (cdr x)) (cond ((null x) (return nil))) (cond ((or (not (symbolp (car x))) (null (cdr x))) (return (error 0 (list "bad args for setq" x))))) (s!:comval (cadr x) env 1) (setq var (car x)) (setq n 0) (setq w (cdr env)) (prog nil lab1143 (cond ((null ( and w (not (eqcar w var)))) (return nil))) (progn (setq n (add1 n)) (setq w ( cdr w))) (go lab1143)) (cond (w (progn (cond ((not (member!*!* (cons (quote loc) w) s!:a_reg_values)) (setq s!:a_reg_values (cons (cons (quote loc) w) s!:a_reg_values)))) (cond ((lessp n 8) (s!:outopcode0 (getv s!:storelocs n) ( list (quote storeloc) var))) (t (cond ((greaterp n 4095) (error 0 "stack frame > 4095")) (t (cond ((greaterp n 255) (s!:outopcode2 (quote BIGSTACK) (plus 64 (truncate n 256)) (logand n 255) (list (quote STORELOC) var))) (t (s!:outopcode1 (quote STORELOC) n var))))))))) (t (cond ((setq w ( s!:find_lexical var s!:lexical_env 0)) (progn (cond ((not (member!*!* (cons ( quote lex) w) s!:a_reg_values)) (setq s!:a_reg_values (cons (cons (quote lex) w) s!:a_reg_values)))) (s!:outlexref (quote STORELEX) (length (cdr env)) ( car w) (cadr w) var))) (t (progn (cond ((or (null var) (eq var t)) (error 0 ( list "bad variable in setq" var))) (t (s!:should_be_fluid var))) (setq w ( cons (quote free) var)) (cond ((not (member!*!* w s!:a_reg_values)) (setq s!:a_reg_values (cons w s!:a_reg_values)))) (s!:outopcode1lit (quote STOREFREE) var env)))))) (cond ((cddr x) (return (s!:comsetq (cdr x) env context)))))) (put (quote setq) (quote s!:compfn) (function s!:comsetq)) (put (quote noisy!-setq) (quote s!:compfn) (function s!:comsetq)) (de s!:comlist (x env context) (prog (w) (cond ((null (setq x (cdr x))) ( return (s!:comval nil env context)))) (setq s!:a_reg_values nil) (cond ((null (setq w (cdr x))) (s!:comval (list (quote ncons) (car x)) env context)) (t ( cond ((null (setq w (cdr w))) (s!:comval (list (quote list2) (car x) (cadr x) ) env context)) (t (cond ((null (cdr w)) (s!:comval (list (quote list3) (car x) (cadr x) (car w)) env context)) (t (s!:comval (list (quote list2!*) (car x ) (cadr x) (cons (quote list) w)) env context))))))))) (put (quote list) (quote s!:compfn) (function s!:comlist)) (de s!:comlist!* (x env context) (prog (w) (cond ((null (setq x (cdr x))) ( return (s!:comval nil env context)))) (setq s!:a_reg_values nil) (cond ((null (setq w (cdr x))) (s!:comval (car x) env context)) (t (cond ((null (setq w ( cdr w))) (s!:comval (list (quote cons) (car x) (cadr x)) env context)) (t ( cond ((null (cdr w)) (s!:comval (list (quote list2!*) (car x) (cadr x) (car w )) env context)) (t (s!:comval (list (quote list2!*) (car x) (cadr x) (cons ( quote list!*) w)) env context))))))))) (put (quote list!*) (quote s!:compfn) (function s!:comlist!*)) (de s!:comcons (x env context) (prog (a b) (setq a (cadr x)) (setq b (caddr x )) (cond ((or (equal b nil) (equal b (quote (quote nil)))) (s!:comval (list ( quote ncons) a) env context)) (t (cond ((eqcar a (quote cons)) (s!:comval ( list (quote acons) (cadr a) (caddr a) b) env context)) (t (cond ((eqcar b ( quote cons)) (cond ((null (caddr b)) (s!:comval (list (quote list2) a (cadr b )) env context)) (t (s!:comval (list (quote list2!*) a (cadr b) (caddr b)) env context)))) (t (cond ((and (not !*ord) (s!:iseasy a) (not (s!:iseasy b))) (s!:comval (list (quote xcons) b a) env context)) (t (s!:comcall x env context))))))))))) (put (quote cons) (quote s!:compfn) (function s!:comcons)) (de s!:comapply (x env context) (prog (a b n) (setq a (cadr x)) (setq b ( caddr x)) (cond ((and (null (cdddr x)) (eqcar b (quote list))) (progn (cond ( (eqcar a (quote quote)) (return (progn (setq n s!:current_function) (prog ( s!:current_function) (setq s!:current_function (compress (append (explode n) (cons (quote !!) (cons (quote !.) (explodec (setq s!:current_count (plus s!:current_count 1)))))))) (return (s!:comval (cons (cadr a) (cdr b)) env context))))))) (setq n (length (setq b (cdr b)))) (return (s!:comval (cons ( quote funcall) (cons a b)) env context)))) (t (cond ((and (null b) (null ( cdddr x))) (return (s!:comval (list (quote funcall) a) env context))) (t ( return (s!:comcall x env context)))))))) (put (quote apply) (quote s!:compfn) (function s!:comapply)) (de s!:imp_funcall (u) (prog (n) (setq u (cdr u)) (cond ((eqcar (car u) ( quote function)) (return (s!:improve (cons (cadar u) (cdr u)))))) (setq n ( length (cdr u))) (setq u (cond ((equal n 0) (cons (quote apply0) u)) (t (cond ((equal n 1) (cons (quote apply1) u)) (t (cond ((equal n 2) (cons (quote apply2) u)) (t (cond ((equal n 3) (cons (quote apply3) u)) (t (cons (quote funcall!*) u)))))))))) (return u))) (put (quote funcall) (quote s!:tidy_fn) (quote s!:imp_funcall)) (de s!:eval_to_eq_safe (x) (or (equal x nil) (equal x t) (and (not (symbolp x )) (eq!-safe x)) (and (not (atom x)) (flagp (car x) (quote eq!-safe))) (and ( eqcar x (quote quote)) (or (symbolp (cadr x)) (eq!-safe (cadr x)))))) (de s!:eval_to_eq_unsafe (x) (or (and (atom x) (not (symbolp x)) (not ( eq!-safe x))) (and (not (atom x)) (flagp (car x) (quote eq!-unsafe))) (and ( eqcar x (quote quote)) (or (not (atom (cadr x))) (and (not (symbolp (cadr x)) ) (not (eq!-safe (cadr x)))))))) (de s!:list_all_eq_safe (u) (or (atom u) (and (or (symbolp (car u)) (eq!-safe (car u))) (s!:list_all_eq_safe (cdr u))))) (de s!:eval_to_list_all_eq_safe (x) (or (null x) (and (eqcar x (quote quote)) (s!:list_all_eq_safe (cadr x))) (and (eqcar x (quote list)) (or (null (cdr x )) (and (s!:eval_to_eq_safe (cadr x)) (s!:eval_to_list_all_eq_safe (cons ( quote list) (cddr x)))))) (and (eqcar x (quote cons)) (s!:eval_to_eq_safe ( cadr x)) (s!:eval_to_list_all_eq_safe (caddr x))))) (de s!:list_some_eq_unsafe (u) (and (not (atom u)) (or (s!:eval_to_eq_unsafe (car u)) (s!:list_some_eq_unsafe (cdr u))))) (de s!:eval_to_list_some_eq_unsafe (x) (cond ((atom x) nil) (t (cond ((eqcar x (quote quote)) (s!:list_some_eq_unsafe (cadr x))) (t (cond ((and (eqcar x ( quote list)) (cdr x)) (or (s!:eval_to_eq_unsafe (cadr x)) ( s!:eval_to_list_some_eq_unsafe (cons (quote list) (cddr x))))) (t (cond (( eqcar x (quote cons)) (or (s!:eval_to_eq_unsafe (cadr x)) ( s!:eval_to_list_some_eq_unsafe (caddr x)))) (t nil))))))))) (de s!:eval_to_car_eq_safe (x) (and (or (eqcar x (quote cons)) (eqcar x ( quote list))) (not (null (cdr x))) (s!:eval_to_eq_safe (cadr x)))) (de s!:eval_to_car_eq_unsafe (x) (and (or (eqcar x (quote cons)) (eqcar x ( quote list))) (not (null (cdr x))) (s!:eval_to_eq_unsafe (cadr x)))) (de s!:alist_eq_safe (u) (or (atom u) (and (not (atom (car u))) (or (symbolp (caar u)) (eq!-safe (caar u))) (s!:alist_eq_safe (cdr u))))) (de s!:eval_to_alist_eq_safe (x) (or (null x) (and (eqcar x (quote quote)) ( s!:alist_eq_safe (cadr x))) (and (eqcar x (quote list)) (or (null (cdr x)) ( and (s!:eval_to_car_eq_safe (cadr x)) (s!:eval_to_alist_eq_safe (cons (quote list) (cddr x)))))) (and (eqcar x (quote cons)) (s!:eval_to_car_eq_safe (cadr x)) (s!:eval_to_alist_eq_safe (caddr x))))) (de s!:alist_eq_unsafe (u) (and (not (atom u)) (not (atom (car u))) (or (not (atom (caar u))) (and (not (symbolp (caar u))) (not (eq!-safe (caar u)))) ( s!:alist_eq_unsafe (cdr u))))) (de s!:eval_to_alist_eq_unsafe (x) (cond ((null x) nil) (t (cond ((eqcar x ( quote quote)) (s!:alist_eq_unsafe (cadr x))) (t (cond ((eqcar x (quote list)) (and (cdr x) (or (s!:eval_to_car_eq_unsafe (cadr x)) ( s!:eval_to_alist_eq_unsafe (cons (quote list) (cddr x)))))) (t (cond ((eqcar x (quote cons)) (or (s!:eval_to_car_eq_unsafe (cadr x)) ( s!:eval_to_alist_eq_safe (caddr x)))) (t nil))))))))) (flag (quote (eq eqcar null not greaterp lessp geq leq minusp atom numberp consp)) (quote eq!-safe)) (cond ((not (eq!-safe 1)) (flag (quote (length plus minus difference times quotient plus2 times2 expt fix float)) (quote eq!-unsafe)))) (de s!:comequal (x env context) (cond ((or (s!:eval_to_eq_safe (cadr x)) ( s!:eval_to_eq_safe (caddr x))) (s!:comcall (cons (quote eq) (cdr x)) env context)) (t (s!:comcall x env context)))) (put (quote equal) (quote s!:compfn) (function s!:comequal)) (de s!:comeq (x env context) (cond ((or (s!:eval_to_eq_unsafe (cadr x)) ( s!:eval_to_eq_unsafe (caddr x))) (progn (cond ((neq (posn) 0) (terpri))) ( princ "++++ EQ on number upgraded to EQUAL in ") (prin s!:current_function) ( princ " : ") (prin (cadr x)) (princ " ") (print (caddr x)) (s!:comcall (cons (quote equal) (cdr x)) env context))) (t (s!:comcall x env context)))) (put (quote eq) (quote s!:compfn) (function s!:comeq)) (de s!:comeqcar (x env context) (cond ((s!:eval_to_eq_unsafe (caddr x)) ( progn (cond ((neq (posn) 0) (terpri))) (princ "++++ EQCAR on number upgraded to EQUALCAR in ") (prin s!:current_function) ( princ " : ") (prin (caddr x)) (s!:comcall (cons (quote equalcar) (cdr x)) env context))) (t (s!:comcall x env context)))) (put (quote eqcar) (quote s!:compfn) (function s!:comeqcar)) (de s!:comsublis (x env context) (cond ((s!:eval_to_alist_eq_safe (cadr x)) ( s!:comval (cons (quote subla) (cdr x)) env context)) (t (s!:comcall x env context)))) (put (quote sublis) (quote s!:compfn) (function s!:comsublis)) (de s!:comsubla (x env context) (cond ((s!:eval_to_alist_eq_unsafe (cadr x)) (progn (cond ((neq (posn) 0) (terpri))) (princ "++++ SUBLA on number upgraded to SUBLIS in ") (prin s!:current_function) ( princ " : ") (print (cadr x)) (s!:comval (cons (quote sublis) (cdr x)) env context))) (t (s!:comcall x env context)))) (put (quote subla) (quote s!:compfn) (function s!:comsubla)) (de s!:comassoc (x env context) (cond ((and (or (s!:eval_to_eq_safe (cadr x)) (s!:eval_to_alist_eq_safe (caddr x))) (equal (length x) 3)) (s!:comval (cons (quote atsoc) (cdr x)) env context)) (t (cond ((equal (length x) 3) ( s!:comcall (cons (quote assoc!*!*) (cdr x)) env context)) (t (s!:comcall x env context)))))) (put (quote assoc) (quote s!:compfn) (function s!:comassoc)) (put (quote assoc!*!*) (quote s!:compfn) (function s!:comassoc)) (de s!:comatsoc (x env context) (cond ((or (s!:eval_to_eq_unsafe (cadr x)) ( s!:eval_to_alist_eq_unsafe (caddr x))) (progn (cond ((neq (posn) 0) (terpri)) ) (princ "++++ ATSOC on number upgraded to ASSOC in ") (prin s!:current_function) (princ " : ") (prin (cadr x)) (princ " ") (print (caddr x)) (s!:comval (cons (quote assoc) (cdr x)) env context))) (t (s!:comcall x env context)))) (put (quote atsoc) (quote s!:compfn) (function s!:comatsoc)) (de s!:commember (x env context) (cond ((and (or (s!:eval_to_eq_safe (cadr x) ) (s!:eval_to_list_all_eq_safe (caddr x))) (equal (length x) 3)) (s!:comval ( cons (quote memq) (cdr x)) env context)) (t (s!:comcall x env context)))) (put (quote member) (quote s!:compfn) (function s!:commember)) (put (quote member!*!*) (quote s!:compfn) (function s!:commember)) (de s!:commemq (x env context) (cond ((or (s!:eval_to_eq_unsafe (cadr x)) ( s!:eval_to_list_some_eq_unsafe (caddr x))) (progn (cond ((neq (posn) 0) ( terpri))) (princ "++++ MEMQ on number upgraded to MEMBER in ") (prin s!:current_function) (princ " : ") (prin (cadr x)) (princ " ") (print (caddr x)) (s!:comval (cons (quote member) (cdr x)) env context))) (t (s!:comcall x env context)))) (put (quote memq) (quote s!:compfn) (function s!:commemq)) (de s!:comdelete (x env context) (cond ((and (or (s!:eval_to_eq_safe (cadr x) ) (s!:eval_to_list_all_eq_safe (caddr x))) (equal (length x) 3)) (s!:comval ( cons (quote deleq) (cdr x)) env context)) (t (s!:comcall x env context)))) (put (quote delete) (quote s!:compfn) (function s!:comdelete)) (de s!:comdeleq (x env context) (cond ((or (s!:eval_to_eq_unsafe (cadr x)) ( s!:eval_to_list_some_eq_unsafe (caddr x))) (progn (cond ((neq (posn) 0) ( terpri))) (princ "++++ DELEQ on number upgraded to DELETE in ") (prin s!:current_function) (princ " : ") (prin (cadr x)) (princ " ") (print (caddr x)) (s!:comval (cons (quote delete) (cdr x)) env context))) (t (s!:comcall x env context)))) (put (quote deleq) (quote s!:compfn) (function s!:comdeleq)) (de s!:commap (fnargs env context) (prog (carp fn fn1 args var avar moveon l1 r s closed) (setq fn (car fnargs)) (cond ((greaterp context 1) (progn (cond ((equal fn (quote mapcar)) (setq fn (quote mapc))) (t (cond ((equal fn (quote maplist)) (setq fn (quote map))))))))) (cond ((or (equal fn (quote mapc)) ( equal fn (quote mapcar)) (equal fn (quote mapcan))) (setq carp t))) (setq fnargs (cdr fnargs)) (cond ((atom fnargs) (error 0 "bad arguments to map function"))) (setq fn1 (cadr fnargs)) (prog nil lab1144 (cond ((null (or (eqcar fn1 (quote function)) (and (eqcar fn1 (quote quote)) (eqcar (cadr fn1) (quote lambda))))) (return nil))) (progn (setq fn1 (cadr fn1)) (setq closed t)) (go lab1144)) (setq args (car fnargs)) (setq l1 ( gensym)) (setq r (gensym)) (setq s (gensym)) (setq var (gensym)) (setq avar var) (cond (carp (setq avar (list (quote car) avar)))) (cond (closed (setq fn1 (list fn1 avar))) (t (setq fn1 (list (quote funcall) fn1 avar)))) (setq moveon (list (quote setq) var (list (quote cdr) var))) (cond ((or (equal fn ( quote map)) (equal fn (quote mapc))) (setq fn (sublis (list (cons (quote l1) l1) (cons (quote var) var) (cons (quote fn) fn1) (cons (quote args) args) ( cons (quote moveon) moveon)) (quote (prog (var) (setq var args) l1 (cond (( not var) (return nil))) fn moveon (go l1)))))) (t (cond ((or (equal fn (quote maplist)) (equal fn (quote mapcar))) (setq fn (sublis (list (cons (quote l1) l1) (cons (quote var) var) (cons (quote fn) fn1) (cons (quote args) args) ( cons (quote moveon) moveon) (cons (quote r) r)) (quote (prog (var r) (setq var args) l1 (cond ((not var) (return (reversip r)))) (setq r (cons fn r)) moveon (go l1)))))) (t (setq fn (sublis (list (cons (quote l1) l1) (cons ( quote l2) (gensym)) (cons (quote var) var) (cons (quote fn) fn1) (cons (quote args) args) (cons (quote moveon) moveon) (cons (quote r) (gensym)) (cons ( quote s) (gensym))) (quote (prog (var r s) (setq var args) (setq r (setq s ( list nil))) l1 (cond ((not var) (return (cdr r)))) (rplacd s fn) l2 (cond (( not (atom (cdr s))) (setq s (cdr s)) (go l2))) moveon (go l1))))))))) ( s!:comval fn env context))) (put (quote map) (quote s!:compfn) (function s!:commap)) (put (quote maplist) (quote s!:compfn) (function s!:commap)) (put (quote mapc) (quote s!:compfn) (function s!:commap)) (put (quote mapcar) (quote s!:compfn) (function s!:commap)) (put (quote mapcon) (quote s!:compfn) (function s!:commap)) (put (quote mapcan) (quote s!:compfn) (function s!:commap)) (de s!:nilargs (use) (cond ((null use) t) (t (cond ((or (equal (car use) ( quote nil)) (equal (car use) (quote (quote nil)))) (s!:nilargs (cdr use))) (t nil))))) (de s!:subargs (args use) (cond ((null use) t) (t (cond ((null args) ( s!:nilargs use)) (t (cond ((not (equal (car args) (car use))) nil) (t ( s!:subargs (cdr args) (cdr use))))))))) (fluid (quote (!*where_defined!*))) (de clear_source_database nil (progn (setq !*where_defined!* (mkhash 10 2 1.5 )) nil)) (de load_source_database (filename) (prog (a b) (clear_source_database) (setq a (open filename (quote input))) (cond ((null a) (return nil))) (setq a (rds a)) (prog nil lab1145 (cond ((null (setq b (read))) (return nil))) (puthash (car b) !*where_defined!* (cdr b)) (go lab1145)) (close (rds a)) (return nil) )) (de save_source_database (filename) (prog (a) (setq a (open filename (quote output))) (cond ((null a) (return nil))) (setq a (wrs a)) (prog (var1147) ( setq var1147 (sort (hashcontents !*where_defined!*) (function orderp))) lab1146 (cond ((null var1147) (return nil))) (prog (z) (setq z (car var1147)) (progn (prin z) (terpri))) (setq var1147 (cdr var1147)) (go lab1146)) (princ nil) (terpri) (wrs a) (setq !*where_defined!* nil) (return nil))) (de display_source_database nil (prog (w) (cond ((null !*where_defined!*) ( return nil))) (setq w (hashcontents !*where_defined!*)) (setq w (sort w ( function orderp))) (terpri) (prog (var1149) (setq var1149 w) lab1148 (cond (( null var1149) (return nil))) (prog (x) (setq x (car var1149)) (progn (princ ( car x)) (ttab 40) (prin (cdr x)) (terpri))) (setq var1149 (cdr var1149)) (go lab1148)))) (fluid (quote (s!:r2i_simple_recurse s!:r2i_cons_recurse))) (de s!:r2i (name args body) (prog (lab v b1 s!:r2i_simple_recurse s!:r2i_cons_recurse) (setq lab (gensym)) (setq v (list (gensym))) (setq b1 ( s!:r2i1 name args body lab v)) (cond (s!:r2i_cons_recurse (progn (setq b1 ( list (quote prog) v lab b1)) (return b1))) (t (cond (s!:r2i_simple_recurse ( progn (setq v (list (gensym))) (setq b1 (s!:r2i2 name args body lab v)) (setq b1 (list (quote prog) (cdr v) lab b1)) (return b1))) (t (return (s!:r2i3 name args body lab v)))))))) (de s!:r2i1 (name args body lab v) (cond ((or (null body) (equal body (quote (progn)))) (list (quote return) (list (quote nreverse) (car v)))) (t (cond (( and (eqcar body name) (equal (length (cdr body)) (length args))) (progn (setq s!:r2i_simple_recurse t) (cons (quote progn) (append (s!:r2isteps args (cdr body) v) (list (list (quote go) lab)))))) (t (cond ((eqcar body (quote cond)) (cons (quote cond) (s!:r2icond name args (cdr body) lab v))) (t (cond (( eqcar body (quote if)) (cons (quote if) (s!:r2iif name args (cdr body) lab v) )) (t (cond ((eqcar body (quote when)) (cons (quote when) (s!:r2iwhen name args (cdr body) lab v))) (t (cond ((eqcar body (quote cons)) (s!:r2icons name args (cadr body) (caddr body) lab v)) (t (cond ((or (eqcar body (quote progn )) (eqcar body (quote prog2))) (cons (quote progn) (s!:r2iprogn name args ( cdr body) lab v))) (t (cond ((eqcar body (quote and)) (s!:r2i1 name args ( s!:r2iand (cdr body)) lab v)) (t (cond ((eqcar body (quote or)) (s!:r2i1 name args (s!:r2ior (cdr body)) lab v)) (t (list (quote return) (list (quote nreverse) (car v) body))))))))))))))))))))) (de s!:r2iand (l) (cond ((null l) t) (t (cond ((null (cdr l)) (car l)) (t ( list (quote cond) (list (car l) (s!:r2iand (cdr l))))))))) (de s!:r2ior (l) (cond ((null l) nil) (t (cons (quote cond) (prog (var1151 var1152) (setq var1151 l) lab1150 (cond ((null var1151) (return (reversip var1152)))) (prog (x) (setq x (car var1151)) (setq var1152 (cons (list x) var1152))) (setq var1151 (cdr var1151)) (go lab1150)))))) (de s!:r2icond (name args b lab v) (cond ((null b) (list (list t (list (quote return) (list (quote nreverse) (car v)))))) (t (cond ((null (cdar b)) (progn (cond ((null (cdr v)) (rplacd v (list (gensym))))) (cons (list (list (quote setq) (cadr v) (caar b)) (list (quote return) (list (quote nreverse) (car v) (cadr v)))) (s!:r2icond name args (cdr b) lab v)))) (t (cond ((eqcar (car b) t) (list (cons t (s!:r2iprogn name args (cdar b) lab v)))) (t (cons (cons ( caar b) (s!:r2iprogn name args (cdar b) lab v)) (s!:r2icond name args (cdr b) lab v))))))))) (de s!:r2iif (name args b lab v) (cond ((null (cddr b)) (list (car b) ( s!:r2i1 name args (cadr b) lab v))) (t (list (car b) (s!:r2i1 name args (cadr b) lab v) (s!:r2i1 name args (caddr b) lab v))))) (de s!:r2iwhen (name args b lab v) (cons (car b) (s!:r2iprogn name args (cdr b) lab v))) (de s!:r2iprogn (name args b lab v) (cond ((null (cdr b)) (list (s!:r2i1 name args (car b) lab v))) (t (cons (car b) (s!:r2iprogn name args (cdr b) lab v) )))) (de s!:r2icons (name args a d lab v) (cond ((eqcar d (quote cons)) ( s!:r2icons2 name args a (cadr d) (caddr d) lab v)) (t (cond ((and (eqcar d name) (equal (length (cdr d)) (length args))) (progn (setq s!:r2i_cons_recurse t) (cons (quote progn) (cons (list (quote setq) (car v) ( list (quote cons) a (car v))) (append (s!:r2isteps args (cdr d) v) (list ( list (quote go) lab))))))) (t (list (quote return) (list (quote nreverse) ( car v) (list (quote cons) a d)))))))) (de s!:r2icons2 (name args a ad dd lab v) (cond ((and (eqcar dd name) (equal (length (cdr dd)) (length args))) (progn (setq s!:r2i_cons_recurse t) (cons ( quote progn) (cons (list (quote setq) (car v) (list (quote cons) a (car v))) (cons (list (quote setq) (car v) (list (quote cons) ad (car v))) (append ( s!:r2isteps args (cdr dd) v) (list (list (quote go) lab)))))))) (t (list ( quote return) (list (quote nreverse) (car v) (list (quote cons) a (list ( quote cons) ad dd))))))) (de s!:r2isteps (vars vals v) (cond ((null vars) (cond ((null vals) nil) (t ( error 0 "too many args in recursive call to self")))) (t (cond ((null vals) ( error 0 "not enough args in recursive call to self")) (t (cond ((equal (car vars) (car vals)) (s!:r2isteps (cdr vars) (cdr vals) v)) (t (cond (( s!:r2i_safestep (car vars) (cdr vars) (cdr vals)) (cons (list (quote setq) ( car vars) (car vals)) (s!:r2isteps (cdr vars) (cdr vals) v))) (t (prog (w) ( cond ((null (cdr v)) (rplacd v (list (gensym))))) (setq v (cdr v)) (setq w ( s!:r2isteps (cdr vars) (cdr vals) v)) (return (cons (list (quote setq) (car v ) (car vals)) (append w (list (list (quote setq) (car vars) (car v))))))))))) ))))) (de s!:r2i_safestep (x vars vals) (cond ((and (null vars) (null vals)) t) (t (cond ((s!:r2i_dependson (car vals) x) nil) (t (s!:r2i_safestep x (cdr vars) (cdr vals))))))) (de s!:r2i_dependson (e x) (cond ((equal e x) t) (t (cond ((or (atom e) ( eqcar e (quote quote))) nil) (t (cond ((not (atom (car e))) t) (t (cond (( flagp (car e) (quote s!:r2i_safe)) (s!:r2i_list_dependson (cdr e) x)) (t ( cond ((or (fluidp x) (globalp x)) t) (t (cond ((or (flagp (car e) (quote s!:r2i_unsafe)) (macro!-function (car e))) t) (t (s!:r2i_list_dependson (cdr e) x)))))))))))))) (flag (quote (car cdr caar cadr cdar cddr caaar caadr cadar caddr cdaar cdadr cddar cdddr cons ncons rcons acons list list2 list3 list!* add1 sub1 plus plus2 times times2 difference minus quotient append reverse nreverse null not assoc atsoc member memq subst sublis subla pair prog1 prog2 progn)) (quote s!:r2i_safe)) (flag (quote (cond if when case de defun dm defmacro prog let let!* flet and or)) (quote s!:r2i_unsafe)) (de s!:r2i_list_dependson (l x) (cond ((null l) nil) (t (cond (( s!:r2i_dependson (car l) x) t) (t (s!:r2i_list_dependson (cdr l) x)))))) (de s!:r2i2 (name args body lab v) (cond ((or (null body) (equal body (quote (progn)))) (list (quote return) nil)) (t (cond ((and (eqcar body name) (equal (length (cdr body)) (length args))) (progn (cons (quote progn) (append ( s!:r2isteps args (cdr body) v) (list (list (quote go) lab)))))) (t (cond (( eqcar body (quote cond)) (cons (quote cond) (s!:r2i2cond name args (cdr body) lab v))) (t (cond ((eqcar body (quote if)) (cons (quote if) (s!:r2i2if name args (cdr body) lab v))) (t (cond ((eqcar body (quote when)) (cons (quote when) (s!:r2i2when name args (cdr body) lab v))) (t (cond ((or (eqcar body ( quote progn)) (eqcar body (quote prog2))) (cons (quote progn) (s!:r2i2progn name args (cdr body) lab v))) (t (cond ((eqcar body (quote and)) (s!:r2i2 name args (s!:r2iand (cdr body)) lab v)) (t (cond ((eqcar body (quote or)) ( s!:r2i2 name args (s!:r2ior (cdr body)) lab v)) (t (list (quote return) body) ))))))))))))))))) (de s!:r2i2cond (name args b lab v) (cond ((null b) (list (list t (list ( quote return) nil)))) (t (cond ((null (cdar b)) (progn (cond ((null (cdr v)) (rplacd v (list (gensym))))) (cons (list (list (quote setq) (cadr v) (caar b) ) (list (quote return) (cadr v))) (s!:r2i2cond name args (cdr b) lab v)))) (t (cond ((eqcar (car b) t) (list (cons t (s!:r2i2progn name args (cdar b) lab v)))) (t (cons (cons (caar b) (s!:r2i2progn name args (cdar b) lab v)) ( s!:r2i2cond name args (cdr b) lab v))))))))) (de s!:r2i2if (name args b lab v) (cond ((null (cddr b)) (list (car b) ( s!:r2i2 name args (cadr b) lab v))) (t (list (car b) (s!:r2i2 name args (cadr b) lab v) (s!:r2i2 name args (caddr b) lab v))))) (de s!:r2i2when (name args b lab v) (cons (car b) (s!:r2i2progn name args ( cdr b) lab v))) (de s!:r2i2progn (name args b lab v) (cond ((null (cdr b)) (list (s!:r2i2 name args (car b) lab v))) (t (cons (car b) (s!:r2i2progn name args (cdr b) lab v))))) (de s!:r2i3 (name args body lab v) (prog (v v1 v2 lab1 lab2 lab3 w P Q g R) ( cond ((s!:any_fluid args) (return body))) (cond ((eqcar body (quote cond)) ( progn (cond ((not (setq w (cdr body))) (return body))) (setq P (car w)) (setq w (cdr w)) (cond ((null P) (return body))) (setq Q (cdr P)) (setq P (car P)) (cond ((or (null Q) (cdr Q)) (return body))) (setq Q (car Q)) (cond ((or ( null w) (cdr w)) (return body))) (setq w (car w)) (cond ((not (eqcar w t)) ( return body))) (setq w (cdr w)) (cond ((or (not w) (cdr w)) (return body))) ( setq w (car w)))) (t (cond ((eqcar body (quote if)) (progn (setq w (cdr body) ) (setq P (car w)) (setq w (cdr w)) (setq Q (car w)) (setq w (cdr w)) (cond ( (null w) (return body))) (setq w (car w)))) (t (return body))))) (cond ((or ( atom w) (atom (cdr w)) (atom (cddr w)) (cdddr w)) (return body))) (setq g ( car w)) (setq R (cadr w)) (setq w (caddr w)) (cond ((not (atom g)) (return body))) (cond ((member g (quote (and or progn prog1 prog2 cond if when))) ( return body))) (cond ((not (eqcar w name)) (return body))) (setq w (cdr w)) ( cond ((not (equal (length w) (length args))) (return body))) (setq v1 (gensym )) (setq v2 (gensym)) (setq v (list v2)) (setq lab1 (gensym)) (setq lab2 ( gensym)) (setq lab3 (gensym)) (setq w (s!:r2isteps args w v)) (setq w (list ( quote prog) (cons v1 v) lab1 (list (quote cond) (list P (list (quote go) lab2 ))) (list (quote setq) v1 (list (quote cons) R v1)) (cons (quote progn) w) ( list (quote go) lab1) lab2 (list (quote setq) v2 Q) lab3 (list (quote cond) ( list (list (quote null) v1) (list (quote return) v2))) (list (quote setq) v2 (list g (list (quote car) v1) v2)) (list (quote setq) v1 (list (quote cdr) v1 )) (list (quote go) lab3))) (return w))) (de s!:any_fluid (l) (cond ((null l) nil) (t (cond ((fluidp (car l)) t) (t ( s!:any_fluid (cdr l))))))) (de s!:compile1 (name args body s!:lexical_env) (prog (w aargs oargs oinit restarg svars nargs nopts env fluids s!:current_function s!:current_label s!:current_block s!:current_size s!:current_procedure s!:current_exitlab s!:current_proglabels s!:other_defs local_decs s!:has_closure s!:local_macros s!:recent_literals s!:a_reg_values w1 w2 s!:current_count s!:env_alist s!:maybe_values checksum) (cond (s!:lexical_env (setq checksum 0)) (t (setq checksum (md60 (cons name (cons args body)))))) (setq s!:current_function name) (setq s!:current_count 0) (cond (!*where_defined!* (progn (setq w name) (puthash w !*where_defined!* (where!-was!-that))))) (setq body ( s!:find_local_decs body nil)) (setq local_decs (car body)) (setq body (cdr body)) (cond ((atom body) (setq body nil)) (t (cond ((null (cdr body)) (setq body (car body))) (t (setq body (cons (quote progn) body)))))) (setq nargs ( setq nopts 0)) (prog nil lab1153 (cond ((null (and args (not (eqcar args ( quote !&optional))) (not (eqcar args (quote !&rest))))) (return nil))) (progn (cond ((or (equal (car args) (quote !&key)) (equal (car args) (quote !&aux)) ) (error 0 "&key/&aux"))) (setq aargs (cons (car args) aargs)) (setq nargs ( plus nargs 1)) (setq args (cdr args))) (go lab1153)) (cond ((eqcar args ( quote !&optional)) (progn (setq args (cdr args)) (prog nil lab1155 (cond (( null (and args (not (eqcar args (quote !&rest))))) (return nil))) (progn ( cond ((or (equal (car args) (quote !&key)) (equal (car args) (quote !&aux))) (error 0 "&key/&aux"))) (setq w (car args)) (prog nil lab1154 (cond ((null ( and (not (atom w)) (or (atom (cdr w)) (equal (cdr w) (quote (nil)))))) ( return nil))) (setq w (car w)) (go lab1154)) (setq args (cdr args)) (setq oargs (cons w oargs)) (setq nopts (plus nopts 1)) (cond ((atom w) (setq aargs (cons w aargs))) (t (progn (setq oinit t) (setq aargs (cons (car w) aargs)) (cond ((not (atom (cddr w))) (setq svars (cons (caddr w) svars)))))))) (go lab1155))))) (cond ((eqcar args (quote !&rest)) (progn (setq w (cadr args)) ( setq aargs (cons w aargs)) (setq restarg w) (setq args (cddr args)) (cond ( args (error 0 "&rest arg not at end")))))) (setq args (reverse aargs)) (setq oargs (reverse oargs)) (prog (var1157) (setq var1157 (append svars args)) lab1156 (cond ((null var1157) (return nil))) (prog (v) (setq v (car var1157)) (progn (cond ((globalp v) (progn (cond (!*pwrds (progn (cond ((neq (posn) 0) (terpri))) (princ "+++++ global ") (prin v) (princ " converted to fluid") ( terpri)))) (unglobal (list v)) (fluid (list v))))))) (setq var1157 (cdr var1157)) (go lab1156)) (cond (oinit (return (s!:compile2 name nargs nopts args oargs restarg body local_decs checksum)))) (setq w nil) (prog (var1159) (setq var1159 args) lab1158 (cond ((null var1159) (return nil))) (prog (v) ( setq v (car var1159)) (setq w (s!:instate_local_decs v local_decs w))) (setq var1159 (cdr var1159)) (go lab1158)) (cond ((and !*r2i (null oargs) (null restarg)) (setq body (s!:r2i name args body)))) (prog (v) (setq v args) lab1160 (cond ((null v) (return nil))) (progn (cond ((fluidp (car v)) (prog ( g) (setq g (gensym)) (setq fluids (cons (cons (car v) g) fluids)) (rplaca v g ))))) (setq v (cdr v)) (go lab1160)) (cond (fluids (progn (setq body (list ( list (quote return) body))) (prog (var1162) (setq var1162 fluids) lab1161 ( cond ((null var1162) (return nil))) (prog (v) (setq v (car var1162)) (setq body (cons (list (quote setq) (car v) (cdr v)) body))) (setq var1162 (cdr var1162)) (go lab1161)) (setq body (cons (quote prog) (cons (prog (var1164 var1165) (setq var1164 fluids) lab1163 (cond ((null var1164) (return ( reversip var1165)))) (prog (v) (setq v (car var1164)) (setq var1165 (cons ( car v) var1165))) (setq var1164 (cdr var1164)) (go lab1163)) body)))))) (setq env (cons (mkhash 10 2 1.5) (reverse args))) (puthash name (car env) (cons 10000000 nil)) (setq w (s!:residual_local_decs local_decs w)) ( s!:start_procedure nargs nopts restarg) (setq w1 body) more (cond ((atom w1) nil) (t (cond ((and (equal (car w1) (quote block)) (equal (length w1) 3)) ( progn (setq w1 (caddr w1)) (go more))) (t (cond ((and (equal (car w1) (quote progn)) (equal (length w1) 2)) (progn (setq w1 (cadr w1)) (go more))) (t ( cond ((and (atom (setq w2 (car w1))) (setq w2 (get w2 (quote s!:newname)))) ( progn (setq w1 (cons w2 (cdr w1))) (go more))) (t (cond ((and (atom (setq w2 (car w1))) (setq w2 (macro!-function w2))) (progn (setq w1 (funcall w2 w1)) ( go more)))))))))))) (cond ((not (equal (setq w2 (s!:improve w1)) w1)) (progn (setq w1 w2) (go more)))) (cond ((and (not (atom w1)) (atom (car w1)) (not ( special!-form!-p (car w1))) (s!:subargs args (cdr w1)) (leq nargs 3) (equal nopts 0) (not restarg) (leq (length (cdr w1)) nargs)) (progn ( s!:cancel_local_decs w) (cond (restarg (setq nopts (plus nopts 512)))) (setq nopts (plus nopts (times 1024 (length w1)))) (setq nargs (plus nargs (times 256 nopts))) (cond (!*pwrds (progn (cond ((neq (posn) 0) (terpri))) (princ "+++ ") (prin name) (princ " compiled as link to ") (princ (car w1)) (terpri) ))) (return (cons (cons name (cons nargs (cons nil (car w1)))) s!:other_defs) )))) (s!:comval body env 0) (s!:cancel_local_decs w) (cond (restarg (setq nopts (plus nopts 512)))) (setq nargs (plus nargs (times 256 nopts))) (return (cons (cons name (cons nargs (s!:endprocedure name env checksum))) s!:other_defs)))) (de s!:compile2 (name nargs nopts args oargs restarg body local_decs checksum ) (prog (fluids env penv g v init atend w) (prog (var1167) (setq var1167 args ) lab1166 (cond ((null var1167) (return nil))) (prog (v) (setq v (car var1167 )) (progn (setq env (cons 0 env)) (setq penv (cons env penv)))) (setq var1167 (cdr var1167)) (go lab1166)) (setq env (cons (mkhash 10 2 1.5) env)) ( puthash name (car env) (cons 10000000 nil)) (setq penv (reversip penv)) (cond (restarg (setq oargs (append oargs (quote (0)))))) (prog (i) (setq i 1) lab1168 (cond ((minusp (times 1 (difference nargs i))) (return nil))) (setq oargs (cons 0 oargs)) (setq i (plus i 1)) (go lab1168)) (s!:start_procedure nargs nopts restarg) (prog nil lab1169 (cond ((null args) (return nil))) ( progn (setq v (car args)) (setq init (car oargs)) (cond ((equal init 0) ( progn (setq w (s!:instate_local_decs v local_decs w)) (cond ((fluidp v) ( progn (setq g (gensym)) (rplaca (car penv) g) (s!:outopcode1lit (quote FREEBIND) (s!:vecof (list v)) env) (rplacd env (cons 3 (cons 0 (cons 0 (cdr env))))) (setq atend (cons (quote FREERSTR) atend)) (s!:comval (list (quote setq) v g) env 2))) (t (rplaca (car penv) v))))) (t (prog (ival sp l1 l2) ( cond ((not (atom init)) (progn (setq init (cdr init)) (setq ival (car init)) (cond ((not (atom (cdr init))) (setq sp (cadr init))))))) (setq l1 (gensym)) (setq g (gensym)) (rplaca (car penv) g) (cond ((and (null ival) (null sp)) ( s!:comval (list (quote setq) g (list (quote spid!-to!-nil) g)) env 1)) (t ( progn (s!:jumpif nil (list (quote is!-spid) g) env l1) (s!:comval (list ( quote setq) g ival) env 1) (cond (sp (progn (cond ((fluidp sp) (progn ( s!:outopcode1lit (quote FREEBIND) (s!:vecof (list sp)) env) (s!:outjump ( quote JUMP) (setq l2 (gensym))) (s!:set_label l1) (s!:outopcode1lit (quote FREEBIND) (s!:vecof (list sp)) env) (rplacd env (cons 3 (cons 0 (cons 0 (cdr env))))) (s!:comval (list (quote setq) sp t) env 1) (s!:set_label l2) (setq atend (cons (quote FREERSTR) atend)))) (t (progn (s!:outopcode0 (quote PUSHNIL) (quote (PUSHNIL))) (s!:outjump (quote JUMP) (setq l2 (gensym))) ( s!:set_label l1) (s!:loadliteral t env) (s!:outopcode0 (quote PUSH) (quote ( PUSH))) (s!:set_label l2) (rplacd env (cons sp (cdr env))) (setq atend (cons (quote LOSE) atend))))))) (t (s!:set_label l1)))))) (setq w ( s!:instate_local_decs v local_decs w)) (cond ((fluidp v) (progn ( s!:outopcode1lit (quote FREEBIND) (s!:vecof (list v)) env) (rplacd env (cons 3 (cons 0 (cons 0 (cdr env))))) (s!:comval (list (quote setq) v g) env 1) ( setq atend (cons (quote FREERSTR) atend)))) (t (rplaca (car penv) v)))))) ( setq args (cdr args)) (setq oargs (cdr oargs)) (setq penv (cdr penv))) (go lab1169)) (setq w (s!:residual_local_decs local_decs w)) (s!:comval body env 0) (prog nil lab1170 (cond ((null atend) (return nil))) (progn (s!:outopcode0 (car atend) (list (car atend))) (setq atend (cdr atend))) (go lab1170)) ( s!:cancel_local_decs w) (setq nopts (plus nopts 256)) (cond (restarg (setq nopts (plus nopts 512)))) (setq nargs (plus nargs (times 256 nopts))) (return (cons (cons name (cons nargs (s!:endprocedure name env checksum))) s!:other_defs)))) (de compile!-all nil (prog (var1172) (setq var1172 (oblist)) lab1171 (cond (( null var1172) (return nil))) (prog (x) (setq x (car var1172)) (prog (w) (setq w (getd x)) (cond ((and (or (eqcar w (quote expr)) (eqcar w (quote macro))) (eqcar (cdr w) (quote lambda))) (progn (princ "Compile: ") (prin x) (terpri) (errorset (list (quote compile) (mkquote (list x))) t t)))))) (setq var1172 ( cdr var1172)) (go lab1171))) (flag (quote (rds deflist flag fluid global remprop remflag unfluid unglobal dm defmacro carcheck faslend c_end)) (quote eval)) (flag (quote (rds)) (quote ignore)) (fluid (quote (!*backtrace))) (de s!:fasl_supervisor nil (prog (u w !*echo) top (setq u (errorset (quote ( read)) t !*backtrace)) (cond ((atom u) (return nil))) (setq u (car u)) (cond ((equal u !$eof!$) (return nil))) (cond ((not (atom u)) (setq u (macroexpand u)))) (cond ((atom u) (go top)) (t (cond ((eqcar u (quote faslend)) (return ( apply (quote faslend) nil))) (t (cond ((eqcar u (quote rdf)) (progn (setq w ( open (setq u (eval (cadr u))) (quote input))) (cond (w (progn (terpri) (princ "Reading file ") (prin u) (terpri) (setq w (rds w)) (s!:fasl_supervisor) ( princ "End of file ") (prin u) (terpri) (close (rds w)))) (t (progn (princ "Failed to open file ") (prin u) (terpri)))))) (t (s!:fslout0 u))))))) (go top))) (de s!:fslout0 (u) (s!:fslout1 u nil)) (de s!:fslout1 (u loadonly) (prog (w) (cond ((not (atom u)) (setq u ( macroexpand u)))) (cond ((atom u) (return nil)) (t (cond ((eqcar u (quote progn)) (progn (prog (var1174) (setq var1174 (cdr u)) lab1173 (cond ((null var1174) (return nil))) (prog (v) (setq v (car var1174)) (s!:fslout1 v loadonly)) (setq var1174 (cdr var1174)) (go lab1173)) (return nil))) (t (cond ((eqcar u (quote eval!-when)) (return (prog nil (setq w (cadr u)) (setq u ( cons (quote progn) (cddr u))) (cond ((and (memq (quote compile) w) (not loadonly)) (eval u))) (cond ((memq (quote load) w) (s!:fslout1 u t))) (return nil)))) (t (cond ((or (flagp (car u) (quote eval)) (and (equal (car u) ( quote setq)) (not (atom (caddr u))) (flagp (caaddr u) (quote eval)))) (cond ( (not loadonly) (errorset u t !*backtrace))))))))))) (cond ((eqcar u (quote rdf)) (prog nil (setq w (open (setq u (eval (cadr u))) (quote input))) (cond (w (progn (princ "Reading file ") (prin u) (terpri) (setq w (rds w)) ( s!:fasl_supervisor) (princ "End of file ") (prin u) (terpri) (close (rds w))) ) (t (progn (princ "Failed to open file ") (prin u) (terpri)))))) (t (cond ( !*nocompile (progn (cond ((and (not (eqcar u (quote faslend))) (not (eqcar u (quote carcheck)))) (write!-module u))))) (t (cond ((or (eqcar u (quote de)) (eqcar u (quote defun))) (progn (cond ((and !*native_code (not (memq (quote win64) lispsystem!*))) (progn (cond ((c!:valid_fndef (caddr u) (cdddr u)) ( prog (pending_functions u1) (c!:ccmpout1a u) (prog nil lab1175 (cond ((null pending_functions) (return nil))) (progn (setq u1 (car pending_functions)) ( setq pending_functions (cdr pending_functions)) (s!:fslout0 u1)) (go lab1175) ))) (t (progn (princ "+++ ") (prin (cadr u)) (printc " can not be compiled into native code"))))))) (setq u (cdr u)) (cond ((and ( setq w (get (car u) (quote c!-version))) (equal w (md60 (cons (car u) (cons ( cadr u) (s!:fully_macroexpand_list (cddr u))))))) (progn (princ "+++ ") (prin (car u)) (printc " not compiled (C version available)") (write!-module (list (quote restore!-c!-code) (mkquote (car u)))))) (t (cond ((flagp (car u) ( quote lose)) (progn (princ "+++ ") (prin (car u)) (printc " not compiled (LOSE flag)"))) (t (progn (cond ((setq w (get (car u) (quote c!-version))) (progn (princ "+++ ") (prin (car u)) (princ " reports C version with checksum ") (print w) (print "+++ differing from this version:") (setq w (cons (car u) (cons (cadr u) ( s!:fully_macroexpand_list (cddr u))))) (princ "::: ") (prettyprint w) (princ "+++ which has checksum ") (print (md60 w))))) (prog (var1177) (setq var1177 (s!:compile1 (car u) (cadr u) (cddr u) nil)) lab1176 (cond ((null var1177) ( return nil))) (prog (p) (setq p (car var1177)) (s!:fslout2 p u)) (setq var1177 (cdr var1177)) (go lab1176))))))))) (t (cond ((or (eqcar u (quote dm) ) (eqcar u (quote defmacro))) (prog (g) (setq g (hashtagged!-name (cadr u) ( cddr u))) (setq u (cdr u)) (cond ((flagp (car u) (quote lose)) (progn (princ "+++ ") (prin (car u)) (printc " not compiled (LOSE flag)") (return nil)))) ( setq w (cadr u)) (cond ((and w (null (cdr w))) (setq w (cons (car w) (cons ( quote !&optional) (cons (gensym) nil)))))) (prog (var1179) (setq var1179 ( s!:compile1 g w (cddr u) nil)) lab1178 (cond ((null var1179) (return nil))) ( prog (p) (setq p (car var1179)) (s!:fslout2 p u)) (setq var1179 (cdr var1179) ) (go lab1178)) (write!-module (list (quote dm) (car u) (quote (u !&optional e)) (list g (quote u) (quote e)))))) (t (cond ((eqcar u (quote putd)) (prog ( a1 a2 a3) (setq a1 (cadr u)) (setq a2 (caddr u)) (setq a3 (cadddr u)) (cond ( (and (eqcar a1 (quote quote)) (or (equal a2 (quote (quote expr))) (equal a2 ( quote (quote macro)))) (or (eqcar a3 (quote quote)) (eqcar a3 (quote function ))) (eqcar (cadr a3) (quote lambda))) (progn (setq a1 (cadr a1)) (setq a2 ( cadr a2)) (setq a3 (cadr a3)) (setq u (cons (cond ((equal a2 (quote expr)) ( quote de)) (t (quote dm))) (cons a1 (cdr a3)))) (s!:fslout1 u loadonly))) (t (write!-module u))))) (t (cond ((and (not (eqcar u (quote faslend))) (not ( eqcar u (quote carcheck)))) (write!-module u))))))))))))))) (de s!:fslout2 (p u) (prog (name nargs code env w) (setq name (car p)) (setq nargs (cadr p)) (setq code (caddr p)) (setq env (cdddr p)) (cond ((and !*savedef (equal name (car u))) (progn (define!-in!-module (minus 1)) ( write!-module (cons (quote lambda) (cons (cadr u) (s!:fully_macroexpand_list (cddr u)))))))) (setq w (irightshift nargs 18)) (setq nargs (logand nargs 262143)) (cond ((not (equal w 0)) (setq code (difference w 1)))) ( define!-in!-module nargs) (write!-module name) (write!-module code) ( write!-module env))) (remprop (quote faslend) (quote stat)) (de faslend nil (prog (copysrc copydest) (cond ((null s!:faslmod_name) ( return nil))) (princ "Completed FASL files for ") (print (car s!:faslmod_name )) (cond ((and !*native_code (not (memq (quote win64) lispsystem!*))) (prog ( cmnd w w1 obj deff) (setq w (C!-end1 nil)) (close C_file) (setq cmnd (append (explodec s!:native_file) (quote (!")))) (cond ((memq (quote win32) lispsystem!*) (setq obj "dll")) (t (setq obj "so"))) (setq obj (tmpnam obj)) (cond ((memq (quote win32) lispsystem!*) (prog (nn) (setq nn (car s!:faslmod_name)) (setq nn (list2string (prog (var1181 var1182) (setq var1181 (explodec nn)) lab1180 (cond ((null var1181) (return (reversip var1182)))) ( prog (c) (setq c (car var1181)) (setq var1182 (cons (cond ((equal c (quote !- )) (quote !_)) (t c)) var1182))) (setq var1181 (cdr var1181)) (go lab1180)))) (setq deff (tmpnam "def")) (setq w1 (open deff (quote output))) (setq w1 ( wrs w1)) (princ "LIBRARY ") (princ (car s!:faslmod_name)) (printc ".dll") ( printc "EXPORTS") (printc " init") (princ " ") (princ nn) (printc "_setup") ( printc "IMPORTS") (print!-imports) (close (wrs w1)) (setq cmnd (append ( explodec deff) (cons (quote ! ) cmnd)))))) (setq cmnd (append (explodec obj) (cons (quote ! ) cmnd))) (setq cmnd (append (explodec " -o ") cmnd)) (prog ( var1184) (setq var1184 (reverse (cdr (assoc (quote compiler!-command) lispsystem!*)))) lab1183 (cond ((null var1184) (return nil))) (prog (x) (setq x (car var1184)) (setq cmnd (append (explodec x) (cons (quote ! ) cmnd)))) ( setq var1184 (cdr var1184)) (go lab1183)) (setq cmnd (compress (cons (quote !") cmnd))) (print cmnd) (cond ((not (zerop (silent!-system cmnd))) (progn ( princ "+++ C compilation for ") (prin (car s!:faslmod_name)) (printc " failed"))) (t (progn (cond (!*strip_native (progn (setq cmnd (compress ( cons (quote !") (append (explodec "strip ") (append (explodec obj) (quote (!" ))))))) (print cmnd) (silent!-system cmnd)))) (setq copysrc obj) (setq copydest (list2string (append (explodec (car s!:faslmod_name)) (cons (quote !.) (explodec (cdr (assoc (quote linker) lispsystem!*))))))) (cond ((not !*save_native) (progn (delete!-file s!:native_file) (cond ((memq (quote win32 ) lispsystem!*) (delete!-file deff)))))) (write!-module (list (quote instate!-c!-code) (mkquote (car s!:faslmod_name)) (mkquote w))))))))) ( start!-module nil) (cond (copysrc (progn (copy!-native copysrc copydest) ( cond ((not !*save_native) (delete!-file copysrc)))))) (setq dfprint!* s!:dfprintsave) (setq !*defn nil) (setq !*comp (cdr s!:faslmod_name)) (setq s!:faslmod_name nil) (return nil))) (put (quote faslend) (quote stat) (quote endstat)) (de s!:file (s) (prog (r) (setq s (reverse (explodec s))) (prog nil lab1185 ( cond ((null (and s (not (or (eqcar s (quote !/)) (eqcar s (quote !\)))))) ( return nil))) (progn (setq r (cons (car s) r)) (setq s (cdr s))) (go lab1185) ) (return (list2string r)))) (de s!:trim!.c (s) (prog (r) (setq s (reverse (explodec s))) (cond ((eqcar s (quote c)) (progn (setq s (cdr s)) (cond ((eqcar s (quote !.)) (setq s (cdr s ))))))) (return (list2string (reverse s))))) (de s!:dir (s) (prog nil (setq s (reverse (explodec s))) (prog nil lab1186 ( cond ((null (and s (not (or (eqcar s (quote !/)) (eqcar s (quote !\)))))) ( return nil))) (setq s (cdr s)) (go lab1186)) (cond (s (setq s (cdr s)))) ( cond ((null s) (return ".")) (t (return (list2string (reverse s))))))) (de faslout (u) (prog nil (terpri) (princ "FASLOUT ") (prin u) (princ ": IN files; or type in expressions") (terpri) (princ "When all done, execute FASLEND;") (terpri) (cond ((not (atom u)) (setq u ( car u)))) (cond ((not (start!-module u)) (progn (cond ((neq (posn) 0) (terpri ))) (princ "+++ Failed to open FASL output file") (terpri) (return nil)))) ( cond ((and !*native_code (not (memq (quote win64) lispsystem!*))) (progn ( setq s!:native_file (tmpnam "c")) (c!:ccompilestart (s!:trim!.c (s!:file s!:native_file)) u (s!:dir s!:native_file) t)))) (setq s!:faslmod_name (cons u !*comp)) (setq s!:dfprintsave dfprint!*) (setq dfprint!* (quote s!:fslout0) ) (setq !*defn t) (setq !*comp nil) (cond ((getd (quote begin)) (return nil)) ) (s!:fasl_supervisor))) (put (quote faslout) (quote stat) (quote rlis)) (de s!:c_supervisor nil (prog (u w !*echo) top (setq u (errorset (quote (read )) t !*backtrace)) (cond ((atom u) (return nil))) (setq u (car u)) (cond (( equal u !$eof!$) (return nil))) (cond ((not (atom u)) (setq u (macroexpand u) ))) (cond ((atom u) (go top)) (t (cond ((eqcar u (quote c_end)) (return ( apply (quote c_end) nil))) (t (cond ((eqcar u (quote rdf)) (progn (setq w ( open (setq u (eval (cadr u))) (quote input))) (cond (w (progn (terpri) (princ "Reading file ") (prin u) (terpri) (setq w (rds w)) (s!:c_supervisor) (princ "End of file ") (prin u) (terpri) (close (rds w)))) (t (progn (princ "Failed to open file ") (prin u) (terpri)))))) (t (s!:cout0 u))))))) (go top) )) (de s!:cout0 (u) (s!:cout1 u nil)) (de s!:cout1 (u loadonly) (prog (s!:into_c) (setq s!:into_c t) (cond ((not ( atom u)) (setq u (macroexpand u)))) (cond ((atom u) (return nil)) (t (cond (( eqcar u (quote progn)) (progn (prog (var1188) (setq var1188 (cdr u)) lab1187 (cond ((null var1188) (return nil))) (prog (v) (setq v (car var1188)) ( s!:cout1 v loadonly)) (setq var1188 (cdr var1188)) (go lab1187)) (return nil) )) (t (cond ((eqcar u (quote eval!-when)) (return (prog (w) (setq w (cadr u)) (setq u (cons (quote progn) (cddr u))) (cond ((and (memq (quote compile) w) (not loadonly)) (eval u))) (cond ((memq (quote load) w) (s!:cout1 u t))) ( return nil)))) (t (cond ((or (flagp (car u) (quote eval)) (and (equal (car u) (quote setq)) (not (atom (caddr u))) (flagp (caaddr u) (quote eval)))) (cond ((not loadonly) (errorset u t !*backtrace))))))))))) (cond ((eqcar u (quote rdf)) (prog (w) (setq w (open (setq u (eval (cadr u))) (quote input))) (cond (w (progn (princ "Reading file ") (prin u) (terpri) (setq w (rds w)) ( s!:c_supervisor) (princ "End of file ") (prin u) (terpri) (close (rds w)))) ( t (progn (princ "Failed to open file ") (prin u) (terpri)))))) (t (cond ((or (eqcar u (quote de)) (eqcar u (quote defun))) (prog (w) (setq u (cdr u)) ( setq w (s!:compile1 (car u) (cadr u) (cddr u) nil)) (prog (var1190) (setq var1190 w) lab1189 (cond ((null var1190) (return nil))) (prog (p) (setq p ( car var1190)) (s!:cgen (car p) (cadr p) (caddr p) (cdddr p))) (setq var1190 ( cdr var1190)) (go lab1189)))) (t (cond ((or (eqcar u (quote dm)) (eqcar u ( quote defmacro))) (prog (w g) (setq g (hashtagged!-name (cadr u) (cddr u))) ( setq u (cdr u)) (setq w (cadr u)) (cond ((and w (null (cdr w))) (setq w (cons (car w) (cons (quote !&optional) (cons (gensym) nil)))))) (setq w ( s!:compile1 g w (cddr u) nil)) (prog (var1192) (setq var1192 w) lab1191 (cond ((null var1192) (return nil))) (prog (p) (setq p (car var1192)) (s!:cgen ( car p) (cadr p) (caddr p) (cdddr p))) (setq var1192 (cdr var1192)) (go lab1191)) (s!:cinit (list (quote dm) (car u) (quote (u !&optional e)) (list g (quote u) (quote e)))))) (t (cond ((eqcar u (quote putd)) (prog (a1 a2 a3) ( setq a1 (cadr u)) (setq a2 (caddr u)) (setq a3 (cadddr u)) (cond ((and (eqcar a1 (quote quote)) (or (equal a2 (quote (quote expr))) (equal a2 (quote ( quote macro)))) (or (eqcar a3 (quote quote)) (eqcar a3 (quote function))) ( eqcar (cadr a3) (quote lambda))) (progn (setq a1 (cadr a1)) (setq a2 (cadr a2 )) (setq a3 (cadr a3)) (setq u (cons (cond ((equal a2 (quote expr)) (quote de )) (t (quote dm))) (cons a1 (cdr a3)))) (s!:cout1 u loadonly))) (t (s!:cinit u))))) (t (cond ((and (not (eqcar u (quote c_end))) (not (eqcar u (quote carcheck)))) (s!:cinit u))))))))))))) (fluid (quote (s!:cmod_name))) (de c_end nil (prog nil (cond ((null s!:cmod_name) (return nil))) (s!:cend) ( setq dfprint!* s!:dfprintsave) (setq !*defn nil) (setq !*comp (cdr s!:cmod_name)) (setq s!:cmod_name nil) (return nil))) (put (quote c_end) (quote stat) (quote endstat)) (de c_out (u) (prog nil (terpri) (princ "C_OUT ") (prin u) (princ ": IN files; or type in expressions") (terpri) (princ "When all done, execute C_END;") (terpri) (cond ((not (atom u)) (setq u (car u)))) (cond ((null (s!:cstart u)) (progn (cond ((neq (posn) 0) (terpri))) ( princ "+++ Failed to open C output file") (terpri) (return nil)))) (setq s!:cmod_name (cons u !*comp)) (setq s!:dfprintsave dfprint!*) (setq dfprint!* (quote s!:cout0)) (setq !*defn t) (setq !*comp nil) (cond ((getd (quote begin)) (return nil))) (s!:c_supervisor))) (put (quote c_out) (quote stat) (quote rlis)) (de s!:compile!-file!* (fromfile !&optional tofile verbose !*pwrds) (prog ( !*comp w save) (cond ((null tofile) (setq tofile fromfile))) (cond (verbose ( progn (cond ((neq (posn) 0) (terpri))) (princ "+++ Compiling file ") (prin fromfile) (terpri) (setq save (verbos nil)) (verbos (ilogand save 4))))) ( cond ((not (start!-module tofile)) (progn (cond ((neq (posn) 0) (terpri))) ( princ "+++ Failed to open FASL output file") (terpri) (cond (save (verbos save))) (return nil)))) (setq w (open fromfile (quote input))) (cond (w ( progn (setq w (rds w)) (s!:fasl_supervisor) (close (rds w)))) (t (progn ( princ "Failed to open file ") (prin fromfile) (terpri)))) (cond (save (verbos save))) (start!-module nil) (cond (verbose (progn (cond ((neq (posn) 0) ( terpri))) (princ "+++ Compilation complete") (terpri)))) (return t))) (de compile!-file!* (fromfile !&optional tofile) (s!:compile!-file!* fromfile tofile t t)) (de compd (name type defn) (prog (g !*comp) (setq !*comp t) (cond ((eqcar defn (quote lambda)) (progn (setq g (dated!-name type)) ( symbol!-set!-definition g defn) (compile (list g)) (setq defn g)))) (put name type defn) (return name))) (de s!:compile0 (name) (prog (w args defn) (setq defn (getd name)) (cond (( and (eqcar defn (quote macro)) (eqcar (cdr defn) (quote lambda))) (prog ( !*comp lx vx bx) (setq lx (cdr defn)) (cond ((not (or (and (equal (length lx) 3) (not (atom (setq bx (caddr lx)))) (equal (cadr lx) (cdr bx))) (and (equal (length lx) 3) (not (atom (setq bx (caddr lx)))) (not (atom (cadr lx))) ( eqcar (cdadr lx) (quote !&optional)) (not (atom (setq bx (cdr bx)))) (equal ( caadr lx) (car bx)) (equal (cddadr lx) (cdr bx))))) (progn (setq w ( hashtagged!-name name defn)) (symbol!-set!-definition w (cdr defn)) ( s!:compile0 w) (cond ((equal 1 (length (cadr lx))) (symbol!-set!-env name ( list (quote (u !&optional env)) (list w (quote u))))) (t (symbol!-set!-env name (list (quote (u !&optional env)) (list w (quote u) (quote env))))))))))) (t (cond ((or (not (eqcar defn (quote expr))) (not (eqcar (cdr defn) (quote lambda)))) (progn (cond (!*pwrds (progn (cond ((neq (posn) 0) (terpri))) ( princ "+++ ") (prin name) (princ " not compilable") (terpri)))))) (t (progn ( setq args (cddr defn)) (setq defn (cdr args)) (setq args (car args)) (cond (( stringp args) (progn (cond (!*pwrds (progn (cond ((neq (posn) 0) (terpri))) ( princ "+++ ") (prin name) (princ " was already compiled") (terpri)))))) (t ( progn (cond (!*savedef (put name (quote !*savedef) (cons (quote lambda) (cons args (s!:fully_macroexpand_list defn)))))) (setq w (s!:compile1 name args defn nil)) (prog (var1194) (setq var1194 w) lab1193 (cond ((null var1194) ( return nil))) (prog (p) (setq p (car var1194)) (symbol!-set!-definition (car p) (cdr p))) (setq var1194 (cdr var1194)) (go lab1193)))))))))))) (de s!:fully_macroexpand_list (l) (cond ((atom l) l) (t (prog (var1196 var1197) (setq var1196 l) lab1195 (cond ((null var1196) (return (reversip var1197)))) (prog (u) (setq u (car var1196)) (setq var1197 (cons ( s!:fully_macroexpand u) var1197))) (setq var1196 (cdr var1196)) (go lab1195)) ))) (de s!:fully_macroexpand (x) (prog (helper) (cond ((or (atom x) (eqcar x ( quote quote))) (return x)) (t (cond ((eqcar (car x) (quote lambda)) (return ( cons (cons (quote lambda) (cons (cadar x) (s!:fully_macroexpand_list (cddar x )))) (s!:fully_macroexpand_list (cdr x))))) (t (cond ((setq helper (get (car x) (quote s!:newname))) (return (s!:fully_macroexpand (cons helper (cdr x)))) ) (t (cond ((setq helper (get (car x) (quote s!:expandfn))) (return (funcall helper x))) (t (cond ((setq helper (macro!-function (car x))) (return ( s!:fully_macroexpand (funcall helper x)))) (t (return (cons (car x) ( s!:fully_macroexpand_list (cdr x)))))))))))))))) (de s!:expandfunction (u) u) (de s!:expandflet (u) (cons (car u) (cons (prog (var1199 var1200) (setq var1199 (cadr u)) lab1198 (cond ((null var1199) (return (reversip var1200)))) (prog (b) (setq b (car var1199)) (setq var1200 (cons (s!:expandfletvars b) var1200))) (setq var1199 (cdr var1199)) (go lab1198)) ( s!:fully_macroexpand_list (cddr u))))) (de s!:expandfletvars (b) (cons (car b) (cons (cadr b) ( s!:fully_macroexpand_list (cddr b))))) (de s!:expandlabels (u) (s!:expandflet u)) (de s!:expandmacrolet (u) (s!:expandflet u)) (de s!:expandprog (u) (cons (car u) (cons (cadr u) (s!:fully_macroexpand_list (cddr u))))) (de s!:expandtagbody (u) (s!:fully_macroexpand_list u)) (de s!:expandprogv (u) (cons (car u) (cons (cadr u) (cons (caddr u) ( s!:fully_macroexpand_list (cadddr u)))))) (de s!:expandblock (u) (cons (car u) (cons (cadr u) ( s!:fully_macroexpand_list (cddr u))))) (de s!:expanddeclare (u) u) (de s!:expandlet (u) (cons (car u) (cons (prog (var1202 var1203) (setq var1202 (cadr u)) lab1201 (cond ((null var1202) (return (reversip var1203)))) (prog (x) (setq x (car var1202)) (setq var1203 (cons ( s!:fully_macroexpand_list x) var1203))) (setq var1202 (cdr var1202)) (go lab1201)) (s!:fully_macroexpand_list (cddr u))))) (de s!:expandlet!* (u) (s!:expandlet u)) (de s!:expandgo (u) u) (de s!:expandreturn!-from (u) (cons (car u) (cons (cadr u) ( s!:fully_macroexpand_list (cddr u))))) (de s!:expandcond (u) (cons (car u) (prog (var1205 var1206) (setq var1205 ( cdr u)) lab1204 (cond ((null var1205) (return (reversip var1206)))) (prog (x) (setq x (car var1205)) (setq var1206 (cons (s!:fully_macroexpand_list x) var1206))) (setq var1205 (cdr var1205)) (go lab1204)))) (de s!:expandcase (u) (cons (car u) (cons (s!:fully_macroexpand (cadr u)) ( prog (var1208 var1209) (setq var1208 (cddr u)) lab1207 (cond ((null var1208) (return (reversip var1209)))) (prog (x) (setq x (car var1208)) (setq var1209 (cons (cons (car x) (s!:fully_macroexpand_list (cdr x))) var1209))) (setq var1208 (cdr var1208)) (go lab1207))))) (de s!:expandeval!-when (u) (cons (car u) (cons (cadr u) ( s!:fully_macroexpand_list (cddr u))))) (de s!:expandthe (u) (cons (car u) (cons (cadr u) (s!:fully_macroexpand_list (cddr u))))) (de s!:expandmv!-call (u) (cons (car u) (cons (cadr u) ( s!:fully_macroexpand_list (cddr u))))) (put (quote function) (quote s!:expandfn) (function s!:expandfunction)) (put (quote flet) (quote s!:expandfn) (function s!:expandflet)) (put (quote labels) (quote s!:expandfn) (function s!:expandlabels)) (put (quote macrolet) (quote s!:expandfn) (function s!:expandmacrolet)) (put (quote prog) (quote s!:expandfn) (function s!:expandprog)) (put (quote tagbody) (quote s!:expandfn) (function s!:expandtagbody)) (put (quote progv) (quote s!:expandfn) (function s!:expandprogv)) (put (quote !~block) (quote s!:expandfn) (function s!:expandblock)) (put (quote declare) (quote s!:expandfn) (function s!:expanddeclare)) (put (quote !~let) (quote s!:expandfn) (function s!:expandlet)) (put (quote let!*) (quote s!:expandfn) (function s!:expandlet!*)) (put (quote go) (quote s!:expandfn) (function s!:expandgo)) (put (quote return!-from) (quote s!:expandfn) (function s!:expandreturn!-from )) (put (quote cond) (quote s!:expandfn) (function s!:expandcond)) (put (quote case) (quote s!:expandfn) (function s!:expandcase)) (put (quote eval!-when) (quote s!:expandfn) (function s!:expandeval!-when)) (put (quote the) (quote s!:expandfn) (function s!:expandthe)) (put (quote multiple!-value!-call) (quote s!:expandfn) (function s!:expandmv!-call)) (de compile (l) (prog nil (cond ((and (atom l) (not (null l))) (setq l (list l)))) (prog (var1211) (setq var1211 l) lab1210 (cond ((null var1211) (return nil))) (prog (name) (setq name (car var1211)) (errorset (list (quote s!:compile0) (mkquote name)) t t)) (setq var1211 (cdr var1211)) (go lab1210)) (return l))) (global (quote (!*fastvector !*unsafecar))) (flag (quote (fastvector unsafecar)) (quote switch)) (fluid (quote (C_file L_file O_file L_contents Setup_name File_name))) (dm c!:printf (u !&optional env) (list (quote c!:printf1) (cadr u) (cons ( quote list) (cddr u)))) (de c!:printf1 (fmt args) (prog (a c) (setq fmt (explode2 fmt)) (prog nil lab1212 (cond ((null fmt) (return nil))) (progn (setq c (car fmt)) (setq fmt (cdr fmt)) (cond ((and (equal c (quote !\)) (or (equal (car fmt) (quote !n)) (equal (car fmt) (quote !N)))) (progn (terpri) (setq fmt (cdr fmt)))) (t ( cond ((and (equal c (quote !\)) (or (equal (car fmt) (quote !q)) (equal (car fmt) (quote !Q)))) (progn (princ (quote !")) (setq fmt (cdr fmt)))) (t (cond ((equal c (quote !%)) (progn (setq c (car fmt)) (cond ((null args) (setq a ( quote missing_arg))) (t (setq a (car args)))) (cond ((or (equal c (quote !v)) (equal c (quote !V))) (cond ((flagp a (quote c!:live_across_call)) (progn ( princ "stack[") (princ (minus (get a (quote c!:location)))) (princ "]"))) (t (princ a)))) (t (cond ((or (equal c (quote !c)) (equal c (quote !C))) ( c!:safeprin a)) (t (cond ((or (equal c (quote !a)) (equal c (quote !A))) ( prin a)) (t (cond ((or (equal c (quote !t)) (equal c (quote !T))) (ttab a)) ( t (cond ((equal c (quote !<)) (progn (setq args (cons nil args)) (cond (( greaterp (posn) 70) (terpri))))) (t (princ a))))))))))) (cond (args (setq args (cdr args)))) (setq fmt (cdr fmt)))) (t (princ c)))))))) (go lab1212)))) (de c!:safeprin (x) (prog (n lastc) (setq n 0) (prog (var1214) (setq var1214 (explode x)) lab1213 (cond ((null var1214) (return nil))) (prog (c) (setq c ( car var1214)) (progn (cond ((and (greaterp n 120) (equal c (quote ! ))) ( progn (terpri) (prin2 "//") (setq n 2))) (t (cond ((and (greaterp n 150) (neq c !$eol!$)) (progn (terpri) (prin2 "// ") (setq n 3))) (t (setq n (plus n 1) ))))) (cond ((and (equal lastc (quote !\)) (equal c !$eol!$)) (princ " (backslash)"))) (setq lastc c) (princ c) (cond ((equal c !$eol!$) (progn ( princ "//") (setq n 2)))))) (setq var1214 (cdr var1214)) (go lab1213)) (cond ((equal lastc (quote !\)) (princ " (backslash)"))))) (de c!:valid_fndef (args body) (cond ((or (memq (quote !&optional) args) ( memq (quote !&rest) args)) nil) (t (c!:valid_list body)))) (de c!:valid_list (x) (cond ((null x) t) (t (cond ((atom x) nil) (t (cond (( not (c!:valid_expr (car x))) nil) (t (c!:valid_list (cdr x))))))))) (de c!:valid_expr (x) (cond ((atom x) t) (t (cond ((not (atom (car x))) ( progn (cond ((not (c!:valid_list (cdr x))) nil) (t (cond ((not (eqcar (car x) (quote lambda))) nil) (t (cond ((atom (cdar x)) nil) (t (c!:valid_fndef ( cadar x) (cddar x)))))))))) (t (cond ((not (idp (car x))) nil) (t (cond (( eqcar x (quote quote)) t) (t (prog (h) (setq h (get (car x) (quote c!:valid)) ) (cond ((null h) (return (c!:valid_list (cdr x))))) (return (funcall h (cdr x))))))))))))) (de c!:cspecform (x env) (error 0 (list "special form" x))) (de c!:valid_specform (x) nil) (progn (put (quote and) (quote c!:code) (function c!:cspecform)) (put (quote catch) (quote c!:code) (function c!:cspecform)) (put (quote compiler!-let) ( quote c!:code) (function c!:cspecform)) (put (quote cond) (quote c!:code) ( function c!:cspecform)) (put (quote declare) (quote c!:code) (function c!:cspecform)) (put (quote de) (quote c!:code) (function c!:cspecform)) (put (quote eval!-when) (quote c!:code) (function c!:cspecform)) (put (quote flet) (quote c!:code) (function c!:cspecform)) (put (quote function) (quote c!:code) (function c!:cspecform)) (put (quote go) (quote c!:code) (function c!:cspecform)) (put (quote if) (quote c!:code) (function c!:cspecform)) (put (quote labels) (quote c!:code) (function c!:cspecform)) (put (quote !~let) ( quote c!:code) (function c!:cspecform)) (put (quote let!*) (quote c!:code) ( function c!:cspecform)) (put (quote list) (quote c!:code) (function c!:cspecform)) (put (quote list!*) (quote c!:code) (function c!:cspecform)) ( put (quote macrolet) (quote c!:code) (function c!:cspecform)) (put (quote multiple!-value!-call) (quote c!:code) (function c!:cspecform)) (put (quote multiple!-value!-prog1) (quote c!:code) (function c!:cspecform)) (put (quote or) (quote c!:code) (function c!:cspecform)) (put (quote prog) (quote c!:code ) (function c!:cspecform)) (put (quote prog!*) (quote c!:code) (function c!:cspecform)) (put (quote prog1) (quote c!:code) (function c!:cspecform)) ( put (quote prog2) (quote c!:code) (function c!:cspecform)) (put (quote progn) (quote c!:code) (function c!:cspecform)) (put (quote progv) (quote c!:code) (function c!:cspecform)) (put (quote quote) (quote c!:code) (function c!:cspecform)) (put (quote return) (quote c!:code) (function c!:cspecform)) ( put (quote return!-from) (quote c!:code) (function c!:cspecform)) (put (quote setq) (quote c!:code) (function c!:cspecform)) (put (quote tagbody) (quote c!:code) (function c!:cspecform)) (put (quote the) (quote c!:code) (function c!:cspecform)) (put (quote unless) (quote c!:code) (function c!:cspecform)) ( put (quote unwind!-protect) (quote c!:code) (function c!:cspecform)) (put ( quote when) (quote c!:code) (function c!:cspecform)) (put (quote catch) ( quote c!:valid) (function c!:valid_specform)) (put (quote compiler!-let) ( quote c!:valid) (function c!:valid_specform)) (put (quote cond) (quote c!:valid) (function c!:valid_specform)) (put (quote declare) (quote c!:valid) (function c!:valid_specform)) (put (quote de) (quote c!:valid) (function c!:valid_specform)) (put (quote eval!-when) (quote c!:valid) (function c!:valid_specform)) (put (quote flet) (quote c!:valid) (function c!:valid_specform)) (put (quote function) (quote c!:valid) (function c!:valid_specform)) (put (quote labels) (quote c!:valid) (function c!:valid_specform)) (put (quote !~let) (quote c!:valid) (function c!:valid_specform)) (put (quote let!*) (quote c!:valid) (function c!:valid_specform)) (put (quote macrolet) (quote c!:valid) (function c!:valid_specform)) (put (quote multiple!-value!-call) (quote c!:valid) ( function c!:valid_specform)) (put (quote multiple!-value!-prog1) (quote c!:valid) (function c!:valid_specform)) (put (quote prog) (quote c!:valid) ( function c!:valid_specform)) (put (quote prog!*) (quote c!:valid) (function c!:valid_specform)) (put (quote progv) (quote c!:valid) (function c!:valid_specform)) (put (quote quote) (quote c!:valid) (function c!:valid_specform)) (put (quote the) (quote c!:valid) (function c!:valid_specform)) (put (quote unwind!-protect) (quote c!:valid) (function c!:valid_specform))) (fluid (quote (c!:current_procedure c!:current_args c!:current_block c!:current_contents c!:all_blocks c!:registers c!:stacklocs))) (fluid (quote (c!:available c!:used))) (setq c!:available (setq c!:used nil)) (de c!:reset_gensyms nil (progn (remflag c!:used (quote c!:live_across_call)) (remflag c!:used (quote c!:visited)) (prog nil lab1215 (cond ((null c!:used) (return nil))) (progn (remprop (car c!:used) (quote c!:contents)) (remprop ( car c!:used) (quote c!:why)) (remprop (car c!:used) (quote c!:where_to)) ( remprop (car c!:used) (quote c!:count)) (remprop (car c!:used) (quote c!:live )) (remprop (car c!:used) (quote c!:clash)) (remprop (car c!:used) (quote c!:chosen)) (remprop (car c!:used) (quote c!:location)) (cond ((plist (car c!:used)) (prog (o) (setq o (wrs nil)) (princ "+++++ ") (prin (car c!:used)) (princ " ") (prin (plist (car c!:used))) (terpri) (wrs o)))) (setq c!:available (cons (car c!:used) c!:available)) (setq c!:used (cdr c!:used))) (go lab1215)))) (de c!:my_gensym nil (prog (w) (cond (c!:available (progn (setq w (car c!:available)) (setq c!:available (cdr c!:available)))) (t (setq w (gensym1 "v")))) (setq c!:used (cons w c!:used)) (cond ((plist w) (progn (princ "????? ") (prin w) (princ " => ") (prin (plist w)) (terpri)))) (return w))) (de c!:newreg nil (prog (r) (setq r (c!:my_gensym)) (setq c!:registers (cons r c!:registers)) (return r))) (de c!:startblock (s) (progn (setq c!:current_block s) (setq c!:current_contents nil))) (de c!:outop (a b c d) (cond (c!:current_block (setq c!:current_contents ( cons (list a b c d) c!:current_contents))))) (de c!:endblock (why where_to) (cond (c!:current_block (progn (put c!:current_block (quote c!:contents) c!:current_contents) (put c!:current_block (quote c!:why) why) (put c!:current_block (quote c!:where_to ) where_to) (setq c!:all_blocks (cons c!:current_block c!:all_blocks)) (setq c!:current_contents nil) (setq c!:current_block nil))))) (de c!:cval_inner (x env) (prog (helper) (setq x (s!:improve x)) (cond ((atom x) (return (c!:catom x env))) (t (cond ((eqcar (car x) (quote lambda)) ( return (c!:clambda (cadar x) (cddar x) (cdr x) env))) (t (cond ((setq helper (get (car x) (quote c!:code))) (return (funcall helper x env))) (t (cond (( and (setq helper (get (car x) (quote c!:compile_macro))) (setq helper ( funcall helper x))) (return (c!:cval helper env))) (t (cond ((and (idp (car x )) (setq helper (macro!-function (car x)))) (return (c!:cval (funcall helper x) env))) (t (return (c!:ccall (car x) (cdr x) env)))))))))))))) (de c!:cval (x env) (prog (r) (setq r (c!:cval_inner x env)) (cond ((and r ( not (member!*!* r c!:registers))) (error 0 (list r "not a register" x)))) ( return r))) (de c!:clambda (bvl body args env) (prog (w w1 fluids env1 decs) (setq env1 ( car env)) (setq w (prog (var1217 var1218) (setq var1217 args) lab1216 (cond ( (null var1217) (return (reversip var1218)))) (prog (a) (setq a (car var1217)) (setq var1218 (cons (c!:cval a env) var1218))) (setq var1217 (cdr var1217)) (go lab1216))) (setq w1 (s!:find_local_decs body nil)) (setq localdecs (cons (car w1) localdecs)) (setq w1 (cdr w1)) (cond ((null w1) (setq body nil)) (t (cond ((null (cdr w1)) (setq body (car w1))) (t (setq body (cons (quote progn ) w1)))))) (prog (var1220) (setq var1220 bvl) lab1219 (cond ((null var1220) ( return nil))) (prog (x) (setq x (car var1220)) (cond ((and (not (fluidp x)) ( not (globalp x)) (c!:local_fluidp x localdecs)) (progn (make!-special x) ( setq decs (cons x decs)))))) (setq var1220 (cdr var1220)) (go lab1219)) (prog (var1222) (setq var1222 bvl) lab1221 (cond ((null var1222) (return nil))) ( prog (v) (setq v (car var1222)) (progn (cond ((globalp v) (prog (oo) (setq oo (wrs nil)) (princ "+++++ ") (prin v) (princ " converted from GLOBAL to FLUID") (terpri) (wrs oo) (unglobal (list v)) ( fluid (list v))))) (cond ((fluidp v) (progn (setq fluids (cons (cons v ( c!:newreg)) fluids)) (flag (list (cdar fluids)) (quote c!:live_across_call)) (setq env1 (cons (cons (quote c!:dummy!:name) (cdar fluids)) env1)) (c!:outop (quote ldrglob) (cdar fluids) v (c!:find_literal v)) (c!:outop (quote strglob) (car w) v (c!:find_literal v)))) (t (progn (setq env1 (cons (cons v (c!:newreg)) env1)) (c!:outop (quote movr) (cdar env1) nil (car w))))) (setq w (cdr w)))) (setq var1222 (cdr var1222)) (go lab1221)) (cond (fluids ( c!:outop (quote fluidbind) nil nil fluids))) (setq env (cons env1 (append fluids (cdr env)))) (setq w (c!:cval body env)) (prog (var1224) (setq var1224 fluids) lab1223 (cond ((null var1224) (return nil))) (prog (v) (setq v (car var1224)) (c!:outop (quote strglob) (cdr v) (car v) (c!:find_literal (car v)) )) (setq var1224 (cdr var1224)) (go lab1223)) (unfluid decs) (setq localdecs (cdr localdecs)) (return w))) (de c!:locally_bound (x env) (atsoc x (car env))) (flag (quote (nil t)) (quote c!:constant)) (fluid (quote (literal_vector))) (de c!:find_literal (x) (prog (n w) (setq w literal_vector) (setq n 0) (prog nil lab1225 (cond ((null (and w (not (equal (car w) x)))) (return nil))) ( progn (setq n (plus n 1)) (setq w (cdr w))) (go lab1225)) (cond ((null w) ( setq literal_vector (append literal_vector (list x))))) (return n))) (de c!:catom (x env) (prog (v w) (setq v (c!:newreg)) (cond ((and (idp x) (or (fluidp x) (globalp x))) (c!:outop (quote ldrglob) v x (c!:find_literal x))) (t (cond ((and (idp x) (setq w (c!:locally_bound x env))) (c!:outop (quote movr) v nil (cdr w))) (t (cond ((or (null x) (equal x (quote t)) ( c!:small_number x)) (c!:outop (quote movk1) v nil x)) (t (cond ((or (not (idp x)) (flagp x (quote c!:constant))) (c!:outop (quote movk) v x ( c!:find_literal x))) (t (c!:outop (quote ldrglob) v x (c!:find_literal x))))) ))))) (return v))) (de c!:cjumpif (x env d1 d2) (prog (helper r) (setq x (s!:improve x)) (cond ( (and (atom x) (or (not (idp x)) (and (flagp x (quote c!:constant)) (not ( c!:locally_bound x env))))) (c!:endblock (quote goto) (list (cond (x d1) (t d2))))) (t (cond ((and (not (atom x)) (setq helper (get (car x) (quote c!:ctest)))) (return (funcall helper x env d1 d2))) (t (progn (setq r ( c!:cval x env)) (c!:endblock (list (quote ifnull) r) (list d2 d1))))))))) (fluid (quote (c!:current))) (de c!:ccall (fn args env) (c!:ccall1 fn args env)) (fluid (quote (c!:visited))) (de c!:has_calls (a b) (prog (c!:visited) (return (c!:has_calls_1 a b)))) (de c!:has_calls_1 (a b) (cond ((or (equal a b) (not (atom a)) (memq a c!:visited)) nil) (t (prog (has_call) (setq c!:visited (cons a c!:visited)) ( prog (var1227) (setq var1227 (get a (quote c!:contents))) lab1226 (cond (( null var1227) (return nil))) (prog (z) (setq z (car var1227)) (cond ((eqcar z (quote call)) (setq has_call t)))) (setq var1227 (cdr var1227)) (go lab1226) ) (cond (has_call (return (prog (c!:visited) (return (c!:can_reach a b)))))) (prog (var1229) (setq var1229 (get a (quote c!:where_to))) lab1228 (cond (( null var1229) (return nil))) (prog (d) (setq d (car var1229)) (cond (( c!:has_calls_1 d b) (setq has_call t)))) (setq var1229 (cdr var1229)) (go lab1228)) (return has_call))))) (de c!:can_reach (a b) (cond ((equal a b) t) (t (cond ((or (not (atom a)) ( memq a c!:visited)) nil) (t (progn (setq c!:visited (cons a c!:visited)) ( c!:any_can_reach (get a (quote c!:where_to)) b))))))) (de c!:any_can_reach (l b) (cond ((null l) nil) (t (cond ((c!:can_reach (car l) b) t) (t (c!:any_can_reach (cdr l) b)))))) (de c!:pareval (args env) (prog (tasks tasks1 merge split r) (setq tasks ( prog (var1231 var1232) (setq var1231 args) lab1230 (cond ((null var1231) ( return (reversip var1232)))) (prog (a) (setq a (car var1231)) (setq var1232 ( cons (cons (c!:my_gensym) (c!:my_gensym)) var1232))) (setq var1231 (cdr var1231)) (go lab1230))) (setq split (c!:my_gensym)) (c!:endblock (quote goto ) (list split)) (prog (var1234) (setq var1234 args) lab1233 (cond ((null var1234) (return nil))) (prog (a) (setq a (car var1234)) (prog (s) (setq s ( car tasks)) (setq tasks (cdr tasks)) (c!:startblock (car s)) (setq r (cons ( c!:cval a env) r)) (c!:endblock (quote goto) (list (cdr s))) (cond ((or t ( c!:has_calls (car s) (cdr s))) (setq tasks1 (cons s tasks1))) (t (setq merge (cons s merge)))))) (setq var1234 (cdr var1234)) (go lab1233)) (prog (var1236 ) (setq var1236 tasks1) lab1235 (cond ((null var1236) (return nil))) (prog (z ) (setq z (car var1236)) (setq merge (cons z merge))) (setq var1236 (cdr var1236)) (go lab1235)) (prog (var1238) (setq var1238 merge) lab1237 (cond (( null var1238) (return nil))) (prog (v) (setq v (car var1238)) (progn ( c!:startblock split) (c!:endblock (quote goto) (list (car v))) (setq split ( cdr v)))) (setq var1238 (cdr var1238)) (go lab1237)) (c!:startblock split) ( return (reversip r)))) (de c!:ccall1 (fn args env) (prog (tasks merge r val) (setq fn (list fn (cdr env))) (setq val (c!:newreg)) (cond ((null args) (c!:outop (quote call) val nil fn)) (t (cond ((null (cdr args)) (c!:outop (quote call) val (list ( c!:cval (car args) env)) fn)) (t (progn (setq r (c!:pareval args env)) ( c!:outop (quote call) val r fn)))))) (c!:outop (quote reloadenv) (quote env) nil nil) (return val))) (fluid (quote (restart_label reloadenv does_call c!:current_c_name))) (de c!:local_fluidp1 (v decs) (and decs (or (and (eqcar (car decs) (quote special)) (memq v (cdar decs))) (c!:local_fluidp1 v (cdr decs))))) (de c!:local_fluidp (v decs) (and decs (or (c!:local_fluidp1 v (car decs)) ( c!:local_fluidp v (cdr decs))))) (fluid (quote (proglabs blockstack localdecs))) (de c!:cfndef (c!:current_procedure c!:current_c_name argsbody checksum) ( prog (env n w c!:current_args c!:current_block restart_label c!:current_contents c!:all_blocks entrypoint exitpoint args1 c!:registers c!:stacklocs literal_vector reloadenv does_call blockstack proglabs args body localdecs varargs) (setq args (car argsbody)) (setq body (cdr argsbody)) ( setq w (s!:find_local_decs body nil)) (setq body (cdr w)) (cond ((atom body) (setq body nil)) (t (cond ((atom (cdr body)) (setq body (car body))) (t (setq body (cons (quote progn) body)))))) (setq localdecs (list (car w))) ( c!:reset_gensyms) (wrs C_file) (linelength 200) (c!:printf "\n\n// Code for %a\n\n" c!:current_procedure) (c!:find_literal c!:current_procedure) (setq c!:current_args args) (setq varargs (or (null args) (geq (length args) 3))) (prog (var1240) (setq var1240 args) lab1239 ( cond ((null var1240) (return nil))) (prog (v) (setq v (car var1240)) (cond (( or (equal v (quote !&optional)) (equal v (quote !&rest))) (error 0 "&optional and &rest not supported by this compiler (yet)")) (t (cond (( globalp v) (prog (oo) (setq oo (wrs nil)) (princ "+++++ ") (prin v) (princ " converted from GLOBAL to FLUID") (terpri) (wrs oo) (unglobal (list v)) ( fluid (list v)) (setq n (cons (cons v (c!:my_gensym)) n)))) (t (cond ((or ( fluidp v) (c!:local_fluidp v localdecs)) (setq n (cons (cons v (c!:my_gensym) ) n))))))))) (setq var1240 (cdr var1240)) (go lab1239)) (cond (!*r2i (setq body (s!:r2i c!:current_procedure args body)))) (setq restart_label ( c!:my_gensym)) (setq body (list (quote c!:private_tagbody) restart_label body )) (cond (n (progn (setq body (list (list (quote return) body))) (setq args ( subla n args)) (prog (var1242) (setq var1242 n) lab1241 (cond ((null var1242) (return nil))) (prog (v) (setq v (car var1242)) (setq body (cons (list ( quote setq) (car v) (cdr v)) body))) (setq var1242 (cdr var1242)) (go lab1241 )) (setq body (cons (quote prog) (cons (prog (var1244 var1245) (setq var1244 (reverse n)) lab1243 (cond ((null var1244) (return (reversip var1245)))) ( prog (v) (setq v (car var1244)) (setq var1245 (cons (car v) var1245))) (setq var1244 (cdr var1244)) (go lab1243)) body)))))) (c!:printf "static LispObject %s(LispObject env" c!:current_c_name) (setq env nil) (cond (varargs (c!:printf ", int nargs, ...")) (t (progn (setq n t) (prog (var1247 ) (setq var1247 args) lab1246 (cond ((null var1247) (return nil))) (prog (x) (setq x (car var1247)) (prog (aa) (c!:printf ",") (cond (n (progn (c!:printf "\n ") (setq n nil))) (t (setq n t))) (setq aa ( c!:my_gensym)) (setq env (cons (cons x aa) env)) (setq c!:registers (cons aa c!:registers)) (setq args1 (cons aa args1)) (c!:printf " LispObject %s" aa))) (setq var1247 (cdr var1247)) (go lab1246))))) (c!:printf ")\n{\n") (cond (( and varargs args) (prog (var1249) (setq var1249 args) lab1248 (cond ((null var1249) (return nil))) (prog (x) (setq x (car var1249)) (prog (aa) (setq aa (c!:my_gensym)) (setq env (cons (cons x aa) env)) (setq c!:registers (cons aa c!:registers)) (setq args1 (cons aa args1)))) (setq var1249 (cdr var1249)) ( go lab1248)))) (c!:startblock (setq entrypoint (c!:my_gensym))) (setq exitpoint c!:current_block) (c!:endblock (quote goto) (list (list (c!:cval body (cons env nil))))) (c!:optimise_flowgraph entrypoint c!:all_blocks env ( cons (length args) c!:current_procedure) args1 varargs) (c!:printf "}\n\n") ( wrs O_file) (setq L_contents (cons (cons c!:current_procedure (cons literal_vector checksum)) L_contents)) (return nil))) (flag (quote (rds deflist flag fluid global remprop remflag unfluid unglobal dm carcheck C!-end)) (quote eval)) (flag (quote (rds)) (quote ignore)) (fluid (quote (!*backtrace))) (de c!:ccompilesupervisor nil (prog (u w) top (setq u (errorset (quote (read) ) t !*backtrace)) (cond ((atom u) (return nil))) (setq u (car u)) (cond (( equal u !$eof!$) (return nil))) (cond ((atom u) (go top)) (t (cond ((eqcar u (quote C!-end)) (return (apply (quote C!-end) nil))) (t (cond ((eqcar u ( quote rdf)) (progn (setq w (open (setq u (eval (cadr u))) (quote input))) ( cond (w (progn (terpri) (princ "Reading file ") (print u) (setq w (rds w)) ( c!:ccompilesupervisor) (princ "End of file ") (print u) (close (rds w)))) (t (progn (princ "Failed to open file ") (print u)))))) (t (c!:ccmpout1 u))))))) (go top))) (global (quote (c!:char_mappings))) (setq c!:char_mappings (quote ((! . !A) (!! . !B) (!# . !C) (!$ . !D) (!% . !E) (!^ . !F) (!& . !G) (!* . !H) (!( . !I) (!) . !J) (!- . !K) (!+ . !L) (!= . !M) (!\ . !N) (!| . !O) (!, . !P) (!. . !Q) (!< . !R) (!> . !S) (!: . !T) (!; . !U) (!/ . !V) (!? . !W) (!~ . !X) (!` . !Y)))) (fluid (quote (c!:names_so_far))) (de c!:inv_name (n) (prog (r w) (cond ((setq w (assoc n c!:names_so_far)) ( setq w (plus (cdr w) 1))) (t (setq w 0))) (setq c!:names_so_far (cons (cons n w) c!:names_so_far)) (setq r (quote (!C !C !"))) (cond ((not (zerop w)) ( setq r (append (reverse (explodec w)) r)))) (setq r (cons (quote !_) r)) ( prog (var1251) (setq var1251 (explode2 n)) lab1250 (cond ((null var1251) ( return nil))) (prog (c) (setq c (car var1251)) (progn (cond ((equal c (quote _)) (setq r (cons (quote _) r))) (t (cond ((or (liter c) (digit c)) (setq r ( cons c r))) (t (cond ((setq w (atsoc c c!:char_mappings)) (setq r (cons (cdr w) r))) (t (setq r (cons (quote !Z) r)))))))))) (setq var1251 (cdr var1251)) (go lab1250)) (setq r (cons (quote !") r)) (return (compress (reverse r))))) (fluid (quote (c!:defnames pending_functions))) (de c!:ccmpout1 (u) (prog (pending_functions) (setq pending_functions (list u )) (prog nil lab1252 (cond ((null pending_functions) (return nil))) (progn ( setq u (car pending_functions)) (setq pending_functions (cdr pending_functions)) (c!:ccmpout1a u)) (go lab1252)))) (de c!:ccmpout1a (u) (prog (w checksum) (cond ((atom u) (return nil)) (t ( cond ((eqcar u (quote progn)) (progn (prog (var1254) (setq var1254 (cdr u)) lab1253 (cond ((null var1254) (return nil))) (prog (v) (setq v (car var1254)) (c!:ccmpout1a v)) (setq var1254 (cdr var1254)) (go lab1253)) (return nil))) (t (cond ((eqcar u (quote C!-end)) nil) (t (cond ((or (flagp (car u) (quote eval)) (and (equal (car u) (quote setq)) (not (atom (caddr u))) (flagp ( caaddr u) (quote eval)))) (errorset u t !*backtrace))))))))) (cond ((eqcar u (quote rdf)) (prog nil (setq w (open (setq u (eval (cadr u))) (quote input))) (cond (w (progn (princ "Reading file ") (print u) (setq w (rds w)) ( c!:ccompilesupervisor) (princ "End of file ") (print u) (close (rds w)))) (t (progn (princ "Failed to open file ") (print u)))))) (t (cond ((eqcar u ( quote de)) (progn (setq u (cdr u)) (setq checksum (md60 u)) (setq c!:defnames (cons (list (car u) (c!:inv_name (car u)) (length (cadr u)) checksum) c!:defnames)) (princ "Compiling ") (prin (caar c!:defnames)) (princ " ... ") (c!:cfndef (caar c!:defnames) (cadar c!:defnames) (cdr u) checksum) (terpri)) )))))) (fluid (quote (!*defn dfprint!* dfprintsave))) (de c!:concat (a b) (compress (cons (quote !") (append (explode2 a) (append ( explode2 b) (quote (!"))))))) (de c!:ccompilestart (name setupname dir hdrnow) (prog (o d w) (reset!-gensym 0) (setq c!:registers (setq c!:available (setq c!:used nil))) (setq File_name (list2string (explodec name))) (setq Setup_name (explodec setupname )) (setq Setup_name (subst (quote !_) (quote !-) Setup_name)) (setq Setup_name (list2string Setup_name)) (cond (dir (progn (cond ((memq (quote win32) lispsystem!*) (setq name (c!:concat dir (c!:concat "\" name)))) (t ( setq name (c!:concat dir (c!:concat "/" name)))))))) (princ "C file = ") ( print name) (setq C_file (open (c!:concat name ".cpp") (quote output))) (setq L_file (c!:concat name ".lsp")) (setq L_contents nil) (setq c!:names_so_far nil) (setq o (reverse (explode (date!-and!-time)))) (prog (i) (setq i 1) lab1255 (cond ((minusp (times 1 (difference 5 i))) (return nil))) (progn ( setq d (cons (car o) d)) (setq o (cdr o))) (setq i (plus i 1)) (go lab1255)) (setq d (cons (quote !-) d)) (setq o (cdddr (cdddr (cddddr o)))) (setq w o) ( setq o (cdddr o)) (setq d (cons (caddr o) (cons (cadr o) (cons (car o) d)))) (setq d (compress (cons (quote !") (cons (cadr w) (cons (car w) (cons (quote !-) d)))))) (setq O_file (wrs C_file)) (setq c!:defnames nil) (cond (hdrnow ( c!:printf "\n// Module: %s %tMachine generated C code\n\n" setupname 25)) (t (c!:printf "\n// %s.c %tMachine generated C code\n\n" name 25))) (c!:printf "// $I") (c!:printf "d: $\n\n") (c!:printf "#include <cstdio>\n") (c!:printf "#include <cstdlib>\n") (c!:printf "#include <cstring>\n") (c!:printf "#include <cctype>\n") (c!:printf "#include <cstdarg>\n") (c!:printf "#include <ctime>\n") (c!:printf "#ifndef _cplusplus\n") (c!:printf "#include <csetjmp>\n") (c!:printf "#endif\n\n") (cond (hdrnow ( print!-config!-header)) (t (c!:printf "#include \qconfig.h\q\n\n"))) ( print!-csl!-headers) (cond (hdrnow (c!:print!-init))) (wrs O_file) (return nil))) (de c!:print!-init nil (progn (c!:printf "\n") (c!:printf "LispObject *nilp;\n") (c!:printf "LispObject **C_stackp;\n") (c!:printf "LispObject * volatile * stackLimitp;\n") (c!:printf "\n") (c!:printf "void init(LispObject *a, LispObject **b, LispObject * volatile *c)\n") ( c!:printf "{\n") (c!:printf " nilp = a;\n") (c!:printf " C_stackp = b;\n") (c!:printf " stackLimitp = c;\n") (c!:printf "}\n") (c!:printf "\n") (c!:printf "#define nil (*nilp)\n") (c!:printf "#define C_stack (*C_stackp)\n") (c!:printf "#define stackLimit (*stackLimitp)\n") (c!:printf "\n"))) (de C!-end nil (C!-end1 t)) (de C!-end1 (create_lfile) (prog (checksum c1 c2 c3) (wrs C_file) (cond ( create_lfile (c!:printf "\n\nsetup_type const %s_setup[] =\n{\n" Setup_name)) (t (c!:printf "\n\nsetup_type_1 const %s_setup[] =\n{\n" Setup_name))) (setq c!:defnames (reverse c!:defnames)) (prog nil lab1256 (cond ((null c!:defnames) (return nil))) (prog (name nargs f1 f2 cast fn) (setq name (caar c!:defnames)) (setq checksum (cadddr (car c!:defnames))) (setq f1 (cadar c!:defnames)) (setq nargs (caddar c!:defnames)) (setq cast "(n_args *)") ( cond ((equal nargs 1) (progn (setq f2 (quote !t!o!o_!m!a!n!y_1)) (setq cast "") (setq fn (quote !w!r!o!n!g_!n!o_1)))) (t (cond ((equal nargs 2) (progn ( setq f2 f1) (setq f1 (quote !t!o!o_!f!e!w_2)) (setq cast "") (setq fn (quote !w!r!o!n!g_!n!o_2)))) (t (progn (setq fn f1) (setq f1 (quote !w!r!o!n!g_!n!o_!n!a)) (setq f2 (quote !w!r!o!n!g_!n!o_!n!b))))))) (cond ( create_lfile (c!:printf " {\q%s\q,%t%s,%t%s,%t%s%s},\n" name 32 f1 48 f2 63 cast fn)) (t (prog (c1 c2) (setq c1 (divide checksum (expt 2 31))) (setq c2 (cdr c1)) (setq c1 (car c1)) (c!:printf " {\q%s\q, %t%s, %t%s, %t%s%s, %t%s, %t%s},\n" name 24 f1 40 f2 52 cast fn 64 c1 76 c2)))) (setq c!:defnames (cdr c!:defnames))) (go lab1256)) (setq c3 (setq checksum (md60 L_contents))) (setq c1 (remainder c3 10000000)) (setq c3 (quotient c3 10000000)) (setq c2 (remainder c3 10000000)) (setq c3 ( quotient c3 10000000)) (setq checksum (list2string (append (explodec c3) ( cons (quote ! ) (append (explodec c2) (cons (quote ! ) (explodec c1))))))) ( c!:printf " {NULL, (one_args *)%a, (two_args *)%a, 0}\n};\n\n" Setup_name checksum) (c!:printf "%<// end of generated code\n") (close C_file) (cond ( create_lfile (progn (setq L_file (open L_file (quote output))) (wrs L_file) ( linelength 72) (terpri) (princ "% ") (princ Setup_name) (princ ".lsp") (ttab 20) (princ "Machine generated Lisp") (terpri) (terpri) (princ "(c!:install ") (princ (quote !")) (princ Setup_name) (princ (quote !")) (princ " ") (princ checksum) (printc ")") (terpri) (prog (var1258) (setq var1258 (reverse L_contents)) lab1257 (cond ((null var1258) (return nil))) (prog (x) (setq x ( car var1258)) (progn (princ "(c!:install '") (prin (car x)) (princ " '") ( prin (cadr x)) (princ " ") (prin (cddr x)) (princ ")") (terpri) (terpri))) ( setq var1258 (cdr var1258)) (go lab1257)) (terpri) (princ "% End of generated Lisp code") (terpri) (terpri) (setq L_contents nil) (wrs O_file) (close L_file) (setq !*defn nil) (setq dfprint!* dfprintsave))) (t ( progn (setq checksum (cons checksum (reverse L_contents))) (setq L_contents nil) (return checksum)))))) (put (quote C!-end) (quote stat) (quote endstat)) (de C!-compile (u) (prog nil (terpri) (princ "C!-COMPILE ") (prin u) (princ ": IN files; or type in expressions") (terpri) (princ "When all done, execute C!-END;") (terpri) (verbos nil) (c!:ccompilestart ( car u) (car u) nil nil) (setq dfprintsave dfprint!*) (setq dfprint!* (quote c!:ccmpout1)) (setq !*defn t) (cond ((getd (quote begin)) (return nil))) ( c!:ccompilesupervisor))) (put (quote C!-compile) (quote stat) (quote rlis)) (de c!:print_opcode (s depth) (prog (op r1 r2 r3 helper) (setq op (car s)) ( setq r1 (cadr s)) (setq r2 (caddr s)) (setq r3 (cadddr s)) (setq helper (get op (quote c!:opcode_printer))) (cond (helper (funcall helper op r1 r2 r3 depth)) (t (progn (prin s) (terpri)))))) (de c!:print_exit_condition (why where_to depth) (prog (helper lab1 drop1 lab2 drop2 negate) (cond ((equal why (quote goto)) (progn (setq where_to (car where_to)) (cond ((atom where_to) (progn (c!:printf " goto %s;\n" where_to) (c!:display_flowgraph where_to depth t))) (t (progn (c!:printf " ") (c!:pgoto where_to depth)))) (return nil))) (t (cond ((eqcar (car why ) (quote call)) (return (prog (args locs g w) (cond ((setq w (get (cadar why) (quote c!:direct_entrypoint))) (progn (prog (var1260) (setq var1260 (cdr why )) lab1259 (cond ((null var1260) (return nil))) (prog (a) (setq a (car var1260)) (cond ((flagp a (quote c!:live_across_call)) (progn (cond ((null g) (c!:printf " {\n"))) (setq g (c!:my_gensym)) (c!:printf " LispObject %s = %v;\n" g a) (setq args (cons g args)))) (t (setq args (cons a args))))) (setq var1260 (cdr var1260)) (go lab1259)) (cond ((neq depth 0) (progn (cond (g (c!:printf " "))) (c!:printf " popv(%s);\n" depth)))) (cond (g (c!:printf " "))) (c!:printf " return %s(" (cdr w)) (setq args (reversip args)) (cond (args (progn (c!:printf "%v" (car args)) ( prog (var1262) (setq var1262 (cdr args)) lab1261 (cond ((null var1262) ( return nil))) (prog (a) (setq a (car var1262)) (c!:printf ", %v" a)) (setq var1262 (cdr var1262)) (go lab1261))))) (c!:printf ");\n") (cond (g ( c!:printf " }\n"))))) (t (cond ((setq w (get (cadar why) (quote c!:c_entrypoint))) (progn (prog (var1264) (setq var1264 (cdr why)) lab1263 ( cond ((null var1264) (return nil))) (prog (a) (setq a (car var1264)) (cond (( flagp a (quote c!:live_across_call)) (progn (cond ((null g) (c!:printf " {\n"))) (setq g (c!:my_gensym)) (c!:printf " LispObject %s = %v;\n" g a) (setq args (cons g args)))) (t (setq args (cons a args))))) (setq var1264 (cdr var1264)) (go lab1263)) (cond ((neq depth 0) (c!:printf " popv(%s);\n" depth))) (c!:printf " return %s(nil" w) (cond ((or (null args) (geq (length args) 3)) ( c!:printf ", %s" (length args)))) (prog (var1266) (setq var1266 (reversip args)) lab1265 (cond ((null var1266) (return nil))) (prog (a) (setq a (car var1266)) (c!:printf ", %v" a)) (setq var1266 (cdr var1266)) (go lab1265)) ( c!:printf ");\n") (cond (g (c!:printf " }\n"))))) (t (prog (nargs) (setq nargs (length (cdr why))) (c!:printf " {\n") (prog (var1268) (setq var1268 (cdr why)) lab1267 (cond ((null var1268) (return nil))) (prog (a) (setq a ( car var1268)) (cond ((flagp a (quote c!:live_across_call)) (progn (setq g ( c!:my_gensym)) (c!:printf " LispObject %s = %v;\n" g a) (setq args ( cons g args)))) (t (setq args (cons a args))))) (setq var1268 (cdr var1268)) (go lab1267)) (cond ((neq depth 0) (c!:printf " popv(%s);\n" depth))) (c!:printf " fn = elt(env, %s); %<// %c\n" (c!:find_literal (cadar why )) (cadar why)) (cond ((equal nargs 1) (c!:printf " return (*qfn1(fn))(qenv(fn)")) (t (cond ((equal nargs 2) (c!:printf " return (*qfn2(fn))(qenv(fn)")) (t (c!:printf " return (*qfnn(fn))(qenv(fn), %s" nargs))))) (prog (var1270) (setq var1270 (reversip args)) lab1269 (cond ((null var1270) (return nil))) (prog ( a) (setq a (car var1270)) (c!:printf ", %s" a)) (setq var1270 (cdr var1270)) (go lab1269)) (c!:printf ");\n }\n")))))) (return nil))))))) (setq lab1 ( car where_to)) (setq drop1 (and (atom lab1) (not (flagp lab1 (quote c!:visited))))) (setq lab2 (cadr where_to)) (setq drop2 (and (atom lab2) (not (flagp drop2 (quote c!:visited))))) (cond ((and drop2 (equal (get lab2 ( quote c!:count)) 1)) (progn (setq where_to (list lab2 lab1)) (setq drop1 t))) (t (cond (drop1 (setq negate t))))) (setq helper (get (car why) (quote c!:exit_helper))) (cond ((null helper) (error 0 (list "Bad exit condition" why)))) (c!:printf " if (") (cond (negate (progn (c!:printf "!(") (funcall helper (cdr why) depth) (c!:printf ")"))) (t (funcall helper (cdr why) depth ))) (c!:printf ") ") (cond ((not drop1) (progn (c!:pgoto (car where_to) depth ) (c!:printf " else ")))) (c!:pgoto (cadr where_to) depth) (cond ((atom ( car where_to)) (c!:display_flowgraph (car where_to) depth drop1))) (cond (( atom (cadr where_to)) (c!:display_flowgraph (cadr where_to) depth nil))))) (de c!:pmovr (op r1 r2 r3 depth) (c!:printf " %v = %v;\n" r1 r3)) (put (quote movr) (quote c!:opcode_printer) (function c!:pmovr)) (de c!:pmovk (op r1 r2 r3 depth) (c!:printf " %v = elt(env, %s); %<// %c\n" r1 r3 r2)) (put (quote movk) (quote c!:opcode_printer) (function c!:pmovk)) (de c!:pmovk1 (op r1 r2 r3 depth) (cond ((null r3) (c!:printf " %v = nil;\n" r1)) (t (cond ((equal r3 (quote t)) (c!:printf " %v = lisp_true;\n" r1)) (t (c!:printf " %v = (LispObject)%s+TAG_FIXNUM; %<// %c\n" r1 (times 16 r3) r3)))))) (put (quote movk1) (quote c!:opcode_printer) (function c!:pmovk1)) (flag (quote (movk1)) (quote c!:uses_nil)) (de c!:preloadenv (op r1 r2 r3 depth) (c!:printf " env = stack[%s];\n" ( minus reloadenv))) (put (quote reloadenv) (quote c!:opcode_printer) (function c!:preloadenv)) (de c!:pldrglob (op r1 r2 r3 depth) (c!:printf " %v = qvalue(elt(env, %s)); %<// %c\n" r1 r3 r2)) (put (quote ldrglob) (quote c!:opcode_printer) (function c!:pldrglob)) (de c!:pstrglob (op r1 r2 r3 depth) (c!:printf " qvalue(elt(env, %s)) = %v; %<// %c\n" r3 r1 r2)) (put (quote strglob) (quote c!:opcode_printer) (function c!:pstrglob)) (de c!:pnilglob (op r1 r2 r3 depth) (c!:printf " qvalue(elt(env, %s)) = nil; %<// %c\n" r3 r2)) (put (quote nilglob) (quote c!:opcode_printer) (function c!:pnilglob)) (flag (quote (nilglob)) (quote c!:uses_nil)) (de c!:pnull (op r1 r2 r3 depth) (c!:printf " %v = (%v == nil ? lisp_true : nil);\n" r1 r3)) (put (quote null) (quote c!:opcode_printer) (function c!:pnull)) (put (quote not) (quote c!:opcode_printer) (function c!:pnull)) (flag (quote (null not)) (quote c!:uses_nil)) (de c!:pfastget (op r1 r2 r3 depth) (progn (c!:printf " if (!symbolp(%v)) %v = nil;\n" r2 r1) (c!:printf " else { %v = qfastgets(%v);\n" r1 r2) (c!:printf " if (%v != nil) { %v = elt(%v, %s); %<// %c\n" r1 r1 r1 (car r3) ( cdr r3)) (c!:printf "#ifdef RECORD_GET\n") (c!:printf " if (%v != SPID_NOPROP)\n" r1) (c!:printf " record_get(elt(fastget_names, %s), 1);\n" (car r3)) ( c!:printf " else record_get(elt(fastget_names, %s), 0),\n" (car r3)) (c!:printf " %v = nil; }\n" r1) (c!:printf " else record_get(elt(fastget_names, %s), 0); }\n" (car r3)) ( c!:printf "#else\n") (c!:printf " if (%v == SPID_NOPROP) %v = nil; }}\n" r1 r1) (c!:printf "#endif\n"))) (put (quote fastget) (quote c!:opcode_printer) (function c!:pfastget)) (flag (quote (fastget)) (quote c!:uses_nil)) (de c!:pfastflag (op r1 r2 r3 depth) (progn (c!:printf " if (!symbolp(%v)) %v = nil;\n" r2 r1) (c!:printf " else { %v = qfastgets(%v);\n" r1 r2) (c!:printf " if (%v != nil) { %v = elt(%v, %s); %<// %c\n" r1 r1 r1 (car r3) ( cdr r3)) (c!:printf "#ifdef RECORD_GET\n") (c!:printf " if (%v == SPID_NOPROP)\n" r1) (c!:printf " record_get(elt(fastget_names, %s), 0),\n" (car r3)) ( c!:printf " %v = nil;\n" r1) (c!:printf " else record_get(elt(fastget_names, %s), 1),\n" (car r3)) ( c!:printf " %v = lisp_true; }\n" r1) (c!:printf " else record_get(elt(fastget_names, %s), 0); }\n" (car r3)) ( c!:printf "#else\n") (c!:printf " if (%v == SPID_NOPROP) %v = nil; else %v = lisp_true; }}\n" r1 r1 r1) (c!:printf "#endif\n"))) (put (quote fastflag) (quote c!:opcode_printer) (function c!:pfastflag)) (flag (quote (fastflag)) (quote c!:uses_nil)) (de c!:pcar (op r1 r2 r3 depth) (prog nil (cond ((not !*unsafecar) (progn ( c!:printf " if (!car_legal(%v)) " r3) (c!:pgoto (c!:find_error_label (list (quote car) r3) r2 depth) depth)))) (c!:printf " %v = qcar(%v);\n" r1 r3) )) (put (quote car) (quote c!:opcode_printer) (function c!:pcar)) (de c!:pcdr (op r1 r2 r3 depth) (prog nil (cond ((not !*unsafecar) (progn ( c!:printf " if (!car_legal(%v)) " r3) (c!:pgoto (c!:find_error_label (list (quote cdr) r3) r2 depth) depth)))) (c!:printf " %v = qcdr(%v);\n" r1 r3) )) (put (quote cdr) (quote c!:opcode_printer) (function c!:pcdr)) (de c!:pqcar (op r1 r2 r3 depth) (c!:printf " %v = qcar(%v);\n" r1 r3)) (put (quote qcar) (quote c!:opcode_printer) (function c!:pqcar)) (de c!:pqcdr (op r1 r2 r3 depth) (c!:printf " %v = qcdr(%v);\n" r1 r3)) (put (quote qcdr) (quote c!:opcode_printer) (function c!:pqcdr)) (de c!:patom (op r1 r2 r3 depth) (c!:printf " %v = (consp(%v) ? nil : lisp_true);\n" r1 r3)) (put (quote atom) (quote c!:opcode_printer) (function c!:patom)) (flag (quote (atom)) (quote c!:uses_nil)) (de c!:pnumberp (op r1 r2 r3 depth) (c!:printf " %v = (is_number(%v) ? lisp_true : nil);\n" r1 r3)) (put (quote numberp) (quote c!:opcode_printer) (function c!:pnumberp)) (flag (quote (numberp)) (quote c!:uses_nil)) (de c!:pfixp (op r1 r2 r3 depth) (c!:printf " %v = integerp(%v);\n" r1 r3) ) (put (quote fixp) (quote c!:opcode_printer) (function c!:pfixp)) (flag (quote (fixp)) (quote c!:uses_nil)) (de c!:piminusp (op r1 r2 r3 depth) (c!:printf " %v = ((intptr_t)(%v) < 0 ? lisp_true : nil);\n" r1 r3)) (put (quote iminusp) (quote c!:opcode_printer) (function c!:piminusp)) (flag (quote (iminusp)) (quote c!:uses_nil)) (de c!:pilessp (op r1 r2 r3 depth) (c!:printf " %v = ((intptr_t)%v < (intptr_t)%v) ? lisp_true : nil;\n" r1 r2 r3)) (put (quote ilessp) (quote c!:opcode_printer) (function c!:pilessp)) (flag (quote (ilessp)) (quote c!:uses_nil)) (de c!:pigreaterp (op r1 r2 r3 depth) (c!:printf " %v = ((intptr_t)%v > (intptr_t)%v) ? lisp_true : nil;\n" r1 r2 r3)) (put (quote igreaterp) (quote c!:opcode_printer) (function c!:pigreaterp)) (flag (quote (igreaterp)) (quote c!:uses_nil)) (de c!:piminus (op r1 r2 r3 depth) (c!:printf " %v = (LispObject)(2-((intptr_t)(%v)));\n" r1 r3)) (put (quote iminus) (quote c!:opcode_printer) (function c!:piminus)) (de c!:piadd1 (op r1 r2 r3 depth) (c!:printf " %v = (LispObject)((intptr_t)(%v) + 0x10);\n" r1 r3)) (put (quote iadd1) (quote c!:opcode_printer) (function c!:piadd1)) (de c!:pisub1 (op r1 r2 r3 depth) (c!:printf " %v = (LispObject)((intptr_t)(%v) - 0x10);\n" r1 r3)) (put (quote isub1) (quote c!:opcode_printer) (function c!:pisub1)) (de c!:piplus2 (op r1 r2 r3 depth) (progn (c!:printf " %v = (LispObject)(intptr_t)((intptr_t)%v +" r1 r2) (c!:printf " (intptr_t)%v - TAG_FIXNUM);\n" r3))) (put (quote iplus2) (quote c!:opcode_printer) (function c!:piplus2)) (de c!:pidifference (op r1 r2 r3 depth) (progn (c!:printf " %v = (LispObject)(intptr_t)((intptr_t)%v - (intptr_t)%v" r1 r2 r3) ( c!:printf " + TAG_FIXNUM);\n"))) (put (quote idifference) (quote c!:opcode_printer) (function c!:pidifference) ) (de c!:pitimes2 (op r1 r2 r3 depth) (progn (c!:printf " %v = fixnum_of_int((intptr_t)(int_of_fixnum(%v) *" r1 r2) (c!:printf " int_of_fixnum(%v)));\n" r3))) (put (quote itimes2) (quote c!:opcode_printer) (function c!:pitimes2)) (de c!:pmodular_plus (op r1 r2 r3 depth) (progn (c!:printf " { intptr_t w = int_of_fixnum(%v) + int_of_fixnum(%v);\n" r2 r3) ( c!:printf " if (w >= current_modulus) w -= current_modulus;\n") ( c!:printf " %v = fixnum_of_int(w);\n" r1) (c!:printf " }\n"))) (put (quote modular!-plus) (quote c!:opcode_printer) (function c!:pmodular_plus)) (de c!:pmodular_difference (op r1 r2 r3 depth) (progn (c!:printf " { intptr_t w = int_of_fixnum(%v) - int_of_fixnum(%v);\n" r2 r3) ( c!:printf " if (w < 0) w += current_modulus;\n") (c!:printf " %v = fixnum_of_int(w);\n" r1) (c!:printf " }\n"))) (put (quote modular!-difference) (quote c!:opcode_printer) (function c!:pmodular_difference)) (de c!:pmodular_minus (op r1 r2 r3 depth) (progn (c!:printf " { intptr_t w = int_of_fixnum(%v);\n" r3) (c!:printf " if (w != 0) w = current_modulus - w;\n") (c!:printf " %v = fixnum_of_int(w);\n" r1) (c!:printf " }\n"))) (put (quote modular!-minus) (quote c!:opcode_printer) (function c!:pmodular_minus)) (de c!:passoc (op r1 r2 r3 depth) (c!:printf " %v = Lassoc(nil, %v, %v);\n" r1 r2 r3)) (put (quote assoc) (quote c!:opcode_printer) (function c!:passoc)) (flag (quote (assoc)) (quote c!:uses_nil)) (de c!:patsoc (op r1 r2 r3 depth) (c!:printf " %v = Latsoc(nil, %v, %v);\n" r1 r2 r3)) (put (quote atsoc) (quote c!:opcode_printer) (function c!:patsoc)) (flag (quote (atsoc)) (quote c!:uses_nil)) (de c!:pmember (op r1 r2 r3 depth) (c!:printf " %v = Lmember(nil, %v, %v);\n" r1 r2 r3)) (put (quote member) (quote c!:opcode_printer) (function c!:pmember)) (flag (quote (member)) (quote c!:uses_nil)) (de c!:pmemq (op r1 r2 r3 depth) (c!:printf " %v = Lmemq(nil, %v, %v);\n" r1 r2 r3)) (put (quote memq) (quote c!:opcode_printer) (function c!:pmemq)) (flag (quote (memq)) (quote c!:uses_nil)) (de c!:pget (op r1 r2 r3 depth) (c!:printf " %v = get(%v, %v);\n" r1 r2 r3 )) (put (quote get) (quote c!:opcode_printer) (function c!:pget)) (de c!:pqgetv (op r1 r2 r3 depth) (progn (c!:printf " %v = *(LispObject *)((char *)%v + (CELL-TAG_VECTOR) +" r1 r2) (c!:printf " (((intptr_t)%v-TAG_FIXNUM)/(16/CELL)));\n" r3))) (put (quote qgetv) (quote c!:opcode_printer) (function c!:pqgetv)) (de c!:pqputv (op r1 r2 r3 depth) (progn (c!:printf " *(LispObject *)((char *)%v + (CELL-TAG_VECTOR) +" r2) (c!:printf " (((intptr_t)%v-TAG_FIXNUM)/(16/CELL))) = %v;\n" r3 r1))) (put (quote qputv) (quote c!:opcode_printer) (function c!:pqputv)) (de c!:peq (op r1 r2 r3 depth) (c!:printf " %v = (%v == %v ? lisp_true : nil);\n" r1 r2 r3)) (put (quote eq) (quote c!:opcode_printer) (function c!:peq)) (flag (quote (eq)) (quote c!:uses_nil)) (de c!:pequal (op r1 r2 r3 depth) (c!:printf " %v = (equal(%v, %v) ? lisp_true : nil);\n" r1 r2 r3 r2 r3)) (put (quote equal) (quote c!:opcode_printer) (function c!:pequal)) (flag (quote (equal)) (quote c!:uses_nil)) (de c!:pfluidbind (op r1 r2 r3 depth) nil) (put (quote fluidbind) (quote c!:opcode_printer) (function c!:pfluidbind)) (de c!:pcall (op r1 r2 r3 depth) (prog (w boolfn) (cond ((setq w (get (car r3 ) (quote c!:direct_entrypoint))) (progn (c!:printf " %v = %s(" r1 (cdr w)) (cond (r2 (progn (c!:printf "%v" (car r2)) (prog (var1272) (setq var1272 ( cdr r2)) lab1271 (cond ((null var1272) (return nil))) (prog (a) (setq a (car var1272)) (c!:printf ", %v" a)) (setq var1272 (cdr var1272)) (go lab1271))))) (c!:printf ");\n"))) (t (cond ((setq w (get (car r3) (quote c!:direct_predicate))) (progn (setq boolfn t) (c!:printf " %v = (LispObject)%s(" r1 (cdr w)) (cond (r2 (progn (c!:printf "%v" (car r2)) (prog (var1274) (setq var1274 (cdr r2)) lab1273 (cond ((null var1274) ( return nil))) (prog (a) (setq a (car var1274)) (c!:printf ", %v" a)) (setq var1274 (cdr var1274)) (go lab1273))))) (c!:printf ");\n"))) (t (cond ((equal (car r3) c!:current_procedure) (progn (setq r2 (c!:fix_nargs r2 c!:current_args)) (c!:printf " %v = %s(env" r1 c!:current_c_name) (cond (( or (null r2) (geq (length r2) 3)) (c!:printf ", %s" (length r2)))) (prog ( var1276) (setq var1276 r2) lab1275 (cond ((null var1276) (return nil))) (prog (a) (setq a (car var1276)) (c!:printf ", %v" a)) (setq var1276 (cdr var1276) ) (go lab1275)) (c!:printf ");\n"))) (t (cond ((setq w (get (car r3) (quote c!:c_entrypoint))) (progn (c!:printf " %v = %s(nil" r1 w) (cond ((or (null r2) (geq (length r2) 3)) (c!:printf ", %s" (length r2)))) (prog (var1278) ( setq var1278 r2) lab1277 (cond ((null var1278) (return nil))) (prog (a) (setq a (car var1278)) (c!:printf ", %v" a)) (setq var1278 (cdr var1278)) (go lab1277)) (c!:printf ");\n"))) (t (prog (nargs) (setq nargs (length r2)) ( c!:printf " fn = elt(env, %s); %<// %c\n" (c!:find_literal (car r3)) (car r3)) (cond ((equal nargs 1) (c!:printf " %v = (*qfn1(fn))(qenv(fn)" r1)) ( t (cond ((equal nargs 2) (c!:printf " %v = (*qfn2(fn))(qenv(fn)" r1)) (t ( c!:printf " %v = (*qfnn(fn))(qenv(fn), %s" r1 nargs))))) (prog (var1280) ( setq var1280 r2) lab1279 (cond ((null var1280) (return nil))) (prog (a) (setq a (car var1280)) (c!:printf ", %v" a)) (setq var1280 (cdr var1280)) (go lab1279)) (c!:printf ");\n")))))))))) (cond ((not (flagp (car r3) (quote c!:no_errors))) (progn (cond ((and (null (cadr r3)) (equal depth 0)) ( c!:printf " errexit();\n")) (t (progn ( c!:printf " if (exception_pending()) ") (c!:pgoto (c!:find_error_label nil (cadr r3) depth) depth))))))) (cond (boolfn (c!:printf " %v = %v ? lisp_true : nil;\n" r1 r1))))) (de c!:fix_nargs (r2 act) (cond ((null act) nil) (t (cond ((null r2) (cons nil (c!:fix_nargs nil (cdr act)))) (t (cons (car r2) (c!:fix_nargs (cdr r2) ( cdr act)))))))) (put (quote call) (quote c!:opcode_printer) (function c!:pcall)) (de c!:pgoto (lab depth) (prog nil (cond ((atom lab) (return (c!:printf "goto %s;\n" lab)))) (setq lab (get (car lab) (quote c!:chosen))) (cond (( zerop depth) (c!:printf "return onevalue(%v);\n" lab)) (t (cond ((flagp lab ( quote c!:live_across_call)) (c!:printf "{ LispObject res = %v; popv(%s); return onevalue(res); }\n" lab depth)) (t ( c!:printf "{ popv(%s); return onevalue(%v); }\n" depth lab))))))) (de c!:pifnull (s depth) (c!:printf "%v == nil" (car s))) (put (quote ifnull) (quote c!:exit_helper) (function c!:pifnull)) (de c!:pifatom (s depth) (c!:printf "!consp(%v)" (car s))) (put (quote ifatom) (quote c!:exit_helper) (function c!:pifatom)) (de c!:pifsymbol (s depth) (c!:printf "symbolp(%v)" (car s))) (put (quote ifsymbol) (quote c!:exit_helper) (function c!:pifsymbol)) (de c!:pifnumber (s depth) (c!:printf "is_number(%v)" (car s))) (put (quote ifnumber) (quote c!:exit_helper) (function c!:pifnumber)) (de c!:pifizerop (s depth) (c!:printf "(%v) == 1" (car s))) (put (quote ifizerop) (quote c!:exit_helper) (function c!:pifizerop)) (de c!:pifeq (s depth) (c!:printf "%v == %v" (car s) (cadr s))) (put (quote ifeq) (quote c!:exit_helper) (function c!:pifeq)) (de c!:pifequal (s depth) (c!:printf "equal(%v, %v)" (car s) (cadr s) (car s) (cadr s))) (put (quote ifequal) (quote c!:exit_helper) (function c!:pifequal)) (de c!:pifilessp (s depth) (c!:printf "((intptr_t)(%v)) < ((intptr_t)(%v))" ( car s) (cadr s))) (put (quote ifilessp) (quote c!:exit_helper) (function c!:pifilessp)) (de c!:pifigreaterp (s depth) (c!:printf "((intptr_t)(%v)) > ((intptr_t)(%v))" (car s) (cadr s))) (put (quote ifigreaterp) (quote c!:exit_helper) (function c!:pifigreaterp)) (de c!:display_flowgraph (s depth dropping_through) (cond ((not (atom s)) ( progn (c!:printf " ") (c!:pgoto s depth))) (t (cond ((not (flagp s (quote c!:visited))) (prog (why where_to) (flag (list s) (quote c!:visited)) (cond ( (or (not dropping_through) (not (equal (get s (quote c!:count)) 1))) ( c!:printf "\n%s:\n" s))) (prog (var1282) (setq var1282 (reverse (get s (quote c!:contents)))) lab1281 (cond ((null var1282) (return nil))) (prog (k) (setq k (car var1282)) (c!:print_opcode k depth)) (setq var1282 (cdr var1282)) (go lab1281)) (setq why (get s (quote c!:why))) (setq where_to (get s (quote c!:where_to))) (cond ((and (equal why (quote goto)) (or (not (atom (car where_to))) (and (not (flagp (car where_to) (quote c!:visited))) (equal (get (car where_to) (quote c!:count)) 1)))) (c!:display_flowgraph (car where_to) depth t)) (t (c!:print_exit_condition why where_to depth))))))))) (fluid (quote (c!:startpoint))) (de c!:branch_chain (s count) (prog (contents why where_to n) (cond ((not ( atom s)) (return s)) (t (cond ((flagp s (quote c!:visited)) (progn (setq n ( get s (quote c!:count))) (cond ((null n) (setq n 1)) (t (setq n (plus n 1)))) (put s (quote c!:count) n) (return s)))))) (flag (list s) (quote c!:visited) ) (setq contents (get s (quote c!:contents))) (setq why (get s (quote c!:why) )) (setq where_to (prog (var1284 var1285) (setq var1284 (get s (quote c!:where_to))) lab1283 (cond ((null var1284) (return (reversip var1285)))) ( prog (z) (setq z (car var1284)) (setq var1285 (cons (c!:branch_chain z count) var1285))) (setq var1284 (cdr var1284)) (go lab1283))) (prog nil lab1286 ( cond ((null (and contents (eqcar (car contents) (quote movr)) (equal why ( quote goto)) (not (atom (car where_to))) (equal (caar where_to) (cadr (car contents))))) (return nil))) (progn (setq where_to (list (list (cadddr (car contents))))) (setq contents (cdr contents))) (go lab1286)) (put s (quote c!:contents) contents) (put s (quote c!:where_to) where_to) (cond ((and (null contents) (equal why (quote goto))) (progn (remflag (list s) (quote c!:visited)) (return (car where_to))))) (cond (count (progn (setq n (get s ( quote c!:count))) (cond ((null n) (setq n 1)) (t (setq n (plus n 1)))) (put s (quote c!:count) n)))) (return s))) (de c!:one_operand (op) (progn (flag (list op) (quote c!:set_r1)) (flag (list op) (quote c!:read_r3)) (put op (quote c!:code) (function c!:builtin_one)))) (de c!:two_operands (op) (progn (flag (list op) (quote c!:set_r1)) (flag ( list op) (quote c!:read_r2)) (flag (list op) (quote c!:read_r3)) (put op ( quote c!:code) (function c!:builtin_two)))) (prog (var1288) (setq var1288 (quote (car cdr qcar qcdr null not atom numberp fixp iminusp iminus iadd1 isub1 modular!-minus))) lab1287 (cond ((null var1288) (return nil))) (prog (n) (setq n (car var1288)) (c!:one_operand n)) (setq var1288 (cdr var1288)) (go lab1287)) (prog (var1290) (setq var1290 (quote (eq equal atsoc memq iplus2 idifference assoc member itimes2 ilessp igreaterp qgetv get modular!-plus modular!-difference))) lab1289 (cond ((null var1290) (return nil))) (prog (n) (setq n (car var1290)) (c!:two_operands n)) (setq var1290 (cdr var1290)) (go lab1289)) (flag (quote (movr movk movk1 ldrglob call reloadenv fastget fastflag)) ( quote c!:set_r1)) (flag (quote (strglob qputv)) (quote c!:read_r1)) (flag (quote (qputv fastget fastflag)) (quote c!:read_r2)) (flag (quote (movr qputv)) (quote c!:read_r3)) (flag (quote (ldrglob strglob nilglob movk call)) (quote c!:read_env)) (fluid (quote (fn_used nil_used nilbase_used))) (de c!:live_variable_analysis (c!:all_blocks) (prog (changed z) (prog nil lab1297 (progn (setq changed nil) (prog (var1296) (setq var1296 c!:all_blocks ) lab1295 (cond ((null var1296) (return nil))) (prog (b) (setq b (car var1296 )) (prog (w live) (prog (var1292) (setq var1292 (get b (quote c!:where_to))) lab1291 (cond ((null var1292) (return nil))) (prog (x) (setq x (car var1292)) (cond ((atom x) (setq live (union live (get x (quote c!:live))))) (t (setq live (union live x))))) (setq var1292 (cdr var1292)) (go lab1291)) (setq w ( get b (quote c!:why))) (cond ((not (atom w)) (progn (cond ((or (eqcar w ( quote ifnull)) (eqcar w (quote ifequal))) (setq nil_used t))) (setq live ( union live (cdr w))) (cond ((and (eqcar (car w) (quote call)) (or (flagp ( cadar w) (quote c!:direct_predicate)) (and (flagp (cadar w) (quote c!:c_entrypoint)) (not (flagp (cadar w) (quote c!:direct_entrypoint)))))) ( setq nil_used t))) (cond ((and (eqcar (car w) (quote call)) (not (equal ( cadar w) c!:current_procedure)) (not (get (cadar w) (quote c!:direct_entrypoint))) (not (get (cadar w) (quote c!:c_entrypoint)))) (progn (setq fn_used t) (setq live (union (quote (env)) live)))))))) (prog (var1294 ) (setq var1294 (get b (quote c!:contents))) lab1293 (cond ((null var1294) ( return nil))) (prog (s) (setq s (car var1294)) (prog (op r1 r2 r3) (setq op ( car s)) (setq r1 (cadr s)) (setq r2 (caddr s)) (setq r3 (cadddr s)) (cond (( equal op (quote movk1)) (progn (cond ((equal r3 nil) (setq nil_used t)) (t ( cond ((equal r3 (quote t)) (setq nilbase_used t))))))) (t (cond ((and (atom op) (flagp op (quote c!:uses_nil))) (setq nil_used t))))) (cond ((flagp op ( quote c!:set_r1)) (cond ((memq r1 live) (setq live (delete r1 live))) (t ( cond ((equal op (quote call)) nil) (t (setq op (quote nop)))))))) (cond (( flagp op (quote c!:read_r1)) (setq live (union live (list r1))))) (cond (( flagp op (quote c!:read_r2)) (setq live (union live (list r2))))) (cond (( flagp op (quote c!:read_r3)) (setq live (union live (list r3))))) (cond (( equal op (quote call)) (progn (cond ((or (not (flagp (car r3) (quote c!:no_errors))) (flagp (car r3) (quote c!:c_entrypoint)) (get (car r3) (quote c!:direct_predicate))) (setq nil_used t))) (setq does_call t) (cond ((and ( not (eqcar r3 c!:current_procedure)) (not (get (car r3) (quote c!:direct_entrypoint))) (not (get (car r3) (quote c!:c_entrypoint)))) (setq fn_used t))) (cond ((not (flagp (car r3) (quote c!:no_errors))) (flag live ( quote c!:live_across_call)))) (setq live (union live r2))))) (cond ((flagp op (quote c!:read_env)) (setq live (union live (quote (env)))))))) (setq var1294 (cdr var1294)) (go lab1293)) (setq live (sort live (function orderp)) ) (cond ((not (equal live (get b (quote c!:live)))) (progn (put b (quote c!:live) live) (setq changed t)))))) (setq var1296 (cdr var1296)) (go lab1295 ))) (cond ((null (not changed)) (go lab1297)))) (setq z c!:registers) (setq c!:registers (setq c!:stacklocs nil)) (prog (var1299) (setq var1299 z) lab1298 (cond ((null var1299) (return nil))) (prog (r) (setq r (car var1299)) (cond ((flagp r (quote c!:live_across_call)) (setq c!:stacklocs (cons r c!:stacklocs))) (t (setq c!:registers (cons r c!:registers))))) (setq var1299 (cdr var1299)) (go lab1298)))) (de c!:insert1 (a b) (cond ((memq a b) b) (t (cons a b)))) (de c!:clash (a b) (cond ((equal (flagp a (quote c!:live_across_call)) (flagp b (quote c!:live_across_call))) (progn (put a (quote c!:clash) (c!:insert1 b (get a (quote c!:clash)))) (put b (quote c!:clash) (c!:insert1 a (get b ( quote c!:clash)))))))) (de c!:build_clash_matrix (c!:all_blocks) (prog nil (prog (var1307) (setq var1307 c!:all_blocks) lab1306 (cond ((null var1307) (return nil))) (prog (b) (setq b (car var1307)) (prog (live w) (prog (var1301) (setq var1301 (get b ( quote c!:where_to))) lab1300 (cond ((null var1301) (return nil))) (prog (x) ( setq x (car var1301)) (cond ((atom x) (setq live (union live (get x (quote c!:live))))) (t (setq live (union live x))))) (setq var1301 (cdr var1301)) ( go lab1300)) (setq w (get b (quote c!:why))) (cond ((not (atom w)) (progn ( setq live (union live (cdr w))) (cond ((and (eqcar (car w) (quote call)) (not (get (cadar w) (quote c!:direct_entrypoint))) (not (get (cadar w) (quote c!:c_entrypoint)))) (setq live (union (quote (env)) live))))))) (prog ( var1305) (setq var1305 (get b (quote c!:contents))) lab1304 (cond ((null var1305) (return nil))) (prog (s) (setq s (car var1305)) (prog (op r1 r2 r3) (setq op (car s)) (setq r1 (cadr s)) (setq r2 (caddr s)) (setq r3 (cadddr s)) (cond ((flagp op (quote c!:set_r1)) (cond ((memq r1 live) (progn (setq live (delete r1 live)) (cond ((equal op (quote reloadenv)) (setq reloadenv t))) ( prog (var1303) (setq var1303 live) lab1302 (cond ((null var1303) (return nil) )) (prog (v) (setq v (car var1303)) (c!:clash r1 v)) (setq var1303 (cdr var1303)) (go lab1302)))) (t (cond ((equal op (quote call)) nil) (t (progn ( setq op (quote nop)) (rplacd s (cons (car s) (cdr s))) (rplaca s op)))))))) ( cond ((flagp op (quote c!:read_r1)) (setq live (union live (list r1))))) ( cond ((flagp op (quote c!:read_r2)) (setq live (union live (list r2))))) ( cond ((flagp op (quote c!:read_r3)) (setq live (union live (list r3))))) ( cond ((equal op (quote call)) (setq live (union live r2)))) (cond ((flagp op (quote c!:read_env)) (setq live (union live (quote (env)))))))) (setq var1305 (cdr var1305)) (go lab1304)))) (setq var1307 (cdr var1307)) (go lab1306)) ( return nil))) (de c!:allocate_registers (rl) (prog (schedule neighbours allocation) (setq neighbours 0) (prog nil lab1311 (cond ((null rl) (return nil))) (prog (w x) ( setq w rl) (prog nil lab1308 (cond ((null (and w (greaterp (length (setq x ( get (car w) (quote c!:clash)))) neighbours))) (return nil))) (setq w (cdr w)) (go lab1308)) (cond (w (progn (setq schedule (cons (car w) schedule)) (setq rl (deleq (car w) rl)) (prog (var1310) (setq var1310 x) lab1309 (cond ((null var1310) (return nil))) (prog (r) (setq r (car var1310)) (put r (quote c!:clash) (deleq (car w) (get r (quote c!:clash))))) (setq var1310 (cdr var1310)) (go lab1309)))) (t (setq neighbours (plus neighbours 1))))) (go lab1311)) (prog (var1315) (setq var1315 schedule) lab1314 (cond ((null var1315) (return nil))) (prog (r) (setq r (car var1315)) (prog (poss) (setq poss allocation) (prog (var1313) (setq var1313 (get r (quote c!:clash))) lab1312 (cond ((null var1313) (return nil))) (prog (x) (setq x (car var1313)) (setq poss (deleq (get x (quote c!:chosen)) poss))) (setq var1313 (cdr var1313)) (go lab1312)) (cond ((null poss) (progn (setq poss (c!:my_gensym)) (setq allocation (append allocation (list poss))))) (t (setq poss (car poss)) )) (put r (quote c!:chosen) poss))) (setq var1315 (cdr var1315)) (go lab1314) ) (return allocation))) (de c!:remove_nops (c!:all_blocks) (prog (var1325) (setq var1325 c!:all_blocks) lab1324 (cond ((null var1325) (return nil))) (prog (b) (setq b (car var1325)) (prog (r) (prog (var1320) (setq var1320 (get b (quote c!:contents))) lab1319 (cond ((null var1320) (return nil))) (prog (s) (setq s (car var1320)) (cond ((not (eqcar s (quote nop))) (prog (op r1 r2 r3) (setq op (car s)) (setq r1 (cadr s)) (setq r2 (caddr s)) (setq r3 (cadddr s)) (cond ((or (flagp op (quote c!:set_r1)) (flagp op (quote c!:read_r1))) (setq r1 ( get r1 (quote c!:chosen))))) (cond ((flagp op (quote c!:read_r2)) (setq r2 ( get r2 (quote c!:chosen))))) (cond ((flagp op (quote c!:read_r3)) (setq r3 ( get r3 (quote c!:chosen))))) (cond ((equal op (quote call)) (setq r2 (prog ( var1317 var1318) (setq var1317 r2) lab1316 (cond ((null var1317) (return ( reversip var1318)))) (prog (v) (setq v (car var1317)) (setq var1318 (cons ( get v (quote c!:chosen)) var1318))) (setq var1317 (cdr var1317)) (go lab1316) )))) (cond ((not (and (equal op (quote movr)) (equal r1 r3))) (setq r (cons ( list op r1 r2 r3) r)))))))) (setq var1320 (cdr var1320)) (go lab1319)) (put b (quote c!:contents) (reversip r)) (setq r (get b (quote c!:why))) (cond (( not (atom r)) (put b (quote c!:why) (cons (car r) (prog (var1322 var1323) ( setq var1322 (cdr r)) lab1321 (cond ((null var1322) (return (reversip var1323 )))) (prog (v) (setq v (car var1322)) (setq var1323 (cons (get v (quote c!:chosen)) var1323))) (setq var1322 (cdr var1322)) (go lab1321)))))))) (setq var1325 (cdr var1325)) (go lab1324))) (fluid (quote (c!:error_labels))) (de c!:find_error_label (why env depth) (prog (w z) (setq z (list why env depth)) (setq w (assoc!*!* z c!:error_labels)) (cond ((null w) (progn (setq w (cons z (c!:my_gensym))) (setq c!:error_labels (cons w c!:error_labels))))) (return (cdr w)))) (de c!:assign (u v c) (cond ((flagp u (quote fluid)) (cons (list (quote strglob) v u (c!:find_literal u)) c)) (t (cons (list (quote movr) u nil v) c) ))) (de c!:insert_tailcall (b) (prog (why dest contents fcall res w) (setq why ( get b (quote c!:why))) (setq dest (get b (quote c!:where_to))) (setq contents (get b (quote c!:contents))) (prog nil lab1326 (cond ((null (and contents ( not (eqcar (car contents) (quote call))))) (return nil))) (progn (setq w ( cons (car contents) w)) (setq contents (cdr contents))) (go lab1326)) (cond ( (null contents) (return nil))) (setq fcall (car contents)) (setq contents ( cdr contents)) (setq res (cadr fcall)) (prog nil lab1327 (cond ((null w) ( return nil))) (progn (cond ((eqcar (car w) (quote reloadenv)) (setq w (cdr w) )) (t (cond ((and (eqcar (car w) (quote movr)) (equal (cadddr (car w)) res)) (progn (setq res (cadr (car w))) (setq w (cdr w)))) (t (setq res (setq w nil) )))))) (go lab1327)) (cond ((null res) (return nil))) (cond ((c!:does_return res why dest) (cond ((equal (car (cadddr fcall)) c!:current_procedure) (progn (prog (var1329) (setq var1329 (pair c!:current_args (caddr fcall))) lab1328 (cond ((null var1329) (return nil))) (prog (p) (setq p (car var1329)) (setq contents (c!:assign (car p) (cdr p) contents))) (setq var1329 (cdr var1329)) (go lab1328)) (put b (quote c!:contents) contents) (put b (quote c!:why) ( quote goto)) (put b (quote c!:where_to) (list restart_label)))) (t (progn ( setq nil_used t) (put b (quote c!:contents) contents) (put b (quote c!:why) ( cons (list (quote call) (car (cadddr fcall))) (caddr fcall))) (put b (quote c!:where_to) nil)))))))) (de c!:does_return (res why where_to) (cond ((not (equal why (quote goto))) nil) (t (cond ((not (atom (car where_to))) (equal res (caar where_to))) (t ( prog (contents) (setq where_to (car where_to)) (setq contents (reverse (get where_to (quote c!:contents)))) (setq why (get where_to (quote c!:why))) ( setq where_to (get where_to (quote c!:where_to))) (prog nil lab1330 (cond (( null contents) (return nil))) (cond ((eqcar (car contents) (quote reloadenv)) (setq contents (cdr contents))) (t (cond ((and (eqcar (car contents) (quote movr)) (equal (cadddr (car contents)) res)) (progn (setq res (cadr (car contents))) (setq contents (cdr contents)))) (t (setq res (setq contents nil) ))))) (go lab1330)) (cond ((null res) (return nil)) (t (return ( c!:does_return res why where_to)))))))))) (de c!:pushpop (op v) (prog (n w) (cond ((null v) (return nil))) (setq n ( length v)) (prog nil lab1332 (cond ((null (greaterp n 0)) (return nil))) ( progn (setq w n) (cond ((greaterp w 6) (setq w 6))) (setq n (difference n w)) (cond ((equal w 1) (c!:printf " %s(%s);\n" op (car v))) (t (progn ( c!:printf " %s%d(%s" op w (car v)) (setq v (cdr v)) (prog (i) (setq i 2) lab1331 (cond ((minusp (times 1 (difference w i))) (return nil))) (progn ( c!:printf ",%s" (car v)) (setq v (cdr v))) (setq i (plus i 1)) (go lab1331)) (c!:printf ");\n"))))) (go lab1332)))) (de c!:optimise_flowgraph (c!:startpoint c!:all_blocks env argch args varargs ) (prog (w n locs stacks c!:error_labels fn_used nil_used nilbase_used) (prog (var1334) (setq var1334 c!:all_blocks) lab1333 (cond ((null var1334) (return nil))) (prog (b) (setq b (car var1334)) (c!:insert_tailcall b)) (setq var1334 (cdr var1334)) (go lab1333)) (setq c!:startpoint (c!:branch_chain c!:startpoint nil)) (remflag c!:all_blocks (quote c!:visited)) ( c!:live_variable_analysis c!:all_blocks) (c!:build_clash_matrix c!:all_blocks ) (cond ((and c!:error_labels env) (setq reloadenv t))) (prog (var1338) (setq var1338 env) lab1337 (cond ((null var1338) (return nil))) (prog (u) (setq u (car var1338)) (prog (var1336) (setq var1336 env) lab1335 (cond ((null var1336) (return nil))) (prog (v) (setq v (car var1336)) (c!:clash (cdr u) ( cdr v))) (setq var1336 (cdr var1336)) (go lab1335))) (setq var1338 (cdr var1338)) (go lab1337)) (setq locs (c!:allocate_registers c!:registers)) ( setq stacks (c!:allocate_registers c!:stacklocs)) (flag stacks (quote c!:live_across_call)) (c!:remove_nops c!:all_blocks) (setq c!:startpoint ( c!:branch_chain c!:startpoint nil)) (remflag c!:all_blocks (quote c!:visited) ) (setq c!:startpoint (c!:branch_chain c!:startpoint t)) (remflag c!:all_blocks (quote c!:visited)) (cond (does_call (setq nil_used t))) (cond (locs (progn (c!:printf " LispObject %s" (car locs)) (prog (var1340) (setq var1340 (cdr locs)) lab1339 (cond ((null var1340) (return nil))) (prog (v) (setq v (car var1340)) (c!:printf ", %s" v)) (setq var1340 (cdr var1340)) (go lab1339)) (c!:printf ";\n")))) (cond (fn_used (c!:printf " LispObject fn;\n"))) (cond ((and varargs args) (progn (setq w " ") (c!:printf " LispObject") (prog (var1342 ) (setq var1342 args) lab1341 (cond ((null var1342) (return nil))) (prog (v) (setq v (car var1342)) (progn (c!:printf "%s%s" w v) (setq w ", "))) (setq var1342 (cdr var1342)) (go lab1341)) (c!:printf ";\n va_list aa;\n") ( c!:printf " va_start(aa, nargs);\n")))) (cond ((or (equal (car argch) 0) ( geq (car argch) 3)) (c!:printf " argcheck(nargs, %s, \q%s\q);\n" (car argch) (cdr argch)))) (cond ((and varargs args) (progn (c!:printf " va_start(aa, nargs);\n") (prog (var1344) (setq var1344 (reverse args)) lab1343 (cond ((null var1344) (return nil))) (prog (v) (setq v (car var1344)) (c!:printf " %s = va_arg(aa, LispObject);\n" v)) (setq var1344 (cdr var1344)) (go lab1343)) (c!:printf " va_end(aa);\n")))) (c!:printf "#ifdef DEBUG_VALIDATE\n") (c!:printf " if (check_env(env)) return aerror(\qenv for %s\q);\n" (cdr argch)) ( c!:printf "#endif\n") (c!:printf "#ifdef CHECK_STACK\n") (c!:printf " if_check_stack;\n") (c!:printf "#endif\n") (cond (does_call (progn ( c!:printf " if (stack >= stackLimit)\n") (c!:printf " {\n") (c!:pushpop (quote push) args) (c!:printf " env = reclaim(env, \qstack\q, GC_STACK, 0);\n") (c!:pushpop (quote pop) (reverse args)) (c!:printf " if (exception_pending()) return nil;\n") (c!:printf " }\n")))) ( cond (reloadenv (c!:printf " push(env);\n"))) (setq n 0) (cond (stacks ( progn (c!:printf "%<// space for vars preserved across procedure calls\n") ( prog (var1346) (setq var1346 stacks) lab1345 (cond ((null var1346) (return nil))) (prog (v) (setq v (car var1346)) (progn (put v (quote c!:location) n) (setq n (plus n 1)))) (setq var1346 (cdr var1346)) (go lab1345)) (setq w n) ( prog nil lab1347 (cond ((null (geq w 5)) (return nil))) (progn (c!:printf " push5(nil, nil, nil, nil, nil);\n") (setq w (difference w 5))) (go lab1347)) (cond ((neq w 0) (progn (cond ((equal w 1) (c!:printf " push(nil);\n")) (t (progn (c!:printf " push%s(nil" w) (prog (i) (setq i 2) lab1348 (cond ((minusp (times 1 (difference w i))) (return nil))) ( c!:printf ", nil") (setq i (plus i 1)) (go lab1348)) (c!:printf ");\n"))))))) ))) (cond (reloadenv (progn (setq reloadenv n) (setq n (plus n 1))))) (cond ( env (c!:printf "%<// copy arguments values to proper place\n"))) (prog ( var1350) (setq var1350 env) lab1349 (cond ((null var1350) (return nil))) ( prog (v) (setq v (car var1350)) (cond ((flagp (cdr v) (quote c!:live_across_call)) (c!:printf " stack[%s] = %s;\n" (minus (get (get ( cdr v) (quote c!:chosen)) (quote c!:location))) (cdr v))) (t (c!:printf " %s = %s;\n" (get (cdr v) (quote c!:chosen)) (cdr v))))) (setq var1350 ( cdr var1350)) (go lab1349)) (c!:printf "%<// end of prologue\n") ( c!:display_flowgraph c!:startpoint n t) (cond (c!:error_labels (progn ( c!:printf "%<// error exit handlers\n") (prog (var1352) (setq var1352 c!:error_labels) lab1351 (cond ((null var1352) (return nil))) (prog (x) (setq x (car var1352)) (progn (c!:printf "%s:\n" (cdr x)) (c!:print_error_return ( caar x) (cadar x) (caddar x)))) (setq var1352 (cdr var1352)) (go lab1351))))) (remflag c!:all_blocks (quote c!:visited)))) (de c!:print_error_return (why env depth) (prog nil (cond ((and reloadenv env ) (c!:printf " env = stack[%s];\n" (minus reloadenv)))) (cond ((null why) (progn (prog (var1354) (setq var1354 env) lab1353 (cond ((null var1354) ( return nil))) (prog (v) (setq v (car var1354)) (c!:printf " qvalue(elt(env, %s)) = %v; %<// %c\n" (c!:find_literal (car v)) (get ( cdr v) (quote c!:chosen)) (car v))) (setq var1354 (cdr var1354)) (go lab1353) ) (cond ((neq depth 0) (c!:printf " popv(%s);\n" depth))) (c!:printf " return nil;\n"))) (t (cond ((flagp (cadr why) (quote c!:live_across_call )) (progn (c!:printf " { LispObject res = %v;\n" (cadr why)) (prog ( var1356) (setq var1356 env) lab1355 (cond ((null var1356) (return nil))) ( prog (v) (setq v (car var1356)) (c!:printf " qvalue(elt(env, %s)) = %v;\n" (c!:find_literal (car v)) (get (cdr v) (quote c!:chosen)))) (setq var1356 (cdr var1356)) (go lab1355)) (cond ((neq depth 0) (c!:printf " popv(%s);\n" depth))) (c!:printf " return error(1, %s, res); }\n" (cond ((eqcar why (quote car)) "err_bad_car") (t (cond ((eqcar why (quote cdr)) "err_bad_cdr") (t (error 0 ( list why "unknown_error"))))))))) (t (progn (prog (var1358) (setq var1358 env ) lab1357 (cond ((null var1358) (return nil))) (prog (v) (setq v (car var1358 )) (c!:printf " qvalue(elt(env, %s)) = %v;\n" (c!:find_literal (car v)) ( get (cdr v) (quote c!:chosen)))) (setq var1358 (cdr var1358)) (go lab1357)) ( cond ((neq depth 0) (c!:printf " popv(%s);\n" depth))) (c!:printf " return error(1, %s, %v);\n" (cond ((eqcar why (quote car)) "err_bad_car" ) (t (cond ((eqcar why (quote cdr)) "err_bad_cdr") (t (error 0 (list why "unknown_error")))))) (cadr why))))))))) (de c!:cand (u env) (prog (w r) (setq w (reverse (cdr u))) (cond ((null w) ( return (c!:cval nil env)))) (setq r (list (list (quote t) (car w)))) (setq w (cdr w)) (prog (var1360) (setq var1360 w) lab1359 (cond ((null var1360) ( return nil))) (prog (z) (setq z (car var1360)) (setq r (cons (list (list ( quote null) z) nil) r))) (setq var1360 (cdr var1360)) (go lab1359)) (setq r ( cons (quote cond) r)) (return (c!:cval r env)))) (put (quote and) (quote c!:code) (function c!:cand)) (de c!:ccatch (u env) (error 0 "catch")) (put (quote catch) (quote c!:code) (function c!:ccatch)) (de c!:ccompile_let (u env) (error 0 "compiler-let")) (put (quote compiler!-let) (quote c!:code) (function c!:ccompiler_let)) (de c!:ccond (u env) (prog (v join) (setq v (c!:newreg)) (setq join ( c!:my_gensym)) (prog (var1362) (setq var1362 (cdr u)) lab1361 (cond ((null var1362) (return nil))) (prog (c) (setq c (car var1362)) (prog (l1 l2) (setq l1 (c!:my_gensym)) (setq l2 (c!:my_gensym)) (cond ((atom (cdr c)) (progn ( c!:outop (quote movr) v nil (c!:cval (car c) env)) (c!:endblock (list (quote ifnull) v) (list l2 join)))) (t (progn (c!:cjumpif (car c) env l1 l2) ( c!:startblock l1) (c!:outop (quote movr) v nil (c!:cval (cons (quote progn) ( cdr c)) env)) (c!:endblock (quote goto) (list join))))) (c!:startblock l2))) (setq var1362 (cdr var1362)) (go lab1361)) (c!:outop (quote movk1) v nil nil) (c!:endblock (quote goto) (list join)) (c!:startblock join) (return v))) (put (quote cond) (quote c!:code) (function c!:ccond)) (de c!:valid_cond (x) (cond ((null x) t) (t (cond ((not (c!:valid_list (car x ))) nil) (t (c!:valid_cond (cdr x))))))) (put (quote cond) (quote c!:valid) (function c!:valid_cond)) (de c!:cdeclare (u env) (error 0 "declare")) (put (quote declare) (quote c!:code) (function c!:cdeclare)) (de c!:cde (u env) (error 0 "de")) (put (quote de) (quote c!:code) (function c!:cde)) (de c!:cdefun (u env) (error 0 "defun")) (put (quote !~defun) (quote c!:code) (function c!:cdefun)) (de c!:ceval_when (u env) (error 0 "eval-when")) (put (quote eval!-when) (quote c!:code) (function c!:ceval_when)) (de c!:cflet (u env) (error 0 "flet")) (put (quote flet) (quote c!:code) (function c!:cflet)) (de c!:cfunction (u env) (prog (v) (setq u (cadr u)) (cond ((not (atom u)) ( progn (cond ((not (eqcar u (quote lambda))) (error 0 (list "lambda expression needed" u)))) (setq v (hashtagged!-name (quote lambda) u)) (setq pending_functions (cons (cons (quote de) (cons v (cdr u))) pending_functions)) (setq u v)))) (setq v (c!:newreg)) (c!:outop (quote movk) v u (c!:find_literal u)) (return v))) (de c!:valid_function (x) (cond ((atom x) nil) (t (cond ((not (null (cdr x))) nil) (t (cond ((idp (car x)) t) (t (cond ((atom (car x)) nil) (t (cond ((not (eqcar (car x) (quote lambda))) nil) (t (cond ((atom (cdar x)) nil) (t ( c!:valid_fndef (cadar x) (cddar x))))))))))))))) (put (quote function) (quote c!:code) (function c!:cfunction)) (put (quote function) (quote c!:valid) (function c!:valid_function)) (de c!:cgo (u env) (prog (w w1) (setq w1 proglabs) (prog nil lab1363 (cond (( null (and (null w) w1)) (return nil))) (progn (setq w (assoc!*!* (cadr u) ( car w1))) (setq w1 (cdr w1))) (go lab1363)) (cond ((null w) (error 0 (list u "label not set")))) (c!:endblock (quote goto) (list (cadr w))) (return nil))) (put (quote go) (quote c!:code) (function c!:cgo)) (put (quote go) (quote c!:valid) (function c!:valid_quote)) (de c!:cif (u env) (prog (v join l1 l2 w) (setq v (c!:newreg)) (setq join ( c!:my_gensym)) (setq l1 (c!:my_gensym)) (setq l2 (c!:my_gensym)) (c!:cjumpif (car (setq u (cdr u))) env l1 l2) (c!:startblock l1) (c!:outop (quote movr) v nil (c!:cval (car (setq u (cdr u))) env)) (c!:endblock (quote goto) (list join)) (c!:startblock l2) (setq u (cdr u)) (cond (u (setq u (car u)))) ( c!:outop (quote movr) v nil (c!:cval u env)) (c!:endblock (quote goto) (list join)) (c!:startblock join) (return v))) (put (quote if) (quote c!:code) (function c!:cif)) (de c!:clabels (u env) (error 0 "labels")) (put (quote labels) (quote c!:code) (function c!:clabels)) (de c!:expand!-let (vl b) (cond ((null vl) (cons (quote progn) b)) (t (cond ( (null (cdr vl)) (c!:expand!-let!* vl b)) (t (prog (vars vals) (prog (var1365) (setq var1365 vl) lab1364 (cond ((null var1365) (return nil))) (prog (v) ( setq v (car var1365)) (cond ((atom v) (progn (setq vars (cons v vars)) (setq vals (cons nil vals)))) (t (cond ((atom (cdr v)) (progn (setq vars (cons (car v) vars)) (setq vals (cons nil vals)))) (t (progn (setq vars (cons (car v) vars)) (setq vals (cons (cadr v) vals)))))))) (setq var1365 (cdr var1365)) ( go lab1364)) (return (cons (cons (quote lambda) (cons vars b)) vals)))))))) (de c!:clet (x env) (c!:cval (c!:expand!-let (cadr x) (cddr x)) env)) (de c!:valid_let (x) (cond ((null x) t) (t (cond ((not (c!:valid_cond (car x) )) nil) (t (c!:valid_list (cdr x))))))) (put (quote !~let) (quote c!:code) (function c!:clet)) (put (quote !~let) (quote c!:valid) (function c!:valid_let)) (de c!:expand!-let!* (vl b) (cond ((null vl) (cons (quote progn) b)) (t (prog (var val) (setq var (car vl)) (cond ((not (atom var)) (progn (setq val (cdr var)) (setq var (car var)) (cond ((not (atom val)) (setq val (car val))))))) (setq b (list (list (quote return) (c!:expand!-let!* (cdr vl) b)))) (cond ( val (setq b (cons (list (quote setq) var val) b)))) (return (cons (quote prog ) (cons (list var) b))))))) (de c!:clet!* (x env) (c!:cval (c!:expand!-let!* (cadr x) (cddr x)) env)) (put (quote let!*) (quote c!:code) (function c!:clet!*)) (put (quote let!*) (quote c!:valid) (function c!:valid_let)) (de c!:clist (u env) (cond ((null (cdr u)) (c!:cval nil env)) (t (cond ((null (cddr u)) (c!:cval (cons (quote ncons) (cdr u)) env)) (t (cond ((eqcar (cadr u) (quote cons)) (c!:cval (list (quote acons) (cadr (cadr u)) (caddr (cadr u )) (cons (quote list) (cddr u))) env)) (t (cond ((null (cdddr u)) (c!:cval ( cons (quote list2) (cdr u)) env)) (t (cond ((null (cddddr u)) (c!:cval (cons (quote list3) (cdr u)) env)) (t (cond ((null (cdr (cddddr u))) (c!:cval (cons (quote list4) (cdr u)) env)) (t (c!:cval (list (quote list3!*) (cadr u) ( caddr u) (cadddr u) (cons (quote list) (cddddr u))) env)))))))))))))) (put (quote list) (quote c!:code) (function c!:clist)) (de c!:clist!* (u env) (prog (v) (setq u (reverse (cdr u))) (setq v (car u)) (prog (var1367) (setq var1367 (cdr u)) lab1366 (cond ((null var1367) (return nil))) (prog (a) (setq a (car var1367)) (setq v (list (quote cons) a v))) ( setq var1367 (cdr var1367)) (go lab1366)) (return (c!:cval v env)))) (put (quote list!*) (quote c!:code) (function c!:clist!*)) (de c!:ccons (u env) (prog (a1 a2) (setq a1 (s!:improve (cadr u))) (setq a2 ( s!:improve (caddr u))) (cond ((or (equal a2 nil) (equal a2 (quote (quote nil) )) (equal a2 (quote (list)))) (return (c!:cval (list (quote ncons) a1) env))) ) (cond ((eqcar a1 (quote cons)) (return (c!:cval (list (quote acons) (cadr a1) (caddr a1) a2) env)))) (cond ((eqcar a2 (quote cons)) (return (c!:cval ( list (quote list2!*) a1 (cadr a2) (caddr a2)) env)))) (cond ((eqcar a2 (quote list)) (return (c!:cval (list (quote cons) a1 (list (quote cons) (cadr a2) ( cons (quote list) (cddr a2)))) env)))) (return (c!:ccall (car u) (cdr u) env) ))) (put (quote cons) (quote c!:code) (function c!:ccons)) (de c!:cget (u env) (prog (a1 a2 w r r1) (setq a1 (s!:improve (cadr u))) ( setq a2 (s!:improve (caddr u))) (cond ((and (eqcar a2 (quote quote)) (idp ( setq w (cadr a2))) (setq w (symbol!-make!-fastget w nil))) (progn (setq r ( c!:newreg)) (c!:outop (quote fastget) r (c!:cval a1 env) (cons w (cadr a2))) (return r))) (t (return (c!:ccall (car u) (cdr u) env)))))) (put (quote get) (quote c!:code) (function c!:cget)) (de c!:cflag (u env) (prog (a1 a2 w r r1) (setq a1 (s!:improve (cadr u))) ( setq a2 (s!:improve (caddr u))) (cond ((and (eqcar a2 (quote quote)) (idp ( setq w (cadr a2))) (setq w (symbol!-make!-fastget w nil))) (progn (setq r ( c!:newreg)) (c!:outop (quote fastflag) r (c!:cval a1 env) (cons w (cadr a2))) (return r))) (t (return (c!:ccall (car u) (cdr u) env)))))) (put (quote flagp) (quote c!:code) (function c!:cflag)) (de c!:cgetv (u env) (cond ((not !*fastvector) (c!:ccall (car u) (cdr u) env) ) (t (c!:cval (cons (quote qgetv) (cdr u)) env)))) (put (quote getv) (quote c!:code) (function c!:cgetv)) (de c!:cputv (u env) (cond ((not !*fastvector) (c!:ccall (car u) (cdr u) env) ) (t (c!:cval (cons (quote qputv) (cdr u)) env)))) (put (quote putv) (quote c!:code) (function c!:cputv)) (de c!:cqputv (x env) (prog (rr) (setq rr (c!:pareval (cdr x) env)) (c!:outop (quote qputv) (caddr rr) (car rr) (cadr rr)) (return (caddr rr)))) (put (quote qputv) (quote c!:code) (function c!:cqputv)) (de c!:cmacrolet (u env) (error 0 "macrolet")) (put (quote macrolet) (quote c!:code) (function c!:cmacrolet)) (de c!:cmultiple_value_call (u env) (error 0 "multiple_value_call")) (put (quote multiple!-value!-call) (quote c!:code) (function c!:cmultiple_value_call)) (de c!:cmultiple_value_prog1 (u env) (error 0 "multiple_value_prog1")) (put (quote multiple!-value!-prog1) (quote c!:code) (function c!:cmultiple_value_prog1)) (de c!:cor (u env) (prog (next done v r) (setq v (c!:newreg)) (setq done ( c!:my_gensym)) (setq u (cdr u)) (prog nil lab1368 (cond ((null (cdr u)) ( return nil))) (progn (setq next (c!:my_gensym)) (c!:outop (quote movr) v nil (c!:cval (car u) env)) (setq u (cdr u)) (c!:endblock (list (quote ifnull) v) (list next done)) (c!:startblock next)) (go lab1368)) (c!:outop (quote movr) v nil (c!:cval (car u) env)) (c!:endblock (quote goto) (list done)) ( c!:startblock done) (return v))) (put (quote or) (quote c!:code) (function c!:cor)) (de c!:cprog (u env) (prog (w w1 bvl local_proglabs progret progexit fluids env1 body decs) (setq env1 (car env)) (setq bvl (cadr u)) (setq w ( s!:find_local_decs (cddr u) t)) (setq body (cdr w)) (setq localdecs (cons ( car w) localdecs)) (prog (var1370) (setq var1370 bvl) lab1369 (cond ((null var1370) (return nil))) (prog (v) (setq v (car var1370)) (progn (cond ((and ( not (globalp v)) (not (fluidp v)) (c!:local_fluidp v localdecs)) (progn ( make!-special v) (setq decs (cons v decs))))))) (setq var1370 (cdr var1370)) (go lab1369)) (prog (var1372) (setq var1372 bvl) lab1371 (cond ((null var1372 ) (return nil))) (prog (v) (setq v (car var1372)) (progn (cond ((globalp v) ( prog (oo) (setq oo (wrs nil)) (princ "+++++ ") (prin v) (princ " converted from GLOBAL to FLUID") (terpri) (wrs oo) (unglobal (list v)) ( fluid (list v))))) (cond ((fluidp v) (progn (setq fluids (cons (cons v ( c!:newreg)) fluids)) (flag (list (cdar fluids)) (quote c!:live_across_call)) (setq env1 (cons (cons (quote c!:dummy!:name) (cdar fluids)) env1)) (c!:outop (quote ldrglob) (cdar fluids) v (c!:find_literal v)) (c!:outop (quote nilglob) nil v (c!:find_literal v)))) (t (progn (setq env1 (cons (cons v ( c!:newreg)) env1)) (c!:outop (quote movk1) (cdar env1) nil nil)))))) (setq var1372 (cdr var1372)) (go lab1371)) (cond (fluids (c!:outop (quote fluidbind ) nil nil fluids))) (setq env (cons env1 (append fluids (cdr env)))) (setq u body) (setq progret (c!:newreg)) (setq progexit (c!:my_gensym)) (setq blockstack (cons (cons nil (cons progret progexit)) blockstack)) (prog ( var1374) (setq var1374 u) lab1373 (cond ((null var1374) (return nil))) (prog (a) (setq a (car var1374)) (cond ((atom a) (cond ((atsoc a local_proglabs) ( progn (cond ((not (null a)) (progn (setq w (wrs nil)) (princ "+++++ multiply defined label: ") (prin a) (terpri) (wrs w)))))) (t (setq local_proglabs (cons (list a (c!:my_gensym)) local_proglabs))))))) (setq var1374 (cdr var1374)) (go lab1373)) (setq proglabs (cons local_proglabs proglabs)) (prog (var1376) (setq var1376 u) lab1375 (cond ((null var1376) ( return nil))) (prog (a) (setq a (car var1376)) (cond ((atom a) (progn (setq w (cdr (assoc!*!* a local_proglabs))) (cond ((null (cdr w)) (progn (rplacd w t ) (c!:endblock (quote goto) (list (car w))) (c!:startblock (car w))))))) (t ( c!:cval a env)))) (setq var1376 (cdr var1376)) (go lab1375)) (c!:outop (quote movk1) progret nil nil) (c!:endblock (quote goto) (list progexit)) ( c!:startblock progexit) (prog (var1378) (setq var1378 fluids) lab1377 (cond ( (null var1378) (return nil))) (prog (v) (setq v (car var1378)) (c!:outop ( quote strglob) (cdr v) (car v) (c!:find_literal (car v)))) (setq var1378 (cdr var1378)) (go lab1377)) (setq blockstack (cdr blockstack)) (setq proglabs ( cdr proglabs)) (unfluid decs) (setq localdecs (cdr localdecs)) (return progret))) (put (quote prog) (quote c!:code) (function c!:cprog)) (de c!:valid_prog (x) (c!:valid_list (cdr x))) (put (quote prog) (quote c!:valid) (function c!:valid_prog)) (de c!:cprog!* (u env) (error 0 "prog*")) (put (quote prog!*) (quote c!:code) (function c!:cprog!*)) (de c!:cprog1 (u env) (prog (g) (setq g (c!:my_gensym)) (setq g (list (quote prog) (list g) (list (quote setq) g (cadr u)) (cons (quote progn) (cddr u)) ( list (quote return) g))) (return (c!:cval g env)))) (put (quote prog1) (quote c!:code) (function c!:cprog1)) (de c!:cprog2 (u env) (prog (g) (setq u (cdr u)) (setq g (c!:my_gensym)) ( setq g (list (quote prog) (list g) (list (quote setq) g (cadr u)) (cons ( quote progn) (cddr u)) (list (quote return) g))) (setq g (list (quote progn) (car u) g)) (return (c!:cval g env)))) (put (quote prog2) (quote c!:code) (function c!:cprog2)) (de c!:cprogn (u env) (prog (r) (setq u (cdr u)) (cond ((equal u nil) (setq u (quote (nil))))) (prog (var1380) (setq var1380 u) lab1379 (cond ((null var1380) (return nil))) (prog (s) (setq s (car var1380)) (setq r (c!:cval s env))) (setq var1380 (cdr var1380)) (go lab1379)) (return r))) (put (quote progn) (quote c!:code) (function c!:cprogn)) (de c!:cprogv (u env) (error 0 "progv")) (put (quote progv) (quote c!:code) (function c!:cprogv)) (de c!:cquote (u env) (prog (v) (setq u (cadr u)) (setq v (c!:newreg)) (cond ((or (null u) (equal u (quote t)) (c!:small_number u)) (c!:outop (quote movk1 ) v nil u)) (t (c!:outop (quote movk) v u (c!:find_literal u)))) (return v))) (de c!:valid_quote (x) t) (put (quote quote) (quote c!:code) (function c!:cquote)) (put (quote quote) (quote c!:valid) (function c!:valid_quote)) (de c!:creturn (u env) (prog (w) (setq w (assoc!*!* nil blockstack)) (cond (( null w) (error 0 "RETURN out of context"))) (c!:outop (quote movr) (cadr w) nil (c!:cval (cadr u) env)) (c!:endblock (quote goto) (list (cddr w))) ( return nil))) (put (quote return) (quote c!:code) (function c!:creturn)) (put (quote return!-from) (quote c!:code) (function c!:creturn_from)) (de c!:csetq (u env) (prog (v w) (setq v (c!:cval (caddr u) env)) (setq u ( cadr u)) (cond ((not (idp u)) (error 0 (list u "bad variable in setq"))) (t ( cond ((setq w (c!:locally_bound u env)) (c!:outop (quote movr) (cdr w) nil v) ) (t (cond ((flagp u (quote c!:constant)) (error 0 (list u "attempt to use setq on a constant"))) (t (c!:outop (quote strglob) v u ( c!:find_literal u)))))))) (return v))) (put (quote setq) (quote c!:code) (function c!:csetq)) (put (quote noisy!-setq) (quote c!:code) (function c!:csetq)) (de c!:cprivate_tagbody (u env) (prog nil (setq u (cdr u)) (c!:endblock ( quote goto) (list (car u))) (c!:startblock (car u)) (setq c!:current_args ( prog (var1382 var1383) (setq var1382 c!:current_args) lab1381 (cond ((null var1382) (return (reversip var1383)))) (prog (v) (setq v (car var1382)) (setq var1383 (cons (prog (z) (setq z (assoc!*!* v (car env))) (return (cond (z ( cdr z)) (t v)))) var1383))) (setq var1382 (cdr var1382)) (go lab1381))) ( return (c!:cval (cadr u) env)))) (put (quote c!:private_tagbody) (quote c!:code) (function c!:cprivate_tagbody )) (de c!:cthe (u env) (c!:cval (caddr u) env)) (put (quote the) (quote c!:code) (function c!:cthe)) (de c!:cunless (u env) (prog (v join l1 l2) (setq v (c!:newreg)) (setq join ( c!:my_gensym)) (setq l1 (c!:my_gensym)) (setq l2 (c!:my_gensym)) (c!:cjumpif (cadr u) env l2 l1) (c!:startblock l1) (c!:outop (quote movr) v nil (c!:cval (cons (quote progn) (cddr u)) env)) (c!:endblock (quote goto) (list join)) ( c!:startblock l2) (c!:outop (quote movk1) v nil nil) (c!:endblock (quote goto ) (list join)) (c!:startblock join) (return v))) (put (quote unless) (quote c!:code) (function c!:cunless)) (de c!:cunwind_protect (u env) (error 0 "unwind_protect")) (put (quote unwind!-protect) (quote c!:code) (function c!:cunwind_protect)) (de c!:cwhen (u env) (prog (v join l1 l2) (setq v (c!:newreg)) (setq join ( c!:my_gensym)) (setq l1 (c!:my_gensym)) (setq l2 (c!:my_gensym)) (c!:cjumpif (cadr u) env l1 l2) (c!:startblock l1) (c!:outop (quote movr) v nil (c!:cval (cons (quote progn) (cddr u)) env)) (c!:endblock (quote goto) (list join)) ( c!:startblock l2) (c!:outop (quote movk1) v nil nil) (c!:endblock (quote goto ) (list join)) (c!:startblock join) (return v))) (put (quote when) (quote c!:code) (function c!:cwhen)) (de c!:expand_map (fnargs) (prog (carp fn fn1 args var avar moveon l1 r s closed) (setq fn (car fnargs)) (cond ((or (equal fn (quote mapc)) (equal fn ( quote mapcar)) (equal fn (quote mapcan))) (setq carp t))) (setq fnargs (cdr fnargs)) (cond ((atom fnargs) (error 0 "bad arguments to map function"))) ( setq fn1 (cadr fnargs)) (prog nil lab1384 (cond ((null (or (eqcar fn1 (quote function)) (and (eqcar fn1 (quote quote)) (eqcar (cadr fn1) (quote lambda)))) ) (return nil))) (progn (setq fn1 (cadr fn1)) (setq closed t)) (go lab1384)) (setq args (car fnargs)) (setq l1 (c!:my_gensym)) (setq r (c!:my_gensym)) ( setq s (c!:my_gensym)) (setq var (c!:my_gensym)) (setq avar var) (cond (carp (setq avar (list (quote car) avar)))) (cond (closed (setq fn1 (list fn1 avar) )) (t (setq fn1 (list (quote apply1) fn1 avar)))) (setq moveon (list (quote setq) var (list (quote cdr) var))) (cond ((or (equal fn (quote map)) (equal fn (quote mapc))) (setq fn (sublis (list (cons (quote l1) l1) (cons (quote var) var) (cons (quote fn) fn1) (cons (quote args) args) (cons (quote moveon) moveon)) (quote (prog (var) (setq var args) l1 (cond ((not var) (return nil) )) fn moveon (go l1)))))) (t (cond ((or (equal fn (quote maplist)) (equal fn (quote mapcar))) (setq fn (sublis (list (cons (quote l1) l1) (cons (quote var ) var) (cons (quote fn) fn1) (cons (quote args) args) (cons (quote moveon) moveon) (cons (quote r) r)) (quote (prog (var r) (setq var args) l1 (cond (( not var) (return (reversip r)))) (setq r (cons fn r)) moveon (go l1)))))) (t (setq fn (sublis (list (cons (quote l1) l1) (cons (quote l2) (c!:my_gensym)) (cons (quote var) var) (cons (quote fn) fn1) (cons (quote args) args) (cons ( quote moveon) moveon) (cons (quote r) (c!:my_gensym)) (cons (quote s) ( c!:my_gensym))) (quote (prog (var r s) (setq var args) (setq r (setq s (list nil))) l1 (cond ((not var) (return (cdr r)))) (rplacd s fn) l2 (cond ((not ( atom (cdr s))) (setq s (cdr s)) (go l2))) moveon (go l1))))))))) (return fn)) ) (put (quote map) (quote c!:compile_macro) (function c!:expand_map)) (put (quote maplist) (quote c!:compile_macro) (function c!:expand_map)) (put (quote mapc) (quote c!:compile_macro) (function c!:expand_map)) (put (quote mapcar) (quote c!:compile_macro) (function c!:expand_map)) (put (quote mapcon) (quote c!:compile_macro) (function c!:expand_map)) (put (quote mapcan) (quote c!:compile_macro) (function c!:expand_map)) (de c!:expand_carcdr (x) (prog (name) (setq name (cdr (reverse (cdr (explode2 (car x)))))) (setq x (cadr x)) (prog (var1386) (setq var1386 name) lab1385 ( cond ((null var1386) (return nil))) (prog (v) (setq v (car var1386)) (setq x (list (cond ((equal v (quote a)) (quote car)) (t (quote cdr))) x))) (setq var1386 (cdr var1386)) (go lab1385)) (return x))) (progn (put (quote caar) (quote c!:compile_macro) (function c!:expand_carcdr) ) (put (quote cadr) (quote c!:compile_macro) (function c!:expand_carcdr)) ( put (quote cdar) (quote c!:compile_macro) (function c!:expand_carcdr)) (put ( quote cddr) (quote c!:compile_macro) (function c!:expand_carcdr)) (put (quote caaar) (quote c!:compile_macro) (function c!:expand_carcdr)) (put (quote caadr) (quote c!:compile_macro) (function c!:expand_carcdr)) (put (quote cadar) (quote c!:compile_macro) (function c!:expand_carcdr)) (put (quote caddr) (quote c!:compile_macro) (function c!:expand_carcdr)) (put (quote cdaar) (quote c!:compile_macro) (function c!:expand_carcdr)) (put (quote cdadr) (quote c!:compile_macro) (function c!:expand_carcdr)) (put (quote cddar) (quote c!:compile_macro) (function c!:expand_carcdr)) (put (quote cdddr) (quote c!:compile_macro) (function c!:expand_carcdr)) (put (quote caaaar) (quote c!:compile_macro) (function c!:expand_carcdr)) (put (quote caaadr) (quote c!:compile_macro) (function c!:expand_carcdr)) (put (quote caadar) (quote c!:compile_macro) (function c!:expand_carcdr)) (put (quote caaddr) (quote c!:compile_macro) (function c!:expand_carcdr)) (put (quote cadaar) (quote c!:compile_macro) (function c!:expand_carcdr)) (put (quote cadadr) (quote c!:compile_macro) (function c!:expand_carcdr)) (put (quote caddar) (quote c!:compile_macro) (function c!:expand_carcdr)) (put (quote cadddr) (quote c!:compile_macro) (function c!:expand_carcdr)) (put (quote cdaaar) (quote c!:compile_macro) (function c!:expand_carcdr)) (put (quote cdaadr) (quote c!:compile_macro) (function c!:expand_carcdr)) (put (quote cdadar) (quote c!:compile_macro) (function c!:expand_carcdr)) (put (quote cdaddr) (quote c!:compile_macro) (function c!:expand_carcdr)) (put (quote cddaar) (quote c!:compile_macro) (function c!:expand_carcdr)) (put (quote cddadr) (quote c!:compile_macro) (function c!:expand_carcdr)) (put (quote cdddar) (quote c!:compile_macro) (function c!:expand_carcdr)) (put (quote cddddr) (quote c!:compile_macro) (function c!:expand_carcdr))) (de c!:builtin_one (x env) (prog (r1 r2) (setq r1 (c!:cval (cadr x) env)) ( c!:outop (car x) (setq r2 (c!:newreg)) (cdr env) r1) (return r2))) (de c!:builtin_two (x env) (prog (a1 a2 r rr) (setq a1 (cadr x)) (setq a2 ( caddr x)) (setq rr (c!:pareval (list a1 a2) env)) (c!:outop (car x) (setq r ( c!:newreg)) (car rr) (cadr rr)) (return r))) (de c!:narg (x env) (c!:cval (expand (cdr x) (get (car x) (quote c!:binary_version))) env)) (prog (var1388) (setq var1388 (quote ((plus plus2) (times times2) (iplus iplus2) (itimes itimes2)))) lab1387 (cond ((null var1388) (return nil))) ( prog (n) (setq n (car var1388)) (progn (put (car n) (quote c!:binary_version) (cadr n)) (put (car n) (quote c!:code) (function c!:narg)))) (setq var1388 ( cdr var1388)) (go lab1387)) (de c!:cplus2 (u env) (prog (a b) (setq a (s!:improve (cadr u))) (setq b ( s!:improve (caddr u))) (return (cond ((and (numberp a) (numberp b)) (c!:cval (plus a b) env)) (t (cond ((equal a 0) (c!:cval b env)) (t (cond ((equal a 1) (c!:cval (list (quote add1) b) env)) (t (cond ((equal b 0) (c!:cval a env)) (t (cond ((equal b 1) (c!:cval (list (quote add1) a) env)) (t (cond ((equal b (minus 1)) (c!:cval (list (quote sub1) a) env)) (t (c!:ccall (car u) (cdr u) env)))))))))))))))) (put (quote plus2) (quote c!:code) (function c!:cplus2)) (de c!:ciplus2 (u env) (prog (a b) (setq a (s!:improve (cadr u))) (setq b ( s!:improve (caddr u))) (return (cond ((and (numberp a) (numberp b)) (c!:cval (plus a b) env)) (t (cond ((equal a 0) (c!:cval b env)) (t (cond ((equal a 1) (c!:cval (list (quote iadd1) b) env)) (t (cond ((equal b 0) (c!:cval a env)) (t (cond ((equal b 1) (c!:cval (list (quote iadd1) a) env)) (t (cond ((equal b (minus 1)) (c!:cval (list (quote isub1) a) env)) (t (c!:builtin_two u env) ))))))))))))))) (put (quote iplus2) (quote c!:code) (function c!:ciplus2)) (de c!:cdifference (u env) (prog (a b) (setq a (s!:improve (cadr u))) (setq b (s!:improve (caddr u))) (return (cond ((and (numberp a) (numberp b)) ( c!:cval (difference a b) env)) (t (cond ((equal a 0) (c!:cval (list (quote minus) b) env)) (t (cond ((equal b 0) (c!:cval a env)) (t (cond ((equal b 1) (c!:cval (list (quote sub1) a) env)) (t (cond ((equal b (minus 1)) (c!:cval ( list (quote add1) a) env)) (t (c!:ccall (car u) (cdr u) env)))))))))))))) (put (quote difference) (quote c!:code) (function c!:cdifference)) (de c!:cidifference (u env) (prog (a b) (setq a (s!:improve (cadr u))) (setq b (s!:improve (caddr u))) (return (cond ((and (numberp a) (numberp b)) ( c!:cval (difference a b) env)) (t (cond ((equal a 0) (c!:cval (list (quote iminus) b) env)) (t (cond ((equal b 0) (c!:cval a env)) (t (cond ((equal b 1) (c!:cval (list (quote isub1) a) env)) (t (cond ((equal b (minus 1)) (c!:cval (list (quote iadd1) a) env)) (t (c!:builtin_two u env)))))))))))))) (put (quote idifference) (quote c!:code) (function c!:cidifference)) (de c!:ctimes2 (u env) (prog (a b) (setq a (s!:improve (cadr u))) (setq b ( s!:improve (caddr u))) (return (cond ((and (numberp a) (numberp b)) (c!:cval (times a b) env)) (t (cond ((or (equal a 0) (equal b 0)) (c!:cval 0 env)) (t (cond ((equal a 1) (c!:cval b env)) (t (cond ((equal b 1) (c!:cval a env)) (t (cond ((equal a (minus 1)) (c!:cval (list (quote minus) b) env)) (t (cond (( equal b (minus 1)) (c!:cval (list (quote minus) a) env)) (t (c!:ccall (car u) (cdr u) env)))))))))))))))) (put (quote times2) (quote c!:code) (function c!:ctimes2)) (de c!:citimes2 (u env) (prog (a b) (setq a (s!:improve (cadr u))) (setq b ( s!:improve (caddr u))) (return (cond ((and (numberp a) (numberp b)) (c!:cval (times a b) env)) (t (cond ((or (equal a 0) (equal b 0)) (c!:cval 0 env)) (t (cond ((equal a 1) (c!:cval b env)) (t (cond ((equal b 1) (c!:cval a env)) (t (cond ((equal a (minus 1)) (c!:cval (list (quote iminus) b) env)) (t (cond ( (equal b (minus 1)) (c!:cval (list (quote iminus) a) env)) (t (c!:builtin_two u env)))))))))))))))) (put (quote itimes2) (quote c!:code) (function c!:citimes2)) (de c!:cminus (u env) (prog (a b) (setq a (s!:improve (cadr u))) (return ( cond ((numberp a) (c!:cval (minus a) env)) (t (cond ((eqcar a (quote minus)) (c!:cval (cadr a) env)) (t (c!:ccall (car u) (cdr u) env)))))))) (put (quote minus) (quote c!:code) (function c!:cminus)) (de c!:ceq (x env) (prog (a1 a2 r rr) (setq a1 (s!:improve (cadr x))) (setq a2 (s!:improve (caddr x))) (cond ((equal a1 nil) (return (c!:cval (list ( quote null) a2) env))) (t (cond ((equal a2 nil) (return (c!:cval (list (quote null) a1) env)))))) (setq rr (c!:pareval (list a1 a2) env)) (c!:outop (quote eq) (setq r (c!:newreg)) (car rr) (cadr rr)) (return r))) (put (quote eq) (quote c!:code) (function c!:ceq)) (de c!:cequal (x env) (prog (a1 a2 r rr) (setq a1 (s!:improve (cadr x))) ( setq a2 (s!:improve (caddr x))) (cond ((equal a1 nil) (return (c!:cval (list (quote null) a2) env))) (t (cond ((equal a2 nil) (return (c!:cval (list ( quote null) a1) env)))))) (setq rr (c!:pareval (list a1 a2) env)) (c!:outop ( cond ((or (c!:eqvalid a1) (c!:eqvalid a2)) (quote eq)) (t (quote equal))) ( setq r (c!:newreg)) (car rr) (cadr rr)) (return r))) (put (quote equal) (quote c!:code) (function c!:cequal)) (de c!:is_fixnum (x) (and (fixp x) (geq x (minus 134217728)) (leq x 134217727 ))) (de c!:certainlyatom (x) (or (null x) (equal x t) (c!:is_fixnum x) (and ( eqcar x (quote quote)) (or (symbolp (cadr x)) (c!:is_fixnum (cadr x)))))) (de c!:atomlist1 (u) (or (atom u) (and (or (symbolp (car u)) (c!:is_fixnum ( car u))) (c!:atomlist1 (cdr u))))) (de c!:atomlist (x) (or (null x) (and (eqcar x (quote quote)) (c!:atomlist1 ( cadr x))) (and (eqcar x (quote list)) (or (null (cdr x)) (and ( c!:certainlyatom (cadr x)) (c!:atomlist (cons (quote list) (cddr x)))))) (and (eqcar x (quote cons)) (c!:certainlyatom (cadr x)) (c!:atomlist (caddr x)))) ) (de c!:atomcar (x) (and (or (eqcar x (quote cons)) (eqcar x (quote list))) ( not (null (cdr x))) (c!:certainlyatom (cadr x)))) (de c!:atomkeys1 (u) (or (atom u) (and (not (atom (car u))) (or (symbolp ( caar u)) (c!:is_fixnum (caar u))) (c!:atomlist1 (cdr u))))) (de c!:atomkeys (x) (or (null x) (and (eqcar x (quote quote)) (c!:atomkeys1 ( cadr x))) (and (eqcar x (quote list)) (or (null (cdr x)) (and (c!:atomcar ( cadr x)) (c!:atomkeys (cons (quote list) (cddr x)))))) (and (eqcar x (quote cons)) (c!:atomcar (cadr x)) (c!:atomkeys (caddr x))))) (de c!:comsublis (x) (cond ((c!:atomkeys (cadr x)) (cons (quote subla) (cdr x ))) (t nil))) (put (quote sublis) (quote c!:compile_macro) (function c!:comsublis)) (de c!:comassoc (x) (cond ((or (c!:certainlyatom (cadr x)) (c!:atomkeys ( caddr x))) (cons (quote atsoc) (cdr x))) (t nil))) (put (quote assoc) (quote c!:compile_macro) (function c!:comassoc)) (put (quote assoc!*!*) (quote c!:compile_macro) (function c!:comassoc)) (de c!:commember (x) (cond ((or (c!:certainlyatom (cadr x)) (c!:atomlist ( caddr x))) (cons (quote memq) (cdr x))) (t nil))) (put (quote member) (quote c!:compile_macro) (function c!:commember)) (de c!:comdelete (x) (cond ((or (c!:certainlyatom (cadr x)) (c!:atomlist ( caddr x))) (cons (quote deleq) (cdr x))) (t nil))) (put (quote delete) (quote c!:compile_macro) (function c!:comdelete)) (de c!:ctestif (x env d1 d2) (prog (l1 l2) (setq l1 (c!:my_gensym)) (setq l2 (c!:my_gensym)) (c!:jumpif (cadr x) l1 l2) (setq x (cddr x)) (c!:startblock l1) (c!:jumpif (car x) d1 d2) (c!:startblock l2) (c!:jumpif (cadr x) d1 d2))) (put (quote if) (quote c!:ctest) (function c!:ctestif)) (de c!:ctestnull (x env d1 d2) (c!:cjumpif (cadr x) env d2 d1)) (put (quote null) (quote c!:ctest) (function c!:ctestnull)) (put (quote not) (quote c!:ctest) (function c!:ctestnull)) (de c!:ctestatom (x env d1 d2) (prog nil (setq x (c!:cval (cadr x) env)) ( c!:endblock (list (quote ifatom) x) (list d1 d2)))) (put (quote atom) (quote c!:ctest) (function c!:ctestatom)) (de c!:ctestconsp (x env d1 d2) (prog nil (setq x (c!:cval (cadr x) env)) ( c!:endblock (list (quote ifatom) x) (list d2 d1)))) (put (quote consp) (quote c!:ctest) (function c!:ctestconsp)) (de c!:ctestsymbol (x env d1 d2) (prog nil (setq x (c!:cval (cadr x) env)) ( c!:endblock (list (quote ifsymbol) x) (list d1 d2)))) (put (quote idp) (quote c!:ctest) (function c!:ctestsymbol)) (de c!:ctestnumberp (x env d1 d2) (prog nil (setq x (c!:cval (cadr x) env)) ( c!:endblock (list (quote ifnumber) x) (list d1 d2)))) (put (quote numberp) (quote c!:ctest) (function c!:ctestnumberp)) (de c!:ctestizerop (x env d1 d2) (prog nil (setq x (c!:cval (cadr x) env)) ( c!:endblock (list (quote ifizerop) x) (list d1 d2)))) (put (quote izerop) (quote c!:ctest) (function c!:ctestizerop)) (de c!:ctesteq (x env d1 d2) (prog (a1 a2 r) (setq a1 (cadr x)) (setq a2 ( caddr x)) (cond ((equal a1 nil) (return (c!:cjumpif a2 env d2 d1))) (t (cond ((equal a2 nil) (return (c!:cjumpif a1 env d2 d1)))))) (setq r (c!:pareval ( list a1 a2) env)) (c!:endblock (cons (quote ifeq) r) (list d1 d2)))) (put (quote eq) (quote c!:ctest) (function c!:ctesteq)) (de c!:ctesteqcar (x env d1 d2) (prog (a1 a2 r d3) (setq a1 (cadr x)) (setq a2 (caddr x)) (setq d3 (c!:my_gensym)) (setq r (c!:pareval (list a1 a2) env)) (c!:endblock (list (quote ifatom) (car r)) (list d2 d3)) (c!:startblock d3) (c!:outop (quote qcar) (car r) nil (car r)) (c!:endblock (cons (quote ifeq) r ) (list d1 d2)))) (put (quote eqcar) (quote c!:ctest) (function c!:ctesteqcar)) (global (quote (least_fixnum greatest_fixnum))) (setq least_fixnum (minus (expt 2 27))) (setq greatest_fixnum (difference (expt 2 27) 1)) (de c!:small_number (x) (and (fixp x) (geq x least_fixnum) (leq x greatest_fixnum))) (de c!:eqvalid (x) (cond ((atom x) (c!:small_number x)) (t (cond ((flagp (car x) (quote c!:fixnum_fn)) t) (t (and (equal (car x) (quote quote)) (or (idp ( cadr x)) (c!:small_number (cadr x))))))))) (flag (quote (iplus iplus2 idifference iminus itimes itimes2)) (quote c!:fixnum_fn)) (de c!:ctestequal (x env d1 d2) (prog (a1 a2 r) (setq a1 (s!:improve (cadr x) )) (setq a2 (s!:improve (caddr x))) (cond ((equal a1 nil) (return (c!:cjumpif a2 env d2 d1))) (t (cond ((equal a2 nil) (return (c!:cjumpif a1 env d2 d1))) ))) (setq r (c!:pareval (list a1 a2) env)) (c!:endblock (cons (cond ((or ( c!:eqvalid a1) (c!:eqvalid a2)) (quote ifeq)) (t (quote ifequal))) r) (list d1 d2)))) (put (quote equal) (quote c!:ctest) (function c!:ctestequal)) (de c!:ctestneq (x env d1 d2) (prog (a1 a2 r) (setq a1 (s!:improve (cadr x))) (setq a2 (s!:improve (caddr x))) (cond ((equal a1 nil) (return (c!:cjumpif a2 env d1 d2))) (t (cond ((equal a2 nil) (return (c!:cjumpif a1 env d1 d2)))) )) (setq r (c!:pareval (list a1 a2) env)) (c!:endblock (cons (cond ((or ( c!:eqvalid a1) (c!:eqvalid a2)) (quote ifeq)) (t (quote ifequal))) r) (list d2 d1)))) (put (quote neq) (quote c!:ctest) (function c!:ctestneq)) (de c!:ctestilessp (x env d1 d2) (prog (r) (setq r (c!:pareval (list (cadr x) (caddr x)) env)) (c!:endblock (cons (quote ifilessp) r) (list d1 d2)))) (put (quote ilessp) (quote c!:ctest) (function c!:ctestilessp)) (de c!:ctestigreaterp (x env d1 d2) (prog (r) (setq r (c!:pareval (list (cadr x) (caddr x)) env)) (c!:endblock (cons (quote ifigreaterp) r) (list d1 d2))) ) (put (quote igreaterp) (quote c!:ctest) (function c!:ctestigreaterp)) (de c!:ctestand (x env d1 d2) (prog (next) (prog (var1390) (setq var1390 (cdr x)) lab1389 (cond ((null var1390) (return nil))) (prog (a) (setq a (car var1390)) (progn (setq next (c!:my_gensym)) (c!:cjumpif a env next d2) ( c!:startblock next))) (setq var1390 (cdr var1390)) (go lab1389)) (c!:endblock (quote goto) (list d1)))) (put (quote and) (quote c!:ctest) (function c!:ctestand)) (de c!:ctestor (x env d1 d2) (prog (next) (prog (var1392) (setq var1392 (cdr x)) lab1391 (cond ((null var1392) (return nil))) (prog (a) (setq a (car var1392)) (progn (setq next (c!:my_gensym)) (c!:cjumpif a env d1 next) ( c!:startblock next))) (setq var1392 (cdr var1392)) (go lab1391)) (c!:endblock (quote goto) (list d2)))) (put (quote or) (quote c!:ctest) (function c!:ctestor)) (fluid (quote (c!:c_entrypoint_list))) (null (setq c!:c_entrypoint_list (quote ((abs c!:c_entrypoint "Labsval") ( apply0 c!:c_entrypoint "Lapply0") (apply1 c!:c_entrypoint "Lapply1") (apply2 c!:c_entrypoint "Lapply2") (apply3 c!:c_entrypoint "Lapply3") (ash1 c!:c_entrypoint "Lash1") (atan c!:c_entrypoint "Latan") (atom c!:c_entrypoint "Latom") (atsoc c!:c_entrypoint "Latsoc") (batchp c!:c_entrypoint "Lbatchp") (boundp c!:c_entrypoint "Lboundp") (bps!-putv c!:c_entrypoint "Lbpsputv") ( caaaar c!:c_entrypoint "Lcaaaar") (caaadr c!:c_entrypoint "Lcaaadr") (caaar c!:c_entrypoint "Lcaaar") (caadar c!:c_entrypoint "Lcaadar") (caaddr c!:c_entrypoint "Lcaaddr") (caadr c!:c_entrypoint "Lcaadr") (caar c!:c_entrypoint "Lcaar") (cadaar c!:c_entrypoint "Lcadaar") (cadadr c!:c_entrypoint "Lcadadr") (cadar c!:c_entrypoint "Lcadar") (caddar c!:c_entrypoint "Lcaddar") (cadddr c!:c_entrypoint "Lcadddr") (caddr c!:c_entrypoint "Lcaddr") (cadr c!:c_entrypoint "Lcadr") (car c!:c_entrypoint "Lcar") (cdaaar c!:c_entrypoint "Lcdaaar") (cdaadr c!:c_entrypoint "Lcdaadr" ) (cdaar c!:c_entrypoint "Lcdaar") (cdadar c!:c_entrypoint "Lcdadar") (cdaddr c!:c_entrypoint "Lcdaddr") (cdadr c!:c_entrypoint "Lcdadr") (cdar c!:c_entrypoint "Lcdar") (cddaar c!:c_entrypoint "Lcddaar") (cddadr c!:c_entrypoint "Lcddadr") (cddar c!:c_entrypoint "Lcddar") (cdddar c!:c_entrypoint "Lcdddar") (cddddr c!:c_entrypoint "Lcddddr") (cdddr c!:c_entrypoint "Lcdddr") (cddr c!:c_entrypoint "Lcddr") (cdr c!:c_entrypoint "Lcdr") (char!-code c!:c_entrypoint "Lchar_code") (close c!:c_entrypoint "Lclose") (codep c!:c_entrypoint "Lcodep") (constantp c!:c_entrypoint "Lconstantp") (date c!:c_entrypoint "Ldate") (deleq c!:c_entrypoint "Ldeleq") (digit c!:c_entrypoint "Ldigitp") (eject c!:c_entrypoint "Leject") (endp c!:c_entrypoint "Lendp") (eq c!:c_entrypoint "Leq") (eqcar c!:c_entrypoint "Leqcar") (eql c!:c_entrypoint "Leql") (eqn c!:c_entrypoint "Leqn") (error1 c!:c_entrypoint "Lerror0") (evenp c!:c_entrypoint "Levenp") (evlis c!:c_entrypoint "Levlis") (explode c!:c_entrypoint "Lexplode") (explode2 c!:c_entrypoint "Lexplodec") (explodec c!:c_entrypoint "Lexplodec") (expt c!:c_entrypoint "Lexpt") (fix c!:c_entrypoint "Ltruncate") (fixp c!:c_entrypoint "Lfixp") (flag c!:c_entrypoint "Lflag") (flagp!*!* c!:c_entrypoint "Lflagp") (flagp c!:c_entrypoint "Lflagp") (flagpcar c!:c_entrypoint "Lflagpcar") (float c!:c_entrypoint "Lfloat") (floatp c!:c_entrypoint "Lfloatp") (fluidp c!:c_entrypoint "Lsymbol_specialp") (gcdn c!:c_entrypoint "Lgcd") (gctime c!:c_entrypoint "Lgctime") (gensym c!:c_entrypoint "Lgensym") (gensym1 c!:c_entrypoint "Lgensym1") (geq c!:c_entrypoint "Lgeq") (get!* c!:c_entrypoint "Lget") (getenv c!:c_entrypoint "Lgetenv") (getv c!:c_entrypoint "Lgetv") (svref c!:c_entrypoint "Lgetv") (globalp c!:c_entrypoint "Lsymbol_globalp") ( greaterp c!:c_entrypoint "Lgreaterp") (iadd1 c!:c_entrypoint "Liadd1") ( idifference c!:c_entrypoint "Lidifference") (idp c!:c_entrypoint "Lsymbolp") (igreaterp c!:c_entrypoint "Ligreaterp") (ilessp c!:c_entrypoint "Lilessp") ( iminus c!:c_entrypoint "Liminus") (iminusp c!:c_entrypoint "Liminusp") ( indirect c!:c_entrypoint "Lindirect") (integerp c!:c_entrypoint "Lintegerp") (iplus2 c!:c_entrypoint "Liplus2") (iquotient c!:c_entrypoint "Liquotient") ( iremainder c!:c_entrypoint "Liremainder") (irightshift c!:c_entrypoint "Lirightshift") (isub1 c!:c_entrypoint "Lisub1") (itimes2 c!:c_entrypoint "Litimes2") (length c!:c_entrypoint "Llength") (lengthc c!:c_entrypoint "Llengthc") (leq c!:c_entrypoint "Lleq") (lessp c!:c_entrypoint "Llessp") ( linelength c!:c_entrypoint "Llinelength") (load!-module c!:c_entrypoint "Lload_module") (lposn c!:c_entrypoint "Llposn") (macro!-function c!:c_entrypoint "Lmacro_function") (macroexpand!-1 c!:c_entrypoint "Lmacroexpand_1") (macroexpand c!:c_entrypoint "Lmacroexpand") (make!-bps c!:c_entrypoint "Lget_bps") (make!-global c!:c_entrypoint "Lmake_global") ( make!-simple!-string c!:c_entrypoint "Lsmkvect") (make!-special c!:c_entrypoint "Lmake_special") (mapstore c!:c_entrypoint "Lmapstore") (max2 c!:c_entrypoint "Lmax2") (memq c!:c_entrypoint "Lmemq") (min2 c!:c_entrypoint "Lmin2") (minus c!:c_entrypoint "Lminus") (minusp c!:c_entrypoint "Lminusp") (mkquote c!:c_entrypoint "Lmkquote") (mkvect c!:c_entrypoint "Lmkvect") (mod c!:c_entrypoint "Lmod") (modular!-difference c!:c_entrypoint "Lmodular_difference") (modular!-expt c!:c_entrypoint "Lmodular_expt") (modular!-minus c!:c_entrypoint "Lmodular_minus") ( modular!-number c!:c_entrypoint "Lmodular_number") (modular!-plus c!:c_entrypoint "Lmodular_plus") (modular!-quotient c!:c_entrypoint "Lmodular_quotient") (modular!-reciprocal c!:c_entrypoint "Lmodular_reciprocal") (modular!-times c!:c_entrypoint "Lmodular_times") ( nconc c!:c_entrypoint "Lnconc") (neq c!:c_entrypoint "Lneq") (not c!:c_entrypoint "Lnull") (null c!:c_entrypoint "Lnull") (numberp c!:c_entrypoint "Lnumberp") (oddp c!:c_entrypoint "Loddp") (onep c!:c_entrypoint "Lonep") (orderp c!:c_entrypoint "Lorderp") (pagelength c!:c_entrypoint "Lpagelength") (pairp c!:c_entrypoint "Lconsp") (plist c!:c_entrypoint "Lplist") (plusp c!:c_entrypoint "Lplusp") (posn c!:c_entrypoint "Lposn") (put c!:c_entrypoint "Lputprop") (putv!-char c!:c_entrypoint "Lsputv") (putv c!:c_entrypoint "Lputv") (qcaar c!:c_entrypoint "Lcaar") (qcadr c!:c_entrypoint "Lcadr") (qcar c!:c_entrypoint "Lcar") (qcdar c!:c_entrypoint "Lcdar") (qcddr c!:c_entrypoint "Lcddr") (qcdr c!:c_entrypoint "Lcdr") (qgetv c!:c_entrypoint "Lgetv") (rds c!:c_entrypoint "Lrds") (reclaim c!:c_entrypoint "Lgc") (remd c!:c_entrypoint "Lremd") (remflag c!:c_entrypoint "Lremflag") (remob c!:c_entrypoint "Lunintern") (remprop c!:c_entrypoint "Lremprop") (reverse c!:c_entrypoint "Lreverse") (reversip c!:c_entrypoint "Lnreverse") (rplaca c!:c_entrypoint "Lrplaca") (rplacd c!:c_entrypoint "Lrplacd") (schar c!:c_entrypoint "Lsgetv") (seprp c!:c_entrypoint "Lwhitespace_char_p") ( set!-small!-modulus c!:c_entrypoint "Lset_small_modulus") (set c!:c_entrypoint "Lset") (smemq c!:c_entrypoint "Lsmemq") (spaces c!:c_entrypoint "Lxtab") (special!-char c!:c_entrypoint "Lspecial_char") ( special!-form!-p c!:c_entrypoint "Lspecial_form_p") (spool c!:c_entrypoint "Lspool") (stop c!:c_entrypoint "Lstop") (stringp c!:c_entrypoint "Lstringp") (subla c!:c_entrypoint "Lsubla") (subst c!:c_entrypoint "Lsubst") ( symbol!-env c!:c_entrypoint "Lsymbol_env") (symbol!-function c!:c_entrypoint "Lsymbol_function") (symbol!-name c!:c_entrypoint "Lsymbol_name") ( symbol!-set!-definition c!:c_entrypoint "Lsymbol_set_definition") ( symbol!-set!-env c!:c_entrypoint "Lsymbol_set_env") (symbol!-value c!:c_entrypoint "Lsymbol_value") (system c!:c_entrypoint "Lsystem") (terpri c!:c_entrypoint "Lterpri") (threevectorp c!:c_entrypoint "Lthreevectorp") ( time c!:c_entrypoint "Ltime") (ttab c!:c_entrypoint "Lttab") (tyo c!:c_entrypoint "Ltyo") (unmake!-global c!:c_entrypoint "Lunmake_global") ( unmake!-special c!:c_entrypoint "Lunmake_special") (upbv c!:c_entrypoint "Lupbv") (verbos c!:c_entrypoint "Lverbos") (wrs c!:c_entrypoint "Lwrs") ( xcons c!:c_entrypoint "Lxcons") (xtab c!:c_entrypoint "Lxtab") (zerop c!:c_entrypoint "Lzerop") (cons c!:direct_entrypoint (2 . "cons")) (ncons c!:direct_entrypoint (1 . "ncons")) (list2 c!:direct_entrypoint (2 . "list2") ) (list2!* c!:direct_entrypoint (3 . "list2star")) (acons c!:direct_entrypoint (3 . "acons")) (list3 c!:direct_entrypoint (3 . "list3") ) (list3!* c!:direct_entrypoint (4 . "list3star")) (list4 c!:direct_entrypoint (4 . "list4")) (plus2 c!:direct_entrypoint (2 . "plus2") ) (difference c!:direct_entrypoint (2 . "difference2")) (add1 c!:direct_entrypoint (1 . "add1")) (sub1 c!:direct_entrypoint (1 . "sub1")) ( lognot c!:direct_entrypoint (1 . "lognot")) (ash c!:direct_entrypoint (2 . "ash")) (quotient c!:direct_entrypoint (2 . "quot2")) (remainder c!:direct_entrypoint (2 . "Cremainder")) (times2 c!:direct_entrypoint (2 . "times2")) (minus c!:direct_entrypoint (1 . "negate")) (lessp c!:direct_predicate (2 . "lessp2")) (leq c!:direct_predicate (2 . "lesseq2")) (greaterp c!:direct_predicate (2 . "greaterp2")) (geq c!:direct_predicate (2 . "geq2")) (zerop c!:direct_predicate (1 . "zerop")))))) (null (setq c!:c_entrypoint_list (append c!:c_entrypoint_list (quote ((append c!:c_entrypoint "Lappend") (assoc c!:c_entrypoint "Lassoc") (compress c!:c_entrypoint "Lcompress") (delete c!:c_entrypoint "Ldelete") (divide c!:c_entrypoint "Ldivide") (equal c!:c_entrypoint "Lequal") (intern c!:c_entrypoint "Lintern") (liter c!:c_entrypoint "Lalpha_char_p") (member c!:c_entrypoint "Lmember") (prin c!:c_entrypoint "Lprin") (prin1 c!:c_entrypoint "Lprin") (prin2 c!:c_entrypoint "Lprinc") (princ c!:c_entrypoint "Lprinc") (print c!:c_entrypoint "Lprint") (printc c!:c_entrypoint "Lprintc") (read c!:c_entrypoint "Lread") (readch c!:c_entrypoint "Lreadch") (sublis c!:c_entrypoint "Lsublis") (vectorp c!:c_entrypoint "Lsimple_vectorp") (get c!:direct_entrypoint (2 . "get")))))) ) (prog (var1394) (setq var1394 c!:c_entrypoint_list) lab1393 (cond ((null var1394) (return nil))) (prog (x) (setq x (car var1394)) (put (car x) (cadr x ) (caddr x))) (setq var1394 (cdr var1394)) (go lab1393)) (flag (quote (atom atsoc codep constantp deleq digit endp eq eqcar evenp eql fixp flagp flagpcar floatp get globalp iadd1 idifference idp igreaterp ilessp iminus iminusp indirect integerp iplus2 irightshift isub1 itimes2 liter memq minusp modular!-difference modular!-expt modular!-minus modular!-number modular!-plus modular!-times not null numberp onep pairp plusp qcaar qcadr qcar qcdar qcddr qcdr remflag remprop reversip seprp special!-form!-p stringp symbol!-env symbol!-name symbol!-value threevectorp vectorp zerop)) (quote c!:no_errors)) % end of file
8499
% RLISP to LISP converter. A C <NAME> 2004-2020 %% %% Copyright (C) 2020, following the master REDUCE source files. * %% * %% 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 relevant * %% copyright notice, this list of conditions and the following * %% disclaimer. * %% * Redistributions in binary form must reproduce the above * %% copyright notice, this list of conditions and the following * %% disclaimer in the documentation and/or other materials provided * %% with the distribution. * %% * %% THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * %% "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * %% LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * %% FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * %% COPYRIGHT OWNERS 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. * %% (global (quote (s!:opcodelist))) (setq s!:opcodelist (quote (LOADLOC LOADLOC0 LOADLOC1 LOADLOC2 LOADLOC3 LOADLOC4 LOADLOC5 LOADLOC6 LOADLOC7 LOADLOC8 LOADLOC9 LOADLOC10 LOADLOC11 LOC0LOC1 LOC1LOC2 LOC2LOC3 LOC1LOC0 LOC2LOC1 LOC3LOC2 VNIL LOADLIT LOADLIT1 LOADLIT2 LOADLIT3 LOADLIT4 LOADLIT5 LOADLIT6 LOADLIT7 LOADFREE LOADFREE1 LOADFREE2 LOADFREE3 LOADFREE4 STORELOC STORELOC0 STORELOC1 STORELOC2 STORELOC3 STORELOC4 STORELOC5 STORELOC6 STORELOC7 STOREFREE STOREFREE1 STOREFREE2 STOREFREE3 LOADLEX STORELEX CLOSURE CARLOC0 CARLOC1 CARLOC2 CARLOC3 CARLOC4 CARLOC5 CARLOC6 CARLOC7 CARLOC8 CARLOC9 CARLOC10 CARLOC11 CDRLOC0 CDRLOC1 CDRLOC2 CDRLOC3 CDRLOC4 CDRLOC5 CAARLOC0 CAARLOC1 CAARLOC2 CAARLOC3 CALL0 CALL1 CALL2 CALL2R CALL3 CALLN CALL0_0 CALL0_1 CALL0_2 CALL0_3 CALL1_0 CALL1_1 CALL1_2 CALL1_3 CALL1_4 CALL1_5 CALL2_0 CALL2_1 CALL2_2 CALL2_3 CALL2_4 BUILTIN0 BUILTIN1 BUILTIN2 BUILTIN2R BUILTIN3 APPLY1 APPLY2 APPLY3 APPLY4 JCALL JCALLN JUMP JUMP_B JUMP_L JUMP_BL JUMPNIL JUMPNIL_B JUMPNIL_L JUMPNIL_BL JUMPT JUMPT_B JUMPT_L JUMPT_BL JUMPATOM JUMPATOM_B JUMPATOM_L JUMPATOM_BL JUMPNATOM JUMPNATOM_B JUMPNATOM_L JUMPNATOM_BL JUMPEQ JUMPEQ_B JUMPEQ_L JUMPEQ_BL JUMPNE JUMPNE_B JUMPNE_L JUMPNE_BL JUMPEQUAL JUMPEQUAL_B JUMPEQUAL_L JUMPEQUAL_BL JUMPNEQUAL JUMPNEQUAL_B JUMPNEQUAL_L JUMPNEQUAL_BL JUMPL0NIL JUMPL0T JUMPL1NIL JUMPL1T JUMPL2NIL JUMPL2T JUMPL3NIL JUMPL3T JUMPL4NIL JUMPL4T JUMPST0NIL JUMPST0T JUMPST1NIL JUMPST1T JUMPST2NIL JUMPST2T JUMPL0ATOM JUMPL0NATOM JUMPL1ATOM JUMPL1NATOM JUMPL2ATOM JUMPL2NATOM JUMPL3ATOM JUMPL3NATOM JUMPFREE1NIL JUMPFREE1T JUMPFREE2NIL JUMPFREE2T JUMPFREE3NIL JUMPFREE3T JUMPFREE4NIL JUMPFREE4T JUMPFREENIL JUMPFREET JUMPLIT1EQ JUMPLIT1NE JUMPLIT2EQ JUMPLIT2NE JUMPLIT3EQ JUMPLIT3NE JUMPLIT4EQ JUMPLIT4NE JUMPLITEQ JUMPLITNE JUMPB1NIL JUMPB1T JUMPB2NIL JUMPB2T JUMPFLAGP JUMPNFLAGP JUMPEQCAR JUMPNEQCAR CATCH CATCH_B CATCH_L CATCH_BL UNCATCH THROW PROTECT UNPROTECT PVBIND PVRESTORE FREEBIND FREERSTR EXIT NILEXIT LOC0EXIT LOC1EXIT LOC2EXIT PUSH PUSHNIL PUSHNIL2 PUSHNIL3 PUSHNILS POP LOSE LOSE2 LOSE3 LOSES SWOP EQ EQCAR EQUAL NUMBERP CAR CDR CAAR CADR CDAR CDDR CONS NCONS XCONS ACONS LENGTH LIST2 LIST2STAR LIST3 PLUS2 ADD1 DIFFERENCE SUB1 TIMES2 GREATERP LESSP FLAGP GET LITGET GETV QGETV QGETVN BIGSTACK BIGCALL ICASE FASTGET ONEVALUE SPARE))) (prog (n) (setq n 0) (prog (var1001) (setq var1001 s!:opcodelist) lab1000 ( cond ((null var1001) (return nil))) (prog (v) (setq v (car var1001)) (progn ( put v (quote s!:opcode) n) (setq n (plus n 1)))) (setq var1001 (cdr var1001)) (go lab1000)) (return (list n (quote opcodes) (quote allocated)))) (setq s!:opcodelist nil) (fluid (quote (s!:env_alist))) (de s!:vecof (l) (prog (w) (setq w (assoc l s!:env_alist)) (cond (w (return ( cdr w)))) (setq w (s!:vecof1 l)) (setq s!:env_alist (cons (cons l w) s!:env_alist)) (return w))) (de s!:vecof1 (l) (prog (v n) (setq v (mkvect (sub1 (length l)))) (setq n 0) (prog (var1003) (setq var1003 l) lab1002 (cond ((null var1003) (return nil))) (prog (x) (setq x (car var1003)) (progn (putv v n x) (setq n (plus n 1)))) ( setq var1003 (cdr var1003)) (go lab1002)) (return v))) (progn (put (quote batchp) (quote s!:builtin0) 0) (put (quote date) (quote s!:builtin0) 1) (put (quote eject) (quote s!:builtin0) 2) (put (quote error1) (quote s!:builtin0) 3) (put (quote gctime) (quote s!:builtin0) 4) (put ( quote lposn) (quote s!:builtin0) 6) (put (quote posn) (quote s!:builtin0) 8) (put (quote read) (quote s!:builtin0) 9) (put (quote readch) (quote s!:builtin0) 10) (put (quote terpri) (quote s!:builtin0) 11) (put (quote time ) (quote s!:builtin0) 12) (put (quote tyi) (quote s!:builtin0) 13) (put ( quote load!-spid) (quote s!:builtin0) 14) (put (quote abs) (quote s!:builtin1 ) 0) (put (quote add1) (quote s!:builtin1) 1) (put (quote atan) (quote s!:builtin1) 2) (put (quote apply0) (quote s!:builtin1) 3) (put (quote atom) (quote s!:builtin1) 4) (put (quote boundp) (quote s!:builtin1) 5) (put (quote char!-code) (quote s!:builtin1) 6) (put (quote close) (quote s!:builtin1) 7) (put (quote codep) (quote s!:builtin1) 8) (put (quote compress) (quote s!:builtin1) 9) (put (quote constantp) (quote s!:builtin1) 10) (put (quote digit) (quote s!:builtin1) 11) (put (quote endp) (quote s!:builtin1) 12) (put (quote eval) (quote s!:builtin1) 13) (put (quote evenp) (quote s!:builtin1) 14) (put (quote evlis) (quote s!:builtin1) 15) (put (quote explode) (quote s!:builtin1) 16) (put (quote explode2lc) (quote s!:builtin1) 17) (put (quote explode2) (quote s!:builtin1) 18) (put (quote explodec) (quote s!:builtin1) 18) (put (quote fixp) (quote s!:builtin1) 19) (put (quote float) (quote s!:builtin1) 20) (put (quote floatp) (quote s!:builtin1) 21) (put (quote symbol!-specialp) (quote s!:builtin1) 22) (put (quote gc) (quote s!:builtin1) 23) (put (quote gensym1) (quote s!:builtin1) 24) (put (quote getenv) (quote s!:builtin1) 25) (put (quote symbol!-globalp) (quote s!:builtin1) 26) (put ( quote iadd1) (quote s!:builtin1) 27) (put (quote symbolp) (quote s!:builtin1) 28) (put (quote iminus) (quote s!:builtin1) 29) (put (quote iminusp) (quote s!:builtin1) 30) (put (quote indirect) (quote s!:builtin1) 31) (put (quote integerp) (quote s!:builtin1) 32) (put (quote intern) (quote s!:builtin1) 33) (put (quote isub1) (quote s!:builtin1) 34) (put (quote length) (quote s!:builtin1) 35) (put (quote lengthc) (quote s!:builtin1) 36) (put (quote linelength) (quote s!:builtin1) 37) (put (quote liter) (quote s!:builtin1) 38 ) (put (quote load!-module) (quote s!:builtin1) 39) (put (quote lognot) ( quote s!:builtin1) 40) (put (quote macroexpand) (quote s!:builtin1) 41) (put (quote macroexpand!-1) (quote s!:builtin1) 42) (put (quote macro!-function) ( quote s!:builtin1) 43) (put (quote make!-bps) (quote s!:builtin1) 44) (put ( quote make!-global) (quote s!:builtin1) 45) (put (quote make!-simple!-string) (quote s!:builtin1) 46) (put (quote make!-special) (quote s!:builtin1) 47) ( put (quote minus) (quote s!:builtin1) 48) (put (quote minusp) (quote s!:builtin1) 49) (put (quote mkvect) (quote s!:builtin1) 50) (put (quote modular!-minus) (quote s!:builtin1) 51) (put (quote modular!-number) (quote s!:builtin1) 52) (put (quote modular!-reciprocal) (quote s!:builtin1) 53) ( put (quote null) (quote s!:builtin1) 54) (put (quote oddp) (quote s!:builtin1 ) 55) (put (quote onep) (quote s!:builtin1) 56) (put (quote pagelength) ( quote s!:builtin1) 57) (put (quote pairp) (quote s!:builtin1) 58) (put (quote plist) (quote s!:builtin1) 59) (put (quote plusp) (quote s!:builtin1) 60) ( put (quote prin) (quote s!:builtin1) 61) (put (quote princ) (quote s!:builtin1) 62) (put (quote print) (quote s!:builtin1) 63) (put (quote printc) (quote s!:builtin1) 64) (put (quote rds) (quote s!:builtin1) 68) (put (quote remd) (quote s!:builtin1) 69) (put (quote reverse) (quote s!:builtin1 ) 70) (put (quote reversip) (quote s!:builtin1) 71) (put (quote seprp) (quote s!:builtin1) 72) (put (quote set!-small!-modulus) (quote s!:builtin1) 73) ( put (quote spaces) (quote s!:builtin1) 74) (put (quote xtab) (quote s!:builtin1) 74) (put (quote special!-char) (quote s!:builtin1) 75) (put ( quote special!-form!-p) (quote s!:builtin1) 76) (put (quote spool) (quote s!:builtin1) 77) (put (quote stop) (quote s!:builtin1) 78) (put (quote stringp) (quote s!:builtin1) 79) (put (quote sub1) (quote s!:builtin1) 80) ( put (quote symbol!-env) (quote s!:builtin1) 81) (put (quote symbol!-function) (quote s!:builtin1) 82) (put (quote symbol!-name) (quote s!:builtin1) 83) ( put (quote symbol!-value) (quote s!:builtin1) 84) (put (quote system) (quote s!:builtin1) 85) (put (quote fix) (quote s!:builtin1) 86) (put (quote ttab) ( quote s!:builtin1) 87) (put (quote tyo) (quote s!:builtin1) 88) (put (quote remob) (quote s!:builtin1) 89) (put (quote unmake!-global) (quote s!:builtin1 ) 90) (put (quote unmake!-special) (quote s!:builtin1) 91) (put (quote upbv) (quote s!:builtin1) 92) (put (quote vectorp) (quote s!:builtin1) 93) (put ( quote verbos) (quote s!:builtin1) 94) (put (quote wrs) (quote s!:builtin1) 95 ) (put (quote zerop) (quote s!:builtin1) 96) (put (quote car) (quote s!:builtin1) 97) (put (quote cdr) (quote s!:builtin1) 98) (put (quote caar) ( quote s!:builtin1) 99) (put (quote cadr) (quote s!:builtin1) 100) (put (quote cdar) (quote s!:builtin1) 101) (put (quote cddr) (quote s!:builtin1) 102) ( put (quote qcar) (quote s!:builtin1) 103) (put (quote qcdr) (quote s!:builtin1) 104) (put (quote qcaar) (quote s!:builtin1) 105) (put (quote qcadr) (quote s!:builtin1) 106) (put (quote qcdar) (quote s!:builtin1) 107) ( put (quote qcddr) (quote s!:builtin1) 108) (put (quote ncons) (quote s!:builtin1) 109) (put (quote numberp) (quote s!:builtin1) 110) (put (quote is!-spid) (quote s!:builtin1) 111) (put (quote spid!-to!-nil) (quote s!:builtin1) 112) (put (quote append) (quote s!:builtin2) 0) (put (quote ash) (quote s!:builtin2) 1) (put (quote assoc) (quote s!:builtin2) 2) (put (quote assoc!*!*) (quote s!:builtin2) 2) (put (quote atsoc) (quote s!:builtin2) 3) (put (quote deleq) (quote s!:builtin2) 4) (put (quote delete) (quote s!:builtin2) 5) (put (quote divide) (quote s!:builtin2) 6) (put (quote eqcar) (quote s!:builtin2) 7) (put (quote eql) (quote s!:builtin2) 8) (put (quote eqn) (quote s!:builtin2) 9) (put (quote expt) (quote s!:builtin2) 10) (put ( quote flag) (quote s!:builtin2) 11) (put (quote flagpcar) (quote s!:builtin2) 12) (put (quote gcdn) (quote s!:builtin2) 13) (put (quote geq) (quote s!:builtin2) 14) (put (quote getv) (quote s!:builtin2) 15) (put (quote greaterp) (quote s!:builtin2) 16) (put (quote idifference) (quote s!:builtin2 ) 17) (put (quote igreaterp) (quote s!:builtin2) 18) (put (quote ilessp) ( quote s!:builtin2) 19) (put (quote imax) (quote s!:builtin2) 20) (put (quote imin) (quote s!:builtin2) 21) (put (quote iplus2) (quote s!:builtin2) 22) ( put (quote iquotient) (quote s!:builtin2) 23) (put (quote iremainder) (quote s!:builtin2) 24) (put (quote irightshift) (quote s!:builtin2) 25) (put (quote itimes2) (quote s!:builtin2) 26) (put (quote leq) (quote s!:builtin2) 28) ( put (quote lessp) (quote s!:builtin2) 29) (put (quote max2) (quote s!:builtin2) 31) (put (quote member) (quote s!:builtin2) 32) (put (quote member!*!*) (quote s!:builtin2) 32) (put (quote memq) (quote s!:builtin2) 33) (put (quote min2) (quote s!:builtin2) 34) (put (quote mod) (quote s!:builtin2) 35) (put (quote modular!-difference) (quote s!:builtin2) 36) ( put (quote modular!-expt) (quote s!:builtin2) 37) (put (quote modular!-plus) (quote s!:builtin2) 38) (put (quote modular!-quotient) (quote s!:builtin2) 39 ) (put (quote modular!-times) (quote s!:builtin2) 40) (put (quote nconc) ( quote s!:builtin2) 41) (put (quote neq) (quote s!:builtin2) 42) (put (quote orderp) (quote s!:builtin2) 43) (put (quote quotient) (quote s!:builtin2) 44) (put (quote remainder) (quote s!:builtin2) 45) (put (quote remflag) (quote s!:builtin2) 46) (put (quote remprop) (quote s!:builtin2) 47) (put (quote rplaca) (quote s!:builtin2) 48) (put (quote rplacd) (quote s!:builtin2) 49) ( put (quote schar) (quote s!:builtin2) 50) (put (quote set) (quote s!:builtin2 ) 51) (put (quote smemq) (quote s!:builtin2) 52) (put (quote subla) (quote s!:builtin2) 53) (put (quote sublis) (quote s!:builtin2) 54) (put (quote symbol!-set!-definition) (quote s!:builtin2) 55) (put (quote symbol!-set!-env ) (quote s!:builtin2) 56) (put (quote times2) (quote s!:builtin2) 57) (put ( quote xcons) (quote s!:builtin2) 58) (put (quote equal) (quote s!:builtin2) 59) (put (quote eq) (quote s!:builtin2) 60) (put (quote cons) (quote s!:builtin2) 61) (put (quote list2) (quote s!:builtin2) 62) (put (quote get) (quote s!:builtin2) 63) (put (quote qgetv) (quote s!:builtin2) 64) (put ( quote flagp) (quote s!:builtin2) 65) (put (quote apply1) (quote s!:builtin2) 66) (put (quote difference) (quote s!:builtin2) 67) (put (quote plus2) (quote s!:builtin2) 68) (put (quote times2) (quote s!:builtin2) 69) (put (quote equalcar) (quote s!:builtin2) 70) (put (quote iequal) (quote s!:builtin2) 71) (put (quote nreverse) (quote s!:builtin2) 72) (put (quote bps!-putv) (quote s!:builtin3) 0) (put (quote errorset) (quote s!:builtin3) 1) (put (quote list2!*) (quote s!:builtin3) 2) (put (quote list3) (quote s!:builtin3) 3) ( put (quote putprop) (quote s!:builtin3) 4) (put (quote putv) (quote s!:builtin3) 5) (put (quote putv!-char) (quote s!:builtin3) 6) (put (quote subst) (quote s!:builtin3) 7) (put (quote apply2) (quote s!:builtin3) 8) (put (quote acons) (quote s!:builtin3) 9) nil) (de s!:prinhex1 (n) (princ (schar "0123456789abcdef" (logand n 15)))) (de s!:prinhex2 (n) (progn (s!:prinhex1 (truncate n 16)) (s!:prinhex1 n))) (de s!:prinhex4 (n) (progn (s!:prinhex2 (truncate n 256)) (s!:prinhex2 n))) (flag (quote (comp plap pgwd pwrds notailcall ord nocompile carcheckflag savedef r2i native_code save_native strip_native)) (quote switch)) (cond ((not (boundp (quote !*comp))) (progn (fluid (quote (!*comp))) (setq !*comp t)))) (cond ((not (boundp (quote !*nocompile))) (progn (fluid (quote (!*nocompile)) ) (setq !*nocompile nil)))) (cond ((not (boundp (quote !*plap))) (progn (fluid (quote (!*plap))) (setq !*plap nil)))) (cond ((not (boundp (quote !*pgwd))) (progn (fluid (quote (!*pgwd))) (setq !*pgwd nil)))) (cond ((not (boundp (quote !*pwrds))) (progn (fluid (quote (!*pwrds))) (setq !*pwrds t)))) (cond ((not (boundp (quote !*notailcall))) (progn (fluid (quote (!*notailcall ))) (setq !*notailcall nil)))) (cond ((not (boundp (quote !*ord))) (progn (fluid (quote (!*ord))) (setq !*ord t)))) (cond ((not (boundp (quote !*savedef))) (progn (fluid (quote (!*savedef))) ( setq !*savedef nil)))) (cond ((not (boundp (quote !*carcheckflag))) (progn (fluid (quote ( !*carcheckflag))) (setq !*carcheckflag t)))) (cond ((not (boundp (quote !*r2i))) (progn (fluid (quote (!*r2i))) (setq !*r2i t)))) (cond ((not (boundp (quote !*native_code))) (progn (fluid (quote ( !*native_code))) (setq !*native_code nil)))) (cond ((not (boundp (quote !*save_native))) (progn (fluid (quote ( !*save_native))) (setq !*save_native nil)))) (cond ((not (boundp (quote !*strip_native))) (progn (fluid (quote ( !*strip_native))) (setq !*strip_native t)))) (global (quote (s!:native_file))) (fluid (quote (s!:current_function s!:current_label s!:current_block s!:current_size s!:current_procedure s!:other_defs s!:lexical_env s!:has_closure s!:recent_literals s!:used_lexicals s!:a_reg_values s!:current_count s!:maybe_values))) (de s!:start_procedure (nargs nopts restarg) (progn (setq s!:current_procedure nil) (setq s!:current_label (gensym)) (setq s!:a_reg_values nil) (cond ((or (not (zerop nopts)) restarg) (progn (setq s!:current_block (list (list (quote OPTARGS) nopts) nopts (list (quote ARGCOUNT) nargs) nargs)) (setq s!:current_size 2))) (t (cond ((greaterp nargs 3) (progn (setq s!:current_block (list (list (quote ARGCOUNT) nargs) nargs)) (setq s!:current_size 1))) (t (progn (setq s!:current_block nil) (setq s!:current_size 0)))))))) (de s!:set_label (x) (progn (cond (s!:current_label (prog (w) (setq w (cons s!:current_size s!:current_block)) (prog (var1005) (setq var1005 s!:recent_literals) lab1004 (cond ((null var1005) (return nil))) (prog (x) ( setq x (car var1005)) (rplaca x w)) (setq var1005 (cdr var1005)) (go lab1004) ) (setq s!:recent_literals nil) (setq s!:current_procedure (cons (cons s!:current_label (cons (list (quote JUMP) x) w)) s!:current_procedure)) (setq s!:current_block nil) (setq s!:current_size 0)))) (setq s!:current_label x) (setq s!:a_reg_values nil))) (de s!:outjump (op lab) (prog (g w) (cond ((not (flagp op (quote s!:preserves_a))) (setq s!:a_reg_values nil))) (cond ((null s!:current_label) (return nil))) (cond ((equal op (quote JUMP)) (setq op (list op lab))) (t ( cond ((equal op (quote ICASE)) (setq op (cons op lab))) (t (setq op (list op lab (setq g (gensym)))))))) (setq w (cons s!:current_size s!:current_block)) (prog (var1007) (setq var1007 s!:recent_literals) lab1006 (cond ((null var1007) (return nil))) (prog (x) (setq x (car var1007)) (rplaca x w)) (setq var1007 (cdr var1007)) (go lab1006)) (setq s!:recent_literals nil) (setq s!:current_procedure (cons (cons s!:current_label (cons op w)) s!:current_procedure)) (setq s!:current_block nil) (setq s!:current_size 0) ( setq s!:current_label g) (return op))) (de s!:outexit nil (prog (w op) (setq op (quote (EXIT))) (cond ((null s!:current_label) (return nil))) (setq w (cons s!:current_size s!:current_block)) (prog (var1009) (setq var1009 s!:recent_literals) lab1008 (cond ((null var1009) (return nil))) (prog (x) (setq x (car var1009)) (rplaca x w)) (setq var1009 (cdr var1009)) (go lab1008)) (setq s!:recent_literals nil) (setq s!:current_procedure (cons (cons s!:current_label (cons op w)) s!:current_procedure)) (setq s!:current_block nil) (setq s!:current_size 0) ( setq s!:current_label nil))) (flag (quote (PUSH PUSHNIL PUSHNIL2 PUSHNIL3 LOSE LOSE2 LOSE3 LOSES STORELOC STORELOC0 STORELOC1 STORELOC2 STORELOC3 STORELOC4 STORELOC5 STORELOC6 STORELOC7 JUMP JUMPT JUMPNIL JUMPEQ JUMPEQUAL JUMPNE JUMPNEQUAL JUMPATOM JUMPNATOM)) (quote s!:preserves_a)) (de s!:outopcode0 (op doc) (prog nil (cond ((not (flagp op (quote s!:preserves_a))) (setq s!:a_reg_values nil))) (cond ((null s!:current_label) (return nil))) (setq s!:current_block (cons op s!:current_block)) (setq s!:current_size (plus s!:current_size 1)) (cond ((or !*plap !*pgwd) (setq s!:current_block (cons doc s!:current_block)))))) (de s!:outopcode1 (op arg doc) (prog nil (cond ((not (flagp op (quote s!:preserves_a))) (setq s!:a_reg_values nil))) (cond ((null s!:current_label) (return nil))) (setq s!:current_block (cons arg (cons op s!:current_block))) (setq s!:current_size (plus s!:current_size 2)) (cond ((or !*plap !*pgwd) ( setq s!:current_block (cons (list op doc) s!:current_block)))))) (deflist (quote ((LOADLIT 1) (LOADFREE 2) (CALL0 2) (CALL1 2) (LITGET 2) ( JUMPLITEQ 2) (JUMPLITNE 2) (JUMPLITEQ!* 2) (JUMPLITNE!* 2) (JUMPFREET 2) ( JUMPFREENIL 2))) (quote s!:short_form_bonus)) (de s!:record_literal (env) (prog (w extra) (setq w (gethash (car s!:current_block) (car env))) (cond ((null w) (setq w (cons 0 nil)))) (setq extra (get (cadr s!:current_block) (quote s!:short_form_bonus))) (cond ((null extra) (setq extra 10)) (t (setq extra (plus extra 10)))) (setq s!:recent_literals (cons (cons nil s!:current_block) s!:recent_literals)) ( puthash (car s!:current_block) (car env) (cons (plus (car w) extra) (cons ( car s!:recent_literals) (cdr w)))))) (de s!:record_literal_for_jump (x env lab) (prog (w extra) (cond ((null s!:current_label) (return nil))) (setq w (gethash (cadr x) (car env))) (cond ((null w) (setq w (cons 0 nil)))) (setq extra (get (car x) (quote s!:short_form_bonus))) (cond ((null extra) (setq extra 10)) (t (setq extra ( plus extra 10)))) (setq x (s!:outjump x lab)) (puthash (cadar x) (car env) ( cons (plus (car w) extra) (cons (cons nil x) (cdr w)))))) (de s!:outopcode1lit (op arg env) (prog nil (cond ((not (flagp op (quote s!:preserves_a))) (setq s!:a_reg_values nil))) (cond ((null s!:current_label) (return nil))) (setq s!:current_block (cons arg (cons op s!:current_block))) (s!:record_literal env) (setq s!:current_size (plus s!:current_size 2)) ( cond ((or !*plap !*pgwd) (setq s!:current_block (cons (list op arg) s!:current_block)))))) (de s!:outopcode2 (op arg1 arg2 doc) (prog nil (cond ((not (flagp op (quote s!:preserves_a))) (setq s!:a_reg_values nil))) (cond ((null s!:current_label) (return nil))) (setq s!:current_block (cons arg2 (cons arg1 (cons op s!:current_block)))) (setq s!:current_size (plus s!:current_size 3)) (cond (( or !*plap !*pgwd) (setq s!:current_block (cons (cons op doc) s!:current_block )))))) (de s!:outopcode2lit (op arg1 arg2 doc env) (prog nil (cond ((not (flagp op ( quote s!:preserves_a))) (setq s!:a_reg_values nil))) (cond ((null s!:current_label) (return nil))) (setq s!:current_block (cons arg1 (cons op s!:current_block))) (s!:record_literal env) (setq s!:current_block (cons arg2 s!:current_block)) (setq s!:current_size (plus s!:current_size 3)) (cond (( or !*plap !*pgwd) (setq s!:current_block (cons (cons op doc) s!:current_block )))))) (de s!:outlexref (op arg1 arg2 arg3 doc) (prog (arg4) (cond ((null s!:current_label) (return nil))) (cond ((or (greaterp arg1 255) (greaterp arg2 255) (greaterp arg3 255)) (progn (cond ((or (greaterp arg1 2047) ( greaterp arg2 31) (greaterp arg3 2047)) (error 0 "stack frame > 2047 or > 31 deep nesting"))) (setq doc (list op doc)) (setq arg4 (logand arg3 255)) (setq arg3 (plus (truncate arg3 256) (times 16 ( logand arg1 15)))) (cond ((equal op (quote LOADLEX)) (setq op (plus 192 arg2) )) (t (setq op (plus 224 arg2)))) (setq arg2 (truncate arg1 16)) (setq arg1 op) (setq op (quote BIGSTACK)))) (t (setq doc (list doc)))) (setq s!:current_block (cons arg3 (cons arg2 (cons arg1 (cons op s!:current_block)) ))) (setq s!:current_size (plus s!:current_size 4)) (cond (arg4 (progn (setq s!:current_block (cons arg4 s!:current_block)) (setq s!:current_size (plus s!:current_size 1))))) (cond ((or !*plap !*pgwd) (setq s!:current_block (cons (cons op doc) s!:current_block)))))) (put (quote LOADLIT) (quote s!:shortform) (cons (quote (1 . 7)) (s!:vecof ( quote (!- LOADLIT1 LOADLIT2 LOADLIT3 LOADLIT4 LOADLIT5 LOADLIT6 LOADLIT7))))) (put (quote LOADFREE) (quote s!:shortform) (cons (quote (1 . 4)) (s!:vecof ( quote (!- LOADFREE1 LOADFREE2 LOADFREE3 LOADFREE4))))) (put (quote STOREFREE) (quote s!:shortform) (cons (quote (1 . 3)) (s!:vecof ( quote (!- STOREFREE1 STOREFREE2 STOREFREE3))))) (put (quote CALL0) (quote s!:shortform) (cons (quote (0 . 3)) (s!:vecof ( quote (CALL0_0 CALL0_1 CALL0_2 CALL0_3))))) (put (quote CALL1) (quote s!:shortform) (cons (quote (0 . 5)) (s!:vecof ( quote (CALL1_0 CALL1_1 CALL1_2 CALL1_3 CALL1_4 CALL1_5))))) (put (quote CALL2) (quote s!:shortform) (cons (quote (0 . 4)) (s!:vecof ( quote (CALL2_0 CALL2_1 CALL2_2 CALL2_3 CALL2_4))))) (put (quote JUMPFREET) (quote s!:shortform) (cons (quote (1 . 4)) (s!:vecof ( quote (!- JUMPFREE1T JUMPFREE2T JUMPFREE3T JUMPFREE4T))))) (put (quote JUMPFREENIL) (quote s!:shortform) (cons (quote (1 . 4)) (s!:vecof (quote (!- JUMPFREE1NIL JUMPFREE2NIL JUMPFREE3NIL JUMPFREE4NIL))))) (put (quote JUMPLITEQ) (quote s!:shortform) (cons (quote (1 . 4)) (s!:vecof ( quote (!- JUMPLIT1EQ JUMPLIT2EQ JUMPLIT3EQ JUMPLIT4EQ))))) (put (quote JUMPLITNE) (quote s!:shortform) (cons (quote (1 . 4)) (s!:vecof ( quote (!- JUMPLIT1NE JUMPLIT2NE JUMPLIT3NE JUMPLIT4NE))))) (put (quote JUMPLITEQ!*) (quote s!:shortform) (get (quote JUMPLITEQ) (quote s!:shortform))) (put (quote JUMPLITNE!*) (quote s!:shortform) (get (quote JUMPLITNE) (quote s!:shortform))) (put (quote CALL0) (quote s!:longform) 0) (put (quote CALL1) (quote s!:longform) 16) (put (quote CALL2) (quote s!:longform) 32) (put (quote CALL3) (quote s!:longform) 48) (put (quote CALLN) (quote s!:longform) 64) (put (quote CALL2R) (quote s!:longform) 80) (put (quote LOADFREE) (quote s!:longform) 96) (put (quote STOREFREE) (quote s!:longform) 112) (put (quote JCALL0) (quote s!:longform) 128) (put (quote JCALL1) (quote s!:longform) 144) (put (quote JCALL2) (quote s!:longform) 160) (put (quote JCALL3) (quote s!:longform) 176) (put (quote JCALLN) (quote s!:longform) 192) (put (quote FREEBIND) (quote s!:longform) 208) (put (quote LITGET) (quote s!:longform) 224) (put (quote LOADLIT) (quote s!:longform) 240) (de s!:literal_order (a b) (cond ((equal (cadr a) (cadr b)) (orderp (car a) ( car b))) (t (greaterp (cadr a) (cadr b))))) (de s!:resolve_literals (env checksum) (prog (w op opspec n litbytes) (setq w (hashcontents (car env))) (setq w (sort w (function s!:literal_order))) ( setq w (append w (list (list checksum 0)))) (setq n (length w)) (setq litbytes (times 4 n)) (cond ((greaterp n 4096) (setq w (s!:too_many_literals w n)))) (setq n 0) (prog (var1011) (setq var1011 w) lab1010 (cond ((null var1011) (return nil))) (prog (x) (setq x (car var1011)) (progn (rplaca (cdr x) n) (setq n (plus n 1)))) (setq var1011 (cdr var1011)) (go lab1010)) (prog (var1015) (setq var1015 w) lab1014 (cond ((null var1015) (return nil))) (prog (x) (setq x (car var1015)) (progn (setq n (cadr x)) (prog (var1013) (setq var1013 (cddr x)) lab1012 (cond ((null var1013) (return nil))) (prog (y) ( setq y (car var1013)) (progn (cond ((null (car y)) (progn (setq op (caadr y)) (setq opspec (get op (quote s!:shortform))) (cond ((and opspec (leq (caar opspec) n) (leq n (cdar opspec))) (rplaca (cdr y) (getv (cdr opspec) n))) (t (rplaca (cdadr y) n))))) (t (progn (setq op (caddr y)) (cond ((greaterp n 255 ) (progn (rplaca (car y) (plus (caar y) 1)) (setq op (plus (get op (quote s!:longform)) (truncate n 256))) (rplaca (cdr y) (ilogand n 255)) (rplaca ( cddr y) (quote BIGCALL)) (rplacd (cdr y) (cons op (cddr y))))) (t (cond ((and (setq opspec (get op (quote s!:shortform))) (leq (caar opspec) n) (leq n ( cdar opspec))) (progn (rplaca (car y) (difference (caar y) 1)) (rplaca (cdr y ) (getv (cdr opspec) n)) (rplacd (cdr y) (cdddr y)))) (t (rplaca (cdr y) n))) ))))))) (setq var1013 (cdr var1013)) (go lab1012)))) (setq var1015 (cdr var1015)) (go lab1014)) (prog (var1017) (setq var1017 w) lab1016 (cond ((null var1017) (return nil))) (prog (x) (setq x (car var1017)) (rplacd x (cadr x)) ) (setq var1017 (cdr var1017)) (go lab1016)) (rplaca env (cons (reversip w) litbytes)))) (de s!:only_loadlit (l) (cond ((null l) t) (t (cond ((null (caar l)) nil) (t (cond ((not (eqcar (cddar l) (quote LOADLIT))) nil) (t (s!:only_loadlit (cdr l))))))))) (de s!:too_many_literals (w n) (prog (k xvecs l r newrefs uses z1) (setq k 0) (setq n (plus n 1)) (prog nil lab1018 (cond ((null (and (greaterp n 4096) ( not (null w)))) (return nil))) (progn (cond ((and (not (equal (cadar w) 10000000)) (s!:only_loadlit (cddar w))) (progn (setq l (cons (car w) l)) ( setq n (difference n 1)) (setq k (plus k 1)) (cond ((equal k 256) (progn ( setq xvecs (cons l xvecs)) (setq l nil) (setq k 0) (setq n (plus n 1))))))) ( t (setq r (cons (car w) r)))) (setq w (cdr w))) (go lab1018)) (cond (( greaterp n 4096) (error 0 "function uses too many literals (4096 is limit)")) ) (setq xvecs (cons l xvecs)) (prog nil lab1019 (cond ((null r) (return nil)) ) (progn (setq w (cons (car r) w)) (setq r (cdr r))) (go lab1019)) (prog ( var1025) (setq var1025 xvecs) lab1024 (cond ((null var1025) (return nil))) ( prog (v) (setq v (car var1025)) (progn (setq newrefs nil) (setq uses 0) (setq r nil) (setq k 0) (prog (var1023) (setq var1023 v) lab1022 (cond ((null var1023) (return nil))) (prog (q) (setq q (car var1023)) (progn (prog ( var1021) (setq var1021 (cddr q)) lab1020 (cond ((null var1021) (return nil))) (prog (z) (setq z (car var1021)) (progn (cond ((car z) (rplaca (car z) (plus (caar z) 2)))) (setq z1 (cons (quote QGETVN) (cons nil (cddr z)))) (rplaca ( cdr z) k) (rplacd (cdr z) z1) (rplacd z (cdr z1)) (setq newrefs (cons z newrefs)) (setq uses (plus uses 11)))) (setq var1021 (cdr var1021)) (go lab1020)) (setq r (cons (car q) r)) (setq k (plus k 1)))) (setq var1023 (cdr var1023)) (go lab1022)) (setq newrefs (cons uses newrefs)) (setq newrefs ( cons (s!:vecof (reversip r)) newrefs)) (setq w (cons newrefs w)))) (setq var1025 (cdr var1025)) (go lab1024)) (return (sort w (function s!:literal_order))))) (fluid (quote (s!:into_c))) (de s!:endprocedure (name env checksum) (prog (pc labelvals w vec) ( s!:outexit) (cond (s!:into_c (return (cons s!:current_procedure env)))) ( s!:resolve_literals env checksum) (setq s!:current_procedure ( s!:tidy_flowgraph s!:current_procedure)) (cond ((and (not !*notailcall) (not s!:has_closure)) (setq s!:current_procedure (s!:try_tailcall s!:current_procedure)))) (setq s!:current_procedure (s!:tidy_exits s!:current_procedure)) (setq labelvals (s!:resolve_labels)) (setq pc (car labelvals)) (setq labelvals (cdr labelvals)) (setq vec (make!-bps pc)) (setq pc 0) (cond ((or !*plap !*pgwd) (progn (terpri) (ttab 23) (princ "+++ ") ( prin name) (princ " +++") (terpri)))) (prog (var1027) (setq var1027 s!:current_procedure) lab1026 (cond ((null var1027) (return nil))) (prog (b) (setq b (car var1027)) (progn (cond ((and (car b) (flagp (car b) (quote used_label)) (or !*plap !*pgwd)) (progn (ttab 20) (prin (car b)) (princ ":") (terpri)))) (setq pc (s!:plant_basic_block vec pc (reverse (cdddr b)))) (setq b (cadr b)) (cond ((and b (neq (car b) (quote ICASE)) (cdr b) (cddr b)) ( setq b (list (car b) (cadr b))))) (setq pc (s!:plant_exit_code vec pc b labelvals)))) (setq var1027 (cdr var1027)) (go lab1026)) (cond (!*pwrds ( progn (cond ((neq (posn) 0) (terpri))) (princ "+++ ") (prin name) (princ " compiled, ") (princ pc) (princ " + ") (princ (cdar env)) (princ " bytes") ( terpri)))) (setq env (caar env)) (cond ((null env) (setq w nil)) (t (progn ( setq w (mkvect (cdar env))) (prog nil lab1028 (cond ((null env) (return nil)) ) (progn (putv w (cdar env) (caar env)) (setq env (cdr env))) (go lab1028)))) ) (return (cons vec w)))) (de s!:add_pending (lab pend blocks) (prog (w) (cond ((not (atom lab)) ( return (cons (list (gensym) lab 0) pend)))) (setq w (atsoc lab pend)) (cond ( w (return (cons w (deleq w pend)))) (t (return (cons (atsoc lab blocks) pend) ))))) (de s!:invent_exit (x blocks) (prog (w) (setq w blocks) scan (cond ((null w) (go not_found)) (t (cond ((and (eqcar (cadar w) x) (equal (caddar w) 0)) ( return (cons (caar w) blocks))) (t (setq w (cdr w)))))) (go scan) not_found ( setq w (gensym)) (return (cons w (cons (list w (list x) 0) blocks))))) (de s!:destination_label (lab blocks) (prog (n w x) (setq w (atsoc lab blocks )) (cond ((s!:is_lose_and_exit w blocks) (return (quote (EXIT))))) (setq x ( cadr w)) (setq n (caddr w)) (setq w (cdddr w)) (cond ((neq n 0) (return lab)) ) (cond ((or (null x) (null (cdr x))) (return x)) (t (cond ((equal (cadr x) lab) (return lab)) (t (cond ((null (cddr x)) (return (s!:destination_label ( cadr x) blocks))) (t (return lab))))))))) (de s!:remlose (b) (prog (w) (setq w b) (prog nil lab1029 (cond ((null (and w (not (atom (car w))))) (return nil))) (setq w (cdr w)) (go lab1029)) (cond ( (null w) (return (cons 0 b)))) (cond ((and (numberp (car w)) (eqcar (cdr w) ( quote LOSES))) (setq w (cons 2 (cddr w)))) (t (cond ((or (equal (car w) ( quote LOSE)) (equal (car w) (quote LOSE2)) (equal (car w) (quote LOSE3))) ( setq w (cons 1 (cdr w)))) (t (return (cons 0 b)))))) (setq b (s!:remlose (cdr w))) (return (cons (plus (car w) (car b)) (cdr b))))) (put (quote CALL0_0) (quote s!:shortcall) (quote (0 . 0))) (put (quote CALL0_1) (quote s!:shortcall) (quote (0 . 1))) (put (quote CALL0_2) (quote s!:shortcall) (quote (0 . 2))) (put (quote CALL0_3) (quote s!:shortcall) (quote (0 . 3))) (put (quote CALL1_0) (quote s!:shortcall) (quote (1 . 0))) (put (quote CALL1_1) (quote s!:shortcall) (quote (1 . 1))) (put (quote CALL1_2) (quote s!:shortcall) (quote (1 . 2))) (put (quote CALL1_3) (quote s!:shortcall) (quote (1 . 3))) (put (quote CALL1_4) (quote s!:shortcall) (quote (1 . 4))) (put (quote CALL1_5) (quote s!:shortcall) (quote (1 . 5))) (put (quote CALL2_0) (quote s!:shortcall) (quote (2 . 0))) (put (quote CALL2_1) (quote s!:shortcall) (quote (2 . 1))) (put (quote CALL2_2) (quote s!:shortcall) (quote (2 . 2))) (put (quote CALL2_3) (quote s!:shortcall) (quote (2 . 3))) (put (quote CALL2_4) (quote s!:shortcall) (quote (2 . 4))) (de s!:remcall (b) (prog (w p q r s) (prog nil lab1030 (cond ((null (and b ( not (atom (car b))))) (return nil))) (progn (setq p (car b)) (setq b (cdr b)) ) (go lab1030)) (cond ((null b) (return nil)) (t (cond ((numberp (car b)) ( progn (setq r (car b)) (setq s 2) (setq b (cdr b)) (cond ((null b) (return nil)) (t (cond ((numberp (car b)) (progn (setq q r) (setq r (car b)) (setq s 3) (setq b (cdr b)) (cond ((and b (numberp (setq w (car b))) (eqcar (cdr b) ( quote BIGCALL)) (equal (truncate w 16) 4)) (progn (setq r (plus (times 256 ( logand w 15)) r)) (setq s 4) (setq b (cdr b)))) (t (cond ((eqcar b (quote BIGCALL)) (progn (setq w (truncate r 16)) (setq r (plus (times 256 (logand r 15)) q)) (setq q w) (cond ((equal q 5) (progn (setq q 2) (setq s (difference s 1)) (setq b (cons (quote BIGCALL) (cons (quote SWOP) (cdr b))))))) (cond (( greaterp q 4) (return nil))))) (t (cond ((not (eqcar b (quote CALLN))) ( return nil))))))))) (t (cond ((equal (car b) (quote CALL0)) (setq q 0)) (t ( cond ((equal (car b) (quote CALL1)) (setq q 1)) (t (cond ((equal (car b) ( quote CALL2)) (setq q 2)) (t (cond ((equal (car b) (quote CALL2R)) (progn ( setq q 2) (setq s (difference s 1)) (setq b (cons (quote CALL2) (cons (quote SWOP) (cdr b)))))) (t (cond ((equal (car b) (quote CALL3)) (setq q 3)) (t ( return nil))))))))))))))) (setq b (cdr b)))) (t (cond ((setq q (get (car b) ( quote s!:shortcall))) (progn (setq r (cdr q)) (setq q (car q)) (setq s 1) ( setq b (cdr b)))) (t (return nil))))))) (return (cons p (cons q (cons r (cons s b))))))) (de s!:is_lose_and_exit (b blocks) (prog (lab exit) (setq lab (car b)) (setq exit (cadr b)) (setq b (cdddr b)) (cond ((null exit) (return nil))) (setq b ( s!:remlose b)) (setq b (cdr b)) (prog nil lab1031 (cond ((null (and b (not ( atom (car b))))) (return nil))) (setq b (cdr b)) (go lab1031)) (cond (b ( return nil)) (t (cond ((equal (car exit) (quote EXIT)) (return t)) (t (cond ( (equal (car exit) (quote JUMP)) (progn (cond ((equal (cadr exit) lab) nil) (t (return (s!:is_lose_and_exit (atsoc (cadr exit) blocks) blocks)))))) (t ( return nil))))))))) (de s!:try_tail_1 (b blocks) (prog (exit size body w w0 w1 w2 op) (setq exit (cadr b)) (cond ((null exit) (return b)) (t (cond ((not (equal (car exit) ( quote EXIT))) (progn (cond ((equal (car exit) (quote JUMP)) (progn (cond (( not (s!:is_lose_and_exit (atsoc (cadr exit) blocks) blocks)) (return b))))) ( t (return b)))))))) (setq size (caddr b)) (setq body (cdddr b)) (setq body ( s!:remlose body)) (setq size (difference size (car body))) (setq body (cdr body)) (setq w (s!:remcall body)) (cond ((null w) (return b))) (setq w0 (cadr w)) (setq w1 (caddr w)) (setq body (cddddr w)) (cond ((and (leq w0 7) (leq w1 31)) (progn (setq body (cons (quote JCALL) body)) (setq body (cons (plus ( times 32 w0) w1) body)) (setq size (difference size 1)))) (t (cond ((lessp w1 256) (setq body (cons w0 (cons w1 (cons (quote JCALLN) body))))) (t (progn ( setq body (cons (quote BIGCALL) body)) (setq w2 (logand w1 255)) (setq w1 ( truncate w1 256)) (cond ((lessp w0 4) (setq body (cons w2 (cons (plus w1 ( times 16 w0) 128) body)))) (t (progn (setq body (cons w0 (cons w2 (cons (plus w1 (plus (times 16 4) 128)) body)))) (setq size (plus size 1)))))))))) (cond ((car w) (setq body (cons (append (car w) (list (quote TAIL))) body)))) ( rplaca (cdr b) nil) (rplaca (cddr b) (plus (difference size (cadddr w)) 3)) ( rplacd (cddr b) body) (return b))) (de s!:try_tailcall (b) (prog (var1033 var1034) (setq var1033 b) lab1032 ( cond ((null var1033) (return (reversip var1034)))) (prog (v) (setq v (car var1033)) (setq var1034 (cons (s!:try_tail_1 v b) var1034))) (setq var1033 ( cdr var1033)) (go lab1032))) (de s!:tidy_exits_1 (b blocks) (prog (exit size body comm w w0 w1 w2 op) ( setq exit (cadr b)) (cond ((null exit) (return b)) (t (cond ((not (equal (car exit) (quote EXIT))) (progn (cond ((equal (car exit) (quote JUMP)) (progn ( cond ((not (s!:is_lose_and_exit (atsoc (cadr exit) blocks) blocks)) (return b ))))) (t (return b)))))))) (setq size (caddr b)) (setq body (cdddr b)) (setq body (s!:remlose body)) (setq size (difference size (car body))) (setq body ( cdr body)) (prog nil lab1035 (cond ((null (and body (not (atom (car body))))) (return nil))) (progn (setq comm (car body)) (setq body (cdr body))) (go lab1035)) (cond ((eqcar body (quote VNIL)) (setq w (quote NILEXIT))) (t (cond ((eqcar body (quote LOADLOC0)) (setq w (quote LOC0EXIT))) (t (cond ((eqcar body (quote LOADLOC1)) (setq w (quote LOC1EXIT))) (t (cond ((eqcar body ( quote LOADLOC2)) (setq w (quote LOC2EXIT))) (t (setq w nil))))))))) (cond (w (progn (rplaca (cdr b) (list w)) (setq body (cdr body)) (setq size ( difference size 1)))) (t (cond (comm (setq body (cons comm body)))))) (rplaca (cddr b) size) (rplacd (cddr b) body) (return b))) (de s!:tidy_exits (b) (prog (var1037 var1038) (setq var1037 b) lab1036 (cond ((null var1037) (return (reversip var1038)))) (prog (v) (setq v (car var1037) ) (setq var1038 (cons (s!:tidy_exits_1 v b) var1038))) (setq var1037 (cdr var1037)) (go lab1036))) (de s!:tidy_flowgraph (b) (prog (r pending) (setq b (reverse b)) (setq pending (list (car b))) (prog nil lab1040 (cond ((null pending) (return nil)) ) (prog (c x l1 l2 done1 done2) (setq c (car pending)) (setq pending (cdr pending)) (flag (list (car c)) (quote coded)) (setq x (cadr c)) (cond ((or ( null x) (null (cdr x))) (setq r (cons c r))) (t (cond ((equal (car x) (quote ICASE)) (progn (rplacd x (reversip (cdr x))) (prog (ll) (setq ll (cdr x)) lab1039 (cond ((null ll) (return nil))) (progn (setq l1 (s!:destination_label (car ll) b)) (cond ((not (atom l1)) (progn (setq l1 (s!:invent_exit (car l1) b)) (setq b (cdr l1)) (setq l1 (cadr l1))))) (rplaca ll l1) (setq done1 ( flagp l1 (quote coded))) (flag (list l1) (quote used_label)) (cond ((not done1) (setq pending (s!:add_pending l1 pending b))))) (setq ll (cdr ll)) (go lab1039)) (rplacd x (reversip (cdr x))) (setq r (cons c r)))) (t (cond (( null (cddr x)) (progn (setq l1 (s!:destination_label (cadr x) b)) (cond ((not (atom l1)) (setq c (cons (car c) (cons l1 (cddr c))))) (t (cond ((flagp l1 ( quote coded)) (progn (flag (list l1) (quote used_label)) (setq c (cons (car c ) (cons (list (car x) l1) (cddr c)))))) (t (progn (setq c (cons (car c) (cons nil (cddr c)))) (setq pending (s!:add_pending l1 pending b))))))) (setq r ( cons c r)))) (t (progn (setq l1 (s!:destination_label (cadr x) b)) (setq l2 ( s!:destination_label (caddr x) b)) (setq done1 (and (atom l1) (flagp l1 ( quote coded)))) (setq done2 (and (atom l2) (flagp l2 (quote coded)))) (cond ( done1 (progn (cond (done2 (progn (flag (list l1) (quote used_label)) (rplaca (cdadr c) l1) (setq pending (cons (list (gensym) (list (quote JUMP) l2) 0) pending)))) (t (progn (flag (list l1) (quote used_label)) (rplaca (cdadr c) l1) (setq pending (s!:add_pending l2 pending b))))))) (t (progn (cond (done2 (progn (flag (list l2) (quote used_label)) (rplaca (cadr c) (s!:negate_jump ( car x))) (rplaca (cdadr c) l2) (setq pending (s!:add_pending l1 pending b)))) (t (progn (cond ((not (atom l1)) (progn (setq l1 (s!:invent_exit (car l1) b) ) (setq b (cdr l1)) (setq l1 (car l1))))) (flag (list l1) (quote used_label)) (rplaca (cdadr c) l1) (cond ((not (flagp l1 (quote coded))) (setq pending ( s!:add_pending l1 pending b)))) (setq pending (s!:add_pending l2 pending b))) ))))) (setq r (cons c r)))))))))) (go lab1040)) (return (reverse r)))) (deflist (quote ((JUMPNIL JUMPT) (JUMPT JUMPNIL) (JUMPATOM JUMPNATOM) ( JUMPNATOM JUMPATOM) (JUMPEQ JUMPNE) (JUMPNE JUMPEQ) (JUMPEQUAL JUMPNEQUAL) ( JUMPNEQUAL JUMPEQUAL) (JUMPL0NIL JUMPL0T) (JUMPL0T JUMPL0NIL) (JUMPL1NIL JUMPL1T) (JUMPL1T JUMPL1NIL) (JUMPL2NIL JUMPL2T) (JUMPL2T JUMPL2NIL) ( JUMPL3NIL JUMPL3T) (JUMPL3T JUMPL3NIL) (JUMPL4NIL JUMPL4T) (JUMPL4T JUMPL4NIL ) (JUMPL0ATOM JUMPL0NATOM) (JUMPL0NATOM JUMPL0ATOM) (JUMPL1ATOM JUMPL1NATOM) (JUMPL1NATOM JUMPL1ATOM) (JUMPL2ATOM JUMPL2NATOM) (JUMPL2NATOM JUMPL2ATOM) ( JUMPL3ATOM JUMPL3NATOM) (JUMPL3NATOM JUMPL3ATOM) (JUMPST0NIL JUMPST0T) ( JUMPST0T JUMPST0NIL) (JUMPST1NIL JUMPST1T) (JUMPST1T JUMPST1NIL) (JUMPST2NIL JUMPST2T) (JUMPST2T JUMPST2NIL) (JUMPFREE1NIL JUMPFREE1T) (JUMPFREE1T JUMPFREE1NIL) (JUMPFREE2NIL JUMPFREE2T) (JUMPFREE2T JUMPFREE2NIL) ( JUMPFREE3NIL JUMPFREE3T) (JUMPFREE3T JUMPFREE3NIL) (JUMPFREE4NIL JUMPFREE4T) (JUMPFREE4T JUMPFREE4NIL) (JUMPFREENIL JUMPFREET) (JUMPFREET JUMPFREENIL) ( JUMPLIT1EQ JUMPLIT1NE) (JUMPLIT1NE JUMPLIT1EQ) (JUMPLIT2EQ JUMPLIT2NE) ( JUMPLIT2NE JUMPLIT2EQ) (JUMPLIT3EQ JUMPLIT3NE) (JUMPLIT3NE JUMPLIT3EQ) ( JUMPLIT4EQ JUMPLIT4NE) (JUMPLIT4NE JUMPLIT4EQ) (JUMPLITEQ JUMPLITNE) ( JUMPLITNE JUMPLITEQ) (JUMPLITEQ!* JUMPLITNE!*) (JUMPLITNE!* JUMPLITEQ!*) ( JUMPB1NIL JUMPB1T) (JUMPB1T JUMPB1NIL) (JUMPB2NIL JUMPB2T) (JUMPB2T JUMPB2NIL ) (JUMPFLAGP JUMPNFLAGP) (JUMPNFLAGP JUMPFLAGP) (JUMPEQCAR JUMPNEQCAR) ( JUMPNEQCAR JUMPEQCAR))) (quote negjump)) (de s!:negate_jump (x) (cond ((atom x) (get x (quote negjump))) (t (rplaca x (get (car x) (quote negjump)))))) (de s!:resolve_labels nil (prog (w labelvals converged pc x) (prog nil lab1043 (progn (setq converged t) (setq pc 0) (prog (var1042) (setq var1042 s!:current_procedure) lab1041 (cond ((null var1042) (return nil))) (prog (b) (setq b (car var1042)) (progn (setq w (assoc!*!* (car b) labelvals)) (cond (( null w) (progn (setq converged nil) (setq w (cons (car b) pc)) (setq labelvals (cons w labelvals)))) (t (cond ((neq (cdr w) pc) (progn (rplacd w pc) (setq converged nil)))))) (setq pc (plus pc (caddr b))) (setq x (cadr b)) (cond ((null x) nil) (t (cond ((null (cdr x)) (setq pc (plus pc 1))) (t ( cond ((equal (car x) (quote ICASE)) (setq pc (plus pc (times 2 (length x))))) (t (progn (setq w (assoc!*!* (cadr x) labelvals)) (cond ((null w) (progn ( setq w 128) (setq converged nil))) (t (setq w (difference (cdr w) pc)))) ( setq w (s!:expand_jump (car x) w)) (setq pc (plus pc (length w)))))))))))) ( setq var1042 (cdr var1042)) (go lab1041))) (cond ((null converged) (go lab1043)))) (return (cons pc labelvals)))) (de s!:plant_basic_block (vec pc b) (prog (tagged) (prog (var1047) (setq var1047 b) lab1046 (cond ((null var1047) (return nil))) (prog (i) (setq i ( car var1047)) (progn (cond ((atom i) (progn (cond ((symbolp i) (setq i (get i (quote s!:opcode))))) (cond ((and (not tagged) (or !*plap !*pgwd)) (progn ( s!:prinhex4 pc) (princ ":") (ttab 8) (setq tagged t)))) (cond ((or (not (fixp i)) (lessp i 0) (greaterp i 255)) (error "bad byte to put" i))) (bps!-putv vec pc i) (cond ((or !*plap !*pgwd) (progn (s!:prinhex2 i) (princ " ")))) ( setq pc (plus pc 1)))) (t (cond ((or !*plap !*pgwd) (progn (ttab 23) (princ ( car i)) (prog (var1045) (setq var1045 (cdr i)) lab1044 (cond ((null var1045) (return nil))) (prog (w) (setq w (car var1045)) (progn (princ " ") (prin w))) (setq var1045 (cdr var1045)) (go lab1044)) (terpri) (setq tagged nil)))))))) (setq var1047 (cdr var1047)) (go lab1046)) (return pc))) (de s!:plant_bytes (vec pc bytelist doc) (prog nil (cond ((or !*plap !*pgwd) (progn (s!:prinhex4 pc) (princ ":") (ttab 8)))) (prog (var1049) (setq var1049 bytelist) lab1048 (cond ((null var1049) (return nil))) (prog (v) (setq v ( car var1049)) (progn (cond ((symbolp v) (setq v (get v (quote s!:opcode))))) (cond ((or (not (fixp v)) (lessp v 0) (greaterp v 255)) (error "bad byte to put" v))) (bps!-putv vec pc v) (cond ((or !*plap !*pgwd) (progn (cond ((greaterp (posn) 50) (progn (terpri) (ttab 8)))) (s!:prinhex2 v) ( princ " ")))) (setq pc (plus pc 1)))) (setq var1049 (cdr var1049)) (go lab1048)) (cond ((or !*plap !*pgwd) (progn (cond ((greaterp (posn) 23) ( terpri))) (ttab 23) (princ (car doc)) (prog (var1051) (setq var1051 (cdr doc) ) lab1050 (cond ((null var1051) (return nil))) (prog (w) (setq w (car var1051 )) (progn (cond ((greaterp (posn) 65) (progn (terpri) (ttab 23)))) (princ " " ) (prin w))) (setq var1051 (cdr var1051)) (go lab1050)) (terpri)))) (return pc))) (de s!:plant_exit_code (vec pc b labelvals) (prog (w loc low high r) (cond (( null b) (return pc)) (t (cond ((null (cdr b)) (return (s!:plant_bytes vec pc (list (get (car b) (quote s!:opcode))) b))) (t (cond ((equal (car b) (quote ICASE)) (progn (setq loc (plus pc 3)) (prog (var1053) (setq var1053 (cdr b)) lab1052 (cond ((null var1053) (return nil))) (prog (ll) (setq ll (car var1053 )) (progn (setq w (difference (cdr (assoc!*!* ll labelvals)) loc)) (setq loc (plus loc 2)) (cond ((lessp w 0) (progn (setq w (minus w)) (setq low (ilogand w 255)) (setq high (plus 128 (truncate (difference w low) 256))))) (t (progn (setq low (ilogand w 255)) (setq high (truncate (difference w low) 256))))) (setq r (cons low (cons high r))))) (setq var1053 (cdr var1053)) (go lab1052) ) (setq r (cons (get (quote ICASE) (quote s!:opcode)) (cons (length (cddr b)) (reversip r)))) (return (s!:plant_bytes vec pc r b))))))))) (setq w ( difference (cdr (assoc!*!* (cadr b) labelvals)) pc)) (setq w (s!:expand_jump (car b) w)) (return (s!:plant_bytes vec pc w b)))) (deflist (quote ((JUMPL0NIL ((LOADLOC0) JUMPNIL)) (JUMPL0T ((LOADLOC0) JUMPT) ) (JUMPL1NIL ((LOADLOC1) JUMPNIL)) (JUMPL1T ((LOADLOC1) JUMPT)) (JUMPL2NIL (( LOADLOC2) JUMPNIL)) (JUMPL2T ((LOADLOC2) JUMPT)) (JUMPL3NIL ((LOADLOC3) JUMPNIL)) (JUMPL3T ((LOADLOC3) JUMPT)) (JUMPL4NIL ((LOADLOC4) JUMPNIL)) ( JUMPL4T ((LOADLOC4) JUMPT)) (JUMPL0ATOM ((LOADLOC0) JUMPATOM)) (JUMPL0NATOM ( (LOADLOC0) JUMPNATOM)) (JUMPL1ATOM ((LOADLOC1) JUMPATOM)) (JUMPL1NATOM (( LOADLOC1) JUMPNATOM)) (JUMPL2ATOM ((LOADLOC2) JUMPATOM)) (JUMPL2NATOM (( LOADLOC2) JUMPNATOM)) (JUMPL3ATOM ((LOADLOC3) JUMPATOM)) (JUMPL3NATOM (( LOADLOC3) JUMPNATOM)) (JUMPST0NIL ((STORELOC0) JUMPNIL)) (JUMPST0T (( STORELOC0) JUMPT)) (JUMPST1NIL ((STORELOC1) JUMPNIL)) (JUMPST1T ((STORELOC1) JUMPT)) (JUMPST2NIL ((STORELOC2) JUMPNIL)) (JUMPST2T ((STORELOC2) JUMPT)) ( JUMPFREE1NIL ((LOADFREE1) JUMPNIL)) (JUMPFREE1T ((LOADFREE1) JUMPT)) ( JUMPFREE2NIL ((LOADFREE2) JUMPNIL)) (JUMPFREE2T ((LOADFREE2) JUMPT)) ( JUMPFREE3NIL ((LOADFREE3) JUMPNIL)) (JUMPFREE3T ((LOADFREE3) JUMPT)) ( JUMPFREE4NIL ((LOADFREE4) JUMPNIL)) (JUMPFREE4T ((LOADFREE4) JUMPT)) ( JUMPFREENIL ((LOADFREE !*) JUMPNIL)) (JUMPFREET ((LOADFREE !*) JUMPT)) ( JUMPLIT1EQ ((LOADLIT1) JUMPEQ)) (JUMPLIT1NE ((LOADLIT1) JUMPNE)) (JUMPLIT2EQ ((LOADLIT2) JUMPEQ)) (JUMPLIT2NE ((LOADLIT2) JUMPNE)) (JUMPLIT3EQ ((LOADLIT3) JUMPEQ)) (JUMPLIT3NE ((LOADLIT3) JUMPNE)) (JUMPLIT4EQ ((LOADLIT4) JUMPEQ)) ( JUMPLIT4NE ((LOADLIT4) JUMPNE)) (JUMPLITEQ ((LOADLIT !*) JUMPEQ)) (JUMPLITNE ((LOADLIT !*) JUMPNE)) (JUMPLITEQ!* ((LOADLIT !* SWOP) JUMPEQ)) (JUMPLITNE!* ((LOADLIT !* SWOP) JUMPNE)) (JUMPB1NIL ((BUILTIN1 !*) JUMPNIL)) (JUMPB1T (( BUILTIN1 !*) JUMPT)) (JUMPB2NIL ((BUILTIN2 !*) JUMPNIL)) (JUMPB2T ((BUILTIN2 !*) JUMPT)) (JUMPFLAGP ((LOADLIT !* FLAGP) JUMPT)) (JUMPNFLAGP ((LOADLIT !* FLAGP) JUMPNIL)) (JUMPEQCAR ((LOADLIT !* EQCAR) JUMPT)) (JUMPNEQCAR ((LOADLIT !* EQCAR) JUMPNIL)))) (quote s!:expand_jump)) (fluid (quote (s!:backwards_jump s!:longer_jump))) (progn (setq s!:backwards_jump (make!-simple!-string 256)) (setq s!:longer_jump (make!-simple!-string 256)) nil) (prog (var1055) (setq var1055 (quote ((JUMP JUMP_B JUMP_L JUMP_BL) (JUMPNIL JUMPNIL_B JUMPNIL_L JUMPNIL_BL) (JUMPT JUMPT_B JUMPT_L JUMPT_BL) (JUMPATOM JUMPATOM_B JUMPATOM_L JUMPATOM_BL) (JUMPNATOM JUMPNATOM_B JUMPNATOM_L JUMPNATOM_BL) (JUMPEQ JUMPEQ_B JUMPEQ_L JUMPEQ_BL) (JUMPNE JUMPNE_B JUMPNE_L JUMPNE_BL) (JUMPEQUAL JUMPEQUAL_B JUMPEQUAL_L JUMPEQUAL_BL) (JUMPNEQUAL JUMPNEQUAL_B JUMPNEQUAL_L JUMPNEQUAL_BL) (CATCH CATCH_B CATCH_L CATCH_BL)))) lab1054 (cond ((null var1055) (return nil))) (prog (op) (setq op (car var1055 )) (progn (putv!-char s!:backwards_jump (get (car op) (quote s!:opcode)) (get (cadr op) (quote s!:opcode))) (putv!-char s!:backwards_jump (get (caddr op) (quote s!:opcode)) (get (cadddr op) (quote s!:opcode))) (putv!-char s!:longer_jump (get (car op) (quote s!:opcode)) (get (caddr op) (quote s!:opcode))) (putv!-char s!:longer_jump (get (cadr op) (quote s!:opcode)) ( get (cadddr op) (quote s!:opcode))))) (setq var1055 (cdr var1055)) (go lab1054)) (de s!:expand_jump (op offset) (prog (arg low high opcode expanded) (cond (( not (atom op)) (progn (setq arg (cadr op)) (setq op (car op)) (setq offset ( difference offset 1))))) (setq expanded (get op (quote s!:expand_jump))) ( cond ((and expanded (not (and (leq 2 offset) (lessp offset (plus 256 2)) (or (null arg) (lessp arg 256))))) (progn (setq op (cadr expanded)) (setq expanded (car expanded)) (cond (arg (progn (cond ((greaterp arg 2047) (error 0 "function uses too many literals (2048 limit)")) (t (cond ((greaterp arg 255) (prog (high low) (setq low (ilogand arg 255)) (setq high (truncate ( difference arg low) 256)) (setq expanded (cons (quote BIGCALL) (cons (plus ( get (car expanded) (quote s!:longform)) high) (cons low (cddr expanded))))))) (t (setq expanded (subst arg (quote !*) expanded)))))) (setq offset (plus offset 1))))) (setq offset (difference offset (length expanded))) (setq arg nil))) (t (setq expanded nil))) (setq opcode (get op (quote s!:opcode))) ( cond ((null opcode) (error 0 (list op offset "invalid block exit")))) (cond ( (and (lessp (plus (minus 256) 2) offset) (lessp offset (plus 256 2))) (setq offset (difference offset 2))) (t (progn (setq high t) (setq offset ( difference offset 3))))) (cond ((lessp offset 0) (progn (setq opcode ( byte!-getv s!:backwards_jump opcode)) (setq offset (minus offset))))) (cond ( high (progn (setq low (logand offset 255)) (setq high (truncate (difference offset low) 256)))) (t (cond ((greaterp (setq low offset) 255) (error 0 "Bad offset in expand_jump"))))) (cond (arg (return (list opcode arg low))) ( t (cond ((not high) (return (append expanded (list opcode low)))) (t (return (append expanded (list (byte!-getv s!:longer_jump opcode) high low))))))))) (de s!:comval (x env context) (prog (helper) (setq x (s!:improve x)) (cond (( atom x) (return (s!:comatom x env context))) (t (cond ((eqcar (car x) (quote lambda)) (return (s!:comlambda (cadar x) (cddar x) (cdr x) env context))) (t (cond ((eq (car x) s!:current_function) (s!:comcall x env context)) (t (cond ((and (setq helper (get (car x) (quote s!:compilermacro))) (setq helper ( funcall helper x env context))) (return (s!:comval helper env context))) (t ( cond ((setq helper (get (car x) (quote s!:newname))) (return (s!:comval (cons helper (cdr x)) env context))) (t (cond ((setq helper (get (car x) (quote s!:compfn))) (return (funcall helper x env context))) (t (cond ((setq helper (macro!-function (car x))) (return (s!:comval (funcall helper x) env context) )) (t (return (s!:comcall x env context)))))))))))))))))) (de s!:comspecform (x env context) (error 0 (list "special form" x))) (cond ((null (get (quote and) (quote s!:compfn))) (progn (put (quote compiler!-let) (quote s!:compfn) (function s!:comspecform)) (put (quote de) ( quote s!:compfn) (function s!:comspecform)) (put (quote defun) (quote s!:compfn) (function s!:comspecform)) (put (quote eval!-when) (quote s!:compfn) (function s!:comspecform)) (put (quote flet) (quote s!:compfn) ( function s!:comspecform)) (put (quote labels) (quote s!:compfn) (function s!:comspecform)) (put (quote macrolet) (quote s!:compfn) (function s!:comspecform)) (put (quote multiple!-value!-call) (quote s!:compfn) ( function s!:comspecform)) (put (quote multiple!-value!-prog1) (quote s!:compfn) (function s!:comspecform)) (put (quote prog!*) (quote s!:compfn) ( function s!:comspecform)) (put (quote progv) (quote s!:compfn) (function s!:comspecform)) nil))) (de s!:improve (u) (prog (w) (cond ((atom u) (return u)) (t (cond ((setq w ( get (car u) (quote s!:tidy_fn))) (return (funcall w u))) (t (cond ((setq w ( get (car u) (quote s!:newname))) (return (s!:improve (cons w (cdr u))))) (t ( return u))))))))) (de s!:imp_minus (u) (prog (a) (setq a (s!:improve (cadr u))) (return (cond ( (numberp a) (minus a)) (t (cond ((or (eqcar a (quote minus)) (eqcar a (quote iminus))) (cadr a)) (t (cond ((eqcar a (quote difference)) (s!:improve (list (quote difference) (caddr a) (cadr a)))) (t (cond ((eqcar a (quote idifference)) (s!:improve (list (quote idifference) (caddr a) (cadr a)))) (t (list (car u) a)))))))))))) (put (quote minus) (quote s!:tidy_fn) (quote s!:imp_minus)) (put (quote iminus) (quote s!:tidy_fn) (quote s!:imp_minus)) (de s!:imp_times (u) (prog (a b) (cond ((not (equal (length u) 3)) (return ( cons (car u) (prog (var1057 var1058) (setq var1057 (cdr u)) lab1056 (cond (( null var1057) (return (reversip var1058)))) (prog (v) (setq v (car var1057)) (setq var1058 (cons (s!:improve v) var1058))) (setq var1057 (cdr var1057)) ( go lab1056)))))) (setq a (s!:improve (cadr u))) (setq b (s!:improve (caddr u) )) (return (cond ((equal a 1) b) (t (cond ((equal b 1) a) (t (cond ((equal a (minus 1)) (s!:imp_minus (list (quote minus) b))) (t (cond ((equal b (minus 1 )) (s!:imp_minus (list (quote minus) a))) (t (list (car u) a b)))))))))))) (put (quote times) (quote s!:tidy_fn) (quote s!:imp_times)) (de s!:imp_itimes (u) (prog (a b) (cond ((not (equal (length u) 3)) (return ( cons (car u) (prog (var1060 var1061) (setq var1060 (cdr u)) lab1059 (cond (( null var1060) (return (reversip var1061)))) (prog (v) (setq v (car var1060)) (setq var1061 (cons (s!:improve v) var1061))) (setq var1060 (cdr var1060)) ( go lab1059)))))) (setq a (s!:improve (cadr u))) (setq b (s!:improve (caddr u) )) (return (cond ((equal a 1) b) (t (cond ((equal b 1) a) (t (cond ((equal a (minus 1)) (s!:imp_minus (list (quote iminus) b))) (t (cond ((equal b (minus 1)) (s!:imp_minus (list (quote iminus) a))) (t (list (car u) a b)))))))))))) (put (quote itimes) (quote s!:tidy_fn) (quote s!:imp_itimes)) (de s!:imp_difference (u) (prog (a b) (setq a (s!:improve (cadr u))) (setq b (s!:improve (caddr u))) (return (cond ((equal a 0) (s!:imp_minus (list (quote minus) b))) (t (cond ((equal b 0) a) (t (list (car u) a b)))))))) (put (quote difference) (quote s!:tidy_fn) (quote s!:imp_difference)) (de s!:imp_idifference (u) (prog (a b) (setq a (s!:improve (cadr u))) (setq b (s!:improve (caddr u))) (return (cond ((equal a 0) (s!:imp_minus (list ( quote iminus) b))) (t (cond ((equal b 0) a) (t (list (car u) a b)))))))) (put (quote idifference) (quote s!:tidy_fn) (quote s!:imp_idifference)) (de s!:boolean_jumpable (u) (or (null u) (equal u t) (and (not (atom u)) ( atom (car u)) (or (flagp (car u) (quote s!:bool_opcode)) (and (or (equal (car u) (quote and)) (equal (car u) (quote or))) (s!:boolean_jumpable_list (cdr u ))))))) (de s!:boolean_jumpable_list (u) (or (atom u) (and (s!:boolean_jumpable (car u)) (s!:boolean_jumpable_list (cdr u))))) (flag (quote (null not eq equal neq eqcar atom flagp)) (quote s!:bool_opcode) ) (de s!:imp_or (u) (prog (w x) (setq w (cdr u)) (cond ((atom w) (return nil))) (setq x (car w)) (cond ((atom (cdr w)) (return (s!:improve x))) (t (cond (( s!:boolean_jumpable x) (return (list (quote cond) (list x t) (list t ( s!:imp_or (cons (quote or) (cdr w))))))) (t (return (list (quote or) ( s!:improve x) (s!:imp_or (cons (quote or) (cdr w))))))))))) (put (quote or) (quote s!:tidy_fn) (quote s!:imp_or)) (de s!:imp_and (u) (prog (w x) (setq w (cdr u)) (cond ((atom w) (return t))) (setq x (car w)) (cond ((atom (cdr w)) (return x)) (t (cond (( s!:boolean_jumpable x) (return (list (quote cond) (list x (s!:imp_and (cons ( quote and) (cdr w)))) (list t nil)))) (t (return (list (quote and) ( s!:improve x) (s!:imp_and (cons (quote and) (cdr w))))))))))) (put (quote and) (quote s!:tidy_fn) (quote s!:imp_and)) (de s!:alwayseasy (x) t) (put (quote quote) (quote s!:helpeasy) (function s!:alwayseasy)) (put (quote function) (quote s!:helpeasy) (function s!:alwayseasy)) (de s!:easyifarg (x) (or (null (cdr x)) (and (null (cddr x)) (s!:iseasy (cadr x))))) (put (quote ncons) (quote s!:helpeasy) (function s!:easyifarg)) (put (quote car) (quote s!:helpeasy) (function s!:easyifarg)) (put (quote cdr) (quote s!:helpeasy) (function s!:easyifarg)) (put (quote caar) (quote s!:helpeasy) (function s!:easyifarg)) (put (quote cadr) (quote s!:helpeasy) (function s!:easyifarg)) (put (quote cdar) (quote s!:helpeasy) (function s!:easyifarg)) (put (quote cddr) (quote s!:helpeasy) (function s!:easyifarg)) (put (quote caaar) (quote s!:helpeasy) (function s!:easyifarg)) (put (quote caadr) (quote s!:helpeasy) (function s!:easyifarg)) (put (quote cadar) (quote s!:helpeasy) (function s!:easyifarg)) (put (quote caddr) (quote s!:helpeasy) (function s!:easyifarg)) (put (quote cdaar) (quote s!:helpeasy) (function s!:easyifarg)) (put (quote cdadr) (quote s!:helpeasy) (function s!:easyifarg)) (put (quote cddar) (quote s!:helpeasy) (function s!:easyifarg)) (put (quote cdddr) (quote s!:helpeasy) (function s!:easyifarg)) (put (quote caaaar) (quote s!:helpeasy) (function s!:easyifarg)) (put (quote caaadr) (quote s!:helpeasy) (function s!:easyifarg)) (put (quote caadar) (quote s!:helpeasy) (function s!:easyifarg)) (put (quote caaddr) (quote s!:helpeasy) (function s!:easyifarg)) (put (quote cadaar) (quote s!:helpeasy) (function s!:easyifarg)) (put (quote cadadr) (quote s!:helpeasy) (function s!:easyifarg)) (put (quote caddar) (quote s!:helpeasy) (function s!:easyifarg)) (put (quote cadddr) (quote s!:helpeasy) (function s!:easyifarg)) (put (quote cdaaar) (quote s!:helpeasy) (function s!:easyifarg)) (put (quote cdaadr) (quote s!:helpeasy) (function s!:easyifarg)) (put (quote cdadar) (quote s!:helpeasy) (function s!:easyifarg)) (put (quote cdaddr) (quote s!:helpeasy) (function s!:easyifarg)) (put (quote cddaar) (quote s!:helpeasy) (function s!:easyifarg)) (put (quote cddadr) (quote s!:helpeasy) (function s!:easyifarg)) (put (quote cdddar) (quote s!:helpeasy) (function s!:easyifarg)) (put (quote cddddr) (quote s!:helpeasy) (function s!:easyifarg)) (de s!:easygetv (x) (prog (a2) (setq a2 (caddr x)) (cond ((and (null !*carcheckflag) (fixp a2) (geq a2 0) (lessp a2 256)) (return (s!:iseasy (cadr x)))) (t (return nil))))) (put (quote getv) (quote s!:helpeasy) (function s!:easygetv)) (de s!:easyqgetv (x) (prog (a2) (setq a2 (caddr x)) (cond ((and (fixp a2) ( geq a2 0) (lessp a2 256)) (return (s!:iseasy (cadr x)))) (t (return nil))))) (put (quote qgetv) (quote s!:helpeasy) (function s!:easyqgetv)) (de s!:iseasy (x) (prog (h) (cond ((atom x) (return t))) (cond ((not (atom ( car x))) (return nil))) (cond ((setq h (get (car x) (quote s!:helpeasy))) ( return (funcall h x))) (t (return nil))))) (de s!:instate_local_decs (v d w) (prog (fg) (cond ((fluidp v) (return w))) ( prog (var1063) (setq var1063 d) lab1062 (cond ((null var1063) (return nil))) (prog (z) (setq z (car var1063)) (cond ((and (eqcar z (quote special)) (memq v (cdr z))) (setq fg t)))) (setq var1063 (cdr var1063)) (go lab1062)) (cond ( fg (progn (make!-special v) (setq w (cons v w))))) (return w))) (de s!:residual_local_decs (d w) (prog nil (prog (var1067) (setq var1067 d) lab1066 (cond ((null var1067) (return nil))) (prog (z) (setq z (car var1067)) (cond ((eqcar z (quote special)) (prog (var1065) (setq var1065 (cdr z)) lab1064 (cond ((null var1065) (return nil))) (prog (v) (setq v (car var1065)) (cond ((and (not (fluidp v)) (not (globalp v))) (progn (make!-special v) ( setq w (cons v w)))))) (setq var1065 (cdr var1065)) (go lab1064))))) (setq var1067 (cdr var1067)) (go lab1066)) (return w))) (de s!:cancel_local_decs (w) (unfluid w)) (de s!:find_local_decs (body isprog) (prog (w local_decs) (cond ((and (not isprog) body (null (cdr body)) (eqcar (car body) (quote progn))) (setq body ( cdar body)))) (prog nil lab1068 (cond ((null (and body (or (eqcar (car body) (quote declare)) (stringp (car body))))) (return nil))) (progn (cond (( stringp (car body)) (setq w (cons (car body) w))) (t (setq local_decs (append local_decs (cdar body))))) (setq body (cdr body))) (go lab1068)) (prog nil lab1069 (cond ((null w) (return nil))) (progn (setq body (cons (car w) body)) (setq w (cdr w))) (go lab1069)) (return (cons local_decs body)))) (de s!:comlambda (bvl body args env context) (prog (s nbvl fluids fl1 w local_decs) (cond ((and (equal context 0) s!:maybe_values) (s!:outopcode0 ( quote ONEVALUE) (quote (onevalue))))) (setq nbvl (setq s (cdr env))) (setq body (s!:find_local_decs body nil)) (setq local_decs (car body)) (setq body ( cdr body)) (cond ((atom body) (setq body nil)) (t (cond ((atom (cdr body)) ( setq body (car body))) (t (setq body (cons (quote progn) body)))))) (setq w nil) (prog (var1071) (setq var1071 bvl) lab1070 (cond ((null var1071) (return nil))) (prog (v) (setq v (car var1071)) (setq w (s!:instate_local_decs v local_decs w))) (setq var1071 (cdr var1071)) (go lab1070)) (prog (var1073) ( setq var1073 bvl) lab1072 (cond ((null var1073) (return nil))) (prog (v) ( setq v (car var1073)) (progn (cond ((or (fluidp v) (globalp v)) (prog (g) ( setq g (gensym)) (setq nbvl (cons g nbvl)) (setq fl1 (cons v fl1)) (setq fluids (cons (cons v g) fluids)))) (t (setq nbvl (cons v nbvl)))) (cond (( equal (car args) nil) (s!:outstack 1)) (t (progn (s!:comval (car args) env 1) (s!:outopcode0 (quote PUSH) (quote (PUSH)))))) (rplacd env (cons 0 (cdr env) )) (setq args (cdr args)))) (setq var1073 (cdr var1073)) (go lab1072)) ( rplacd env nbvl) (cond (fluids (progn (setq fl1 (s!:vecof fl1)) ( s!:outopcode1lit (quote FREEBIND) fl1 env) (prog (var1075) (setq var1075 ( cons nil fluids)) lab1074 (cond ((null var1075) (return nil))) (prog (v) ( setq v (car var1075)) (rplacd env (cons 0 (cdr env)))) (setq var1075 (cdr var1075)) (go lab1074)) (rplacd env (cons (plus 2 (length fluids)) (cdr env)) ) (prog (var1077) (setq var1077 fluids) lab1076 (cond ((null var1077) (return nil))) (prog (v) (setq v (car var1077)) (s!:comval (list (quote setq) (car v ) (cdr v)) env 2)) (setq var1077 (cdr var1077)) (go lab1076))))) (setq w ( s!:residual_local_decs local_decs w)) (s!:comval body env 1) ( s!:cancel_local_decs w) (cond (fluids (s!:outopcode0 (quote FREERSTR) (quote (FREERSTR))))) (s!:outlose (length bvl)) (rplacd env s))) (de s!:loadliteral (x env) (cond ((member!*!* (list (quote quote) x) s!:a_reg_values) nil) (t (progn (cond ((equal x nil) (s!:outopcode0 (quote VNIL) (quote (loadlit nil)))) (t (s!:outopcode1lit (quote LOADLIT) x env))) ( setq s!:a_reg_values (list (list (quote quote) x))))))) (de s!:comquote (x env context) (progn (cond ((and (equal context 0) s!:maybe_values) (s!:outopcode0 (quote ONEVALUE) (quote (onevalue))))) (cond ((leq context 1) (s!:loadliteral (cadr x) env))))) (put (quote quote) (quote s!:compfn) (function s!:comquote)) (fluid (quote (s!:current_exitlab s!:current_proglabels s!:local_macros))) (de s!:comfunction (x env context) (progn (cond ((and (equal context 0) s!:maybe_values) (s!:outopcode0 (quote ONEVALUE) (quote (onevalue))))) (cond ((leq context 1) (progn (setq x (cadr x)) (cond ((eqcar x (quote lambda)) ( prog (g w s!:used_lexicals) (setq s!:has_closure t) (setq g (hashtagged!-name (quote lambda) (cdr x))) (setq w (s!:compile1 g (cadr x) (cddr x) (cons ( list (cdr env) s!:current_exitlab s!:current_proglabels s!:local_macros) s!:lexical_env))) (cond (s!:used_lexicals (setq w (s!:compile1 g (cons ( gensym) (cadr x)) (cddr x) (cons (list (cdr env) s!:current_exitlab s!:current_proglabels s!:local_macros) s!:lexical_env))))) (setq s!:other_defs (append w s!:other_defs)) (s!:loadliteral g env) (setq w ( length (cdr env))) (cond (s!:used_lexicals (progn (setq s!:has_closure t) ( cond ((greaterp w 4095) (error 0 "stack frame > 4095")) (t (cond ((greaterp w 255) (s!:outopcode2 (quote BIGSTACK) (plus 128 (truncate w 256)) (logand w 255) (list (quote CLOSURE) w))) (t (s!:outopcode1 (quote CLOSURE) w x)))))))) )) (t (s!:loadliteral x env)))))))) (put (quote function) (quote s!:compfn) (function s!:comfunction)) (de s!:should_be_fluid (x) (cond ((not (or (fluidp x) (globalp x))) (progn ( cond (!*pwrds (progn (cond ((neq (posn) 0) (terpri))) (princ "+++ ") (prin x) (princ " declared fluid") (terpri)))) (fluid (list x)) nil)))) (de s!:find_lexical (x lex n) (prog (p) (cond ((null lex) (return nil))) ( setq p (memq x (caar lex))) (cond (p (progn (cond ((not (memq x s!:used_lexicals)) (setq s!:used_lexicals (cons x s!:used_lexicals)))) ( return (list n (length p))))) (t (return (s!:find_lexical x (cdr lex) (plus n 1))))))) (global (quote (s!:loadlocs))) (setq s!:loadlocs (s!:vecof (quote (LOADLOC0 LOADLOC1 LOADLOC2 LOADLOC3 LOADLOC4 LOADLOC5 LOADLOC6 LOADLOC7 LOADLOC8 LOADLOC9 LOADLOC10 LOADLOC11)))) (de s!:comatom (x env context) (prog (n w) (cond ((and (equal context 0) s!:maybe_values) (s!:outopcode0 (quote ONEVALUE) (quote (onevalue))))) (cond ((greaterp context 1) (return nil)) (t (cond ((or (null x) (not (symbolp x))) (return (s!:loadliteral x env)))))) (setq n 0) (setq w (cdr env)) (prog nil lab1078 (cond ((null (and w (not (eqcar w x)))) (return nil))) (progn (setq n (add1 n)) (setq w (cdr w))) (go lab1078)) (cond (w (progn (setq w (cons ( quote loc) w)) (cond ((member!*!* w s!:a_reg_values) (return nil)) (t (progn (cond ((lessp n 12) (s!:outopcode0 (getv s!:loadlocs n) (list (quote LOADLOC) x))) (t (cond ((greaterp n 4095) (error 0 "stack frame > 4095")) (t (cond (( greaterp n 255) (s!:outopcode2 (quote BIGSTACK) (truncate n 256) (logand n 255) (list (quote LOADLOC) x))) (t (s!:outopcode1 (quote LOADLOC) n x))))))) (setq s!:a_reg_values (list w)) (return nil))))))) (cond ((setq w ( s!:find_lexical x s!:lexical_env 0)) (progn (cond ((member!*!* (cons (quote lex) w) s!:a_reg_values) (return nil))) (s!:outlexref (quote LOADLEX) (length (cdr env)) (car w) (cadr w) x) (setq s!:a_reg_values (list (cons (quote lex) w))) (return nil)))) (s!:should_be_fluid x) (cond ((flagp x (quote constant!?)) (return (s!:loadliteral (eval x) env)))) (setq w (cons (quote free) x)) (cond ((member!*!* w s!:a_reg_values) (return nil))) ( s!:outopcode1lit (quote LOADFREE) x env) (setq s!:a_reg_values (list w)))) (flag (quote (t !$EOL!$ !$EOF!$)) (quote constant!?)) (de s!:islocal (x env) (prog (n w) (cond ((or (null x) (not (symbolp x)) (eq x t)) (return 99999))) (setq n 0) (setq w (cdr env)) (prog nil lab1079 (cond ((null (and w (not (eqcar w x)))) (return nil))) (progn (setq n (add1 n)) ( setq w (cdr w))) (go lab1079)) (cond (w (return n)) (t (return 99999))))) (de s!:load2 (a b env) (progn (cond ((s!:iseasy b) (prog (wa wb w) (setq wa ( s!:islocal a env)) (setq wb (s!:islocal b env)) (cond ((and (lessp wa 4) ( lessp wb 4)) (progn (cond ((and (equal wa 0) (equal wb 1)) (setq w (quote LOC0LOC1))) (t (cond ((and (equal wa 1) (equal wb 2)) (setq w (quote LOC1LOC2 ))) (t (cond ((and (equal wa 2) (equal wb 3)) (setq w (quote LOC2LOC3))) (t ( cond ((and (equal wa 1) (equal wb 0)) (setq w (quote LOC1LOC0))) (t (cond (( and (equal wa 2) (equal wb 1)) (setq w (quote LOC2LOC1))) (t (cond ((and ( equal wa 3) (equal wb 2)) (setq w (quote LOC3LOC2)))))))))))))) (cond (w ( progn (s!:outopcode0 w (list (quote LOCLOC) a b)) (return nil))))))) ( s!:comval a env 1) (setq s!:a_reg_values nil) (s!:comval b env 1) (return nil ))) (t (cond (!*ord (progn (s!:comval a env 1) (s!:outopcode0 (quote PUSH) ( quote (PUSH))) (rplacd env (cons 0 (cdr env))) (setq s!:a_reg_values nil) ( s!:comval b env 1) (s!:outopcode0 (quote POP) (quote (POP))) (rplacd env ( cddr env)) t)) (t (cond ((s!:iseasy a) (progn (s!:comval b env 1) (setq s!:a_reg_values nil) (s!:comval a env 1) t)) (t (progn (s!:comval b env 1) ( s!:outopcode0 (quote PUSH) (quote (PUSH))) (rplacd env (cons 0 (cdr env))) ( setq s!:a_reg_values nil) (s!:comval a env 1) (s!:outopcode0 (quote POP) ( quote (POP))) (rplacd env (cddr env)) nil))))))))) (global (quote (s!:carlocs s!:cdrlocs s!:caarlocs))) (setq s!:carlocs (s!:vecof (quote (CARLOC0 CARLOC1 CARLOC2 CARLOC3 CARLOC4 CARLOC5 CARLOC6 CARLOC7 CARLOC8 CARLOC9 CARLOC10 CARLOC11)))) (setq s!:cdrlocs (s!:vecof (quote (CDRLOC0 CDRLOC1 CDRLOC2 CDRLOC3 CDRLOC4 CDRLOC5)))) (setq s!:caarlocs (s!:vecof (quote (CAARLOC0 CAARLOC1 CAARLOC2 CAARLOC3)))) (flag (quote (plus2 times2 eq equal)) (quote s!:symmetric)) (flag (quote (car cdr caar cadr cdar cddr ncons add1 sub1 numberp length)) ( quote s!:onearg)) (flag (quote (cons xcons list2 get flagp plus2 difference times2 greaterp lessp apply1 eq equal getv qgetv eqcar)) (quote s!:twoarg)) (flag (quote (apply2 list2!* list3 acons)) (quote s!:threearg)) (de s!:comcall (x env context) (prog (fn args nargs op s w1 w2 w3 sw) (setq fn (car x)) (cond ((not (symbolp fn)) (error 0 "non-symbol used in function position"))) (setq args (prog (var1081 var1082) (setq var1081 (cdr x)) lab1080 (cond ((null var1081) (return (reversip var1082)))) (prog (v) (setq v (car var1081)) (setq var1082 (cons (s!:improve v) var1082))) (setq var1081 (cdr var1081)) (go lab1080))) (setq nargs (length args)) (cond ((and (greaterp nargs 15) !*pwrds) (progn (cond ((neq (posn) 0) (terpri))) (princ "+++ ") (prin fn) (princ " called with ") (prin nargs) ( princ " from function ") (prin s!:current_function) (terpri)))) (setq s (cdr env)) (cond ((and (equal context 0) s!:maybe_values) (s!:outopcode0 (quote ONEVALUE) (quote (onevalue))))) (cond ((equal nargs 0) (cond ((setq w2 (get fn (quote s!:builtin0))) (s!:outopcode1 (quote BUILTIN0) w2 fn)) (t (progn ( s!:outopcode1lit (quote CALL0) fn env) (cond ((neq fn s!:current_function) ( setq s!:maybe_values t))))))) (t (cond ((equal nargs 1) (progn (cond ((and ( equal fn (quote car)) (lessp (setq w2 (s!:islocal (car args) env)) 12)) ( s!:outopcode0 (getv s!:carlocs w2) (list (quote carloc) (car args)))) (t ( cond ((and (equal fn (quote cdr)) (lessp (setq w2 (s!:islocal (car args) env) ) 6)) (s!:outopcode0 (getv s!:cdrlocs w2) (list (quote cdrloc) (car args)))) (t (cond ((and (equal fn (quote caar)) (lessp (setq w2 (s!:islocal (car args) env)) 4)) (s!:outopcode0 (getv s!:caarlocs w2) (list (quote caarloc) (car args)))) (t (progn (s!:comval (car args) env 1) (cond ((flagp fn (quote s!:onearg)) (s!:outopcode0 fn (list fn))) (t (cond ((setq w2 (get fn (quote s!:builtin1))) (s!:outopcode1 (quote BUILTIN1) w2 fn)) (t (progn (cond ((and (equal context 0) s!:maybe_values) (s!:outopcode0 (quote ONEVALUE) (quote ( onevalue))))) (s!:outopcode1lit (quote CALL1) fn env) (cond ((neq fn s!:current_function) (setq s!:maybe_values t))))))))))))))))) (t (cond (( equal nargs 2) (progn (setq sw (s!:load2 (car args) (cadr args) env)) (cond ( (flagp fn (quote s!:symmetric)) (setq sw nil))) (cond ((flagp fn (quote s!:twoarg)) (progn (cond (sw (s!:outopcode0 (quote SWOP) (quote (SWOP))))) ( s!:outopcode0 fn (list fn)))) (t (progn (setq w3 (get fn (quote s!:builtin2)) ) (cond (sw (progn (cond (w3 (s!:outopcode1 (quote BUILTIN2R) w3 fn)) (t ( s!:outopcode1lit (quote CALL2R) fn env))))) (t (cond (w3 (s!:outopcode1 ( quote BUILTIN2) w3 fn)) (t (progn (cond ((and (equal context 0) s!:maybe_values) (s!:outopcode0 (quote ONEVALUE) (quote (onevalue))))) ( s!:outopcode1lit (quote CALL2) fn env) (cond ((neq fn s!:current_function) ( setq s!:maybe_values t))))))))))))) (t (cond ((equal nargs 3) (progn (cond (( equal (car args) nil) (s!:outstack 1)) (t (progn (s!:comval (car args) env 1) (s!:outopcode0 (quote PUSH) (quote (PUSHA3)))))) (rplacd env (cons 0 (cdr env))) (setq s!:a_reg_values nil) (cond ((s!:load2 (cadr args) (caddr args) env) (s!:outopcode0 (quote SWOP) (quote (SWOP))))) (cond ((flagp fn (quote s!:threearg)) (s!:outopcode0 (cond ((equal fn (quote list2!*)) (quote list2star)) (t fn)) (list fn))) (t (cond ((setq w2 (get fn (quote s!:builtin3 ))) (s!:outopcode1 (quote BUILTIN3) w2 fn)) (t (progn (cond ((and (equal context 0) s!:maybe_values) (s!:outopcode0 (quote ONEVALUE) (quote (onevalue) )))) (s!:outopcode1lit (quote CALL3) fn env) (cond ((neq fn s!:current_function) (setq s!:maybe_values t)))))))) (rplacd env (cddr env))) ) (t (prog (largs) (setq largs (reverse args)) (prog (var1084) (setq var1084 (reverse (cddr largs))) lab1083 (cond ((null var1084) (return nil))) (prog (a ) (setq a (car var1084)) (progn (cond ((null a) (s!:outstack 1)) (t (progn ( s!:comval a env 1) (cond ((equal nargs 4) (s!:outopcode0 (quote PUSH) (quote (PUSHA4)))) (t (s!:outopcode0 (quote PUSH) (quote (PUSHARG)))))))) (rplacd env (cons 0 (cdr env))) (setq s!:a_reg_values nil))) (setq var1084 (cdr var1084)) (go lab1083)) (cond ((s!:load2 (cadr largs) (car largs) env) ( s!:outopcode0 (quote SWOP) (quote (SWOP))))) (cond ((and (equal fn (quote apply3)) (equal nargs 4)) (s!:outopcode0 (quote APPLY3) (quote (APPLY3)))) (t (cond ((greaterp nargs 255) (error 0 "Over 255 args in a function call")) (t (progn (cond ((and (equal context 0) s!:maybe_values) (s!:outopcode0 (quote ONEVALUE) (quote (onevalue))))) (s!:outopcode2lit (quote CALLN) fn nargs ( list nargs fn) env) (cond ((neq fn s!:current_function) (setq s!:maybe_values t)))))))) (rplacd env s)))))))))))) (de s!:ad_name (l) (cond ((equal (car l) (quote a)) (cond ((equal (cadr l) ( quote a)) (quote caar)) (t (quote cadr)))) (t (cond ((equal (cadr l) (quote a )) (quote cdar)) (t (quote cddr)))))) (de s!:comcarcdr3 (x env context) (prog (name outer c1 c2) (setq name (cdr ( explode2 (car x)))) (setq x (list (s!:ad_name name) (list (cond ((equal ( caddr name) (quote a)) (quote car)) (t (quote cdr))) (cadr x)))) (return ( s!:comval x env context)))) (put (quote caaar) (quote s!:compfn) (function s!:comcarcdr3)) (put (quote caadr) (quote s!:compfn) (function s!:comcarcdr3)) (put (quote cadar) (quote s!:compfn) (function s!:comcarcdr3)) (put (quote caddr) (quote s!:compfn) (function s!:comcarcdr3)) (put (quote cdaar) (quote s!:compfn) (function s!:comcarcdr3)) (put (quote cdadr) (quote s!:compfn) (function s!:comcarcdr3)) (put (quote cddar) (quote s!:compfn) (function s!:comcarcdr3)) (put (quote cdddr) (quote s!:compfn) (function s!:comcarcdr3)) (de s!:comcarcdr4 (x env context) (prog (name outer c1 c2) (setq name (cdr ( explode2 (car x)))) (setq x (list (s!:ad_name name) (list (s!:ad_name (cddr name)) (cadr x)))) (return (s!:comval x env context)))) (put (quote caaaar) (quote s!:compfn) (function s!:comcarcdr4)) (put (quote caaadr) (quote s!:compfn) (function s!:comcarcdr4)) (put (quote caadar) (quote s!:compfn) (function s!:comcarcdr4)) (put (quote caaddr) (quote s!:compfn) (function s!:comcarcdr4)) (put (quote cadaar) (quote s!:compfn) (function s!:comcarcdr4)) (put (quote cadadr) (quote s!:compfn) (function s!:comcarcdr4)) (put (quote caddar) (quote s!:compfn) (function s!:comcarcdr4)) (put (quote cadddr) (quote s!:compfn) (function s!:comcarcdr4)) (put (quote cdaaar) (quote s!:compfn) (function s!:comcarcdr4)) (put (quote cdaadr) (quote s!:compfn) (function s!:comcarcdr4)) (put (quote cdadar) (quote s!:compfn) (function s!:comcarcdr4)) (put (quote cdaddr) (quote s!:compfn) (function s!:comcarcdr4)) (put (quote cddaar) (quote s!:compfn) (function s!:comcarcdr4)) (put (quote cddadr) (quote s!:compfn) (function s!:comcarcdr4)) (put (quote cdddar) (quote s!:compfn) (function s!:comcarcdr4)) (put (quote cddddr) (quote s!:compfn) (function s!:comcarcdr4)) (de s!:comgetv (x env context) (cond (!*carcheckflag (s!:comcall x env context)) (t (s!:comval (cons (quote qgetv) (cdr x)) env context)))) (put (quote getv) (quote s!:compfn) (function s!:comgetv)) (de s!:comqgetv (x env context) (cond ((and (fixp (caddr x)) (geq (caddr x) 0 ) (lessp (caddr x) 256)) (progn (s!:comval (cadr x) env 1) (s!:outopcode1 ( quote QGETVN) (caddr x) (caddr x)))) (t (s!:comcall x env context)))) (put (quote qgetv) (quote s!:compfn) (function s!:comqgetv)) (de s!:comget (x env context) (prog (a b c w) (setq a (cadr x)) (setq b ( caddr x)) (setq c (cdddr x)) (cond ((eqcar b (quote quote)) (progn (setq b ( cadr b)) (setq w (symbol!-make!-fastget b nil)) (cond (c (progn (cond (w ( progn (cond ((s!:load2 a b env) (s!:outopcode0 (quote SWOP) (quote (SWOP))))) (s!:outopcode1 (quote FASTGET) (logor w 64) b))) (t (s!:comcall x env context))))) (t (progn (s!:comval a env 1) (cond (w (s!:outopcode1 (quote FASTGET) w b)) (t (s!:outopcode1lit (quote LITGET) b env)))))))) (t ( s!:comcall x env context))))) (put (quote get) (quote s!:compfn) (function s!:comget)) (de s!:comflagp (x env context) (prog (a b) (setq a (cadr x)) (setq b (caddr x)) (cond ((eqcar b (quote quote)) (progn (setq b (cadr b)) (s!:comval a env 1) (setq a (symbol!-make!-fastget b nil)) (cond (a (s!:outopcode1 (quote FASTGET) (logor a 128) b)) (t (s!:comcall x env context))))) (t (s!:comcall x env context))))) (put (quote flagp) (quote s!:compfn) (function s!:comflagp)) (de s!:complus (x env context) (s!:comval (expand (cdr x) (quote plus2)) env context)) (put (quote plus) (quote s!:compfn) (function s!:complus)) (de s!:comtimes (x env context) (s!:comval (expand (cdr x) (quote times2)) env context)) (put (quote times) (quote s!:compfn) (function s!:comtimes)) (de s!:comiplus (x env context) (s!:comval (expand (cdr x) (quote iplus2)) env context)) (put (quote iplus) (quote s!:compfn) (function s!:comiplus)) (de s!:comitimes (x env context) (s!:comval (expand (cdr x) (quote itimes2)) env context)) (put (quote itimes) (quote s!:compfn) (function s!:comitimes)) (de s!:complus2 (x env context) (prog (a b) (setq a (s!:improve (cadr x))) ( setq b (s!:improve (caddr x))) (return (cond ((and (numberp a) (numberp b)) ( s!:comval (plus a b) env context)) (t (cond ((equal a 0) (s!:comval b env context)) (t (cond ((equal a 1) (s!:comval (list (quote add1) b) env context) ) (t (cond ((equal b 0) (s!:comval a env context)) (t (cond ((equal b 1) ( s!:comval (list (quote add1) a) env context)) (t (cond ((equal b (minus 1)) ( s!:comval (list (quote sub1) a) env context)) (t (s!:comcall x env context))) ))))))))))))) (put (quote plus2) (quote s!:compfn) (function s!:complus2)) (de s!:comdifference (x env context) (prog (a b) (setq a (s!:improve (cadr x) )) (setq b (s!:improve (caddr x))) (return (cond ((and (numberp a) (numberp b )) (s!:comval (difference a b) env context)) (t (cond ((equal a 0) (s!:comval (list (quote minus) b) env context)) (t (cond ((equal b 0) (s!:comval a env context)) (t (cond ((equal b 1) (s!:comval (list (quote sub1) a) env context) ) (t (cond ((equal b (minus 1)) (s!:comval (list (quote add1) a) env context) ) (t (s!:comcall x env context)))))))))))))) (put (quote difference) (quote s!:compfn) (function s!:comdifference)) (de s!:comiplus2 (x env context) (prog (a b) (setq a (s!:improve (cadr x))) ( setq b (s!:improve (caddr x))) (return (cond ((and (numberp a) (numberp b)) ( s!:comval (plus a b) env context)) (t (cond ((equal a 1) (s!:comval (list ( quote iadd1) b) env context)) (t (cond ((equal b 1) (s!:comval (list (quote iadd1) a) env context)) (t (cond ((equal b (minus 1)) (s!:comval (list (quote isub1) a) env context)) (t (s!:comcall x env context)))))))))))) (put (quote iplus2) (quote s!:compfn) (function s!:comiplus2)) (de s!:comidifference (x env context) (prog (a b) (setq a (s!:improve (cadr x ))) (setq b (s!:improve (caddr x))) (return (cond ((and (numberp a) (numberp b)) (s!:comval (difference a b) env context)) (t (cond ((equal b 1) ( s!:comval (list (quote isub1) a) env context)) (t (cond ((equal b (minus 1)) (s!:comval (list (quote iadd1) a) env context)) (t (s!:comcall x env context) ))))))))) (put (quote idifference) (quote s!:compfn) (function s!:comidifference)) (de s!:comtimes2 (x env context) (prog (a b) (setq a (s!:improve (cadr x))) ( setq b (s!:improve (caddr x))) (return (cond ((and (numberp a) (numberp b)) ( s!:comval (times a b) env context)) (t (cond ((equal a 1) (s!:comval b env context)) (t (cond ((equal a (minus 1)) (s!:comval (list (quote minus) b) env context)) (t (cond ((equal b 1) (s!:comval a env context)) (t (cond ((equal b (minus 1)) (s!:comval (list (quote minus) a) env context)) (t (s!:comcall x env context)))))))))))))) (put (quote times2) (quote s!:compfn) (function s!:comtimes2)) (put (quote itimes2) (quote s!:compfn) (function s!:comtimes2)) (de s!:comminus (x env context) (prog (a b) (setq a (s!:improve (cadr x))) ( return (cond ((numberp a) (s!:comval (minus a) env context)) (t (cond ((eqcar a (quote minus)) (s!:comval (cadr a) env context)) (t (s!:comcall x env context)))))))) (put (quote minus) (quote s!:compfn) (function s!:comminus)) (de s!:comminusp (x env context) (prog (a) (setq a (s!:improve (cadr x))) ( cond ((eqcar a (quote difference)) (return (s!:comval (cons (quote lessp) ( cdr a)) env context))) (t (return (s!:comcall x env context)))))) (put (quote minusp) (quote s!:compfn) (function s!:comminusp)) (de s!:comlessp (x env context) (prog (a b) (setq a (s!:improve (cadr x))) ( setq b (s!:improve (caddr x))) (cond ((equal b 0) (return (s!:comval (list ( quote minusp) a) env context))) (t (return (s!:comcall x env context)))))) (put (quote lessp) (quote s!:compfn) (function s!:comlessp)) (de s!:comiminusp (x env context) (prog (a) (setq a (s!:improve (cadr x))) ( cond ((eqcar a (quote difference)) (return (s!:comval (cons (quote ilessp) ( cdr a)) env context))) (t (return (s!:comcall x env context)))))) (put (quote iminusp) (quote s!:compfn) (function s!:comiminusp)) (de s!:comilessp (x env context) (prog (a b) (setq a (s!:improve (cadr x))) ( setq b (s!:improve (caddr x))) (cond ((equal b 0) (return (s!:comval (list ( quote iminusp) a) env context))) (t (return (s!:comcall x env context)))))) (put (quote ilessp) (quote s!:compfn) (function s!:comilessp)) (de s!:comprogn (x env context) (progn (setq x (cdr x)) (cond ((null x) ( s!:comval nil env context)) (t (prog (a) (setq a (car x)) (prog nil lab1085 ( cond ((null (setq x (cdr x))) (return nil))) (progn (s!:comval a env (cond (( geq context 4) context) (t 2))) (setq a (car x))) (go lab1085)) (s!:comval a env context)))))) (put (quote progn) (quote s!:compfn) (function s!:comprogn)) (de s!:comprog1 (x env context) (prog nil (setq x (cdr x)) (cond ((null x) ( return (s!:comval nil env context)))) (s!:comval (car x) env context) (cond ( (null (setq x (cdr x))) (return nil))) (s!:outopcode0 (quote PUSH) (quote ( PUSH))) (rplacd env (cons 0 (cdr env))) (prog (var1087) (setq var1087 x) lab1086 (cond ((null var1087) (return nil))) (prog (a) (setq a (car var1087)) (s!:comval a env (cond ((geq context 4) context) (t 2)))) (setq var1087 (cdr var1087)) (go lab1086)) (s!:outopcode0 (quote POP) (quote (POP))) (rplacd env (cddr env)))) (put (quote prog1) (quote s!:compfn) (function s!:comprog1)) (de s!:comprog2 (x env context) (prog (a) (setq x (cdr x)) (cond ((null x) ( return (s!:comval nil env context)))) (setq a (car x)) (s!:comval a env (cond ((geq context 4) context) (t 2))) (s!:comprog1 x env context))) (put (quote prog2) (quote s!:compfn) (function s!:comprog2)) (de s!:outstack (n) (prog (w a) (setq w s!:current_block) (prog nil lab1088 ( cond ((null (and w (not (atom (car w))))) (return nil))) (setq w (cdr w)) (go lab1088)) (cond ((eqcar w (quote PUSHNIL)) (setq a 1)) (t (cond ((eqcar w ( quote PUSHNIL2)) (setq a 2)) (t (cond ((eqcar w (quote PUSHNIL3)) (setq a 3)) (t (cond ((and w (numberp (setq a (car w))) (not (equal a 255)) (eqcar (cdr w) (quote PUSHNILS))) (progn (setq w (cdr w)) (setq s!:current_size ( difference s!:current_size 1)))) (t (setq a nil))))))))) (cond (a (progn ( setq s!:current_block (cdr w)) (setq s!:current_size (difference s!:current_size 1)) (setq n (plus n a))))) (cond ((equal n 1) (s!:outopcode0 (quote PUSHNIL) (quote (PUSHNIL)))) (t (cond ((equal n 2) (s!:outopcode0 ( quote PUSHNIL2) (quote (PUSHNIL2)))) (t (cond ((equal n 3) (s!:outopcode0 ( quote PUSHNIL3) (quote (PUSHNIL3)))) (t (cond ((greaterp n 255) (progn ( s!:outopcode1 (quote PUSHNILS) 255 255) (s!:outstack (difference n 255)))) (t (cond ((greaterp n 3) (s!:outopcode1 (quote PUSHNILS) n n))))))))))))) (de s!:outlose (n) (prog (w a) (setq w s!:current_block) (prog nil lab1089 ( cond ((null (and w (not (atom (car w))))) (return nil))) (setq w (cdr w)) (go lab1089)) (cond ((eqcar w (quote LOSE)) (setq a 1)) (t (cond ((eqcar w ( quote LOSE2)) (setq a 2)) (t (cond ((eqcar w (quote LOSE3)) (setq a 3)) (t ( cond ((and w (numberp (setq a (car w))) (not (equal a 255)) (eqcar (cdr w) ( quote LOSES))) (progn (setq w (cdr w)) (setq s!:current_size (difference s!:current_size 1)))) (t (setq a nil))))))))) (cond (a (progn (setq s!:current_block (cdr w)) (setq s!:current_size (difference s!:current_size 1 )) (setq n (plus n a))))) (cond ((equal n 1) (s!:outopcode0 (quote LOSE) ( quote (LOSE)))) (t (cond ((equal n 2) (s!:outopcode0 (quote LOSE2) (quote ( LOSE2)))) (t (cond ((equal n 3) (s!:outopcode0 (quote LOSE3) (quote (LOSE3))) ) (t (cond ((greaterp n 255) (progn (s!:outopcode1 (quote LOSES) 255 255) ( s!:outlose (difference n 255)))) (t (cond ((greaterp n 3) (s!:outopcode1 ( quote LOSES) n n))))))))))))) (de s!:comprog (x env context) (prog (labs s bvl fluids n body local_decs w) (setq body (s!:find_local_decs (cddr x) t)) (setq local_decs (car body)) ( setq body (cdr body)) (setq n 0) (prog (var1091) (setq var1091 (cadr x)) lab1090 (cond ((null var1091) (return nil))) (prog (v) (setq v (car var1091)) (setq w (s!:instate_local_decs v local_decs w))) (setq var1091 (cdr var1091) ) (go lab1090)) (prog (var1093) (setq var1093 (cadr x)) lab1092 (cond ((null var1093) (return nil))) (prog (v) (setq v (car var1093)) (progn (cond (( globalp v) (progn (cond (!*pwrds (progn (cond ((neq (posn) 0) (terpri))) ( princ "+++++ global ") (prin v) (princ " converted to fluid") (terpri)))) ( unglobal (list v)) (fluid (list v))))) (cond ((fluidp v) (setq fluids (cons v fluids))) (t (progn (setq n (plus n 1)) (setq bvl (cons v bvl))))))) (setq var1093 (cdr var1093)) (go lab1092)) (setq s (cdr env)) (setq s!:current_exitlab (cons (cons nil (cons (gensym) s)) s!:current_exitlab)) ( s!:outstack n) (rplacd env (append bvl (cdr env))) (cond (fluids (prog (fl1) (setq fl1 (s!:vecof fluids)) (s!:outopcode1lit (quote FREEBIND) fl1 env) ( prog (var1095) (setq var1095 (cons nil fluids)) lab1094 (cond ((null var1095) (return nil))) (prog (v) (setq v (car var1095)) (rplacd env (cons 0 (cdr env )))) (setq var1095 (cdr var1095)) (go lab1094)) (rplacd env (cons (plus 2 ( length fluids)) (cdr env))) (cond ((equal context 0) (setq context 1)))))) ( prog (var1097) (setq var1097 body) lab1096 (cond ((null var1097) (return nil) )) (prog (a) (setq a (car var1097)) (cond ((atom a) (progn (cond ((atsoc a labs) (progn (cond ((not (null a)) (progn (cond ((neq (posn) 0) (terpri))) ( princ "+++++ label ") (prin a) (princ " multiply defined") (terpri)))))) (t ( setq labs (cons (cons a (cons (cons (gensym) (cdr env)) nil)) labs)))))))) ( setq var1097 (cdr var1097)) (go lab1096)) (setq s!:current_proglabels (cons labs s!:current_proglabels)) (setq w (s!:residual_local_decs local_decs w)) ( prog (var1099) (setq var1099 body) lab1098 (cond ((null var1099) (return nil) )) (prog (a) (setq a (car var1099)) (cond ((not (atom a)) (s!:comval a env ( plus context 4))) (t (prog (d) (setq d (atsoc a labs)) (cond ((null (cddr d)) (progn (rplacd (cdr d) t) (s!:set_label (caadr d))))))))) (setq var1099 (cdr var1099)) (go lab1098)) (s!:cancel_local_decs w) (s!:comval nil env context) (cond (fluids (s!:outopcode0 (quote FREERSTR) (quote (FREERSTR))))) ( s!:outlose n) (rplacd env s) (s!:set_label (cadar s!:current_exitlab)) (setq s!:current_exitlab (cdr s!:current_exitlab)) (setq s!:current_proglabels (cdr s!:current_proglabels)))) (put (quote prog) (quote s!:compfn) (function s!:comprog)) (de s!:comtagbody (x env context) (prog (labs) (prog (var1101) (setq var1101 (cdr x)) lab1100 (cond ((null var1101) (return nil))) (prog (a) (setq a (car var1101)) (cond ((atom a) (progn (cond ((atsoc a labs) (progn (cond ((not ( null a)) (progn (cond ((neq (posn) 0) (terpri))) (princ "+++++ label ") (prin a) (princ " multiply defined") (terpri)))))) (t (setq labs (cons (cons a ( cons (cons (gensym) (cdr env)) nil)) labs)))))))) (setq var1101 (cdr var1101) ) (go lab1100)) (setq s!:current_proglabels (cons labs s!:current_proglabels) ) (prog (var1103) (setq var1103 (cdr x)) lab1102 (cond ((null var1103) ( return nil))) (prog (a) (setq a (car var1103)) (cond ((not (atom a)) ( s!:comval a env (plus context 4))) (t (prog (d) (setq d (atsoc a labs)) (cond ((null (cddr d)) (progn (rplacd (cdr d) t) (s!:set_label (caadr d))))))))) ( setq var1103 (cdr var1103)) (go lab1102)) (s!:comval nil env context) (setq s!:current_proglabels (cdr s!:current_proglabels)))) (put (quote tagbody) (quote s!:compfn) (function s!:comtagbody)) (de s!:comblock (x env context) (prog nil (setq s!:current_exitlab (cons ( cons (cadr x) (cons (gensym) (cdr env))) s!:current_exitlab)) (s!:comval ( cons (quote progn) (cddr x)) env context) (s!:set_label (cadar s!:current_exitlab)) (setq s!:current_exitlab (cdr s!:current_exitlab)))) (put (quote !~block) (quote s!:compfn) (function s!:comblock)) (de s!:comcatch (x env context) (prog (g) (setq g (gensym)) (s!:comval (cadr x) env 1) (s!:outjump (quote CATCH) g) (rplacd env (cons (quote (catch)) ( cons 0 (cons 0 (cdr env))))) (s!:comval (cons (quote progn) (cddr x)) env context) (s!:outopcode0 (quote UNCATCH) (quote (UNCATCH))) (rplacd env ( cddddr env)) (s!:set_label g))) (put (quote catch) (quote s!:compfn) (quote s!:comcatch)) (de s!:comthrow (x env context) (prog nil (s!:comval (cadr x) env 1) ( s!:outopcode0 (quote PUSH) (quote (PUSH))) (rplacd env (cons 0 (cdr env))) ( s!:comval (caddr x) env 1) (s!:outopcode0 (quote THROW) (quote (THROW))) ( rplacd env (cddr env)))) (put (quote throw) (quote s!:compfn) (quote s!:comthrow)) (de s!:comunwind!-protect (x env context) (prog (g) (setq g (gensym)) ( s!:comval (quote (load!-spid)) env 1) (s!:outjump (quote CATCH) g) (rplacd env (cons (list (quote unwind!-protect) (cddr x)) (cons 0 (cons 0 (cdr env))) )) (s!:comval (cadr x) env context) (s!:outopcode0 (quote PROTECT) (quote ( PROTECT))) (s!:set_label g) (rplaca (cdr env) 0) (s!:comval (cons (quote progn) (cddr x)) env context) (s!:outopcode0 (quote UNPROTECT) (quote ( UNPROTECT))) (rplacd env (cddddr env)))) (put (quote unwind!-protect) (quote s!:compfn) (quote s!:comunwind!-protect)) (de s!:comdeclare (x env context) (prog nil (cond (!*pwrds (progn (princ "+++ ") (prin x) (princ " ignored") (terpri)))))) (put (quote declare) (quote s!:compfn) (function s!:comdeclare)) (de s!:expand_let (vl b) (prog (vars vals) (prog (var1105) (setq var1105 vl) lab1104 (cond ((null var1105) (return nil))) (prog (v) (setq v (car var1105)) (cond ((atom v) (progn (setq vars (cons v vars)) (setq vals (cons nil vals)) )) (t (cond ((atom (cdr v)) (progn (setq vars (cons (car v) vars)) (setq vals (cons nil vals)))) (t (progn (setq vars (cons (car v) vars)) (setq vals ( cons (cadr v) vals)))))))) (setq var1105 (cdr var1105)) (go lab1104)) (return (list (cons (cons (quote lambda) (cons vars b)) vals))))) (de s!:comlet (x env context) (s!:comval (cons (quote progn) (s!:expand_let ( cadr x) (cddr x))) env context)) (put (quote !~let) (quote s!:compfn) (function s!:comlet)) (de s!:expand_let!* (vl local_decs b) (prog (r var val) (setq r (cons (cons ( quote declare) local_decs) b)) (prog (var1109) (setq var1109 (reverse vl)) lab1108 (cond ((null var1109) (return nil))) (prog (x) (setq x (car var1109)) (progn (setq val nil) (cond ((atom x) (setq var x)) (t (cond ((atom (cdr x)) (setq var (car x))) (t (progn (setq var (car x)) (setq val (cadr x))))))) ( prog (var1107) (setq var1107 local_decs) lab1106 (cond ((null var1107) ( return nil))) (prog (z) (setq z (car var1107)) (cond ((eqcar z (quote special )) (cond ((memq var (cdr z)) (setq r (cons (list (quote declare) (list (quote special) var)) r))))))) (setq var1107 (cdr var1107)) (go lab1106)) (setq r ( list (list (cons (quote lambda) (cons (list var) r)) val))))) (setq var1109 ( cdr var1109)) (go lab1108)) (cond ((eqcar (car r) (quote declare)) (setq r ( list (cons (quote lambda) (cons nil r))))) (t (setq r (cons (quote progn) r)) )) (return r))) (de s!:comlet!* (x env context) (prog (b) (setq b (s!:find_local_decs (cddr x ) nil)) (return (s!:comval (s!:expand_let!* (cadr x) (car b) (cdr b)) env context)))) (put (quote let!*) (quote s!:compfn) (function s!:comlet!*)) (de s!:restore_stack (e1 e2) (prog (n) (setq n 0) (prog nil lab1111 (cond (( null (not (equal e1 e2))) (return nil))) (progn (cond ((null e1) (error 0 "bad block nesting with GO or RETURN-FROM"))) (cond ((and (numberp (car e1)) (greaterp (car e1) 2)) (progn (cond ((not (zerop n)) (s!:outlose n))) (setq n (car e1)) (s!:outopcode0 (quote FREERSTR) (quote (FREERSTR))) (prog (i) ( setq i 1) lab1110 (cond ((minusp (times 1 (difference n i))) (return nil))) ( setq e1 (cdr e1)) (setq i (plus i 1)) (go lab1110)) (setq n 0))) (t (cond (( equal (car e1) (quote (catch))) (progn (cond ((not (zerop n)) (s!:outlose n)) ) (s!:outopcode0 (quote UNCATCH) (quote (UNCATCH))) (setq e1 (cdddr e1)) ( setq n 0))) (t (cond ((eqcar (car e1) (quote unwind!-protect)) (progn (cond ( (not (zerop n)) (s!:outlose n))) (s!:outopcode0 (quote PROTECT) (quote ( PROTECT))) (s!:comval (cons (quote progn) (cadar e1)) e1 2) (s!:outopcode0 ( quote UNPROTECT) (quote (UNPROTECT))) (setq e1 (cdddr e1)) (setq n 0))) (t ( progn (setq e1 (cdr e1)) (setq n (plus n 1)))))))))) (go lab1111)) (cond (( not (zerop n)) (s!:outlose n))))) (de s!:comgo (x env context) (prog (pl d) (cond ((lessp context 4) (progn ( princ "go not in program context") (terpri)))) (setq pl s!:current_proglabels ) (prog nil lab1112 (cond ((null (and pl (null d))) (return nil))) (progn ( setq d (atsoc (cadr x) (car pl))) (cond ((null d) (setq pl (cdr pl))))) (go lab1112)) (cond ((null d) (progn (cond ((neq (posn) 0) (terpri))) (princ "+++++ label ") (prin (cadr x)) (princ " not set") (terpri) (return nil)))) ( setq d (cadr d)) (s!:restore_stack (cdr env) (cdr d)) (s!:outjump (quote JUMP ) (car d)))) (put (quote go) (quote s!:compfn) (function s!:comgo)) (de s!:comreturn!-from (x env context) (prog (tag) (cond ((lessp context 4) ( progn (princ "+++++ return or return-from not in prog context") (terpri)))) ( setq x (cdr x)) (setq tag (car x)) (cond ((cdr x) (setq x (cadr x))) (t (setq x nil))) (s!:comval x env (difference context 4)) (setq x (atsoc tag s!:current_exitlab)) (cond ((null x) (error 0 (list "invalid return-from" tag )))) (setq x (cdr x)) (s!:restore_stack (cdr env) (cdr x)) (s!:outjump (quote JUMP) (car x)))) (put (quote return!-from) (quote s!:compfn) (function s!:comreturn!-from)) (de s!:comreturn (x env context) (s!:comreturn!-from (cons (quote return!-from) (cons nil (cdr x))) env context)) (put (quote return) (quote s!:compfn) (function s!:comreturn)) (global (quote (s!:jumplts s!:jumplnils s!:jumpatoms s!:jumpnatoms))) (setq s!:jumplts (s!:vecof (quote (JUMPL0T JUMPL1T JUMPL2T JUMPL3T JUMPL4T))) ) (setq s!:jumplnils (s!:vecof (quote (JUMPL0NIL JUMPL1NIL JUMPL2NIL JUMPL3NIL JUMPL4NIL)))) (setq s!:jumpatoms (s!:vecof (quote (JUMPL0ATOM JUMPL1ATOM JUMPL2ATOM JUMPL3ATOM)))) (setq s!:jumpnatoms (s!:vecof (quote (JUMPL0NATOM JUMPL1NATOM JUMPL2NATOM JUMPL3NATOM)))) (de s!:jumpif (neg x env lab) (prog (w w1 j) top (cond ((null x) (progn (cond ((not neg) (s!:outjump (quote JUMP) lab))) (return nil))) (t (cond ((or (eq x t) (and (eqcar x (quote quote)) (cadr x)) (and (atom x) (not (symbolp x)))) (progn (cond (neg (s!:outjump (quote JUMP) lab))) (return nil))) (t (cond (( lessp (setq w (s!:islocal x env)) 5) (return (s!:outjump (getv (cond (neg s!:jumplts) (t s!:jumplnils)) w) lab))) (t (cond ((and (equal w 99999) ( symbolp x)) (progn (s!:should_be_fluid x) (setq w (list (cond (neg (quote JUMPFREET)) (t (quote JUMPFREENIL))) x x)) (return ( s!:record_literal_for_jump w env lab))))))))))) (cond ((and (not (atom x)) ( atom (car x)) (setq w (get (car x) (quote s!:testfn)))) (return (funcall w neg x env lab)))) (cond ((not (atom x)) (progn (setq w (s!:improve x)) (cond ((or (atom w) (not (eqcar x (car w)))) (progn (setq x w) (go top)))) (cond (( and (setq w1 (get (car w) (quote s!:compilermacro))) (setq w1 (funcall w1 w env 1))) (progn (setq x w1) (go top))))))) remacro (cond ((and (not (atom w)) (setq w1 (macro!-function (car w)))) (progn (setq w (funcall w1 w)) (cond (( or (atom w) (eqcar w (quote quote)) (get (car w) (quote s!:testfn)) (get (car w) (quote s!:compilermacro))) (progn (setq x w) (go top)))) (go remacro)))) (s!:comval x env 1) (setq w s!:current_block) (prog nil lab1113 (cond ((null (and w (not (atom (car w))))) (return nil))) (setq w (cdr w)) (go lab1113)) ( setq j (quote (JUMPNIL . JUMPT))) (cond (w (progn (setq w1 (car w)) (setq w ( cdr w)) (cond ((equal w1 (quote STORELOC0)) (progn (setq s!:current_block w) (setq s!:current_size (difference s!:current_size 1)) (setq j (quote ( JUMPST0NIL . JUMPST0T))))) (t (cond ((equal w1 (quote STORELOC1)) (progn ( setq s!:current_block w) (setq s!:current_size (difference s!:current_size 1) ) (setq j (quote (JUMPST1NIL . JUMPST1T))))) (t (cond ((equal w1 (quote STORELOC2)) (progn (setq s!:current_block w) (setq s!:current_size ( difference s!:current_size 1)) (setq j (quote (JUMPST2NIL . JUMPST2T))))) (t (cond ((eqcar w (quote BUILTIN1)) (progn (setq s!:current_block (cdr w)) ( setq s!:current_size (difference s!:current_size 2)) (setq j (cons (list ( quote JUMPB1NIL) w1) (list (quote JUMPB1T) w1))))) (t (cond ((eqcar w (quote BUILTIN2)) (progn (setq s!:current_block (cdr w)) (setq s!:current_size ( difference s!:current_size 2)) (setq j (cons (list (quote JUMPB2NIL) w1) ( list (quote JUMPB2T) w1))))))))))))))))) (return (s!:outjump (cond (neg (cdr j)) (t (car j))) lab)))) (de s!:testnot (neg x env lab) (s!:jumpif (not neg) (cadr x) env lab)) (put (quote null) (quote s!:testfn) (function s!:testnot)) (put (quote not) (quote s!:testfn) (function s!:testnot)) (de s!:testatom (neg x env lab) (prog (w) (cond ((lessp (setq w (s!:islocal ( cadr x) env)) 4) (return (s!:outjump (getv (cond (neg s!:jumpatoms) (t s!:jumpnatoms)) w) lab)))) (s!:comval (cadr x) env 1) (cond (neg (s!:outjump (quote JUMPATOM) lab)) (t (s!:outjump (quote JUMPNATOM) lab))))) (put (quote atom) (quote s!:testfn) (function s!:testatom)) (de s!:testconsp (neg x env lab) (prog (w) (cond ((lessp (setq w (s!:islocal (cadr x) env)) 4) (return (s!:outjump (getv (cond (neg s!:jumpnatoms) (t s!:jumpatoms)) w) lab)))) (s!:comval (cadr x) env 1) (cond (neg (s!:outjump ( quote JUMPNATOM) lab)) (t (s!:outjump (quote JUMPATOM) lab))))) (put (quote consp) (quote s!:testfn) (function s!:testconsp)) (de s!:comcond (x env context) (prog (l1 l2 w) (setq l1 (gensym)) (prog nil lab1114 (cond ((null (setq x (cdr x))) (return nil))) (progn (setq w (car x)) (cond ((atom (cdr w)) (progn (s!:comval (car w) env 1) (s!:outjump (quote JUMPT) l1) (setq l2 nil))) (t (progn (cond ((equal (car w) t) (setq l2 nil)) (t (progn (setq l2 (gensym)) (s!:jumpif nil (car w) env l2)))) (setq w (cdr w )) (cond ((null (cdr w)) (setq w (car w))) (t (setq w (cons (quote progn) w)) )) (s!:comval w env context) (cond (l2 (progn (s!:outjump (quote JUMP) l1) ( s!:set_label l2))) (t (setq x (quote (nil))))))))) (go lab1114)) (cond (l2 ( s!:comval nil env context))) (s!:set_label l1))) (put (quote cond) (quote s!:compfn) (function s!:comcond)) (de s!:comif (x env context) (prog (l1 l2) (setq l2 (gensym)) (s!:jumpif nil (cadr x) env l2) (setq x (cddr x)) (s!:comval (car x) env context) (setq x ( cdr x)) (cond ((or x (and (lessp context 2) (setq x (quote (nil))))) (progn ( setq l1 (gensym)) (s!:outjump (quote JUMP) l1) (s!:set_label l2) (s!:comval ( car x) env context) (s!:set_label l1))) (t (s!:set_label l2))))) (put (quote if) (quote s!:compfn) (function s!:comif)) (de s!:comwhen (x env context) (prog (l2) (setq l2 (gensym)) (cond ((lessp context 2) (progn (s!:comval (cadr x) env 1) (s!:outjump (quote JUMPNIL) l2)) ) (t (s!:jumpif nil (cadr x) env l2))) (s!:comval (cons (quote progn) (cddr x )) env context) (s!:set_label l2))) (put (quote when) (quote s!:compfn) (function s!:comwhen)) (de s!:comunless (x env context) (s!:comwhen (list!* (quote when) (list ( quote not) (cadr x)) (cddr x)) env context)) (put (quote unless) (quote s!:compfn) (function s!:comunless)) (de s!:comicase (x env context) (prog (l1 labs labassoc w) (setq x (cdr x)) ( prog (var1116) (setq var1116 (cdr x)) lab1115 (cond ((null var1116) (return nil))) (prog (v) (setq v (car var1116)) (progn (setq w (assoc!*!* v labassoc) ) (cond (w (setq l1 (cons (cdr w) l1))) (t (progn (setq l1 (gensym)) (setq labs (cons l1 labs)) (setq labassoc (cons (cons v l1) labassoc))))))) (setq var1116 (cdr var1116)) (go lab1115)) (s!:comval (car x) env 1) (s!:outjump ( quote ICASE) (reversip labs)) (setq l1 (gensym)) (prog (var1118) (setq var1118 labassoc) lab1117 (cond ((null var1118) (return nil))) (prog (v) ( setq v (car var1118)) (progn (s!:set_label (cdr v)) (s!:comval (car v) env context) (s!:outjump (quote JUMP) l1))) (setq var1118 (cdr var1118)) (go lab1117)) (s!:set_label l1))) (put (quote s!:icase) (quote s!:compfn) (function s!:comicase)) (put (quote JUMPLITEQ!*) (quote s!:opcode) (get (quote JUMPLITEQ) (quote s!:opcode))) (put (quote JUMPLITNE!*) (quote s!:opcode) (get (quote JUMPLITNE) (quote s!:opcode))) (de s!:jumpliteql (val lab env) (prog (w) (cond ((or (idp val) (eq!-safe val) ) (progn (setq w (list (quote JUMPLITEQ!*) val val)) ( s!:record_literal_for_jump w env lab))) (t (progn (s!:outopcode0 (quote PUSH) (quote (PUSH))) (s!:loadliteral val env) (s!:outopcode1 (quote BUILTIN2) ( get (quote eql) (quote s!:builtin2)) (quote eql)) (s!:outjump (quote JUMPT) lab) (flag (list lab) (quote s!:jumpliteql)) (s!:outopcode0 (quote POP) ( quote (POP)))))))) (de s!:casebranch (sw env dflt) (prog (size w w1 r g) (setq size (plus 4 ( truncate (length sw) 2))) (prog nil lab1119 (cond ((null (or (equal ( remainder size 2) 0) (equal (remainder size 3) 0) (equal (remainder size 5) 0 ) (equal (remainder size 13) 0))) (return nil))) (setq size (plus size 1)) ( go lab1119)) (prog (var1121) (setq var1121 sw) lab1120 (cond ((null var1121) (return nil))) (prog (p) (setq p (car var1121)) (progn (setq w (remainder ( eqlhash (car p)) size)) (setq w1 (assoc!*!* w r)) (cond (w1 (rplacd (cdr w1) (cons p (cddr w1)))) (t (setq r (cons (list w (gensym) p) r)))))) (setq var1121 (cdr var1121)) (go lab1120)) (s!:outopcode0 (quote PUSH) (quote (PUSH ))) (rplacd env (cons 0 (cdr env))) (s!:outopcode1lit (quote CALL1) (quote eqlhash) env) (s!:loadliteral size env) (setq g (gensym)) (s!:outopcode1 ( quote BUILTIN2) (get (quote iremainder) (quote s!:builtin2)) (quote iremainder)) (s!:outjump (quote ICASE) (cons g (prog (i var1123) (setq i 0) lab1122 (cond ((minusp (times 1 (difference (difference size 1) i))) (return (reversip var1123)))) (setq var1123 (cons (progn (setq w (assoc!*!* i r)) ( cond (w (cadr w)) (t g))) var1123)) (setq i (plus i 1)) (go lab1122)))) (prog (var1127) (setq var1127 r) lab1126 (cond ((null var1127) (return nil))) ( prog (p) (setq p (car var1127)) (progn (s!:set_label (cadr p)) (s!:outopcode0 (quote POP) (quote (POP))) (prog (var1125) (setq var1125 (cddr p)) lab1124 ( cond ((null var1125) (return nil))) (prog (q) (setq q (car var1125)) ( s!:jumpliteql (car q) (cdr q) env)) (setq var1125 (cdr var1125)) (go lab1124) ) (s!:outjump (quote JUMP) dflt))) (setq var1127 (cdr var1127)) (go lab1126)) (s!:set_label g) (s!:outopcode0 (quote POP) (quote (POP))) (s!:outjump ( quote JUMP) dflt) (rplacd env (cddr env)))) (de s!:comcase (x env context) (prog (keyform blocks v w g dflt sw keys nonnum) (setq x (cdr x)) (setq keyform (car x)) (prog (y) (setq y (cdr x)) lab1130 (cond ((null y) (return nil))) (progn (setq w (assoc!*!* (cdar y) blocks)) (cond (w (setq g (cdr w))) (t (progn (setq g (gensym)) (setq blocks (cons (cons (cdar y) g) blocks))))) (setq w (caar y)) (cond ((and (null (cdr y)) (or (equal w t) (equal w (quote otherwise)))) (setq dflt g)) (t (progn ( cond ((atom w) (setq w (list w)))) (prog (var1129) (setq var1129 w) lab1128 ( cond ((null var1129) (return nil))) (prog (n) (setq n (car var1129)) (progn ( cond ((or (idp n) (numberp n)) (progn (cond ((not (fixp n)) (setq nonnum t))) (setq keys (cons n keys)) (setq sw (cons (cons n g) sw)))) (t (error 0 (list "illegal case label" n)))))) (setq var1129 (cdr var1129)) (go lab1128)))))) (setq y (cdr y)) (go lab1130)) (cond ((null dflt) (progn (cond ((setq w ( assoc!*!* nil blocks)) (setq dflt (cdr w))) (t (setq blocks (cons (cons nil ( setq dflt (gensym))) blocks))))))) (cond ((not nonnum) (progn (setq keys ( sort keys (function lessp))) (setq nonnum (car keys)) (setq g (lastcar keys)) (cond ((lessp (difference g nonnum) (times 2 (length keys))) (progn (cond (( not (equal nonnum 0)) (progn (setq keyform (list (quote xdifference) keyform nonnum)) (setq sw (prog (var1132 var1133) (setq var1132 sw) lab1131 (cond (( null var1132) (return (reversip var1133)))) (prog (y) (setq y (car var1132)) (setq var1133 (cons (cons (difference (car y) nonnum) (cdr y)) var1133))) ( setq var1132 (cdr var1132)) (go lab1131)))))) (s!:comval keyform env 1) (setq w nil) (prog (i) (setq i 0) lab1134 (cond ((minusp (times 1 (difference g i) )) (return nil))) (cond ((setq v (assoc!*!* i sw)) (setq w (cons (cdr v) w))) (t (setq w (cons dflt w)))) (setq i (plus i 1)) (go lab1134)) (setq w (cons dflt (reversip w))) (s!:outjump (quote ICASE) w) (setq nonnum nil))) (t (setq nonnum t)))))) (cond (nonnum (progn (s!:comval keyform env 1) (cond ((lessp (length sw) 7) (progn (prog (var1136) (setq var1136 sw) lab1135 (cond ((null var1136) (return nil))) (prog (y) (setq y (car var1136)) (s!:jumpliteql (car y) (cdr y) env)) (setq var1136 (cdr var1136)) (go lab1135)) (s!:outjump ( quote JUMP) dflt))) (t (s!:casebranch sw env dflt)))))) (setq g (gensym)) ( prog (var1138) (setq var1138 blocks) lab1137 (cond ((null var1138) (return nil))) (prog (v) (setq v (car var1138)) (progn (s!:set_label (cdr v)) (cond ( (flagp (cdr v) (quote s!:jumpliteql)) (s!:outlose 1))) (s!:comval (cons ( quote progn) (car v)) env context) (s!:outjump (quote JUMP) g))) (setq var1138 (cdr var1138)) (go lab1137)) (s!:set_label g))) (put (quote case) (quote s!:compfn) (function s!:comcase)) (fluid (quote (!*defn dfprint!* s!:dfprintsave s!:faslmod_name))) (de s!:comeval!-when (x env context) (prog (y) (setq x (cdr x)) (setq y (car x)) (princ "COMPILING eval-when: ") (print y) (print x) (setq x (cons (quote progn) (cdr x))) (cond ((memq (quote compile) y) (eval x))) (cond ((memq ( quote load) y) (progn (cond (dfprint!* (apply1 dfprint!* x)))))) (cond ((memq (quote eval) y) (s!:comval x env context)) (t (s!:comval nil env context)))) ) (put (quote eval!-when) (quote s!:compfn) (function s!:comeval!-when)) (de s!:comthe (x env context) (s!:comval (caddr x) env context)) (put (quote the) (quote s!:compfn) (function s!:comthe)) (de s!:comand (x env context) (prog (l) (setq l (gensym)) (setq x (cdr x)) ( s!:comval (car x) env 1) (prog nil lab1139 (cond ((null (setq x (cdr x))) ( return nil))) (progn (s!:outjump (quote JUMPNIL) l) (s!:comval (car x) env 1) ) (go lab1139)) (s!:set_label l))) (put (quote and) (quote s!:compfn) (function s!:comand)) (de s!:comor (x env context) (prog (l) (setq l (gensym)) (setq x (cdr x)) ( s!:comval (car x) env 1) (prog nil lab1140 (cond ((null (setq x (cdr x))) ( return nil))) (progn (s!:outjump (quote JUMPT) l) (s!:comval (car x) env 1)) (go lab1140)) (s!:set_label l))) (put (quote or) (quote s!:compfn) (function s!:comor)) (de s!:combool (neg x env lab) (prog (fn) (setq fn (eqcar x (quote or))) ( cond ((eq fn neg) (prog nil lab1141 (cond ((null (setq x (cdr x))) (return nil))) (s!:jumpif fn (car x) env lab) (go lab1141))) (t (progn (setq neg ( gensym)) (prog nil lab1142 (cond ((null (setq x (cdr x))) (return nil))) ( s!:jumpif fn (car x) env neg) (go lab1142)) (s!:outjump (quote JUMP) lab) ( s!:set_label neg)))))) (put (quote and) (quote s!:testfn) (function s!:combool)) (put (quote or) (quote s!:testfn) (function s!:combool)) (de s!:testeq (neg x env lab) (prog (a b) (setq a (s!:improve (cadr x))) ( setq b (s!:improve (caddr x))) (cond ((or (s!:eval_to_eq_unsafe a) ( s!:eval_to_eq_unsafe b)) (progn (cond ((neq (posn) 0) (terpri))) (princ "++++ EQ on number upgraded to EQUAL in ") (prin s!:current_function) (princ " : ") (prin a) (princ " ") (print b) (return (s!:testequal neg (cons (quote equal) (cdr x)) env lab))))) (cond ((null a) (s!:jumpif (not neg) b env lab)) (t (cond ((null b) (s!:jumpif (not neg) a env lab)) (t (cond ((or (eqcar a ( quote quote)) (and (atom a) (not (symbolp a)))) (progn (s!:comval b env 1) ( cond ((eqcar a (quote quote)) (setq a (cadr a)))) (setq b (list (cond (neg ( quote JUMPLITEQ)) (t (quote JUMPLITNE))) a a)) (s!:record_literal_for_jump b env lab))) (t (cond ((or (eqcar b (quote quote)) (and (atom b) (not (symbolp b)))) (progn (s!:comval a env 1) (cond ((eqcar b (quote quote)) (setq b (cadr b)))) (setq a (list (cond (neg (quote JUMPLITEQ)) (t (quote JUMPLITNE))) b b )) (s!:record_literal_for_jump a env lab))) (t (progn (s!:load2 a b env) ( cond (neg (s!:outjump (quote JUMPEQ) lab)) (t (s!:outjump (quote JUMPNE) lab) ))))))))))))) (de s!:testeq1 (neg x env lab) (prog (a b) (setq a (s!:improve (cadr x))) ( setq b (s!:improve (caddr x))) (cond ((null a) (s!:jumpif (not neg) b env lab )) (t (cond ((null b) (s!:jumpif (not neg) a env lab)) (t (cond ((or (eqcar a (quote quote)) (and (atom a) (not (symbolp a)))) (progn (s!:comval b env 1) (cond ((eqcar a (quote quote)) (setq a (cadr a)))) (setq b (list (cond (neg ( quote JUMPLITEQ)) (t (quote JUMPLITNE))) a a)) (s!:record_literal_for_jump b env lab))) (t (cond ((or (eqcar b (quote quote)) (and (atom b) (not (symbolp b)))) (progn (s!:comval a env 1) (cond ((eqcar b (quote quote)) (setq b (cadr b)))) (setq a (list (cond (neg (quote JUMPLITEQ)) (t (quote JUMPLITNE))) b b )) (s!:record_literal_for_jump a env lab))) (t (progn (s!:load2 a b env) ( cond (neg (s!:outjump (quote JUMPEQ) lab)) (t (s!:outjump (quote JUMPNE) lab) ))))))))))))) (put (quote eq) (quote s!:testfn) (function s!:testeq)) (cond ((eq!-safe 0) (put (quote iequal) (quote s!:testfn) (function s!:testeq1))) (t (put (quote iequal) (quote s!:testfn) (function s!:testequal )))) (de s!:testequal (neg x env lab) (prog (a b) (setq a (cadr x)) (setq b (caddr x)) (cond ((null a) (s!:jumpif (not neg) b env lab)) (t (cond ((null b) ( s!:jumpif (not neg) a env lab)) (t (cond ((or (and (eqcar a (quote quote)) ( or (symbolp (cadr a)) (eq!-safe (cadr a)))) (and (eqcar b (quote quote)) (or (symbolp (cadr b)) (eq!-safe (cadr b)))) (and (not (idp a)) (eq!-safe a)) ( and (not (idp b)) (eq!-safe b))) (s!:testeq1 neg (cons (quote eq) (cdr x)) env lab)) (t (progn (s!:load2 a b env) (cond (neg (s!:outjump (quote JUMPEQUAL) lab)) (t (s!:outjump (quote JUMPNEQUAL) lab)))))))))))) (put (quote equal) (quote s!:testfn) (function s!:testequal)) (de s!:testneq (neg x env lab) (s!:testequal (not neg) (cons (quote equal) ( cdr x)) env lab)) (put (quote neq) (quote s!:testfn) (function s!:testneq)) (de s!:testeqcar (neg x env lab) (prog (a b sw promote) (setq a (cadr x)) ( setq b (s!:improve (caddr x))) (cond ((s!:eval_to_eq_unsafe b) (progn (cond ( (neq (posn) 0) (terpri))) (princ "++++ EQCAR on number upgraded to EQUALCAR in ") (prin s!:current_function) ( princ " : ") (print b) (setq promote t)))) (cond ((and (not promote) (eqcar b (quote quote))) (progn (s!:comval a env 1) (setq b (cadr b)) (setq a (list ( cond (neg (quote JUMPEQCAR)) (t (quote JUMPNEQCAR))) b b)) ( s!:record_literal_for_jump a env lab))) (t (cond ((or (equal b nil) (equal b t) (and (not (symbolp b)) (eq!-safe b))) (progn (s!:comval a env 1) (setq a ( list (cond (neg (quote JUMPEQCAR)) (t (quote JUMPNEQCAR))) b b)) ( s!:record_literal_for_jump a env lab))) (t (progn (setq sw (s!:load2 a b env) ) (cond (sw (s!:outopcode0 (quote SWOP) (quote (SWOP))))) (cond (promote ( s!:outopcode1 (quote BUILTIN2) (get (quote equalcar) (quote s!:builtin2)) ( quote equalcar))) (t (s!:outopcode0 (quote EQCAR) (quote (EQCAR))))) ( s!:outjump (cond (neg (quote JUMPT)) (t (quote JUMPNIL))) lab)))))))) (put (quote eqcar) (quote s!:testfn) (function s!:testeqcar)) (de s!:testflagp (neg x env lab) (prog (a b sw) (setq a (cadr x)) (setq b ( caddr x)) (cond ((eqcar b (quote quote)) (progn (s!:comval a env 1) (setq b ( cadr b)) (setq sw (symbol!-make!-fastget b nil)) (cond (sw (progn ( s!:outopcode1 (quote FASTGET) (logor sw 128) b) (s!:outjump (cond (neg (quote JUMPT)) (t (quote JUMPNIL))) lab))) (t (progn (setq a (list (cond (neg ( quote JUMPFLAGP)) (t (quote JUMPNFLAGP))) b b)) (s!:record_literal_for_jump a env lab)))))) (t (progn (setq sw (s!:load2 a b env)) (cond (sw ( s!:outopcode0 (quote SWOP) (quote (SWOP))))) (s!:outopcode0 (quote FLAGP) ( quote (FLAGP))) (s!:outjump (cond (neg (quote JUMPT)) (t (quote JUMPNIL))) lab)))))) (put (quote flagp) (quote s!:testfn) (function s!:testflagp)) (global (quote (s!:storelocs))) (setq s!:storelocs (s!:vecof (quote (STORELOC0 STORELOC1 STORELOC2 STORELOC3 STORELOC4 STORELOC5 STORELOC6 STORELOC7)))) (de s!:comsetq (x env context) (prog (n w var) (setq x (cdr x)) (cond ((null x) (return nil))) (cond ((or (not (symbolp (car x))) (null (cdr x))) (return (error 0 (list "bad args for setq" x))))) (s!:comval (cadr x) env 1) (setq var (car x)) (setq n 0) (setq w (cdr env)) (prog nil lab1143 (cond ((null ( and w (not (eqcar w var)))) (return nil))) (progn (setq n (add1 n)) (setq w ( cdr w))) (go lab1143)) (cond (w (progn (cond ((not (member!*!* (cons (quote loc) w) s!:a_reg_values)) (setq s!:a_reg_values (cons (cons (quote loc) w) s!:a_reg_values)))) (cond ((lessp n 8) (s!:outopcode0 (getv s!:storelocs n) ( list (quote storeloc) var))) (t (cond ((greaterp n 4095) (error 0 "stack frame > 4095")) (t (cond ((greaterp n 255) (s!:outopcode2 (quote BIGSTACK) (plus 64 (truncate n 256)) (logand n 255) (list (quote STORELOC) var))) (t (s!:outopcode1 (quote STORELOC) n var))))))))) (t (cond ((setq w ( s!:find_lexical var s!:lexical_env 0)) (progn (cond ((not (member!*!* (cons ( quote lex) w) s!:a_reg_values)) (setq s!:a_reg_values (cons (cons (quote lex) w) s!:a_reg_values)))) (s!:outlexref (quote STORELEX) (length (cdr env)) ( car w) (cadr w) var))) (t (progn (cond ((or (null var) (eq var t)) (error 0 ( list "bad variable in setq" var))) (t (s!:should_be_fluid var))) (setq w ( cons (quote free) var)) (cond ((not (member!*!* w s!:a_reg_values)) (setq s!:a_reg_values (cons w s!:a_reg_values)))) (s!:outopcode1lit (quote STOREFREE) var env)))))) (cond ((cddr x) (return (s!:comsetq (cdr x) env context)))))) (put (quote setq) (quote s!:compfn) (function s!:comsetq)) (put (quote noisy!-setq) (quote s!:compfn) (function s!:comsetq)) (de s!:comlist (x env context) (prog (w) (cond ((null (setq x (cdr x))) ( return (s!:comval nil env context)))) (setq s!:a_reg_values nil) (cond ((null (setq w (cdr x))) (s!:comval (list (quote ncons) (car x)) env context)) (t ( cond ((null (setq w (cdr w))) (s!:comval (list (quote list2) (car x) (cadr x) ) env context)) (t (cond ((null (cdr w)) (s!:comval (list (quote list3) (car x) (cadr x) (car w)) env context)) (t (s!:comval (list (quote list2!*) (car x ) (cadr x) (cons (quote list) w)) env context))))))))) (put (quote list) (quote s!:compfn) (function s!:comlist)) (de s!:comlist!* (x env context) (prog (w) (cond ((null (setq x (cdr x))) ( return (s!:comval nil env context)))) (setq s!:a_reg_values nil) (cond ((null (setq w (cdr x))) (s!:comval (car x) env context)) (t (cond ((null (setq w ( cdr w))) (s!:comval (list (quote cons) (car x) (cadr x)) env context)) (t ( cond ((null (cdr w)) (s!:comval (list (quote list2!*) (car x) (cadr x) (car w )) env context)) (t (s!:comval (list (quote list2!*) (car x) (cadr x) (cons ( quote list!*) w)) env context))))))))) (put (quote list!*) (quote s!:compfn) (function s!:comlist!*)) (de s!:comcons (x env context) (prog (a b) (setq a (cadr x)) (setq b (caddr x )) (cond ((or (equal b nil) (equal b (quote (quote nil)))) (s!:comval (list ( quote ncons) a) env context)) (t (cond ((eqcar a (quote cons)) (s!:comval ( list (quote acons) (cadr a) (caddr a) b) env context)) (t (cond ((eqcar b ( quote cons)) (cond ((null (caddr b)) (s!:comval (list (quote list2) a (cadr b )) env context)) (t (s!:comval (list (quote list2!*) a (cadr b) (caddr b)) env context)))) (t (cond ((and (not !*ord) (s!:iseasy a) (not (s!:iseasy b))) (s!:comval (list (quote xcons) b a) env context)) (t (s!:comcall x env context))))))))))) (put (quote cons) (quote s!:compfn) (function s!:comcons)) (de s!:comapply (x env context) (prog (a b n) (setq a (cadr x)) (setq b ( caddr x)) (cond ((and (null (cdddr x)) (eqcar b (quote list))) (progn (cond ( (eqcar a (quote quote)) (return (progn (setq n s!:current_function) (prog ( s!:current_function) (setq s!:current_function (compress (append (explode n) (cons (quote !!) (cons (quote !.) (explodec (setq s!:current_count (plus s!:current_count 1)))))))) (return (s!:comval (cons (cadr a) (cdr b)) env context))))))) (setq n (length (setq b (cdr b)))) (return (s!:comval (cons ( quote funcall) (cons a b)) env context)))) (t (cond ((and (null b) (null ( cdddr x))) (return (s!:comval (list (quote funcall) a) env context))) (t ( return (s!:comcall x env context)))))))) (put (quote apply) (quote s!:compfn) (function s!:comapply)) (de s!:imp_funcall (u) (prog (n) (setq u (cdr u)) (cond ((eqcar (car u) ( quote function)) (return (s!:improve (cons (cadar u) (cdr u)))))) (setq n ( length (cdr u))) (setq u (cond ((equal n 0) (cons (quote apply0) u)) (t (cond ((equal n 1) (cons (quote apply1) u)) (t (cond ((equal n 2) (cons (quote apply2) u)) (t (cond ((equal n 3) (cons (quote apply3) u)) (t (cons (quote funcall!*) u)))))))))) (return u))) (put (quote funcall) (quote s!:tidy_fn) (quote s!:imp_funcall)) (de s!:eval_to_eq_safe (x) (or (equal x nil) (equal x t) (and (not (symbolp x )) (eq!-safe x)) (and (not (atom x)) (flagp (car x) (quote eq!-safe))) (and ( eqcar x (quote quote)) (or (symbolp (cadr x)) (eq!-safe (cadr x)))))) (de s!:eval_to_eq_unsafe (x) (or (and (atom x) (not (symbolp x)) (not ( eq!-safe x))) (and (not (atom x)) (flagp (car x) (quote eq!-unsafe))) (and ( eqcar x (quote quote)) (or (not (atom (cadr x))) (and (not (symbolp (cadr x)) ) (not (eq!-safe (cadr x)))))))) (de s!:list_all_eq_safe (u) (or (atom u) (and (or (symbolp (car u)) (eq!-safe (car u))) (s!:list_all_eq_safe (cdr u))))) (de s!:eval_to_list_all_eq_safe (x) (or (null x) (and (eqcar x (quote quote)) (s!:list_all_eq_safe (cadr x))) (and (eqcar x (quote list)) (or (null (cdr x )) (and (s!:eval_to_eq_safe (cadr x)) (s!:eval_to_list_all_eq_safe (cons ( quote list) (cddr x)))))) (and (eqcar x (quote cons)) (s!:eval_to_eq_safe ( cadr x)) (s!:eval_to_list_all_eq_safe (caddr x))))) (de s!:list_some_eq_unsafe (u) (and (not (atom u)) (or (s!:eval_to_eq_unsafe (car u)) (s!:list_some_eq_unsafe (cdr u))))) (de s!:eval_to_list_some_eq_unsafe (x) (cond ((atom x) nil) (t (cond ((eqcar x (quote quote)) (s!:list_some_eq_unsafe (cadr x))) (t (cond ((and (eqcar x ( quote list)) (cdr x)) (or (s!:eval_to_eq_unsafe (cadr x)) ( s!:eval_to_list_some_eq_unsafe (cons (quote list) (cddr x))))) (t (cond (( eqcar x (quote cons)) (or (s!:eval_to_eq_unsafe (cadr x)) ( s!:eval_to_list_some_eq_unsafe (caddr x)))) (t nil))))))))) (de s!:eval_to_car_eq_safe (x) (and (or (eqcar x (quote cons)) (eqcar x ( quote list))) (not (null (cdr x))) (s!:eval_to_eq_safe (cadr x)))) (de s!:eval_to_car_eq_unsafe (x) (and (or (eqcar x (quote cons)) (eqcar x ( quote list))) (not (null (cdr x))) (s!:eval_to_eq_unsafe (cadr x)))) (de s!:alist_eq_safe (u) (or (atom u) (and (not (atom (car u))) (or (symbolp (caar u)) (eq!-safe (caar u))) (s!:alist_eq_safe (cdr u))))) (de s!:eval_to_alist_eq_safe (x) (or (null x) (and (eqcar x (quote quote)) ( s!:alist_eq_safe (cadr x))) (and (eqcar x (quote list)) (or (null (cdr x)) ( and (s!:eval_to_car_eq_safe (cadr x)) (s!:eval_to_alist_eq_safe (cons (quote list) (cddr x)))))) (and (eqcar x (quote cons)) (s!:eval_to_car_eq_safe (cadr x)) (s!:eval_to_alist_eq_safe (caddr x))))) (de s!:alist_eq_unsafe (u) (and (not (atom u)) (not (atom (car u))) (or (not (atom (caar u))) (and (not (symbolp (caar u))) (not (eq!-safe (caar u)))) ( s!:alist_eq_unsafe (cdr u))))) (de s!:eval_to_alist_eq_unsafe (x) (cond ((null x) nil) (t (cond ((eqcar x ( quote quote)) (s!:alist_eq_unsafe (cadr x))) (t (cond ((eqcar x (quote list)) (and (cdr x) (or (s!:eval_to_car_eq_unsafe (cadr x)) ( s!:eval_to_alist_eq_unsafe (cons (quote list) (cddr x)))))) (t (cond ((eqcar x (quote cons)) (or (s!:eval_to_car_eq_unsafe (cadr x)) ( s!:eval_to_alist_eq_safe (caddr x)))) (t nil))))))))) (flag (quote (eq eqcar null not greaterp lessp geq leq minusp atom numberp consp)) (quote eq!-safe)) (cond ((not (eq!-safe 1)) (flag (quote (length plus minus difference times quotient plus2 times2 expt fix float)) (quote eq!-unsafe)))) (de s!:comequal (x env context) (cond ((or (s!:eval_to_eq_safe (cadr x)) ( s!:eval_to_eq_safe (caddr x))) (s!:comcall (cons (quote eq) (cdr x)) env context)) (t (s!:comcall x env context)))) (put (quote equal) (quote s!:compfn) (function s!:comequal)) (de s!:comeq (x env context) (cond ((or (s!:eval_to_eq_unsafe (cadr x)) ( s!:eval_to_eq_unsafe (caddr x))) (progn (cond ((neq (posn) 0) (terpri))) ( princ "++++ EQ on number upgraded to EQUAL in ") (prin s!:current_function) ( princ " : ") (prin (cadr x)) (princ " ") (print (caddr x)) (s!:comcall (cons (quote equal) (cdr x)) env context))) (t (s!:comcall x env context)))) (put (quote eq) (quote s!:compfn) (function s!:comeq)) (de s!:comeqcar (x env context) (cond ((s!:eval_to_eq_unsafe (caddr x)) ( progn (cond ((neq (posn) 0) (terpri))) (princ "++++ EQCAR on number upgraded to EQUALCAR in ") (prin s!:current_function) ( princ " : ") (prin (caddr x)) (s!:comcall (cons (quote equalcar) (cdr x)) env context))) (t (s!:comcall x env context)))) (put (quote eqcar) (quote s!:compfn) (function s!:comeqcar)) (de s!:comsublis (x env context) (cond ((s!:eval_to_alist_eq_safe (cadr x)) ( s!:comval (cons (quote subla) (cdr x)) env context)) (t (s!:comcall x env context)))) (put (quote sublis) (quote s!:compfn) (function s!:comsublis)) (de s!:comsubla (x env context) (cond ((s!:eval_to_alist_eq_unsafe (cadr x)) (progn (cond ((neq (posn) 0) (terpri))) (princ "++++ SUBLA on number upgraded to SUBLIS in ") (prin s!:current_function) ( princ " : ") (print (cadr x)) (s!:comval (cons (quote sublis) (cdr x)) env context))) (t (s!:comcall x env context)))) (put (quote subla) (quote s!:compfn) (function s!:comsubla)) (de s!:comassoc (x env context) (cond ((and (or (s!:eval_to_eq_safe (cadr x)) (s!:eval_to_alist_eq_safe (caddr x))) (equal (length x) 3)) (s!:comval (cons (quote atsoc) (cdr x)) env context)) (t (cond ((equal (length x) 3) ( s!:comcall (cons (quote assoc!*!*) (cdr x)) env context)) (t (s!:comcall x env context)))))) (put (quote assoc) (quote s!:compfn) (function s!:comassoc)) (put (quote assoc!*!*) (quote s!:compfn) (function s!:comassoc)) (de s!:comatsoc (x env context) (cond ((or (s!:eval_to_eq_unsafe (cadr x)) ( s!:eval_to_alist_eq_unsafe (caddr x))) (progn (cond ((neq (posn) 0) (terpri)) ) (princ "++++ ATSOC on number upgraded to ASSOC in ") (prin s!:current_function) (princ " : ") (prin (cadr x)) (princ " ") (print (caddr x)) (s!:comval (cons (quote assoc) (cdr x)) env context))) (t (s!:comcall x env context)))) (put (quote atsoc) (quote s!:compfn) (function s!:comatsoc)) (de s!:commember (x env context) (cond ((and (or (s!:eval_to_eq_safe (cadr x) ) (s!:eval_to_list_all_eq_safe (caddr x))) (equal (length x) 3)) (s!:comval ( cons (quote memq) (cdr x)) env context)) (t (s!:comcall x env context)))) (put (quote member) (quote s!:compfn) (function s!:commember)) (put (quote member!*!*) (quote s!:compfn) (function s!:commember)) (de s!:commemq (x env context) (cond ((or (s!:eval_to_eq_unsafe (cadr x)) ( s!:eval_to_list_some_eq_unsafe (caddr x))) (progn (cond ((neq (posn) 0) ( terpri))) (princ "++++ MEMQ on number upgraded to MEMBER in ") (prin s!:current_function) (princ " : ") (prin (cadr x)) (princ " ") (print (caddr x)) (s!:comval (cons (quote member) (cdr x)) env context))) (t (s!:comcall x env context)))) (put (quote memq) (quote s!:compfn) (function s!:commemq)) (de s!:comdelete (x env context) (cond ((and (or (s!:eval_to_eq_safe (cadr x) ) (s!:eval_to_list_all_eq_safe (caddr x))) (equal (length x) 3)) (s!:comval ( cons (quote deleq) (cdr x)) env context)) (t (s!:comcall x env context)))) (put (quote delete) (quote s!:compfn) (function s!:comdelete)) (de s!:comdeleq (x env context) (cond ((or (s!:eval_to_eq_unsafe (cadr x)) ( s!:eval_to_list_some_eq_unsafe (caddr x))) (progn (cond ((neq (posn) 0) ( terpri))) (princ "++++ DELEQ on number upgraded to DELETE in ") (prin s!:current_function) (princ " : ") (prin (cadr x)) (princ " ") (print (caddr x)) (s!:comval (cons (quote delete) (cdr x)) env context))) (t (s!:comcall x env context)))) (put (quote deleq) (quote s!:compfn) (function s!:comdeleq)) (de s!:commap (fnargs env context) (prog (carp fn fn1 args var avar moveon l1 r s closed) (setq fn (car fnargs)) (cond ((greaterp context 1) (progn (cond ((equal fn (quote mapcar)) (setq fn (quote mapc))) (t (cond ((equal fn (quote maplist)) (setq fn (quote map))))))))) (cond ((or (equal fn (quote mapc)) ( equal fn (quote mapcar)) (equal fn (quote mapcan))) (setq carp t))) (setq fnargs (cdr fnargs)) (cond ((atom fnargs) (error 0 "bad arguments to map function"))) (setq fn1 (cadr fnargs)) (prog nil lab1144 (cond ((null (or (eqcar fn1 (quote function)) (and (eqcar fn1 (quote quote)) (eqcar (cadr fn1) (quote lambda))))) (return nil))) (progn (setq fn1 (cadr fn1)) (setq closed t)) (go lab1144)) (setq args (car fnargs)) (setq l1 ( gensym)) (setq r (gensym)) (setq s (gensym)) (setq var (gensym)) (setq avar var) (cond (carp (setq avar (list (quote car) avar)))) (cond (closed (setq fn1 (list fn1 avar))) (t (setq fn1 (list (quote funcall) fn1 avar)))) (setq moveon (list (quote setq) var (list (quote cdr) var))) (cond ((or (equal fn ( quote map)) (equal fn (quote mapc))) (setq fn (sublis (list (cons (quote l1) l1) (cons (quote var) var) (cons (quote fn) fn1) (cons (quote args) args) ( cons (quote moveon) moveon)) (quote (prog (var) (setq var args) l1 (cond (( not var) (return nil))) fn moveon (go l1)))))) (t (cond ((or (equal fn (quote maplist)) (equal fn (quote mapcar))) (setq fn (sublis (list (cons (quote l1) l1) (cons (quote var) var) (cons (quote fn) fn1) (cons (quote args) args) ( cons (quote moveon) moveon) (cons (quote r) r)) (quote (prog (var r) (setq var args) l1 (cond ((not var) (return (reversip r)))) (setq r (cons fn r)) moveon (go l1)))))) (t (setq fn (sublis (list (cons (quote l1) l1) (cons ( quote l2) (gensym)) (cons (quote var) var) (cons (quote fn) fn1) (cons (quote args) args) (cons (quote moveon) moveon) (cons (quote r) (gensym)) (cons ( quote s) (gensym))) (quote (prog (var r s) (setq var args) (setq r (setq s ( list nil))) l1 (cond ((not var) (return (cdr r)))) (rplacd s fn) l2 (cond (( not (atom (cdr s))) (setq s (cdr s)) (go l2))) moveon (go l1))))))))) ( s!:comval fn env context))) (put (quote map) (quote s!:compfn) (function s!:commap)) (put (quote maplist) (quote s!:compfn) (function s!:commap)) (put (quote mapc) (quote s!:compfn) (function s!:commap)) (put (quote mapcar) (quote s!:compfn) (function s!:commap)) (put (quote mapcon) (quote s!:compfn) (function s!:commap)) (put (quote mapcan) (quote s!:compfn) (function s!:commap)) (de s!:nilargs (use) (cond ((null use) t) (t (cond ((or (equal (car use) ( quote nil)) (equal (car use) (quote (quote nil)))) (s!:nilargs (cdr use))) (t nil))))) (de s!:subargs (args use) (cond ((null use) t) (t (cond ((null args) ( s!:nilargs use)) (t (cond ((not (equal (car args) (car use))) nil) (t ( s!:subargs (cdr args) (cdr use))))))))) (fluid (quote (!*where_defined!*))) (de clear_source_database nil (progn (setq !*where_defined!* (mkhash 10 2 1.5 )) nil)) (de load_source_database (filename) (prog (a b) (clear_source_database) (setq a (open filename (quote input))) (cond ((null a) (return nil))) (setq a (rds a)) (prog nil lab1145 (cond ((null (setq b (read))) (return nil))) (puthash (car b) !*where_defined!* (cdr b)) (go lab1145)) (close (rds a)) (return nil) )) (de save_source_database (filename) (prog (a) (setq a (open filename (quote output))) (cond ((null a) (return nil))) (setq a (wrs a)) (prog (var1147) ( setq var1147 (sort (hashcontents !*where_defined!*) (function orderp))) lab1146 (cond ((null var1147) (return nil))) (prog (z) (setq z (car var1147)) (progn (prin z) (terpri))) (setq var1147 (cdr var1147)) (go lab1146)) (princ nil) (terpri) (wrs a) (setq !*where_defined!* nil) (return nil))) (de display_source_database nil (prog (w) (cond ((null !*where_defined!*) ( return nil))) (setq w (hashcontents !*where_defined!*)) (setq w (sort w ( function orderp))) (terpri) (prog (var1149) (setq var1149 w) lab1148 (cond (( null var1149) (return nil))) (prog (x) (setq x (car var1149)) (progn (princ ( car x)) (ttab 40) (prin (cdr x)) (terpri))) (setq var1149 (cdr var1149)) (go lab1148)))) (fluid (quote (s!:r2i_simple_recurse s!:r2i_cons_recurse))) (de s!:r2i (name args body) (prog (lab v b1 s!:r2i_simple_recurse s!:r2i_cons_recurse) (setq lab (gensym)) (setq v (list (gensym))) (setq b1 ( s!:r2i1 name args body lab v)) (cond (s!:r2i_cons_recurse (progn (setq b1 ( list (quote prog) v lab b1)) (return b1))) (t (cond (s!:r2i_simple_recurse ( progn (setq v (list (gensym))) (setq b1 (s!:r2i2 name args body lab v)) (setq b1 (list (quote prog) (cdr v) lab b1)) (return b1))) (t (return (s!:r2i3 name args body lab v)))))))) (de s!:r2i1 (name args body lab v) (cond ((or (null body) (equal body (quote (progn)))) (list (quote return) (list (quote nreverse) (car v)))) (t (cond (( and (eqcar body name) (equal (length (cdr body)) (length args))) (progn (setq s!:r2i_simple_recurse t) (cons (quote progn) (append (s!:r2isteps args (cdr body) v) (list (list (quote go) lab)))))) (t (cond ((eqcar body (quote cond)) (cons (quote cond) (s!:r2icond name args (cdr body) lab v))) (t (cond (( eqcar body (quote if)) (cons (quote if) (s!:r2iif name args (cdr body) lab v) )) (t (cond ((eqcar body (quote when)) (cons (quote when) (s!:r2iwhen name args (cdr body) lab v))) (t (cond ((eqcar body (quote cons)) (s!:r2icons name args (cadr body) (caddr body) lab v)) (t (cond ((or (eqcar body (quote progn )) (eqcar body (quote prog2))) (cons (quote progn) (s!:r2iprogn name args ( cdr body) lab v))) (t (cond ((eqcar body (quote and)) (s!:r2i1 name args ( s!:r2iand (cdr body)) lab v)) (t (cond ((eqcar body (quote or)) (s!:r2i1 name args (s!:r2ior (cdr body)) lab v)) (t (list (quote return) (list (quote nreverse) (car v) body))))))))))))))))))))) (de s!:r2iand (l) (cond ((null l) t) (t (cond ((null (cdr l)) (car l)) (t ( list (quote cond) (list (car l) (s!:r2iand (cdr l))))))))) (de s!:r2ior (l) (cond ((null l) nil) (t (cons (quote cond) (prog (var1151 var1152) (setq var1151 l) lab1150 (cond ((null var1151) (return (reversip var1152)))) (prog (x) (setq x (car var1151)) (setq var1152 (cons (list x) var1152))) (setq var1151 (cdr var1151)) (go lab1150)))))) (de s!:r2icond (name args b lab v) (cond ((null b) (list (list t (list (quote return) (list (quote nreverse) (car v)))))) (t (cond ((null (cdar b)) (progn (cond ((null (cdr v)) (rplacd v (list (gensym))))) (cons (list (list (quote setq) (cadr v) (caar b)) (list (quote return) (list (quote nreverse) (car v) (cadr v)))) (s!:r2icond name args (cdr b) lab v)))) (t (cond ((eqcar (car b) t) (list (cons t (s!:r2iprogn name args (cdar b) lab v)))) (t (cons (cons ( caar b) (s!:r2iprogn name args (cdar b) lab v)) (s!:r2icond name args (cdr b) lab v))))))))) (de s!:r2iif (name args b lab v) (cond ((null (cddr b)) (list (car b) ( s!:r2i1 name args (cadr b) lab v))) (t (list (car b) (s!:r2i1 name args (cadr b) lab v) (s!:r2i1 name args (caddr b) lab v))))) (de s!:r2iwhen (name args b lab v) (cons (car b) (s!:r2iprogn name args (cdr b) lab v))) (de s!:r2iprogn (name args b lab v) (cond ((null (cdr b)) (list (s!:r2i1 name args (car b) lab v))) (t (cons (car b) (s!:r2iprogn name args (cdr b) lab v) )))) (de s!:r2icons (name args a d lab v) (cond ((eqcar d (quote cons)) ( s!:r2icons2 name args a (cadr d) (caddr d) lab v)) (t (cond ((and (eqcar d name) (equal (length (cdr d)) (length args))) (progn (setq s!:r2i_cons_recurse t) (cons (quote progn) (cons (list (quote setq) (car v) ( list (quote cons) a (car v))) (append (s!:r2isteps args (cdr d) v) (list ( list (quote go) lab))))))) (t (list (quote return) (list (quote nreverse) ( car v) (list (quote cons) a d)))))))) (de s!:r2icons2 (name args a ad dd lab v) (cond ((and (eqcar dd name) (equal (length (cdr dd)) (length args))) (progn (setq s!:r2i_cons_recurse t) (cons ( quote progn) (cons (list (quote setq) (car v) (list (quote cons) a (car v))) (cons (list (quote setq) (car v) (list (quote cons) ad (car v))) (append ( s!:r2isteps args (cdr dd) v) (list (list (quote go) lab)))))))) (t (list ( quote return) (list (quote nreverse) (car v) (list (quote cons) a (list ( quote cons) ad dd))))))) (de s!:r2isteps (vars vals v) (cond ((null vars) (cond ((null vals) nil) (t ( error 0 "too many args in recursive call to self")))) (t (cond ((null vals) ( error 0 "not enough args in recursive call to self")) (t (cond ((equal (car vars) (car vals)) (s!:r2isteps (cdr vars) (cdr vals) v)) (t (cond (( s!:r2i_safestep (car vars) (cdr vars) (cdr vals)) (cons (list (quote setq) ( car vars) (car vals)) (s!:r2isteps (cdr vars) (cdr vals) v))) (t (prog (w) ( cond ((null (cdr v)) (rplacd v (list (gensym))))) (setq v (cdr v)) (setq w ( s!:r2isteps (cdr vars) (cdr vals) v)) (return (cons (list (quote setq) (car v ) (car vals)) (append w (list (list (quote setq) (car vars) (car v))))))))))) ))))) (de s!:r2i_safestep (x vars vals) (cond ((and (null vars) (null vals)) t) (t (cond ((s!:r2i_dependson (car vals) x) nil) (t (s!:r2i_safestep x (cdr vars) (cdr vals))))))) (de s!:r2i_dependson (e x) (cond ((equal e x) t) (t (cond ((or (atom e) ( eqcar e (quote quote))) nil) (t (cond ((not (atom (car e))) t) (t (cond (( flagp (car e) (quote s!:r2i_safe)) (s!:r2i_list_dependson (cdr e) x)) (t ( cond ((or (fluidp x) (globalp x)) t) (t (cond ((or (flagp (car e) (quote s!:r2i_unsafe)) (macro!-function (car e))) t) (t (s!:r2i_list_dependson (cdr e) x)))))))))))))) (flag (quote (car cdr caar cadr cdar cddr caaar caadr cadar caddr cdaar cdadr cddar cdddr cons ncons rcons acons list list2 list3 list!* add1 sub1 plus plus2 times times2 difference minus quotient append reverse nreverse null not assoc atsoc member memq subst sublis subla pair prog1 prog2 progn)) (quote s!:r2i_safe)) (flag (quote (cond if when case de defun dm defmacro prog let let!* flet and or)) (quote s!:r2i_unsafe)) (de s!:r2i_list_dependson (l x) (cond ((null l) nil) (t (cond (( s!:r2i_dependson (car l) x) t) (t (s!:r2i_list_dependson (cdr l) x)))))) (de s!:r2i2 (name args body lab v) (cond ((or (null body) (equal body (quote (progn)))) (list (quote return) nil)) (t (cond ((and (eqcar body name) (equal (length (cdr body)) (length args))) (progn (cons (quote progn) (append ( s!:r2isteps args (cdr body) v) (list (list (quote go) lab)))))) (t (cond (( eqcar body (quote cond)) (cons (quote cond) (s!:r2i2cond name args (cdr body) lab v))) (t (cond ((eqcar body (quote if)) (cons (quote if) (s!:r2i2if name args (cdr body) lab v))) (t (cond ((eqcar body (quote when)) (cons (quote when) (s!:r2i2when name args (cdr body) lab v))) (t (cond ((or (eqcar body ( quote progn)) (eqcar body (quote prog2))) (cons (quote progn) (s!:r2i2progn name args (cdr body) lab v))) (t (cond ((eqcar body (quote and)) (s!:r2i2 name args (s!:r2iand (cdr body)) lab v)) (t (cond ((eqcar body (quote or)) ( s!:r2i2 name args (s!:r2ior (cdr body)) lab v)) (t (list (quote return) body) ))))))))))))))))) (de s!:r2i2cond (name args b lab v) (cond ((null b) (list (list t (list ( quote return) nil)))) (t (cond ((null (cdar b)) (progn (cond ((null (cdr v)) (rplacd v (list (gensym))))) (cons (list (list (quote setq) (cadr v) (caar b) ) (list (quote return) (cadr v))) (s!:r2i2cond name args (cdr b) lab v)))) (t (cond ((eqcar (car b) t) (list (cons t (s!:r2i2progn name args (cdar b) lab v)))) (t (cons (cons (caar b) (s!:r2i2progn name args (cdar b) lab v)) ( s!:r2i2cond name args (cdr b) lab v))))))))) (de s!:r2i2if (name args b lab v) (cond ((null (cddr b)) (list (car b) ( s!:r2i2 name args (cadr b) lab v))) (t (list (car b) (s!:r2i2 name args (cadr b) lab v) (s!:r2i2 name args (caddr b) lab v))))) (de s!:r2i2when (name args b lab v) (cons (car b) (s!:r2i2progn name args ( cdr b) lab v))) (de s!:r2i2progn (name args b lab v) (cond ((null (cdr b)) (list (s!:r2i2 name args (car b) lab v))) (t (cons (car b) (s!:r2i2progn name args (cdr b) lab v))))) (de s!:r2i3 (name args body lab v) (prog (v v1 v2 lab1 lab2 lab3 w P Q g R) ( cond ((s!:any_fluid args) (return body))) (cond ((eqcar body (quote cond)) ( progn (cond ((not (setq w (cdr body))) (return body))) (setq P (car w)) (setq w (cdr w)) (cond ((null P) (return body))) (setq Q (cdr P)) (setq P (car P)) (cond ((or (null Q) (cdr Q)) (return body))) (setq Q (car Q)) (cond ((or ( null w) (cdr w)) (return body))) (setq w (car w)) (cond ((not (eqcar w t)) ( return body))) (setq w (cdr w)) (cond ((or (not w) (cdr w)) (return body))) ( setq w (car w)))) (t (cond ((eqcar body (quote if)) (progn (setq w (cdr body) ) (setq P (car w)) (setq w (cdr w)) (setq Q (car w)) (setq w (cdr w)) (cond ( (null w) (return body))) (setq w (car w)))) (t (return body))))) (cond ((or ( atom w) (atom (cdr w)) (atom (cddr w)) (cdddr w)) (return body))) (setq g ( car w)) (setq R (cadr w)) (setq w (caddr w)) (cond ((not (atom g)) (return body))) (cond ((member g (quote (and or progn prog1 prog2 cond if when))) ( return body))) (cond ((not (eqcar w name)) (return body))) (setq w (cdr w)) ( cond ((not (equal (length w) (length args))) (return body))) (setq v1 (gensym )) (setq v2 (gensym)) (setq v (list v2)) (setq lab1 (gensym)) (setq lab2 ( gensym)) (setq lab3 (gensym)) (setq w (s!:r2isteps args w v)) (setq w (list ( quote prog) (cons v1 v) lab1 (list (quote cond) (list P (list (quote go) lab2 ))) (list (quote setq) v1 (list (quote cons) R v1)) (cons (quote progn) w) ( list (quote go) lab1) lab2 (list (quote setq) v2 Q) lab3 (list (quote cond) ( list (list (quote null) v1) (list (quote return) v2))) (list (quote setq) v2 (list g (list (quote car) v1) v2)) (list (quote setq) v1 (list (quote cdr) v1 )) (list (quote go) lab3))) (return w))) (de s!:any_fluid (l) (cond ((null l) nil) (t (cond ((fluidp (car l)) t) (t ( s!:any_fluid (cdr l))))))) (de s!:compile1 (name args body s!:lexical_env) (prog (w aargs oargs oinit restarg svars nargs nopts env fluids s!:current_function s!:current_label s!:current_block s!:current_size s!:current_procedure s!:current_exitlab s!:current_proglabels s!:other_defs local_decs s!:has_closure s!:local_macros s!:recent_literals s!:a_reg_values w1 w2 s!:current_count s!:env_alist s!:maybe_values checksum) (cond (s!:lexical_env (setq checksum 0)) (t (setq checksum (md60 (cons name (cons args body)))))) (setq s!:current_function name) (setq s!:current_count 0) (cond (!*where_defined!* (progn (setq w name) (puthash w !*where_defined!* (where!-was!-that))))) (setq body ( s!:find_local_decs body nil)) (setq local_decs (car body)) (setq body (cdr body)) (cond ((atom body) (setq body nil)) (t (cond ((null (cdr body)) (setq body (car body))) (t (setq body (cons (quote progn) body)))))) (setq nargs ( setq nopts 0)) (prog nil lab1153 (cond ((null (and args (not (eqcar args ( quote !&optional))) (not (eqcar args (quote !&rest))))) (return nil))) (progn (cond ((or (equal (car args) (quote !&key)) (equal (car args) (quote !&aux)) ) (error 0 "&key/&aux"))) (setq aargs (cons (car args) aargs)) (setq nargs ( plus nargs 1)) (setq args (cdr args))) (go lab1153)) (cond ((eqcar args ( quote !&optional)) (progn (setq args (cdr args)) (prog nil lab1155 (cond (( null (and args (not (eqcar args (quote !&rest))))) (return nil))) (progn ( cond ((or (equal (car args) (quote !&key)) (equal (car args) (quote !&aux))) (error 0 "&key/&aux"))) (setq w (car args)) (prog nil lab1154 (cond ((null ( and (not (atom w)) (or (atom (cdr w)) (equal (cdr w) (quote (nil)))))) ( return nil))) (setq w (car w)) (go lab1154)) (setq args (cdr args)) (setq oargs (cons w oargs)) (setq nopts (plus nopts 1)) (cond ((atom w) (setq aargs (cons w aargs))) (t (progn (setq oinit t) (setq aargs (cons (car w) aargs)) (cond ((not (atom (cddr w))) (setq svars (cons (caddr w) svars)))))))) (go lab1155))))) (cond ((eqcar args (quote !&rest)) (progn (setq w (cadr args)) ( setq aargs (cons w aargs)) (setq restarg w) (setq args (cddr args)) (cond ( args (error 0 "&rest arg not at end")))))) (setq args (reverse aargs)) (setq oargs (reverse oargs)) (prog (var1157) (setq var1157 (append svars args)) lab1156 (cond ((null var1157) (return nil))) (prog (v) (setq v (car var1157)) (progn (cond ((globalp v) (progn (cond (!*pwrds (progn (cond ((neq (posn) 0) (terpri))) (princ "+++++ global ") (prin v) (princ " converted to fluid") ( terpri)))) (unglobal (list v)) (fluid (list v))))))) (setq var1157 (cdr var1157)) (go lab1156)) (cond (oinit (return (s!:compile2 name nargs nopts args oargs restarg body local_decs checksum)))) (setq w nil) (prog (var1159) (setq var1159 args) lab1158 (cond ((null var1159) (return nil))) (prog (v) ( setq v (car var1159)) (setq w (s!:instate_local_decs v local_decs w))) (setq var1159 (cdr var1159)) (go lab1158)) (cond ((and !*r2i (null oargs) (null restarg)) (setq body (s!:r2i name args body)))) (prog (v) (setq v args) lab1160 (cond ((null v) (return nil))) (progn (cond ((fluidp (car v)) (prog ( g) (setq g (gensym)) (setq fluids (cons (cons (car v) g) fluids)) (rplaca v g ))))) (setq v (cdr v)) (go lab1160)) (cond (fluids (progn (setq body (list ( list (quote return) body))) (prog (var1162) (setq var1162 fluids) lab1161 ( cond ((null var1162) (return nil))) (prog (v) (setq v (car var1162)) (setq body (cons (list (quote setq) (car v) (cdr v)) body))) (setq var1162 (cdr var1162)) (go lab1161)) (setq body (cons (quote prog) (cons (prog (var1164 var1165) (setq var1164 fluids) lab1163 (cond ((null var1164) (return ( reversip var1165)))) (prog (v) (setq v (car var1164)) (setq var1165 (cons ( car v) var1165))) (setq var1164 (cdr var1164)) (go lab1163)) body)))))) (setq env (cons (mkhash 10 2 1.5) (reverse args))) (puthash name (car env) (cons 10000000 nil)) (setq w (s!:residual_local_decs local_decs w)) ( s!:start_procedure nargs nopts restarg) (setq w1 body) more (cond ((atom w1) nil) (t (cond ((and (equal (car w1) (quote block)) (equal (length w1) 3)) ( progn (setq w1 (caddr w1)) (go more))) (t (cond ((and (equal (car w1) (quote progn)) (equal (length w1) 2)) (progn (setq w1 (cadr w1)) (go more))) (t ( cond ((and (atom (setq w2 (car w1))) (setq w2 (get w2 (quote s!:newname)))) ( progn (setq w1 (cons w2 (cdr w1))) (go more))) (t (cond ((and (atom (setq w2 (car w1))) (setq w2 (macro!-function w2))) (progn (setq w1 (funcall w2 w1)) ( go more)))))))))))) (cond ((not (equal (setq w2 (s!:improve w1)) w1)) (progn (setq w1 w2) (go more)))) (cond ((and (not (atom w1)) (atom (car w1)) (not ( special!-form!-p (car w1))) (s!:subargs args (cdr w1)) (leq nargs 3) (equal nopts 0) (not restarg) (leq (length (cdr w1)) nargs)) (progn ( s!:cancel_local_decs w) (cond (restarg (setq nopts (plus nopts 512)))) (setq nopts (plus nopts (times 1024 (length w1)))) (setq nargs (plus nargs (times 256 nopts))) (cond (!*pwrds (progn (cond ((neq (posn) 0) (terpri))) (princ "+++ ") (prin name) (princ " compiled as link to ") (princ (car w1)) (terpri) ))) (return (cons (cons name (cons nargs (cons nil (car w1)))) s!:other_defs) )))) (s!:comval body env 0) (s!:cancel_local_decs w) (cond (restarg (setq nopts (plus nopts 512)))) (setq nargs (plus nargs (times 256 nopts))) (return (cons (cons name (cons nargs (s!:endprocedure name env checksum))) s!:other_defs)))) (de s!:compile2 (name nargs nopts args oargs restarg body local_decs checksum ) (prog (fluids env penv g v init atend w) (prog (var1167) (setq var1167 args ) lab1166 (cond ((null var1167) (return nil))) (prog (v) (setq v (car var1167 )) (progn (setq env (cons 0 env)) (setq penv (cons env penv)))) (setq var1167 (cdr var1167)) (go lab1166)) (setq env (cons (mkhash 10 2 1.5) env)) ( puthash name (car env) (cons 10000000 nil)) (setq penv (reversip penv)) (cond (restarg (setq oargs (append oargs (quote (0)))))) (prog (i) (setq i 1) lab1168 (cond ((minusp (times 1 (difference nargs i))) (return nil))) (setq oargs (cons 0 oargs)) (setq i (plus i 1)) (go lab1168)) (s!:start_procedure nargs nopts restarg) (prog nil lab1169 (cond ((null args) (return nil))) ( progn (setq v (car args)) (setq init (car oargs)) (cond ((equal init 0) ( progn (setq w (s!:instate_local_decs v local_decs w)) (cond ((fluidp v) ( progn (setq g (gensym)) (rplaca (car penv) g) (s!:outopcode1lit (quote FREEBIND) (s!:vecof (list v)) env) (rplacd env (cons 3 (cons 0 (cons 0 (cdr env))))) (setq atend (cons (quote FREERSTR) atend)) (s!:comval (list (quote setq) v g) env 2))) (t (rplaca (car penv) v))))) (t (prog (ival sp l1 l2) ( cond ((not (atom init)) (progn (setq init (cdr init)) (setq ival (car init)) (cond ((not (atom (cdr init))) (setq sp (cadr init))))))) (setq l1 (gensym)) (setq g (gensym)) (rplaca (car penv) g) (cond ((and (null ival) (null sp)) ( s!:comval (list (quote setq) g (list (quote spid!-to!-nil) g)) env 1)) (t ( progn (s!:jumpif nil (list (quote is!-spid) g) env l1) (s!:comval (list ( quote setq) g ival) env 1) (cond (sp (progn (cond ((fluidp sp) (progn ( s!:outopcode1lit (quote FREEBIND) (s!:vecof (list sp)) env) (s!:outjump ( quote JUMP) (setq l2 (gensym))) (s!:set_label l1) (s!:outopcode1lit (quote FREEBIND) (s!:vecof (list sp)) env) (rplacd env (cons 3 (cons 0 (cons 0 (cdr env))))) (s!:comval (list (quote setq) sp t) env 1) (s!:set_label l2) (setq atend (cons (quote FREERSTR) atend)))) (t (progn (s!:outopcode0 (quote PUSHNIL) (quote (PUSHNIL))) (s!:outjump (quote JUMP) (setq l2 (gensym))) ( s!:set_label l1) (s!:loadliteral t env) (s!:outopcode0 (quote PUSH) (quote ( PUSH))) (s!:set_label l2) (rplacd env (cons sp (cdr env))) (setq atend (cons (quote LOSE) atend))))))) (t (s!:set_label l1)))))) (setq w ( s!:instate_local_decs v local_decs w)) (cond ((fluidp v) (progn ( s!:outopcode1lit (quote FREEBIND) (s!:vecof (list v)) env) (rplacd env (cons 3 (cons 0 (cons 0 (cdr env))))) (s!:comval (list (quote setq) v g) env 1) ( setq atend (cons (quote FREERSTR) atend)))) (t (rplaca (car penv) v)))))) ( setq args (cdr args)) (setq oargs (cdr oargs)) (setq penv (cdr penv))) (go lab1169)) (setq w (s!:residual_local_decs local_decs w)) (s!:comval body env 0) (prog nil lab1170 (cond ((null atend) (return nil))) (progn (s!:outopcode0 (car atend) (list (car atend))) (setq atend (cdr atend))) (go lab1170)) ( s!:cancel_local_decs w) (setq nopts (plus nopts 256)) (cond (restarg (setq nopts (plus nopts 512)))) (setq nargs (plus nargs (times 256 nopts))) (return (cons (cons name (cons nargs (s!:endprocedure name env checksum))) s!:other_defs)))) (de compile!-all nil (prog (var1172) (setq var1172 (oblist)) lab1171 (cond (( null var1172) (return nil))) (prog (x) (setq x (car var1172)) (prog (w) (setq w (getd x)) (cond ((and (or (eqcar w (quote expr)) (eqcar w (quote macro))) (eqcar (cdr w) (quote lambda))) (progn (princ "Compile: ") (prin x) (terpri) (errorset (list (quote compile) (mkquote (list x))) t t)))))) (setq var1172 ( cdr var1172)) (go lab1171))) (flag (quote (rds deflist flag fluid global remprop remflag unfluid unglobal dm defmacro carcheck faslend c_end)) (quote eval)) (flag (quote (rds)) (quote ignore)) (fluid (quote (!*backtrace))) (de s!:fasl_supervisor nil (prog (u w !*echo) top (setq u (errorset (quote ( read)) t !*backtrace)) (cond ((atom u) (return nil))) (setq u (car u)) (cond ((equal u !$eof!$) (return nil))) (cond ((not (atom u)) (setq u (macroexpand u)))) (cond ((atom u) (go top)) (t (cond ((eqcar u (quote faslend)) (return ( apply (quote faslend) nil))) (t (cond ((eqcar u (quote rdf)) (progn (setq w ( open (setq u (eval (cadr u))) (quote input))) (cond (w (progn (terpri) (princ "Reading file ") (prin u) (terpri) (setq w (rds w)) (s!:fasl_supervisor) ( princ "End of file ") (prin u) (terpri) (close (rds w)))) (t (progn (princ "Failed to open file ") (prin u) (terpri)))))) (t (s!:fslout0 u))))))) (go top))) (de s!:fslout0 (u) (s!:fslout1 u nil)) (de s!:fslout1 (u loadonly) (prog (w) (cond ((not (atom u)) (setq u ( macroexpand u)))) (cond ((atom u) (return nil)) (t (cond ((eqcar u (quote progn)) (progn (prog (var1174) (setq var1174 (cdr u)) lab1173 (cond ((null var1174) (return nil))) (prog (v) (setq v (car var1174)) (s!:fslout1 v loadonly)) (setq var1174 (cdr var1174)) (go lab1173)) (return nil))) (t (cond ((eqcar u (quote eval!-when)) (return (prog nil (setq w (cadr u)) (setq u ( cons (quote progn) (cddr u))) (cond ((and (memq (quote compile) w) (not loadonly)) (eval u))) (cond ((memq (quote load) w) (s!:fslout1 u t))) (return nil)))) (t (cond ((or (flagp (car u) (quote eval)) (and (equal (car u) ( quote setq)) (not (atom (caddr u))) (flagp (caaddr u) (quote eval)))) (cond ( (not loadonly) (errorset u t !*backtrace))))))))))) (cond ((eqcar u (quote rdf)) (prog nil (setq w (open (setq u (eval (cadr u))) (quote input))) (cond (w (progn (princ "Reading file ") (prin u) (terpri) (setq w (rds w)) ( s!:fasl_supervisor) (princ "End of file ") (prin u) (terpri) (close (rds w))) ) (t (progn (princ "Failed to open file ") (prin u) (terpri)))))) (t (cond ( !*nocompile (progn (cond ((and (not (eqcar u (quote faslend))) (not (eqcar u (quote carcheck)))) (write!-module u))))) (t (cond ((or (eqcar u (quote de)) (eqcar u (quote defun))) (progn (cond ((and !*native_code (not (memq (quote win64) lispsystem!*))) (progn (cond ((c!:valid_fndef (caddr u) (cdddr u)) ( prog (pending_functions u1) (c!:ccmpout1a u) (prog nil lab1175 (cond ((null pending_functions) (return nil))) (progn (setq u1 (car pending_functions)) ( setq pending_functions (cdr pending_functions)) (s!:fslout0 u1)) (go lab1175) ))) (t (progn (princ "+++ ") (prin (cadr u)) (printc " can not be compiled into native code"))))))) (setq u (cdr u)) (cond ((and ( setq w (get (car u) (quote c!-version))) (equal w (md60 (cons (car u) (cons ( cadr u) (s!:fully_macroexpand_list (cddr u))))))) (progn (princ "+++ ") (prin (car u)) (printc " not compiled (C version available)") (write!-module (list (quote restore!-c!-code) (mkquote (car u)))))) (t (cond ((flagp (car u) ( quote lose)) (progn (princ "+++ ") (prin (car u)) (printc " not compiled (LOSE flag)"))) (t (progn (cond ((setq w (get (car u) (quote c!-version))) (progn (princ "+++ ") (prin (car u)) (princ " reports C version with checksum ") (print w) (print "+++ differing from this version:") (setq w (cons (car u) (cons (cadr u) ( s!:fully_macroexpand_list (cddr u))))) (princ "::: ") (prettyprint w) (princ "+++ which has checksum ") (print (md60 w))))) (prog (var1177) (setq var1177 (s!:compile1 (car u) (cadr u) (cddr u) nil)) lab1176 (cond ((null var1177) ( return nil))) (prog (p) (setq p (car var1177)) (s!:fslout2 p u)) (setq var1177 (cdr var1177)) (go lab1176))))))))) (t (cond ((or (eqcar u (quote dm) ) (eqcar u (quote defmacro))) (prog (g) (setq g (hashtagged!-name (cadr u) ( cddr u))) (setq u (cdr u)) (cond ((flagp (car u) (quote lose)) (progn (princ "+++ ") (prin (car u)) (printc " not compiled (LOSE flag)") (return nil)))) ( setq w (cadr u)) (cond ((and w (null (cdr w))) (setq w (cons (car w) (cons ( quote !&optional) (cons (gensym) nil)))))) (prog (var1179) (setq var1179 ( s!:compile1 g w (cddr u) nil)) lab1178 (cond ((null var1179) (return nil))) ( prog (p) (setq p (car var1179)) (s!:fslout2 p u)) (setq var1179 (cdr var1179) ) (go lab1178)) (write!-module (list (quote dm) (car u) (quote (u !&optional e)) (list g (quote u) (quote e)))))) (t (cond ((eqcar u (quote putd)) (prog ( a1 a2 a3) (setq a1 (cadr u)) (setq a2 (caddr u)) (setq a3 (cadddr u)) (cond ( (and (eqcar a1 (quote quote)) (or (equal a2 (quote (quote expr))) (equal a2 ( quote (quote macro)))) (or (eqcar a3 (quote quote)) (eqcar a3 (quote function ))) (eqcar (cadr a3) (quote lambda))) (progn (setq a1 (cadr a1)) (setq a2 ( cadr a2)) (setq a3 (cadr a3)) (setq u (cons (cond ((equal a2 (quote expr)) ( quote de)) (t (quote dm))) (cons a1 (cdr a3)))) (s!:fslout1 u loadonly))) (t (write!-module u))))) (t (cond ((and (not (eqcar u (quote faslend))) (not ( eqcar u (quote carcheck)))) (write!-module u))))))))))))))) (de s!:fslout2 (p u) (prog (name nargs code env w) (setq name (car p)) (setq nargs (cadr p)) (setq code (caddr p)) (setq env (cdddr p)) (cond ((and !*savedef (equal name (car u))) (progn (define!-in!-module (minus 1)) ( write!-module (cons (quote lambda) (cons (cadr u) (s!:fully_macroexpand_list (cddr u)))))))) (setq w (irightshift nargs 18)) (setq nargs (logand nargs 262143)) (cond ((not (equal w 0)) (setq code (difference w 1)))) ( define!-in!-module nargs) (write!-module name) (write!-module code) ( write!-module env))) (remprop (quote faslend) (quote stat)) (de faslend nil (prog (copysrc copydest) (cond ((null s!:faslmod_name) ( return nil))) (princ "Completed FASL files for ") (print (car s!:faslmod_name )) (cond ((and !*native_code (not (memq (quote win64) lispsystem!*))) (prog ( cmnd w w1 obj deff) (setq w (C!-end1 nil)) (close C_file) (setq cmnd (append (explodec s!:native_file) (quote (!")))) (cond ((memq (quote win32) lispsystem!*) (setq obj "dll")) (t (setq obj "so"))) (setq obj (tmpnam obj)) (cond ((memq (quote win32) lispsystem!*) (prog (nn) (setq nn (car s!:faslmod_name)) (setq nn (list2string (prog (var1181 var1182) (setq var1181 (explodec nn)) lab1180 (cond ((null var1181) (return (reversip var1182)))) ( prog (c) (setq c (car var1181)) (setq var1182 (cons (cond ((equal c (quote !- )) (quote !_)) (t c)) var1182))) (setq var1181 (cdr var1181)) (go lab1180)))) (setq deff (tmpnam "def")) (setq w1 (open deff (quote output))) (setq w1 ( wrs w1)) (princ "LIBRARY ") (princ (car s!:faslmod_name)) (printc ".dll") ( printc "EXPORTS") (printc " init") (princ " ") (princ nn) (printc "_setup") ( printc "IMPORTS") (print!-imports) (close (wrs w1)) (setq cmnd (append ( explodec deff) (cons (quote ! ) cmnd)))))) (setq cmnd (append (explodec obj) (cons (quote ! ) cmnd))) (setq cmnd (append (explodec " -o ") cmnd)) (prog ( var1184) (setq var1184 (reverse (cdr (assoc (quote compiler!-command) lispsystem!*)))) lab1183 (cond ((null var1184) (return nil))) (prog (x) (setq x (car var1184)) (setq cmnd (append (explodec x) (cons (quote ! ) cmnd)))) ( setq var1184 (cdr var1184)) (go lab1183)) (setq cmnd (compress (cons (quote !") cmnd))) (print cmnd) (cond ((not (zerop (silent!-system cmnd))) (progn ( princ "+++ C compilation for ") (prin (car s!:faslmod_name)) (printc " failed"))) (t (progn (cond (!*strip_native (progn (setq cmnd (compress ( cons (quote !") (append (explodec "strip ") (append (explodec obj) (quote (!" ))))))) (print cmnd) (silent!-system cmnd)))) (setq copysrc obj) (setq copydest (list2string (append (explodec (car s!:faslmod_name)) (cons (quote !.) (explodec (cdr (assoc (quote linker) lispsystem!*))))))) (cond ((not !*save_native) (progn (delete!-file s!:native_file) (cond ((memq (quote win32 ) lispsystem!*) (delete!-file deff)))))) (write!-module (list (quote instate!-c!-code) (mkquote (car s!:faslmod_name)) (mkquote w))))))))) ( start!-module nil) (cond (copysrc (progn (copy!-native copysrc copydest) ( cond ((not !*save_native) (delete!-file copysrc)))))) (setq dfprint!* s!:dfprintsave) (setq !*defn nil) (setq !*comp (cdr s!:faslmod_name)) (setq s!:faslmod_name nil) (return nil))) (put (quote faslend) (quote stat) (quote endstat)) (de s!:file (s) (prog (r) (setq s (reverse (explodec s))) (prog nil lab1185 ( cond ((null (and s (not (or (eqcar s (quote !/)) (eqcar s (quote !\)))))) ( return nil))) (progn (setq r (cons (car s) r)) (setq s (cdr s))) (go lab1185) ) (return (list2string r)))) (de s!:trim!.c (s) (prog (r) (setq s (reverse (explodec s))) (cond ((eqcar s (quote c)) (progn (setq s (cdr s)) (cond ((eqcar s (quote !.)) (setq s (cdr s ))))))) (return (list2string (reverse s))))) (de s!:dir (s) (prog nil (setq s (reverse (explodec s))) (prog nil lab1186 ( cond ((null (and s (not (or (eqcar s (quote !/)) (eqcar s (quote !\)))))) ( return nil))) (setq s (cdr s)) (go lab1186)) (cond (s (setq s (cdr s)))) ( cond ((null s) (return ".")) (t (return (list2string (reverse s))))))) (de faslout (u) (prog nil (terpri) (princ "FASLOUT ") (prin u) (princ ": IN files; or type in expressions") (terpri) (princ "When all done, execute FASLEND;") (terpri) (cond ((not (atom u)) (setq u ( car u)))) (cond ((not (start!-module u)) (progn (cond ((neq (posn) 0) (terpri ))) (princ "+++ Failed to open FASL output file") (terpri) (return nil)))) ( cond ((and !*native_code (not (memq (quote win64) lispsystem!*))) (progn ( setq s!:native_file (tmpnam "c")) (c!:ccompilestart (s!:trim!.c (s!:file s!:native_file)) u (s!:dir s!:native_file) t)))) (setq s!:faslmod_name (cons u !*comp)) (setq s!:dfprintsave dfprint!*) (setq dfprint!* (quote s!:fslout0) ) (setq !*defn t) (setq !*comp nil) (cond ((getd (quote begin)) (return nil)) ) (s!:fasl_supervisor))) (put (quote faslout) (quote stat) (quote rlis)) (de s!:c_supervisor nil (prog (u w !*echo) top (setq u (errorset (quote (read )) t !*backtrace)) (cond ((atom u) (return nil))) (setq u (car u)) (cond (( equal u !$eof!$) (return nil))) (cond ((not (atom u)) (setq u (macroexpand u) ))) (cond ((atom u) (go top)) (t (cond ((eqcar u (quote c_end)) (return ( apply (quote c_end) nil))) (t (cond ((eqcar u (quote rdf)) (progn (setq w ( open (setq u (eval (cadr u))) (quote input))) (cond (w (progn (terpri) (princ "Reading file ") (prin u) (terpri) (setq w (rds w)) (s!:c_supervisor) (princ "End of file ") (prin u) (terpri) (close (rds w)))) (t (progn (princ "Failed to open file ") (prin u) (terpri)))))) (t (s!:cout0 u))))))) (go top) )) (de s!:cout0 (u) (s!:cout1 u nil)) (de s!:cout1 (u loadonly) (prog (s!:into_c) (setq s!:into_c t) (cond ((not ( atom u)) (setq u (macroexpand u)))) (cond ((atom u) (return nil)) (t (cond (( eqcar u (quote progn)) (progn (prog (var1188) (setq var1188 (cdr u)) lab1187 (cond ((null var1188) (return nil))) (prog (v) (setq v (car var1188)) ( s!:cout1 v loadonly)) (setq var1188 (cdr var1188)) (go lab1187)) (return nil) )) (t (cond ((eqcar u (quote eval!-when)) (return (prog (w) (setq w (cadr u)) (setq u (cons (quote progn) (cddr u))) (cond ((and (memq (quote compile) w) (not loadonly)) (eval u))) (cond ((memq (quote load) w) (s!:cout1 u t))) ( return nil)))) (t (cond ((or (flagp (car u) (quote eval)) (and (equal (car u) (quote setq)) (not (atom (caddr u))) (flagp (caaddr u) (quote eval)))) (cond ((not loadonly) (errorset u t !*backtrace))))))))))) (cond ((eqcar u (quote rdf)) (prog (w) (setq w (open (setq u (eval (cadr u))) (quote input))) (cond (w (progn (princ "Reading file ") (prin u) (terpri) (setq w (rds w)) ( s!:c_supervisor) (princ "End of file ") (prin u) (terpri) (close (rds w)))) ( t (progn (princ "Failed to open file ") (prin u) (terpri)))))) (t (cond ((or (eqcar u (quote de)) (eqcar u (quote defun))) (prog (w) (setq u (cdr u)) ( setq w (s!:compile1 (car u) (cadr u) (cddr u) nil)) (prog (var1190) (setq var1190 w) lab1189 (cond ((null var1190) (return nil))) (prog (p) (setq p ( car var1190)) (s!:cgen (car p) (cadr p) (caddr p) (cdddr p))) (setq var1190 ( cdr var1190)) (go lab1189)))) (t (cond ((or (eqcar u (quote dm)) (eqcar u ( quote defmacro))) (prog (w g) (setq g (hashtagged!-name (cadr u) (cddr u))) ( setq u (cdr u)) (setq w (cadr u)) (cond ((and w (null (cdr w))) (setq w (cons (car w) (cons (quote !&optional) (cons (gensym) nil)))))) (setq w ( s!:compile1 g w (cddr u) nil)) (prog (var1192) (setq var1192 w) lab1191 (cond ((null var1192) (return nil))) (prog (p) (setq p (car var1192)) (s!:cgen ( car p) (cadr p) (caddr p) (cdddr p))) (setq var1192 (cdr var1192)) (go lab1191)) (s!:cinit (list (quote dm) (car u) (quote (u !&optional e)) (list g (quote u) (quote e)))))) (t (cond ((eqcar u (quote putd)) (prog (a1 a2 a3) ( setq a1 (cadr u)) (setq a2 (caddr u)) (setq a3 (cadddr u)) (cond ((and (eqcar a1 (quote quote)) (or (equal a2 (quote (quote expr))) (equal a2 (quote ( quote macro)))) (or (eqcar a3 (quote quote)) (eqcar a3 (quote function))) ( eqcar (cadr a3) (quote lambda))) (progn (setq a1 (cadr a1)) (setq a2 (cadr a2 )) (setq a3 (cadr a3)) (setq u (cons (cond ((equal a2 (quote expr)) (quote de )) (t (quote dm))) (cons a1 (cdr a3)))) (s!:cout1 u loadonly))) (t (s!:cinit u))))) (t (cond ((and (not (eqcar u (quote c_end))) (not (eqcar u (quote carcheck)))) (s!:cinit u))))))))))))) (fluid (quote (s!:cmod_name))) (de c_end nil (prog nil (cond ((null s!:cmod_name) (return nil))) (s!:cend) ( setq dfprint!* s!:dfprintsave) (setq !*defn nil) (setq !*comp (cdr s!:cmod_name)) (setq s!:cmod_name nil) (return nil))) (put (quote c_end) (quote stat) (quote endstat)) (de c_out (u) (prog nil (terpri) (princ "C_OUT ") (prin u) (princ ": IN files; or type in expressions") (terpri) (princ "When all done, execute C_END;") (terpri) (cond ((not (atom u)) (setq u (car u)))) (cond ((null (s!:cstart u)) (progn (cond ((neq (posn) 0) (terpri))) ( princ "+++ Failed to open C output file") (terpri) (return nil)))) (setq s!:cmod_name (cons u !*comp)) (setq s!:dfprintsave dfprint!*) (setq dfprint!* (quote s!:cout0)) (setq !*defn t) (setq !*comp nil) (cond ((getd (quote begin)) (return nil))) (s!:c_supervisor))) (put (quote c_out) (quote stat) (quote rlis)) (de s!:compile!-file!* (fromfile !&optional tofile verbose !*pwrds) (prog ( !*comp w save) (cond ((null tofile) (setq tofile fromfile))) (cond (verbose ( progn (cond ((neq (posn) 0) (terpri))) (princ "+++ Compiling file ") (prin fromfile) (terpri) (setq save (verbos nil)) (verbos (ilogand save 4))))) ( cond ((not (start!-module tofile)) (progn (cond ((neq (posn) 0) (terpri))) ( princ "+++ Failed to open FASL output file") (terpri) (cond (save (verbos save))) (return nil)))) (setq w (open fromfile (quote input))) (cond (w ( progn (setq w (rds w)) (s!:fasl_supervisor) (close (rds w)))) (t (progn ( princ "Failed to open file ") (prin fromfile) (terpri)))) (cond (save (verbos save))) (start!-module nil) (cond (verbose (progn (cond ((neq (posn) 0) ( terpri))) (princ "+++ Compilation complete") (terpri)))) (return t))) (de compile!-file!* (fromfile !&optional tofile) (s!:compile!-file!* fromfile tofile t t)) (de compd (name type defn) (prog (g !*comp) (setq !*comp t) (cond ((eqcar defn (quote lambda)) (progn (setq g (dated!-name type)) ( symbol!-set!-definition g defn) (compile (list g)) (setq defn g)))) (put name type defn) (return name))) (de s!:compile0 (name) (prog (w args defn) (setq defn (getd name)) (cond (( and (eqcar defn (quote macro)) (eqcar (cdr defn) (quote lambda))) (prog ( !*comp lx vx bx) (setq lx (cdr defn)) (cond ((not (or (and (equal (length lx) 3) (not (atom (setq bx (caddr lx)))) (equal (cadr lx) (cdr bx))) (and (equal (length lx) 3) (not (atom (setq bx (caddr lx)))) (not (atom (cadr lx))) ( eqcar (cdadr lx) (quote !&optional)) (not (atom (setq bx (cdr bx)))) (equal ( caadr lx) (car bx)) (equal (cddadr lx) (cdr bx))))) (progn (setq w ( hashtagged!-name name defn)) (symbol!-set!-definition w (cdr defn)) ( s!:compile0 w) (cond ((equal 1 (length (cadr lx))) (symbol!-set!-env name ( list (quote (u !&optional env)) (list w (quote u))))) (t (symbol!-set!-env name (list (quote (u !&optional env)) (list w (quote u) (quote env))))))))))) (t (cond ((or (not (eqcar defn (quote expr))) (not (eqcar (cdr defn) (quote lambda)))) (progn (cond (!*pwrds (progn (cond ((neq (posn) 0) (terpri))) ( princ "+++ ") (prin name) (princ " not compilable") (terpri)))))) (t (progn ( setq args (cddr defn)) (setq defn (cdr args)) (setq args (car args)) (cond (( stringp args) (progn (cond (!*pwrds (progn (cond ((neq (posn) 0) (terpri))) ( princ "+++ ") (prin name) (princ " was already compiled") (terpri)))))) (t ( progn (cond (!*savedef (put name (quote !*savedef) (cons (quote lambda) (cons args (s!:fully_macroexpand_list defn)))))) (setq w (s!:compile1 name args defn nil)) (prog (var1194) (setq var1194 w) lab1193 (cond ((null var1194) ( return nil))) (prog (p) (setq p (car var1194)) (symbol!-set!-definition (car p) (cdr p))) (setq var1194 (cdr var1194)) (go lab1193)))))))))))) (de s!:fully_macroexpand_list (l) (cond ((atom l) l) (t (prog (var1196 var1197) (setq var1196 l) lab1195 (cond ((null var1196) (return (reversip var1197)))) (prog (u) (setq u (car var1196)) (setq var1197 (cons ( s!:fully_macroexpand u) var1197))) (setq var1196 (cdr var1196)) (go lab1195)) ))) (de s!:fully_macroexpand (x) (prog (helper) (cond ((or (atom x) (eqcar x ( quote quote))) (return x)) (t (cond ((eqcar (car x) (quote lambda)) (return ( cons (cons (quote lambda) (cons (cadar x) (s!:fully_macroexpand_list (cddar x )))) (s!:fully_macroexpand_list (cdr x))))) (t (cond ((setq helper (get (car x) (quote s!:newname))) (return (s!:fully_macroexpand (cons helper (cdr x)))) ) (t (cond ((setq helper (get (car x) (quote s!:expandfn))) (return (funcall helper x))) (t (cond ((setq helper (macro!-function (car x))) (return ( s!:fully_macroexpand (funcall helper x)))) (t (return (cons (car x) ( s!:fully_macroexpand_list (cdr x)))))))))))))))) (de s!:expandfunction (u) u) (de s!:expandflet (u) (cons (car u) (cons (prog (var1199 var1200) (setq var1199 (cadr u)) lab1198 (cond ((null var1199) (return (reversip var1200)))) (prog (b) (setq b (car var1199)) (setq var1200 (cons (s!:expandfletvars b) var1200))) (setq var1199 (cdr var1199)) (go lab1198)) ( s!:fully_macroexpand_list (cddr u))))) (de s!:expandfletvars (b) (cons (car b) (cons (cadr b) ( s!:fully_macroexpand_list (cddr b))))) (de s!:expandlabels (u) (s!:expandflet u)) (de s!:expandmacrolet (u) (s!:expandflet u)) (de s!:expandprog (u) (cons (car u) (cons (cadr u) (s!:fully_macroexpand_list (cddr u))))) (de s!:expandtagbody (u) (s!:fully_macroexpand_list u)) (de s!:expandprogv (u) (cons (car u) (cons (cadr u) (cons (caddr u) ( s!:fully_macroexpand_list (cadddr u)))))) (de s!:expandblock (u) (cons (car u) (cons (cadr u) ( s!:fully_macroexpand_list (cddr u))))) (de s!:expanddeclare (u) u) (de s!:expandlet (u) (cons (car u) (cons (prog (var1202 var1203) (setq var1202 (cadr u)) lab1201 (cond ((null var1202) (return (reversip var1203)))) (prog (x) (setq x (car var1202)) (setq var1203 (cons ( s!:fully_macroexpand_list x) var1203))) (setq var1202 (cdr var1202)) (go lab1201)) (s!:fully_macroexpand_list (cddr u))))) (de s!:expandlet!* (u) (s!:expandlet u)) (de s!:expandgo (u) u) (de s!:expandreturn!-from (u) (cons (car u) (cons (cadr u) ( s!:fully_macroexpand_list (cddr u))))) (de s!:expandcond (u) (cons (car u) (prog (var1205 var1206) (setq var1205 ( cdr u)) lab1204 (cond ((null var1205) (return (reversip var1206)))) (prog (x) (setq x (car var1205)) (setq var1206 (cons (s!:fully_macroexpand_list x) var1206))) (setq var1205 (cdr var1205)) (go lab1204)))) (de s!:expandcase (u) (cons (car u) (cons (s!:fully_macroexpand (cadr u)) ( prog (var1208 var1209) (setq var1208 (cddr u)) lab1207 (cond ((null var1208) (return (reversip var1209)))) (prog (x) (setq x (car var1208)) (setq var1209 (cons (cons (car x) (s!:fully_macroexpand_list (cdr x))) var1209))) (setq var1208 (cdr var1208)) (go lab1207))))) (de s!:expandeval!-when (u) (cons (car u) (cons (cadr u) ( s!:fully_macroexpand_list (cddr u))))) (de s!:expandthe (u) (cons (car u) (cons (cadr u) (s!:fully_macroexpand_list (cddr u))))) (de s!:expandmv!-call (u) (cons (car u) (cons (cadr u) ( s!:fully_macroexpand_list (cddr u))))) (put (quote function) (quote s!:expandfn) (function s!:expandfunction)) (put (quote flet) (quote s!:expandfn) (function s!:expandflet)) (put (quote labels) (quote s!:expandfn) (function s!:expandlabels)) (put (quote macrolet) (quote s!:expandfn) (function s!:expandmacrolet)) (put (quote prog) (quote s!:expandfn) (function s!:expandprog)) (put (quote tagbody) (quote s!:expandfn) (function s!:expandtagbody)) (put (quote progv) (quote s!:expandfn) (function s!:expandprogv)) (put (quote !~block) (quote s!:expandfn) (function s!:expandblock)) (put (quote declare) (quote s!:expandfn) (function s!:expanddeclare)) (put (quote !~let) (quote s!:expandfn) (function s!:expandlet)) (put (quote let!*) (quote s!:expandfn) (function s!:expandlet!*)) (put (quote go) (quote s!:expandfn) (function s!:expandgo)) (put (quote return!-from) (quote s!:expandfn) (function s!:expandreturn!-from )) (put (quote cond) (quote s!:expandfn) (function s!:expandcond)) (put (quote case) (quote s!:expandfn) (function s!:expandcase)) (put (quote eval!-when) (quote s!:expandfn) (function s!:expandeval!-when)) (put (quote the) (quote s!:expandfn) (function s!:expandthe)) (put (quote multiple!-value!-call) (quote s!:expandfn) (function s!:expandmv!-call)) (de compile (l) (prog nil (cond ((and (atom l) (not (null l))) (setq l (list l)))) (prog (var1211) (setq var1211 l) lab1210 (cond ((null var1211) (return nil))) (prog (name) (setq name (car var1211)) (errorset (list (quote s!:compile0) (mkquote name)) t t)) (setq var1211 (cdr var1211)) (go lab1210)) (return l))) (global (quote (!*fastvector !*unsafecar))) (flag (quote (fastvector unsafecar)) (quote switch)) (fluid (quote (C_file L_file O_file L_contents Setup_name File_name))) (dm c!:printf (u !&optional env) (list (quote c!:printf1) (cadr u) (cons ( quote list) (cddr u)))) (de c!:printf1 (fmt args) (prog (a c) (setq fmt (explode2 fmt)) (prog nil lab1212 (cond ((null fmt) (return nil))) (progn (setq c (car fmt)) (setq fmt (cdr fmt)) (cond ((and (equal c (quote !\)) (or (equal (car fmt) (quote !n)) (equal (car fmt) (quote !N)))) (progn (terpri) (setq fmt (cdr fmt)))) (t ( cond ((and (equal c (quote !\)) (or (equal (car fmt) (quote !q)) (equal (car fmt) (quote !Q)))) (progn (princ (quote !")) (setq fmt (cdr fmt)))) (t (cond ((equal c (quote !%)) (progn (setq c (car fmt)) (cond ((null args) (setq a ( quote missing_arg))) (t (setq a (car args)))) (cond ((or (equal c (quote !v)) (equal c (quote !V))) (cond ((flagp a (quote c!:live_across_call)) (progn ( princ "stack[") (princ (minus (get a (quote c!:location)))) (princ "]"))) (t (princ a)))) (t (cond ((or (equal c (quote !c)) (equal c (quote !C))) ( c!:safeprin a)) (t (cond ((or (equal c (quote !a)) (equal c (quote !A))) ( prin a)) (t (cond ((or (equal c (quote !t)) (equal c (quote !T))) (ttab a)) ( t (cond ((equal c (quote !<)) (progn (setq args (cons nil args)) (cond (( greaterp (posn) 70) (terpri))))) (t (princ a))))))))))) (cond (args (setq args (cdr args)))) (setq fmt (cdr fmt)))) (t (princ c)))))))) (go lab1212)))) (de c!:safeprin (x) (prog (n lastc) (setq n 0) (prog (var1214) (setq var1214 (explode x)) lab1213 (cond ((null var1214) (return nil))) (prog (c) (setq c ( car var1214)) (progn (cond ((and (greaterp n 120) (equal c (quote ! ))) ( progn (terpri) (prin2 "//") (setq n 2))) (t (cond ((and (greaterp n 150) (neq c !$eol!$)) (progn (terpri) (prin2 "// ") (setq n 3))) (t (setq n (plus n 1) ))))) (cond ((and (equal lastc (quote !\)) (equal c !$eol!$)) (princ " (backslash)"))) (setq lastc c) (princ c) (cond ((equal c !$eol!$) (progn ( princ "//") (setq n 2)))))) (setq var1214 (cdr var1214)) (go lab1213)) (cond ((equal lastc (quote !\)) (princ " (backslash)"))))) (de c!:valid_fndef (args body) (cond ((or (memq (quote !&optional) args) ( memq (quote !&rest) args)) nil) (t (c!:valid_list body)))) (de c!:valid_list (x) (cond ((null x) t) (t (cond ((atom x) nil) (t (cond (( not (c!:valid_expr (car x))) nil) (t (c!:valid_list (cdr x))))))))) (de c!:valid_expr (x) (cond ((atom x) t) (t (cond ((not (atom (car x))) ( progn (cond ((not (c!:valid_list (cdr x))) nil) (t (cond ((not (eqcar (car x) (quote lambda))) nil) (t (cond ((atom (cdar x)) nil) (t (c!:valid_fndef ( cadar x) (cddar x)))))))))) (t (cond ((not (idp (car x))) nil) (t (cond (( eqcar x (quote quote)) t) (t (prog (h) (setq h (get (car x) (quote c!:valid)) ) (cond ((null h) (return (c!:valid_list (cdr x))))) (return (funcall h (cdr x))))))))))))) (de c!:cspecform (x env) (error 0 (list "special form" x))) (de c!:valid_specform (x) nil) (progn (put (quote and) (quote c!:code) (function c!:cspecform)) (put (quote catch) (quote c!:code) (function c!:cspecform)) (put (quote compiler!-let) ( quote c!:code) (function c!:cspecform)) (put (quote cond) (quote c!:code) ( function c!:cspecform)) (put (quote declare) (quote c!:code) (function c!:cspecform)) (put (quote de) (quote c!:code) (function c!:cspecform)) (put (quote eval!-when) (quote c!:code) (function c!:cspecform)) (put (quote flet) (quote c!:code) (function c!:cspecform)) (put (quote function) (quote c!:code) (function c!:cspecform)) (put (quote go) (quote c!:code) (function c!:cspecform)) (put (quote if) (quote c!:code) (function c!:cspecform)) (put (quote labels) (quote c!:code) (function c!:cspecform)) (put (quote !~let) ( quote c!:code) (function c!:cspecform)) (put (quote let!*) (quote c!:code) ( function c!:cspecform)) (put (quote list) (quote c!:code) (function c!:cspecform)) (put (quote list!*) (quote c!:code) (function c!:cspecform)) ( put (quote macrolet) (quote c!:code) (function c!:cspecform)) (put (quote multiple!-value!-call) (quote c!:code) (function c!:cspecform)) (put (quote multiple!-value!-prog1) (quote c!:code) (function c!:cspecform)) (put (quote or) (quote c!:code) (function c!:cspecform)) (put (quote prog) (quote c!:code ) (function c!:cspecform)) (put (quote prog!*) (quote c!:code) (function c!:cspecform)) (put (quote prog1) (quote c!:code) (function c!:cspecform)) ( put (quote prog2) (quote c!:code) (function c!:cspecform)) (put (quote progn) (quote c!:code) (function c!:cspecform)) (put (quote progv) (quote c!:code) (function c!:cspecform)) (put (quote quote) (quote c!:code) (function c!:cspecform)) (put (quote return) (quote c!:code) (function c!:cspecform)) ( put (quote return!-from) (quote c!:code) (function c!:cspecform)) (put (quote setq) (quote c!:code) (function c!:cspecform)) (put (quote tagbody) (quote c!:code) (function c!:cspecform)) (put (quote the) (quote c!:code) (function c!:cspecform)) (put (quote unless) (quote c!:code) (function c!:cspecform)) ( put (quote unwind!-protect) (quote c!:code) (function c!:cspecform)) (put ( quote when) (quote c!:code) (function c!:cspecform)) (put (quote catch) ( quote c!:valid) (function c!:valid_specform)) (put (quote compiler!-let) ( quote c!:valid) (function c!:valid_specform)) (put (quote cond) (quote c!:valid) (function c!:valid_specform)) (put (quote declare) (quote c!:valid) (function c!:valid_specform)) (put (quote de) (quote c!:valid) (function c!:valid_specform)) (put (quote eval!-when) (quote c!:valid) (function c!:valid_specform)) (put (quote flet) (quote c!:valid) (function c!:valid_specform)) (put (quote function) (quote c!:valid) (function c!:valid_specform)) (put (quote labels) (quote c!:valid) (function c!:valid_specform)) (put (quote !~let) (quote c!:valid) (function c!:valid_specform)) (put (quote let!*) (quote c!:valid) (function c!:valid_specform)) (put (quote macrolet) (quote c!:valid) (function c!:valid_specform)) (put (quote multiple!-value!-call) (quote c!:valid) ( function c!:valid_specform)) (put (quote multiple!-value!-prog1) (quote c!:valid) (function c!:valid_specform)) (put (quote prog) (quote c!:valid) ( function c!:valid_specform)) (put (quote prog!*) (quote c!:valid) (function c!:valid_specform)) (put (quote progv) (quote c!:valid) (function c!:valid_specform)) (put (quote quote) (quote c!:valid) (function c!:valid_specform)) (put (quote the) (quote c!:valid) (function c!:valid_specform)) (put (quote unwind!-protect) (quote c!:valid) (function c!:valid_specform))) (fluid (quote (c!:current_procedure c!:current_args c!:current_block c!:current_contents c!:all_blocks c!:registers c!:stacklocs))) (fluid (quote (c!:available c!:used))) (setq c!:available (setq c!:used nil)) (de c!:reset_gensyms nil (progn (remflag c!:used (quote c!:live_across_call)) (remflag c!:used (quote c!:visited)) (prog nil lab1215 (cond ((null c!:used) (return nil))) (progn (remprop (car c!:used) (quote c!:contents)) (remprop ( car c!:used) (quote c!:why)) (remprop (car c!:used) (quote c!:where_to)) ( remprop (car c!:used) (quote c!:count)) (remprop (car c!:used) (quote c!:live )) (remprop (car c!:used) (quote c!:clash)) (remprop (car c!:used) (quote c!:chosen)) (remprop (car c!:used) (quote c!:location)) (cond ((plist (car c!:used)) (prog (o) (setq o (wrs nil)) (princ "+++++ ") (prin (car c!:used)) (princ " ") (prin (plist (car c!:used))) (terpri) (wrs o)))) (setq c!:available (cons (car c!:used) c!:available)) (setq c!:used (cdr c!:used))) (go lab1215)))) (de c!:my_gensym nil (prog (w) (cond (c!:available (progn (setq w (car c!:available)) (setq c!:available (cdr c!:available)))) (t (setq w (gensym1 "v")))) (setq c!:used (cons w c!:used)) (cond ((plist w) (progn (princ "????? ") (prin w) (princ " => ") (prin (plist w)) (terpri)))) (return w))) (de c!:newreg nil (prog (r) (setq r (c!:my_gensym)) (setq c!:registers (cons r c!:registers)) (return r))) (de c!:startblock (s) (progn (setq c!:current_block s) (setq c!:current_contents nil))) (de c!:outop (a b c d) (cond (c!:current_block (setq c!:current_contents ( cons (list a b c d) c!:current_contents))))) (de c!:endblock (why where_to) (cond (c!:current_block (progn (put c!:current_block (quote c!:contents) c!:current_contents) (put c!:current_block (quote c!:why) why) (put c!:current_block (quote c!:where_to ) where_to) (setq c!:all_blocks (cons c!:current_block c!:all_blocks)) (setq c!:current_contents nil) (setq c!:current_block nil))))) (de c!:cval_inner (x env) (prog (helper) (setq x (s!:improve x)) (cond ((atom x) (return (c!:catom x env))) (t (cond ((eqcar (car x) (quote lambda)) ( return (c!:clambda (cadar x) (cddar x) (cdr x) env))) (t (cond ((setq helper (get (car x) (quote c!:code))) (return (funcall helper x env))) (t (cond (( and (setq helper (get (car x) (quote c!:compile_macro))) (setq helper ( funcall helper x))) (return (c!:cval helper env))) (t (cond ((and (idp (car x )) (setq helper (macro!-function (car x)))) (return (c!:cval (funcall helper x) env))) (t (return (c!:ccall (car x) (cdr x) env)))))))))))))) (de c!:cval (x env) (prog (r) (setq r (c!:cval_inner x env)) (cond ((and r ( not (member!*!* r c!:registers))) (error 0 (list r "not a register" x)))) ( return r))) (de c!:clambda (bvl body args env) (prog (w w1 fluids env1 decs) (setq env1 ( car env)) (setq w (prog (var1217 var1218) (setq var1217 args) lab1216 (cond ( (null var1217) (return (reversip var1218)))) (prog (a) (setq a (car var1217)) (setq var1218 (cons (c!:cval a env) var1218))) (setq var1217 (cdr var1217)) (go lab1216))) (setq w1 (s!:find_local_decs body nil)) (setq localdecs (cons (car w1) localdecs)) (setq w1 (cdr w1)) (cond ((null w1) (setq body nil)) (t (cond ((null (cdr w1)) (setq body (car w1))) (t (setq body (cons (quote progn ) w1)))))) (prog (var1220) (setq var1220 bvl) lab1219 (cond ((null var1220) ( return nil))) (prog (x) (setq x (car var1220)) (cond ((and (not (fluidp x)) ( not (globalp x)) (c!:local_fluidp x localdecs)) (progn (make!-special x) ( setq decs (cons x decs)))))) (setq var1220 (cdr var1220)) (go lab1219)) (prog (var1222) (setq var1222 bvl) lab1221 (cond ((null var1222) (return nil))) ( prog (v) (setq v (car var1222)) (progn (cond ((globalp v) (prog (oo) (setq oo (wrs nil)) (princ "+++++ ") (prin v) (princ " converted from GLOBAL to FLUID") (terpri) (wrs oo) (unglobal (list v)) ( fluid (list v))))) (cond ((fluidp v) (progn (setq fluids (cons (cons v ( c!:newreg)) fluids)) (flag (list (cdar fluids)) (quote c!:live_across_call)) (setq env1 (cons (cons (quote c!:dummy!:name) (cdar fluids)) env1)) (c!:outop (quote ldrglob) (cdar fluids) v (c!:find_literal v)) (c!:outop (quote strglob) (car w) v (c!:find_literal v)))) (t (progn (setq env1 (cons (cons v (c!:newreg)) env1)) (c!:outop (quote movr) (cdar env1) nil (car w))))) (setq w (cdr w)))) (setq var1222 (cdr var1222)) (go lab1221)) (cond (fluids ( c!:outop (quote fluidbind) nil nil fluids))) (setq env (cons env1 (append fluids (cdr env)))) (setq w (c!:cval body env)) (prog (var1224) (setq var1224 fluids) lab1223 (cond ((null var1224) (return nil))) (prog (v) (setq v (car var1224)) (c!:outop (quote strglob) (cdr v) (car v) (c!:find_literal (car v)) )) (setq var1224 (cdr var1224)) (go lab1223)) (unfluid decs) (setq localdecs (cdr localdecs)) (return w))) (de c!:locally_bound (x env) (atsoc x (car env))) (flag (quote (nil t)) (quote c!:constant)) (fluid (quote (literal_vector))) (de c!:find_literal (x) (prog (n w) (setq w literal_vector) (setq n 0) (prog nil lab1225 (cond ((null (and w (not (equal (car w) x)))) (return nil))) ( progn (setq n (plus n 1)) (setq w (cdr w))) (go lab1225)) (cond ((null w) ( setq literal_vector (append literal_vector (list x))))) (return n))) (de c!:catom (x env) (prog (v w) (setq v (c!:newreg)) (cond ((and (idp x) (or (fluidp x) (globalp x))) (c!:outop (quote ldrglob) v x (c!:find_literal x))) (t (cond ((and (idp x) (setq w (c!:locally_bound x env))) (c!:outop (quote movr) v nil (cdr w))) (t (cond ((or (null x) (equal x (quote t)) ( c!:small_number x)) (c!:outop (quote movk1) v nil x)) (t (cond ((or (not (idp x)) (flagp x (quote c!:constant))) (c!:outop (quote movk) v x ( c!:find_literal x))) (t (c!:outop (quote ldrglob) v x (c!:find_literal x))))) ))))) (return v))) (de c!:cjumpif (x env d1 d2) (prog (helper r) (setq x (s!:improve x)) (cond ( (and (atom x) (or (not (idp x)) (and (flagp x (quote c!:constant)) (not ( c!:locally_bound x env))))) (c!:endblock (quote goto) (list (cond (x d1) (t d2))))) (t (cond ((and (not (atom x)) (setq helper (get (car x) (quote c!:ctest)))) (return (funcall helper x env d1 d2))) (t (progn (setq r ( c!:cval x env)) (c!:endblock (list (quote ifnull) r) (list d2 d1))))))))) (fluid (quote (c!:current))) (de c!:ccall (fn args env) (c!:ccall1 fn args env)) (fluid (quote (c!:visited))) (de c!:has_calls (a b) (prog (c!:visited) (return (c!:has_calls_1 a b)))) (de c!:has_calls_1 (a b) (cond ((or (equal a b) (not (atom a)) (memq a c!:visited)) nil) (t (prog (has_call) (setq c!:visited (cons a c!:visited)) ( prog (var1227) (setq var1227 (get a (quote c!:contents))) lab1226 (cond (( null var1227) (return nil))) (prog (z) (setq z (car var1227)) (cond ((eqcar z (quote call)) (setq has_call t)))) (setq var1227 (cdr var1227)) (go lab1226) ) (cond (has_call (return (prog (c!:visited) (return (c!:can_reach a b)))))) (prog (var1229) (setq var1229 (get a (quote c!:where_to))) lab1228 (cond (( null var1229) (return nil))) (prog (d) (setq d (car var1229)) (cond (( c!:has_calls_1 d b) (setq has_call t)))) (setq var1229 (cdr var1229)) (go lab1228)) (return has_call))))) (de c!:can_reach (a b) (cond ((equal a b) t) (t (cond ((or (not (atom a)) ( memq a c!:visited)) nil) (t (progn (setq c!:visited (cons a c!:visited)) ( c!:any_can_reach (get a (quote c!:where_to)) b))))))) (de c!:any_can_reach (l b) (cond ((null l) nil) (t (cond ((c!:can_reach (car l) b) t) (t (c!:any_can_reach (cdr l) b)))))) (de c!:pareval (args env) (prog (tasks tasks1 merge split r) (setq tasks ( prog (var1231 var1232) (setq var1231 args) lab1230 (cond ((null var1231) ( return (reversip var1232)))) (prog (a) (setq a (car var1231)) (setq var1232 ( cons (cons (c!:my_gensym) (c!:my_gensym)) var1232))) (setq var1231 (cdr var1231)) (go lab1230))) (setq split (c!:my_gensym)) (c!:endblock (quote goto ) (list split)) (prog (var1234) (setq var1234 args) lab1233 (cond ((null var1234) (return nil))) (prog (a) (setq a (car var1234)) (prog (s) (setq s ( car tasks)) (setq tasks (cdr tasks)) (c!:startblock (car s)) (setq r (cons ( c!:cval a env) r)) (c!:endblock (quote goto) (list (cdr s))) (cond ((or t ( c!:has_calls (car s) (cdr s))) (setq tasks1 (cons s tasks1))) (t (setq merge (cons s merge)))))) (setq var1234 (cdr var1234)) (go lab1233)) (prog (var1236 ) (setq var1236 tasks1) lab1235 (cond ((null var1236) (return nil))) (prog (z ) (setq z (car var1236)) (setq merge (cons z merge))) (setq var1236 (cdr var1236)) (go lab1235)) (prog (var1238) (setq var1238 merge) lab1237 (cond (( null var1238) (return nil))) (prog (v) (setq v (car var1238)) (progn ( c!:startblock split) (c!:endblock (quote goto) (list (car v))) (setq split ( cdr v)))) (setq var1238 (cdr var1238)) (go lab1237)) (c!:startblock split) ( return (reversip r)))) (de c!:ccall1 (fn args env) (prog (tasks merge r val) (setq fn (list fn (cdr env))) (setq val (c!:newreg)) (cond ((null args) (c!:outop (quote call) val nil fn)) (t (cond ((null (cdr args)) (c!:outop (quote call) val (list ( c!:cval (car args) env)) fn)) (t (progn (setq r (c!:pareval args env)) ( c!:outop (quote call) val r fn)))))) (c!:outop (quote reloadenv) (quote env) nil nil) (return val))) (fluid (quote (restart_label reloadenv does_call c!:current_c_name))) (de c!:local_fluidp1 (v decs) (and decs (or (and (eqcar (car decs) (quote special)) (memq v (cdar decs))) (c!:local_fluidp1 v (cdr decs))))) (de c!:local_fluidp (v decs) (and decs (or (c!:local_fluidp1 v (car decs)) ( c!:local_fluidp v (cdr decs))))) (fluid (quote (proglabs blockstack localdecs))) (de c!:cfndef (c!:current_procedure c!:current_c_name argsbody checksum) ( prog (env n w c!:current_args c!:current_block restart_label c!:current_contents c!:all_blocks entrypoint exitpoint args1 c!:registers c!:stacklocs literal_vector reloadenv does_call blockstack proglabs args body localdecs varargs) (setq args (car argsbody)) (setq body (cdr argsbody)) ( setq w (s!:find_local_decs body nil)) (setq body (cdr w)) (cond ((atom body) (setq body nil)) (t (cond ((atom (cdr body)) (setq body (car body))) (t (setq body (cons (quote progn) body)))))) (setq localdecs (list (car w))) ( c!:reset_gensyms) (wrs C_file) (linelength 200) (c!:printf "\n\n// Code for %a\n\n" c!:current_procedure) (c!:find_literal c!:current_procedure) (setq c!:current_args args) (setq varargs (or (null args) (geq (length args) 3))) (prog (var1240) (setq var1240 args) lab1239 ( cond ((null var1240) (return nil))) (prog (v) (setq v (car var1240)) (cond (( or (equal v (quote !&optional)) (equal v (quote !&rest))) (error 0 "&optional and &rest not supported by this compiler (yet)")) (t (cond (( globalp v) (prog (oo) (setq oo (wrs nil)) (princ "+++++ ") (prin v) (princ " converted from GLOBAL to FLUID") (terpri) (wrs oo) (unglobal (list v)) ( fluid (list v)) (setq n (cons (cons v (c!:my_gensym)) n)))) (t (cond ((or ( fluidp v) (c!:local_fluidp v localdecs)) (setq n (cons (cons v (c!:my_gensym) ) n))))))))) (setq var1240 (cdr var1240)) (go lab1239)) (cond (!*r2i (setq body (s!:r2i c!:current_procedure args body)))) (setq restart_label ( c!:my_gensym)) (setq body (list (quote c!:private_tagbody) restart_label body )) (cond (n (progn (setq body (list (list (quote return) body))) (setq args ( subla n args)) (prog (var1242) (setq var1242 n) lab1241 (cond ((null var1242) (return nil))) (prog (v) (setq v (car var1242)) (setq body (cons (list ( quote setq) (car v) (cdr v)) body))) (setq var1242 (cdr var1242)) (go lab1241 )) (setq body (cons (quote prog) (cons (prog (var1244 var1245) (setq var1244 (reverse n)) lab1243 (cond ((null var1244) (return (reversip var1245)))) ( prog (v) (setq v (car var1244)) (setq var1245 (cons (car v) var1245))) (setq var1244 (cdr var1244)) (go lab1243)) body)))))) (c!:printf "static LispObject %s(LispObject env" c!:current_c_name) (setq env nil) (cond (varargs (c!:printf ", int nargs, ...")) (t (progn (setq n t) (prog (var1247 ) (setq var1247 args) lab1246 (cond ((null var1247) (return nil))) (prog (x) (setq x (car var1247)) (prog (aa) (c!:printf ",") (cond (n (progn (c!:printf "\n ") (setq n nil))) (t (setq n t))) (setq aa ( c!:my_gensym)) (setq env (cons (cons x aa) env)) (setq c!:registers (cons aa c!:registers)) (setq args1 (cons aa args1)) (c!:printf " LispObject %s" aa))) (setq var1247 (cdr var1247)) (go lab1246))))) (c!:printf ")\n{\n") (cond (( and varargs args) (prog (var1249) (setq var1249 args) lab1248 (cond ((null var1249) (return nil))) (prog (x) (setq x (car var1249)) (prog (aa) (setq aa (c!:my_gensym)) (setq env (cons (cons x aa) env)) (setq c!:registers (cons aa c!:registers)) (setq args1 (cons aa args1)))) (setq var1249 (cdr var1249)) ( go lab1248)))) (c!:startblock (setq entrypoint (c!:my_gensym))) (setq exitpoint c!:current_block) (c!:endblock (quote goto) (list (list (c!:cval body (cons env nil))))) (c!:optimise_flowgraph entrypoint c!:all_blocks env ( cons (length args) c!:current_procedure) args1 varargs) (c!:printf "}\n\n") ( wrs O_file) (setq L_contents (cons (cons c!:current_procedure (cons literal_vector checksum)) L_contents)) (return nil))) (flag (quote (rds deflist flag fluid global remprop remflag unfluid unglobal dm carcheck C!-end)) (quote eval)) (flag (quote (rds)) (quote ignore)) (fluid (quote (!*backtrace))) (de c!:ccompilesupervisor nil (prog (u w) top (setq u (errorset (quote (read) ) t !*backtrace)) (cond ((atom u) (return nil))) (setq u (car u)) (cond (( equal u !$eof!$) (return nil))) (cond ((atom u) (go top)) (t (cond ((eqcar u (quote C!-end)) (return (apply (quote C!-end) nil))) (t (cond ((eqcar u ( quote rdf)) (progn (setq w (open (setq u (eval (cadr u))) (quote input))) ( cond (w (progn (terpri) (princ "Reading file ") (print u) (setq w (rds w)) ( c!:ccompilesupervisor) (princ "End of file ") (print u) (close (rds w)))) (t (progn (princ "Failed to open file ") (print u)))))) (t (c!:ccmpout1 u))))))) (go top))) (global (quote (c!:char_mappings))) (setq c!:char_mappings (quote ((! . !A) (!! . !B) (!# . !C) (!$ . !D) (!% . !E) (!^ . !F) (!& . !G) (!* . !H) (!( . !I) (!) . !J) (!- . !K) (!+ . !L) (!= . !M) (!\ . !N) (!| . !O) (!, . !P) (!. . !Q) (!< . !R) (!> . !S) (!: . !T) (!; . !U) (!/ . !V) (!? . !W) (!~ . !X) (!` . !Y)))) (fluid (quote (c!:names_so_far))) (de c!:inv_name (n) (prog (r w) (cond ((setq w (assoc n c!:names_so_far)) ( setq w (plus (cdr w) 1))) (t (setq w 0))) (setq c!:names_so_far (cons (cons n w) c!:names_so_far)) (setq r (quote (!C !C !"))) (cond ((not (zerop w)) ( setq r (append (reverse (explodec w)) r)))) (setq r (cons (quote !_) r)) ( prog (var1251) (setq var1251 (explode2 n)) lab1250 (cond ((null var1251) ( return nil))) (prog (c) (setq c (car var1251)) (progn (cond ((equal c (quote _)) (setq r (cons (quote _) r))) (t (cond ((or (liter c) (digit c)) (setq r ( cons c r))) (t (cond ((setq w (atsoc c c!:char_mappings)) (setq r (cons (cdr w) r))) (t (setq r (cons (quote !Z) r)))))))))) (setq var1251 (cdr var1251)) (go lab1250)) (setq r (cons (quote !") r)) (return (compress (reverse r))))) (fluid (quote (c!:defnames pending_functions))) (de c!:ccmpout1 (u) (prog (pending_functions) (setq pending_functions (list u )) (prog nil lab1252 (cond ((null pending_functions) (return nil))) (progn ( setq u (car pending_functions)) (setq pending_functions (cdr pending_functions)) (c!:ccmpout1a u)) (go lab1252)))) (de c!:ccmpout1a (u) (prog (w checksum) (cond ((atom u) (return nil)) (t ( cond ((eqcar u (quote progn)) (progn (prog (var1254) (setq var1254 (cdr u)) lab1253 (cond ((null var1254) (return nil))) (prog (v) (setq v (car var1254)) (c!:ccmpout1a v)) (setq var1254 (cdr var1254)) (go lab1253)) (return nil))) (t (cond ((eqcar u (quote C!-end)) nil) (t (cond ((or (flagp (car u) (quote eval)) (and (equal (car u) (quote setq)) (not (atom (caddr u))) (flagp ( caaddr u) (quote eval)))) (errorset u t !*backtrace))))))))) (cond ((eqcar u (quote rdf)) (prog nil (setq w (open (setq u (eval (cadr u))) (quote input))) (cond (w (progn (princ "Reading file ") (print u) (setq w (rds w)) ( c!:ccompilesupervisor) (princ "End of file ") (print u) (close (rds w)))) (t (progn (princ "Failed to open file ") (print u)))))) (t (cond ((eqcar u ( quote de)) (progn (setq u (cdr u)) (setq checksum (md60 u)) (setq c!:defnames (cons (list (car u) (c!:inv_name (car u)) (length (cadr u)) checksum) c!:defnames)) (princ "Compiling ") (prin (caar c!:defnames)) (princ " ... ") (c!:cfndef (caar c!:defnames) (cadar c!:defnames) (cdr u) checksum) (terpri)) )))))) (fluid (quote (!*defn dfprint!* dfprintsave))) (de c!:concat (a b) (compress (cons (quote !") (append (explode2 a) (append ( explode2 b) (quote (!"))))))) (de c!:ccompilestart (name setupname dir hdrnow) (prog (o d w) (reset!-gensym 0) (setq c!:registers (setq c!:available (setq c!:used nil))) (setq File_name (list2string (explodec name))) (setq Setup_name (explodec setupname )) (setq Setup_name (subst (quote !_) (quote !-) Setup_name)) (setq Setup_name (list2string Setup_name)) (cond (dir (progn (cond ((memq (quote win32) lispsystem!*) (setq name (c!:concat dir (c!:concat "\" name)))) (t ( setq name (c!:concat dir (c!:concat "/" name)))))))) (princ "C file = ") ( print name) (setq C_file (open (c!:concat name ".cpp") (quote output))) (setq L_file (c!:concat name ".lsp")) (setq L_contents nil) (setq c!:names_so_far nil) (setq o (reverse (explode (date!-and!-time)))) (prog (i) (setq i 1) lab1255 (cond ((minusp (times 1 (difference 5 i))) (return nil))) (progn ( setq d (cons (car o) d)) (setq o (cdr o))) (setq i (plus i 1)) (go lab1255)) (setq d (cons (quote !-) d)) (setq o (cdddr (cdddr (cddddr o)))) (setq w o) ( setq o (cdddr o)) (setq d (cons (caddr o) (cons (cadr o) (cons (car o) d)))) (setq d (compress (cons (quote !") (cons (cadr w) (cons (car w) (cons (quote !-) d)))))) (setq O_file (wrs C_file)) (setq c!:defnames nil) (cond (hdrnow ( c!:printf "\n// Module: %s %tMachine generated C code\n\n" setupname 25)) (t (c!:printf "\n// %s.c %tMachine generated C code\n\n" name 25))) (c!:printf "// $I") (c!:printf "d: $\n\n") (c!:printf "#include <cstdio>\n") (c!:printf "#include <cstdlib>\n") (c!:printf "#include <cstring>\n") (c!:printf "#include <cctype>\n") (c!:printf "#include <cstdarg>\n") (c!:printf "#include <ctime>\n") (c!:printf "#ifndef _cplusplus\n") (c!:printf "#include <csetjmp>\n") (c!:printf "#endif\n\n") (cond (hdrnow ( print!-config!-header)) (t (c!:printf "#include \qconfig.h\q\n\n"))) ( print!-csl!-headers) (cond (hdrnow (c!:print!-init))) (wrs O_file) (return nil))) (de c!:print!-init nil (progn (c!:printf "\n") (c!:printf "LispObject *nilp;\n") (c!:printf "LispObject **C_stackp;\n") (c!:printf "LispObject * volatile * stackLimitp;\n") (c!:printf "\n") (c!:printf "void init(LispObject *a, LispObject **b, LispObject * volatile *c)\n") ( c!:printf "{\n") (c!:printf " nilp = a;\n") (c!:printf " C_stackp = b;\n") (c!:printf " stackLimitp = c;\n") (c!:printf "}\n") (c!:printf "\n") (c!:printf "#define nil (*nilp)\n") (c!:printf "#define C_stack (*C_stackp)\n") (c!:printf "#define stackLimit (*stackLimitp)\n") (c!:printf "\n"))) (de C!-end nil (C!-end1 t)) (de C!-end1 (create_lfile) (prog (checksum c1 c2 c3) (wrs C_file) (cond ( create_lfile (c!:printf "\n\nsetup_type const %s_setup[] =\n{\n" Setup_name)) (t (c!:printf "\n\nsetup_type_1 const %s_setup[] =\n{\n" Setup_name))) (setq c!:defnames (reverse c!:defnames)) (prog nil lab1256 (cond ((null c!:defnames) (return nil))) (prog (name nargs f1 f2 cast fn) (setq name (caar c!:defnames)) (setq checksum (cadddr (car c!:defnames))) (setq f1 (cadar c!:defnames)) (setq nargs (caddar c!:defnames)) (setq cast "(n_args *)") ( cond ((equal nargs 1) (progn (setq f2 (quote !t!o!o_!m!a!n!y_1)) (setq cast "") (setq fn (quote !w!r!o!n!g_!n!o_1)))) (t (cond ((equal nargs 2) (progn ( setq f2 f1) (setq f1 (quote !t!o!o_!f!e!w_2)) (setq cast "") (setq fn (quote !w!r!o!n!g_!n!o_2)))) (t (progn (setq fn f1) (setq f1 (quote !w!r!o!n!g_!n!o_!n!a)) (setq f2 (quote !w!r!o!n!g_!n!o_!n!b))))))) (cond ( create_lfile (c!:printf " {\q%s\q,%t%s,%t%s,%t%s%s},\n" name 32 f1 48 f2 63 cast fn)) (t (prog (c1 c2) (setq c1 (divide checksum (expt 2 31))) (setq c2 (cdr c1)) (setq c1 (car c1)) (c!:printf " {\q%s\q, %t%s, %t%s, %t%s%s, %t%s, %t%s},\n" name 24 f1 40 f2 52 cast fn 64 c1 76 c2)))) (setq c!:defnames (cdr c!:defnames))) (go lab1256)) (setq c3 (setq checksum (md60 L_contents))) (setq c1 (remainder c3 10000000)) (setq c3 (quotient c3 10000000)) (setq c2 (remainder c3 10000000)) (setq c3 ( quotient c3 10000000)) (setq checksum (list2string (append (explodec c3) ( cons (quote ! ) (append (explodec c2) (cons (quote ! ) (explodec c1))))))) ( c!:printf " {NULL, (one_args *)%a, (two_args *)%a, 0}\n};\n\n" Setup_name checksum) (c!:printf "%<// end of generated code\n") (close C_file) (cond ( create_lfile (progn (setq L_file (open L_file (quote output))) (wrs L_file) ( linelength 72) (terpri) (princ "% ") (princ Setup_name) (princ ".lsp") (ttab 20) (princ "Machine generated Lisp") (terpri) (terpri) (princ "(c!:install ") (princ (quote !")) (princ Setup_name) (princ (quote !")) (princ " ") (princ checksum) (printc ")") (terpri) (prog (var1258) (setq var1258 (reverse L_contents)) lab1257 (cond ((null var1258) (return nil))) (prog (x) (setq x ( car var1258)) (progn (princ "(c!:install '") (prin (car x)) (princ " '") ( prin (cadr x)) (princ " ") (prin (cddr x)) (princ ")") (terpri) (terpri))) ( setq var1258 (cdr var1258)) (go lab1257)) (terpri) (princ "% End of generated Lisp code") (terpri) (terpri) (setq L_contents nil) (wrs O_file) (close L_file) (setq !*defn nil) (setq dfprint!* dfprintsave))) (t ( progn (setq checksum (cons checksum (reverse L_contents))) (setq L_contents nil) (return checksum)))))) (put (quote C!-end) (quote stat) (quote endstat)) (de C!-compile (u) (prog nil (terpri) (princ "C!-COMPILE ") (prin u) (princ ": IN files; or type in expressions") (terpri) (princ "When all done, execute C!-END;") (terpri) (verbos nil) (c!:ccompilestart ( car u) (car u) nil nil) (setq dfprintsave dfprint!*) (setq dfprint!* (quote c!:ccmpout1)) (setq !*defn t) (cond ((getd (quote begin)) (return nil))) ( c!:ccompilesupervisor))) (put (quote C!-compile) (quote stat) (quote rlis)) (de c!:print_opcode (s depth) (prog (op r1 r2 r3 helper) (setq op (car s)) ( setq r1 (cadr s)) (setq r2 (caddr s)) (setq r3 (cadddr s)) (setq helper (get op (quote c!:opcode_printer))) (cond (helper (funcall helper op r1 r2 r3 depth)) (t (progn (prin s) (terpri)))))) (de c!:print_exit_condition (why where_to depth) (prog (helper lab1 drop1 lab2 drop2 negate) (cond ((equal why (quote goto)) (progn (setq where_to (car where_to)) (cond ((atom where_to) (progn (c!:printf " goto %s;\n" where_to) (c!:display_flowgraph where_to depth t))) (t (progn (c!:printf " ") (c!:pgoto where_to depth)))) (return nil))) (t (cond ((eqcar (car why ) (quote call)) (return (prog (args locs g w) (cond ((setq w (get (cadar why) (quote c!:direct_entrypoint))) (progn (prog (var1260) (setq var1260 (cdr why )) lab1259 (cond ((null var1260) (return nil))) (prog (a) (setq a (car var1260)) (cond ((flagp a (quote c!:live_across_call)) (progn (cond ((null g) (c!:printf " {\n"))) (setq g (c!:my_gensym)) (c!:printf " LispObject %s = %v;\n" g a) (setq args (cons g args)))) (t (setq args (cons a args))))) (setq var1260 (cdr var1260)) (go lab1259)) (cond ((neq depth 0) (progn (cond (g (c!:printf " "))) (c!:printf " popv(%s);\n" depth)))) (cond (g (c!:printf " "))) (c!:printf " return %s(" (cdr w)) (setq args (reversip args)) (cond (args (progn (c!:printf "%v" (car args)) ( prog (var1262) (setq var1262 (cdr args)) lab1261 (cond ((null var1262) ( return nil))) (prog (a) (setq a (car var1262)) (c!:printf ", %v" a)) (setq var1262 (cdr var1262)) (go lab1261))))) (c!:printf ");\n") (cond (g ( c!:printf " }\n"))))) (t (cond ((setq w (get (cadar why) (quote c!:c_entrypoint))) (progn (prog (var1264) (setq var1264 (cdr why)) lab1263 ( cond ((null var1264) (return nil))) (prog (a) (setq a (car var1264)) (cond (( flagp a (quote c!:live_across_call)) (progn (cond ((null g) (c!:printf " {\n"))) (setq g (c!:my_gensym)) (c!:printf " LispObject %s = %v;\n" g a) (setq args (cons g args)))) (t (setq args (cons a args))))) (setq var1264 (cdr var1264)) (go lab1263)) (cond ((neq depth 0) (c!:printf " popv(%s);\n" depth))) (c!:printf " return %s(nil" w) (cond ((or (null args) (geq (length args) 3)) ( c!:printf ", %s" (length args)))) (prog (var1266) (setq var1266 (reversip args)) lab1265 (cond ((null var1266) (return nil))) (prog (a) (setq a (car var1266)) (c!:printf ", %v" a)) (setq var1266 (cdr var1266)) (go lab1265)) ( c!:printf ");\n") (cond (g (c!:printf " }\n"))))) (t (prog (nargs) (setq nargs (length (cdr why))) (c!:printf " {\n") (prog (var1268) (setq var1268 (cdr why)) lab1267 (cond ((null var1268) (return nil))) (prog (a) (setq a ( car var1268)) (cond ((flagp a (quote c!:live_across_call)) (progn (setq g ( c!:my_gensym)) (c!:printf " LispObject %s = %v;\n" g a) (setq args ( cons g args)))) (t (setq args (cons a args))))) (setq var1268 (cdr var1268)) (go lab1267)) (cond ((neq depth 0) (c!:printf " popv(%s);\n" depth))) (c!:printf " fn = elt(env, %s); %<// %c\n" (c!:find_literal (cadar why )) (cadar why)) (cond ((equal nargs 1) (c!:printf " return (*qfn1(fn))(qenv(fn)")) (t (cond ((equal nargs 2) (c!:printf " return (*qfn2(fn))(qenv(fn)")) (t (c!:printf " return (*qfnn(fn))(qenv(fn), %s" nargs))))) (prog (var1270) (setq var1270 (reversip args)) lab1269 (cond ((null var1270) (return nil))) (prog ( a) (setq a (car var1270)) (c!:printf ", %s" a)) (setq var1270 (cdr var1270)) (go lab1269)) (c!:printf ");\n }\n")))))) (return nil))))))) (setq lab1 ( car where_to)) (setq drop1 (and (atom lab1) (not (flagp lab1 (quote c!:visited))))) (setq lab2 (cadr where_to)) (setq drop2 (and (atom lab2) (not (flagp drop2 (quote c!:visited))))) (cond ((and drop2 (equal (get lab2 ( quote c!:count)) 1)) (progn (setq where_to (list lab2 lab1)) (setq drop1 t))) (t (cond (drop1 (setq negate t))))) (setq helper (get (car why) (quote c!:exit_helper))) (cond ((null helper) (error 0 (list "Bad exit condition" why)))) (c!:printf " if (") (cond (negate (progn (c!:printf "!(") (funcall helper (cdr why) depth) (c!:printf ")"))) (t (funcall helper (cdr why) depth ))) (c!:printf ") ") (cond ((not drop1) (progn (c!:pgoto (car where_to) depth ) (c!:printf " else ")))) (c!:pgoto (cadr where_to) depth) (cond ((atom ( car where_to)) (c!:display_flowgraph (car where_to) depth drop1))) (cond (( atom (cadr where_to)) (c!:display_flowgraph (cadr where_to) depth nil))))) (de c!:pmovr (op r1 r2 r3 depth) (c!:printf " %v = %v;\n" r1 r3)) (put (quote movr) (quote c!:opcode_printer) (function c!:pmovr)) (de c!:pmovk (op r1 r2 r3 depth) (c!:printf " %v = elt(env, %s); %<// %c\n" r1 r3 r2)) (put (quote movk) (quote c!:opcode_printer) (function c!:pmovk)) (de c!:pmovk1 (op r1 r2 r3 depth) (cond ((null r3) (c!:printf " %v = nil;\n" r1)) (t (cond ((equal r3 (quote t)) (c!:printf " %v = lisp_true;\n" r1)) (t (c!:printf " %v = (LispObject)%s+TAG_FIXNUM; %<// %c\n" r1 (times 16 r3) r3)))))) (put (quote movk1) (quote c!:opcode_printer) (function c!:pmovk1)) (flag (quote (movk1)) (quote c!:uses_nil)) (de c!:preloadenv (op r1 r2 r3 depth) (c!:printf " env = stack[%s];\n" ( minus reloadenv))) (put (quote reloadenv) (quote c!:opcode_printer) (function c!:preloadenv)) (de c!:pldrglob (op r1 r2 r3 depth) (c!:printf " %v = qvalue(elt(env, %s)); %<// %c\n" r1 r3 r2)) (put (quote ldrglob) (quote c!:opcode_printer) (function c!:pldrglob)) (de c!:pstrglob (op r1 r2 r3 depth) (c!:printf " qvalue(elt(env, %s)) = %v; %<// %c\n" r3 r1 r2)) (put (quote strglob) (quote c!:opcode_printer) (function c!:pstrglob)) (de c!:pnilglob (op r1 r2 r3 depth) (c!:printf " qvalue(elt(env, %s)) = nil; %<// %c\n" r3 r2)) (put (quote nilglob) (quote c!:opcode_printer) (function c!:pnilglob)) (flag (quote (nilglob)) (quote c!:uses_nil)) (de c!:pnull (op r1 r2 r3 depth) (c!:printf " %v = (%v == nil ? lisp_true : nil);\n" r1 r3)) (put (quote null) (quote c!:opcode_printer) (function c!:pnull)) (put (quote not) (quote c!:opcode_printer) (function c!:pnull)) (flag (quote (null not)) (quote c!:uses_nil)) (de c!:pfastget (op r1 r2 r3 depth) (progn (c!:printf " if (!symbolp(%v)) %v = nil;\n" r2 r1) (c!:printf " else { %v = qfastgets(%v);\n" r1 r2) (c!:printf " if (%v != nil) { %v = elt(%v, %s); %<// %c\n" r1 r1 r1 (car r3) ( cdr r3)) (c!:printf "#ifdef RECORD_GET\n") (c!:printf " if (%v != SPID_NOPROP)\n" r1) (c!:printf " record_get(elt(fastget_names, %s), 1);\n" (car r3)) ( c!:printf " else record_get(elt(fastget_names, %s), 0),\n" (car r3)) (c!:printf " %v = nil; }\n" r1) (c!:printf " else record_get(elt(fastget_names, %s), 0); }\n" (car r3)) ( c!:printf "#else\n") (c!:printf " if (%v == SPID_NOPROP) %v = nil; }}\n" r1 r1) (c!:printf "#endif\n"))) (put (quote fastget) (quote c!:opcode_printer) (function c!:pfastget)) (flag (quote (fastget)) (quote c!:uses_nil)) (de c!:pfastflag (op r1 r2 r3 depth) (progn (c!:printf " if (!symbolp(%v)) %v = nil;\n" r2 r1) (c!:printf " else { %v = qfastgets(%v);\n" r1 r2) (c!:printf " if (%v != nil) { %v = elt(%v, %s); %<// %c\n" r1 r1 r1 (car r3) ( cdr r3)) (c!:printf "#ifdef RECORD_GET\n") (c!:printf " if (%v == SPID_NOPROP)\n" r1) (c!:printf " record_get(elt(fastget_names, %s), 0),\n" (car r3)) ( c!:printf " %v = nil;\n" r1) (c!:printf " else record_get(elt(fastget_names, %s), 1),\n" (car r3)) ( c!:printf " %v = lisp_true; }\n" r1) (c!:printf " else record_get(elt(fastget_names, %s), 0); }\n" (car r3)) ( c!:printf "#else\n") (c!:printf " if (%v == SPID_NOPROP) %v = nil; else %v = lisp_true; }}\n" r1 r1 r1) (c!:printf "#endif\n"))) (put (quote fastflag) (quote c!:opcode_printer) (function c!:pfastflag)) (flag (quote (fastflag)) (quote c!:uses_nil)) (de c!:pcar (op r1 r2 r3 depth) (prog nil (cond ((not !*unsafecar) (progn ( c!:printf " if (!car_legal(%v)) " r3) (c!:pgoto (c!:find_error_label (list (quote car) r3) r2 depth) depth)))) (c!:printf " %v = qcar(%v);\n" r1 r3) )) (put (quote car) (quote c!:opcode_printer) (function c!:pcar)) (de c!:pcdr (op r1 r2 r3 depth) (prog nil (cond ((not !*unsafecar) (progn ( c!:printf " if (!car_legal(%v)) " r3) (c!:pgoto (c!:find_error_label (list (quote cdr) r3) r2 depth) depth)))) (c!:printf " %v = qcdr(%v);\n" r1 r3) )) (put (quote cdr) (quote c!:opcode_printer) (function c!:pcdr)) (de c!:pqcar (op r1 r2 r3 depth) (c!:printf " %v = qcar(%v);\n" r1 r3)) (put (quote qcar) (quote c!:opcode_printer) (function c!:pqcar)) (de c!:pqcdr (op r1 r2 r3 depth) (c!:printf " %v = qcdr(%v);\n" r1 r3)) (put (quote qcdr) (quote c!:opcode_printer) (function c!:pqcdr)) (de c!:patom (op r1 r2 r3 depth) (c!:printf " %v = (consp(%v) ? nil : lisp_true);\n" r1 r3)) (put (quote atom) (quote c!:opcode_printer) (function c!:patom)) (flag (quote (atom)) (quote c!:uses_nil)) (de c!:pnumberp (op r1 r2 r3 depth) (c!:printf " %v = (is_number(%v) ? lisp_true : nil);\n" r1 r3)) (put (quote numberp) (quote c!:opcode_printer) (function c!:pnumberp)) (flag (quote (numberp)) (quote c!:uses_nil)) (de c!:pfixp (op r1 r2 r3 depth) (c!:printf " %v = integerp(%v);\n" r1 r3) ) (put (quote fixp) (quote c!:opcode_printer) (function c!:pfixp)) (flag (quote (fixp)) (quote c!:uses_nil)) (de c!:piminusp (op r1 r2 r3 depth) (c!:printf " %v = ((intptr_t)(%v) < 0 ? lisp_true : nil);\n" r1 r3)) (put (quote iminusp) (quote c!:opcode_printer) (function c!:piminusp)) (flag (quote (iminusp)) (quote c!:uses_nil)) (de c!:pilessp (op r1 r2 r3 depth) (c!:printf " %v = ((intptr_t)%v < (intptr_t)%v) ? lisp_true : nil;\n" r1 r2 r3)) (put (quote ilessp) (quote c!:opcode_printer) (function c!:pilessp)) (flag (quote (ilessp)) (quote c!:uses_nil)) (de c!:pigreaterp (op r1 r2 r3 depth) (c!:printf " %v = ((intptr_t)%v > (intptr_t)%v) ? lisp_true : nil;\n" r1 r2 r3)) (put (quote igreaterp) (quote c!:opcode_printer) (function c!:pigreaterp)) (flag (quote (igreaterp)) (quote c!:uses_nil)) (de c!:piminus (op r1 r2 r3 depth) (c!:printf " %v = (LispObject)(2-((intptr_t)(%v)));\n" r1 r3)) (put (quote iminus) (quote c!:opcode_printer) (function c!:piminus)) (de c!:piadd1 (op r1 r2 r3 depth) (c!:printf " %v = (LispObject)((intptr_t)(%v) + 0x10);\n" r1 r3)) (put (quote iadd1) (quote c!:opcode_printer) (function c!:piadd1)) (de c!:pisub1 (op r1 r2 r3 depth) (c!:printf " %v = (LispObject)((intptr_t)(%v) - 0x10);\n" r1 r3)) (put (quote isub1) (quote c!:opcode_printer) (function c!:pisub1)) (de c!:piplus2 (op r1 r2 r3 depth) (progn (c!:printf " %v = (LispObject)(intptr_t)((intptr_t)%v +" r1 r2) (c!:printf " (intptr_t)%v - TAG_FIXNUM);\n" r3))) (put (quote iplus2) (quote c!:opcode_printer) (function c!:piplus2)) (de c!:pidifference (op r1 r2 r3 depth) (progn (c!:printf " %v = (LispObject)(intptr_t)((intptr_t)%v - (intptr_t)%v" r1 r2 r3) ( c!:printf " + TAG_FIXNUM);\n"))) (put (quote idifference) (quote c!:opcode_printer) (function c!:pidifference) ) (de c!:pitimes2 (op r1 r2 r3 depth) (progn (c!:printf " %v = fixnum_of_int((intptr_t)(int_of_fixnum(%v) *" r1 r2) (c!:printf " int_of_fixnum(%v)));\n" r3))) (put (quote itimes2) (quote c!:opcode_printer) (function c!:pitimes2)) (de c!:pmodular_plus (op r1 r2 r3 depth) (progn (c!:printf " { intptr_t w = int_of_fixnum(%v) + int_of_fixnum(%v);\n" r2 r3) ( c!:printf " if (w >= current_modulus) w -= current_modulus;\n") ( c!:printf " %v = fixnum_of_int(w);\n" r1) (c!:printf " }\n"))) (put (quote modular!-plus) (quote c!:opcode_printer) (function c!:pmodular_plus)) (de c!:pmodular_difference (op r1 r2 r3 depth) (progn (c!:printf " { intptr_t w = int_of_fixnum(%v) - int_of_fixnum(%v);\n" r2 r3) ( c!:printf " if (w < 0) w += current_modulus;\n") (c!:printf " %v = fixnum_of_int(w);\n" r1) (c!:printf " }\n"))) (put (quote modular!-difference) (quote c!:opcode_printer) (function c!:pmodular_difference)) (de c!:pmodular_minus (op r1 r2 r3 depth) (progn (c!:printf " { intptr_t w = int_of_fixnum(%v);\n" r3) (c!:printf " if (w != 0) w = current_modulus - w;\n") (c!:printf " %v = fixnum_of_int(w);\n" r1) (c!:printf " }\n"))) (put (quote modular!-minus) (quote c!:opcode_printer) (function c!:pmodular_minus)) (de c!:passoc (op r1 r2 r3 depth) (c!:printf " %v = Lassoc(nil, %v, %v);\n" r1 r2 r3)) (put (quote assoc) (quote c!:opcode_printer) (function c!:passoc)) (flag (quote (assoc)) (quote c!:uses_nil)) (de c!:patsoc (op r1 r2 r3 depth) (c!:printf " %v = Latsoc(nil, %v, %v);\n" r1 r2 r3)) (put (quote atsoc) (quote c!:opcode_printer) (function c!:patsoc)) (flag (quote (atsoc)) (quote c!:uses_nil)) (de c!:pmember (op r1 r2 r3 depth) (c!:printf " %v = Lmember(nil, %v, %v);\n" r1 r2 r3)) (put (quote member) (quote c!:opcode_printer) (function c!:pmember)) (flag (quote (member)) (quote c!:uses_nil)) (de c!:pmemq (op r1 r2 r3 depth) (c!:printf " %v = Lmemq(nil, %v, %v);\n" r1 r2 r3)) (put (quote memq) (quote c!:opcode_printer) (function c!:pmemq)) (flag (quote (memq)) (quote c!:uses_nil)) (de c!:pget (op r1 r2 r3 depth) (c!:printf " %v = get(%v, %v);\n" r1 r2 r3 )) (put (quote get) (quote c!:opcode_printer) (function c!:pget)) (de c!:pqgetv (op r1 r2 r3 depth) (progn (c!:printf " %v = *(LispObject *)((char *)%v + (CELL-TAG_VECTOR) +" r1 r2) (c!:printf " (((intptr_t)%v-TAG_FIXNUM)/(16/CELL)));\n" r3))) (put (quote qgetv) (quote c!:opcode_printer) (function c!:pqgetv)) (de c!:pqputv (op r1 r2 r3 depth) (progn (c!:printf " *(LispObject *)((char *)%v + (CELL-TAG_VECTOR) +" r2) (c!:printf " (((intptr_t)%v-TAG_FIXNUM)/(16/CELL))) = %v;\n" r3 r1))) (put (quote qputv) (quote c!:opcode_printer) (function c!:pqputv)) (de c!:peq (op r1 r2 r3 depth) (c!:printf " %v = (%v == %v ? lisp_true : nil);\n" r1 r2 r3)) (put (quote eq) (quote c!:opcode_printer) (function c!:peq)) (flag (quote (eq)) (quote c!:uses_nil)) (de c!:pequal (op r1 r2 r3 depth) (c!:printf " %v = (equal(%v, %v) ? lisp_true : nil);\n" r1 r2 r3 r2 r3)) (put (quote equal) (quote c!:opcode_printer) (function c!:pequal)) (flag (quote (equal)) (quote c!:uses_nil)) (de c!:pfluidbind (op r1 r2 r3 depth) nil) (put (quote fluidbind) (quote c!:opcode_printer) (function c!:pfluidbind)) (de c!:pcall (op r1 r2 r3 depth) (prog (w boolfn) (cond ((setq w (get (car r3 ) (quote c!:direct_entrypoint))) (progn (c!:printf " %v = %s(" r1 (cdr w)) (cond (r2 (progn (c!:printf "%v" (car r2)) (prog (var1272) (setq var1272 ( cdr r2)) lab1271 (cond ((null var1272) (return nil))) (prog (a) (setq a (car var1272)) (c!:printf ", %v" a)) (setq var1272 (cdr var1272)) (go lab1271))))) (c!:printf ");\n"))) (t (cond ((setq w (get (car r3) (quote c!:direct_predicate))) (progn (setq boolfn t) (c!:printf " %v = (LispObject)%s(" r1 (cdr w)) (cond (r2 (progn (c!:printf "%v" (car r2)) (prog (var1274) (setq var1274 (cdr r2)) lab1273 (cond ((null var1274) ( return nil))) (prog (a) (setq a (car var1274)) (c!:printf ", %v" a)) (setq var1274 (cdr var1274)) (go lab1273))))) (c!:printf ");\n"))) (t (cond ((equal (car r3) c!:current_procedure) (progn (setq r2 (c!:fix_nargs r2 c!:current_args)) (c!:printf " %v = %s(env" r1 c!:current_c_name) (cond (( or (null r2) (geq (length r2) 3)) (c!:printf ", %s" (length r2)))) (prog ( var1276) (setq var1276 r2) lab1275 (cond ((null var1276) (return nil))) (prog (a) (setq a (car var1276)) (c!:printf ", %v" a)) (setq var1276 (cdr var1276) ) (go lab1275)) (c!:printf ");\n"))) (t (cond ((setq w (get (car r3) (quote c!:c_entrypoint))) (progn (c!:printf " %v = %s(nil" r1 w) (cond ((or (null r2) (geq (length r2) 3)) (c!:printf ", %s" (length r2)))) (prog (var1278) ( setq var1278 r2) lab1277 (cond ((null var1278) (return nil))) (prog (a) (setq a (car var1278)) (c!:printf ", %v" a)) (setq var1278 (cdr var1278)) (go lab1277)) (c!:printf ");\n"))) (t (prog (nargs) (setq nargs (length r2)) ( c!:printf " fn = elt(env, %s); %<// %c\n" (c!:find_literal (car r3)) (car r3)) (cond ((equal nargs 1) (c!:printf " %v = (*qfn1(fn))(qenv(fn)" r1)) ( t (cond ((equal nargs 2) (c!:printf " %v = (*qfn2(fn))(qenv(fn)" r1)) (t ( c!:printf " %v = (*qfnn(fn))(qenv(fn), %s" r1 nargs))))) (prog (var1280) ( setq var1280 r2) lab1279 (cond ((null var1280) (return nil))) (prog (a) (setq a (car var1280)) (c!:printf ", %v" a)) (setq var1280 (cdr var1280)) (go lab1279)) (c!:printf ");\n")))))))))) (cond ((not (flagp (car r3) (quote c!:no_errors))) (progn (cond ((and (null (cadr r3)) (equal depth 0)) ( c!:printf " errexit();\n")) (t (progn ( c!:printf " if (exception_pending()) ") (c!:pgoto (c!:find_error_label nil (cadr r3) depth) depth))))))) (cond (boolfn (c!:printf " %v = %v ? lisp_true : nil;\n" r1 r1))))) (de c!:fix_nargs (r2 act) (cond ((null act) nil) (t (cond ((null r2) (cons nil (c!:fix_nargs nil (cdr act)))) (t (cons (car r2) (c!:fix_nargs (cdr r2) ( cdr act)))))))) (put (quote call) (quote c!:opcode_printer) (function c!:pcall)) (de c!:pgoto (lab depth) (prog nil (cond ((atom lab) (return (c!:printf "goto %s;\n" lab)))) (setq lab (get (car lab) (quote c!:chosen))) (cond (( zerop depth) (c!:printf "return onevalue(%v);\n" lab)) (t (cond ((flagp lab ( quote c!:live_across_call)) (c!:printf "{ LispObject res = %v; popv(%s); return onevalue(res); }\n" lab depth)) (t ( c!:printf "{ popv(%s); return onevalue(%v); }\n" depth lab))))))) (de c!:pifnull (s depth) (c!:printf "%v == nil" (car s))) (put (quote ifnull) (quote c!:exit_helper) (function c!:pifnull)) (de c!:pifatom (s depth) (c!:printf "!consp(%v)" (car s))) (put (quote ifatom) (quote c!:exit_helper) (function c!:pifatom)) (de c!:pifsymbol (s depth) (c!:printf "symbolp(%v)" (car s))) (put (quote ifsymbol) (quote c!:exit_helper) (function c!:pifsymbol)) (de c!:pifnumber (s depth) (c!:printf "is_number(%v)" (car s))) (put (quote ifnumber) (quote c!:exit_helper) (function c!:pifnumber)) (de c!:pifizerop (s depth) (c!:printf "(%v) == 1" (car s))) (put (quote ifizerop) (quote c!:exit_helper) (function c!:pifizerop)) (de c!:pifeq (s depth) (c!:printf "%v == %v" (car s) (cadr s))) (put (quote ifeq) (quote c!:exit_helper) (function c!:pifeq)) (de c!:pifequal (s depth) (c!:printf "equal(%v, %v)" (car s) (cadr s) (car s) (cadr s))) (put (quote ifequal) (quote c!:exit_helper) (function c!:pifequal)) (de c!:pifilessp (s depth) (c!:printf "((intptr_t)(%v)) < ((intptr_t)(%v))" ( car s) (cadr s))) (put (quote ifilessp) (quote c!:exit_helper) (function c!:pifilessp)) (de c!:pifigreaterp (s depth) (c!:printf "((intptr_t)(%v)) > ((intptr_t)(%v))" (car s) (cadr s))) (put (quote ifigreaterp) (quote c!:exit_helper) (function c!:pifigreaterp)) (de c!:display_flowgraph (s depth dropping_through) (cond ((not (atom s)) ( progn (c!:printf " ") (c!:pgoto s depth))) (t (cond ((not (flagp s (quote c!:visited))) (prog (why where_to) (flag (list s) (quote c!:visited)) (cond ( (or (not dropping_through) (not (equal (get s (quote c!:count)) 1))) ( c!:printf "\n%s:\n" s))) (prog (var1282) (setq var1282 (reverse (get s (quote c!:contents)))) lab1281 (cond ((null var1282) (return nil))) (prog (k) (setq k (car var1282)) (c!:print_opcode k depth)) (setq var1282 (cdr var1282)) (go lab1281)) (setq why (get s (quote c!:why))) (setq where_to (get s (quote c!:where_to))) (cond ((and (equal why (quote goto)) (or (not (atom (car where_to))) (and (not (flagp (car where_to) (quote c!:visited))) (equal (get (car where_to) (quote c!:count)) 1)))) (c!:display_flowgraph (car where_to) depth t)) (t (c!:print_exit_condition why where_to depth))))))))) (fluid (quote (c!:startpoint))) (de c!:branch_chain (s count) (prog (contents why where_to n) (cond ((not ( atom s)) (return s)) (t (cond ((flagp s (quote c!:visited)) (progn (setq n ( get s (quote c!:count))) (cond ((null n) (setq n 1)) (t (setq n (plus n 1)))) (put s (quote c!:count) n) (return s)))))) (flag (list s) (quote c!:visited) ) (setq contents (get s (quote c!:contents))) (setq why (get s (quote c!:why) )) (setq where_to (prog (var1284 var1285) (setq var1284 (get s (quote c!:where_to))) lab1283 (cond ((null var1284) (return (reversip var1285)))) ( prog (z) (setq z (car var1284)) (setq var1285 (cons (c!:branch_chain z count) var1285))) (setq var1284 (cdr var1284)) (go lab1283))) (prog nil lab1286 ( cond ((null (and contents (eqcar (car contents) (quote movr)) (equal why ( quote goto)) (not (atom (car where_to))) (equal (caar where_to) (cadr (car contents))))) (return nil))) (progn (setq where_to (list (list (cadddr (car contents))))) (setq contents (cdr contents))) (go lab1286)) (put s (quote c!:contents) contents) (put s (quote c!:where_to) where_to) (cond ((and (null contents) (equal why (quote goto))) (progn (remflag (list s) (quote c!:visited)) (return (car where_to))))) (cond (count (progn (setq n (get s ( quote c!:count))) (cond ((null n) (setq n 1)) (t (setq n (plus n 1)))) (put s (quote c!:count) n)))) (return s))) (de c!:one_operand (op) (progn (flag (list op) (quote c!:set_r1)) (flag (list op) (quote c!:read_r3)) (put op (quote c!:code) (function c!:builtin_one)))) (de c!:two_operands (op) (progn (flag (list op) (quote c!:set_r1)) (flag ( list op) (quote c!:read_r2)) (flag (list op) (quote c!:read_r3)) (put op ( quote c!:code) (function c!:builtin_two)))) (prog (var1288) (setq var1288 (quote (car cdr qcar qcdr null not atom numberp fixp iminusp iminus iadd1 isub1 modular!-minus))) lab1287 (cond ((null var1288) (return nil))) (prog (n) (setq n (car var1288)) (c!:one_operand n)) (setq var1288 (cdr var1288)) (go lab1287)) (prog (var1290) (setq var1290 (quote (eq equal atsoc memq iplus2 idifference assoc member itimes2 ilessp igreaterp qgetv get modular!-plus modular!-difference))) lab1289 (cond ((null var1290) (return nil))) (prog (n) (setq n (car var1290)) (c!:two_operands n)) (setq var1290 (cdr var1290)) (go lab1289)) (flag (quote (movr movk movk1 ldrglob call reloadenv fastget fastflag)) ( quote c!:set_r1)) (flag (quote (strglob qputv)) (quote c!:read_r1)) (flag (quote (qputv fastget fastflag)) (quote c!:read_r2)) (flag (quote (movr qputv)) (quote c!:read_r3)) (flag (quote (ldrglob strglob nilglob movk call)) (quote c!:read_env)) (fluid (quote (fn_used nil_used nilbase_used))) (de c!:live_variable_analysis (c!:all_blocks) (prog (changed z) (prog nil lab1297 (progn (setq changed nil) (prog (var1296) (setq var1296 c!:all_blocks ) lab1295 (cond ((null var1296) (return nil))) (prog (b) (setq b (car var1296 )) (prog (w live) (prog (var1292) (setq var1292 (get b (quote c!:where_to))) lab1291 (cond ((null var1292) (return nil))) (prog (x) (setq x (car var1292)) (cond ((atom x) (setq live (union live (get x (quote c!:live))))) (t (setq live (union live x))))) (setq var1292 (cdr var1292)) (go lab1291)) (setq w ( get b (quote c!:why))) (cond ((not (atom w)) (progn (cond ((or (eqcar w ( quote ifnull)) (eqcar w (quote ifequal))) (setq nil_used t))) (setq live ( union live (cdr w))) (cond ((and (eqcar (car w) (quote call)) (or (flagp ( cadar w) (quote c!:direct_predicate)) (and (flagp (cadar w) (quote c!:c_entrypoint)) (not (flagp (cadar w) (quote c!:direct_entrypoint)))))) ( setq nil_used t))) (cond ((and (eqcar (car w) (quote call)) (not (equal ( cadar w) c!:current_procedure)) (not (get (cadar w) (quote c!:direct_entrypoint))) (not (get (cadar w) (quote c!:c_entrypoint)))) (progn (setq fn_used t) (setq live (union (quote (env)) live)))))))) (prog (var1294 ) (setq var1294 (get b (quote c!:contents))) lab1293 (cond ((null var1294) ( return nil))) (prog (s) (setq s (car var1294)) (prog (op r1 r2 r3) (setq op ( car s)) (setq r1 (cadr s)) (setq r2 (caddr s)) (setq r3 (cadddr s)) (cond (( equal op (quote movk1)) (progn (cond ((equal r3 nil) (setq nil_used t)) (t ( cond ((equal r3 (quote t)) (setq nilbase_used t))))))) (t (cond ((and (atom op) (flagp op (quote c!:uses_nil))) (setq nil_used t))))) (cond ((flagp op ( quote c!:set_r1)) (cond ((memq r1 live) (setq live (delete r1 live))) (t ( cond ((equal op (quote call)) nil) (t (setq op (quote nop)))))))) (cond (( flagp op (quote c!:read_r1)) (setq live (union live (list r1))))) (cond (( flagp op (quote c!:read_r2)) (setq live (union live (list r2))))) (cond (( flagp op (quote c!:read_r3)) (setq live (union live (list r3))))) (cond (( equal op (quote call)) (progn (cond ((or (not (flagp (car r3) (quote c!:no_errors))) (flagp (car r3) (quote c!:c_entrypoint)) (get (car r3) (quote c!:direct_predicate))) (setq nil_used t))) (setq does_call t) (cond ((and ( not (eqcar r3 c!:current_procedure)) (not (get (car r3) (quote c!:direct_entrypoint))) (not (get (car r3) (quote c!:c_entrypoint)))) (setq fn_used t))) (cond ((not (flagp (car r3) (quote c!:no_errors))) (flag live ( quote c!:live_across_call)))) (setq live (union live r2))))) (cond ((flagp op (quote c!:read_env)) (setq live (union live (quote (env)))))))) (setq var1294 (cdr var1294)) (go lab1293)) (setq live (sort live (function orderp)) ) (cond ((not (equal live (get b (quote c!:live)))) (progn (put b (quote c!:live) live) (setq changed t)))))) (setq var1296 (cdr var1296)) (go lab1295 ))) (cond ((null (not changed)) (go lab1297)))) (setq z c!:registers) (setq c!:registers (setq c!:stacklocs nil)) (prog (var1299) (setq var1299 z) lab1298 (cond ((null var1299) (return nil))) (prog (r) (setq r (car var1299)) (cond ((flagp r (quote c!:live_across_call)) (setq c!:stacklocs (cons r c!:stacklocs))) (t (setq c!:registers (cons r c!:registers))))) (setq var1299 (cdr var1299)) (go lab1298)))) (de c!:insert1 (a b) (cond ((memq a b) b) (t (cons a b)))) (de c!:clash (a b) (cond ((equal (flagp a (quote c!:live_across_call)) (flagp b (quote c!:live_across_call))) (progn (put a (quote c!:clash) (c!:insert1 b (get a (quote c!:clash)))) (put b (quote c!:clash) (c!:insert1 a (get b ( quote c!:clash)))))))) (de c!:build_clash_matrix (c!:all_blocks) (prog nil (prog (var1307) (setq var1307 c!:all_blocks) lab1306 (cond ((null var1307) (return nil))) (prog (b) (setq b (car var1307)) (prog (live w) (prog (var1301) (setq var1301 (get b ( quote c!:where_to))) lab1300 (cond ((null var1301) (return nil))) (prog (x) ( setq x (car var1301)) (cond ((atom x) (setq live (union live (get x (quote c!:live))))) (t (setq live (union live x))))) (setq var1301 (cdr var1301)) ( go lab1300)) (setq w (get b (quote c!:why))) (cond ((not (atom w)) (progn ( setq live (union live (cdr w))) (cond ((and (eqcar (car w) (quote call)) (not (get (cadar w) (quote c!:direct_entrypoint))) (not (get (cadar w) (quote c!:c_entrypoint)))) (setq live (union (quote (env)) live))))))) (prog ( var1305) (setq var1305 (get b (quote c!:contents))) lab1304 (cond ((null var1305) (return nil))) (prog (s) (setq s (car var1305)) (prog (op r1 r2 r3) (setq op (car s)) (setq r1 (cadr s)) (setq r2 (caddr s)) (setq r3 (cadddr s)) (cond ((flagp op (quote c!:set_r1)) (cond ((memq r1 live) (progn (setq live (delete r1 live)) (cond ((equal op (quote reloadenv)) (setq reloadenv t))) ( prog (var1303) (setq var1303 live) lab1302 (cond ((null var1303) (return nil) )) (prog (v) (setq v (car var1303)) (c!:clash r1 v)) (setq var1303 (cdr var1303)) (go lab1302)))) (t (cond ((equal op (quote call)) nil) (t (progn ( setq op (quote nop)) (rplacd s (cons (car s) (cdr s))) (rplaca s op)))))))) ( cond ((flagp op (quote c!:read_r1)) (setq live (union live (list r1))))) ( cond ((flagp op (quote c!:read_r2)) (setq live (union live (list r2))))) ( cond ((flagp op (quote c!:read_r3)) (setq live (union live (list r3))))) ( cond ((equal op (quote call)) (setq live (union live r2)))) (cond ((flagp op (quote c!:read_env)) (setq live (union live (quote (env)))))))) (setq var1305 (cdr var1305)) (go lab1304)))) (setq var1307 (cdr var1307)) (go lab1306)) ( return nil))) (de c!:allocate_registers (rl) (prog (schedule neighbours allocation) (setq neighbours 0) (prog nil lab1311 (cond ((null rl) (return nil))) (prog (w x) ( setq w rl) (prog nil lab1308 (cond ((null (and w (greaterp (length (setq x ( get (car w) (quote c!:clash)))) neighbours))) (return nil))) (setq w (cdr w)) (go lab1308)) (cond (w (progn (setq schedule (cons (car w) schedule)) (setq rl (deleq (car w) rl)) (prog (var1310) (setq var1310 x) lab1309 (cond ((null var1310) (return nil))) (prog (r) (setq r (car var1310)) (put r (quote c!:clash) (deleq (car w) (get r (quote c!:clash))))) (setq var1310 (cdr var1310)) (go lab1309)))) (t (setq neighbours (plus neighbours 1))))) (go lab1311)) (prog (var1315) (setq var1315 schedule) lab1314 (cond ((null var1315) (return nil))) (prog (r) (setq r (car var1315)) (prog (poss) (setq poss allocation) (prog (var1313) (setq var1313 (get r (quote c!:clash))) lab1312 (cond ((null var1313) (return nil))) (prog (x) (setq x (car var1313)) (setq poss (deleq (get x (quote c!:chosen)) poss))) (setq var1313 (cdr var1313)) (go lab1312)) (cond ((null poss) (progn (setq poss (c!:my_gensym)) (setq allocation (append allocation (list poss))))) (t (setq poss (car poss)) )) (put r (quote c!:chosen) poss))) (setq var1315 (cdr var1315)) (go lab1314) ) (return allocation))) (de c!:remove_nops (c!:all_blocks) (prog (var1325) (setq var1325 c!:all_blocks) lab1324 (cond ((null var1325) (return nil))) (prog (b) (setq b (car var1325)) (prog (r) (prog (var1320) (setq var1320 (get b (quote c!:contents))) lab1319 (cond ((null var1320) (return nil))) (prog (s) (setq s (car var1320)) (cond ((not (eqcar s (quote nop))) (prog (op r1 r2 r3) (setq op (car s)) (setq r1 (cadr s)) (setq r2 (caddr s)) (setq r3 (cadddr s)) (cond ((or (flagp op (quote c!:set_r1)) (flagp op (quote c!:read_r1))) (setq r1 ( get r1 (quote c!:chosen))))) (cond ((flagp op (quote c!:read_r2)) (setq r2 ( get r2 (quote c!:chosen))))) (cond ((flagp op (quote c!:read_r3)) (setq r3 ( get r3 (quote c!:chosen))))) (cond ((equal op (quote call)) (setq r2 (prog ( var1317 var1318) (setq var1317 r2) lab1316 (cond ((null var1317) (return ( reversip var1318)))) (prog (v) (setq v (car var1317)) (setq var1318 (cons ( get v (quote c!:chosen)) var1318))) (setq var1317 (cdr var1317)) (go lab1316) )))) (cond ((not (and (equal op (quote movr)) (equal r1 r3))) (setq r (cons ( list op r1 r2 r3) r)))))))) (setq var1320 (cdr var1320)) (go lab1319)) (put b (quote c!:contents) (reversip r)) (setq r (get b (quote c!:why))) (cond (( not (atom r)) (put b (quote c!:why) (cons (car r) (prog (var1322 var1323) ( setq var1322 (cdr r)) lab1321 (cond ((null var1322) (return (reversip var1323 )))) (prog (v) (setq v (car var1322)) (setq var1323 (cons (get v (quote c!:chosen)) var1323))) (setq var1322 (cdr var1322)) (go lab1321)))))))) (setq var1325 (cdr var1325)) (go lab1324))) (fluid (quote (c!:error_labels))) (de c!:find_error_label (why env depth) (prog (w z) (setq z (list why env depth)) (setq w (assoc!*!* z c!:error_labels)) (cond ((null w) (progn (setq w (cons z (c!:my_gensym))) (setq c!:error_labels (cons w c!:error_labels))))) (return (cdr w)))) (de c!:assign (u v c) (cond ((flagp u (quote fluid)) (cons (list (quote strglob) v u (c!:find_literal u)) c)) (t (cons (list (quote movr) u nil v) c) ))) (de c!:insert_tailcall (b) (prog (why dest contents fcall res w) (setq why ( get b (quote c!:why))) (setq dest (get b (quote c!:where_to))) (setq contents (get b (quote c!:contents))) (prog nil lab1326 (cond ((null (and contents ( not (eqcar (car contents) (quote call))))) (return nil))) (progn (setq w ( cons (car contents) w)) (setq contents (cdr contents))) (go lab1326)) (cond ( (null contents) (return nil))) (setq fcall (car contents)) (setq contents ( cdr contents)) (setq res (cadr fcall)) (prog nil lab1327 (cond ((null w) ( return nil))) (progn (cond ((eqcar (car w) (quote reloadenv)) (setq w (cdr w) )) (t (cond ((and (eqcar (car w) (quote movr)) (equal (cadddr (car w)) res)) (progn (setq res (cadr (car w))) (setq w (cdr w)))) (t (setq res (setq w nil) )))))) (go lab1327)) (cond ((null res) (return nil))) (cond ((c!:does_return res why dest) (cond ((equal (car (cadddr fcall)) c!:current_procedure) (progn (prog (var1329) (setq var1329 (pair c!:current_args (caddr fcall))) lab1328 (cond ((null var1329) (return nil))) (prog (p) (setq p (car var1329)) (setq contents (c!:assign (car p) (cdr p) contents))) (setq var1329 (cdr var1329)) (go lab1328)) (put b (quote c!:contents) contents) (put b (quote c!:why) ( quote goto)) (put b (quote c!:where_to) (list restart_label)))) (t (progn ( setq nil_used t) (put b (quote c!:contents) contents) (put b (quote c!:why) ( cons (list (quote call) (car (cadddr fcall))) (caddr fcall))) (put b (quote c!:where_to) nil)))))))) (de c!:does_return (res why where_to) (cond ((not (equal why (quote goto))) nil) (t (cond ((not (atom (car where_to))) (equal res (caar where_to))) (t ( prog (contents) (setq where_to (car where_to)) (setq contents (reverse (get where_to (quote c!:contents)))) (setq why (get where_to (quote c!:why))) ( setq where_to (get where_to (quote c!:where_to))) (prog nil lab1330 (cond (( null contents) (return nil))) (cond ((eqcar (car contents) (quote reloadenv)) (setq contents (cdr contents))) (t (cond ((and (eqcar (car contents) (quote movr)) (equal (cadddr (car contents)) res)) (progn (setq res (cadr (car contents))) (setq contents (cdr contents)))) (t (setq res (setq contents nil) ))))) (go lab1330)) (cond ((null res) (return nil)) (t (return ( c!:does_return res why where_to)))))))))) (de c!:pushpop (op v) (prog (n w) (cond ((null v) (return nil))) (setq n ( length v)) (prog nil lab1332 (cond ((null (greaterp n 0)) (return nil))) ( progn (setq w n) (cond ((greaterp w 6) (setq w 6))) (setq n (difference n w)) (cond ((equal w 1) (c!:printf " %s(%s);\n" op (car v))) (t (progn ( c!:printf " %s%d(%s" op w (car v)) (setq v (cdr v)) (prog (i) (setq i 2) lab1331 (cond ((minusp (times 1 (difference w i))) (return nil))) (progn ( c!:printf ",%s" (car v)) (setq v (cdr v))) (setq i (plus i 1)) (go lab1331)) (c!:printf ");\n"))))) (go lab1332)))) (de c!:optimise_flowgraph (c!:startpoint c!:all_blocks env argch args varargs ) (prog (w n locs stacks c!:error_labels fn_used nil_used nilbase_used) (prog (var1334) (setq var1334 c!:all_blocks) lab1333 (cond ((null var1334) (return nil))) (prog (b) (setq b (car var1334)) (c!:insert_tailcall b)) (setq var1334 (cdr var1334)) (go lab1333)) (setq c!:startpoint (c!:branch_chain c!:startpoint nil)) (remflag c!:all_blocks (quote c!:visited)) ( c!:live_variable_analysis c!:all_blocks) (c!:build_clash_matrix c!:all_blocks ) (cond ((and c!:error_labels env) (setq reloadenv t))) (prog (var1338) (setq var1338 env) lab1337 (cond ((null var1338) (return nil))) (prog (u) (setq u (car var1338)) (prog (var1336) (setq var1336 env) lab1335 (cond ((null var1336) (return nil))) (prog (v) (setq v (car var1336)) (c!:clash (cdr u) ( cdr v))) (setq var1336 (cdr var1336)) (go lab1335))) (setq var1338 (cdr var1338)) (go lab1337)) (setq locs (c!:allocate_registers c!:registers)) ( setq stacks (c!:allocate_registers c!:stacklocs)) (flag stacks (quote c!:live_across_call)) (c!:remove_nops c!:all_blocks) (setq c!:startpoint ( c!:branch_chain c!:startpoint nil)) (remflag c!:all_blocks (quote c!:visited) ) (setq c!:startpoint (c!:branch_chain c!:startpoint t)) (remflag c!:all_blocks (quote c!:visited)) (cond (does_call (setq nil_used t))) (cond (locs (progn (c!:printf " LispObject %s" (car locs)) (prog (var1340) (setq var1340 (cdr locs)) lab1339 (cond ((null var1340) (return nil))) (prog (v) (setq v (car var1340)) (c!:printf ", %s" v)) (setq var1340 (cdr var1340)) (go lab1339)) (c!:printf ";\n")))) (cond (fn_used (c!:printf " LispObject fn;\n"))) (cond ((and varargs args) (progn (setq w " ") (c!:printf " LispObject") (prog (var1342 ) (setq var1342 args) lab1341 (cond ((null var1342) (return nil))) (prog (v) (setq v (car var1342)) (progn (c!:printf "%s%s" w v) (setq w ", "))) (setq var1342 (cdr var1342)) (go lab1341)) (c!:printf ";\n va_list aa;\n") ( c!:printf " va_start(aa, nargs);\n")))) (cond ((or (equal (car argch) 0) ( geq (car argch) 3)) (c!:printf " argcheck(nargs, %s, \q%s\q);\n" (car argch) (cdr argch)))) (cond ((and varargs args) (progn (c!:printf " va_start(aa, nargs);\n") (prog (var1344) (setq var1344 (reverse args)) lab1343 (cond ((null var1344) (return nil))) (prog (v) (setq v (car var1344)) (c!:printf " %s = va_arg(aa, LispObject);\n" v)) (setq var1344 (cdr var1344)) (go lab1343)) (c!:printf " va_end(aa);\n")))) (c!:printf "#ifdef DEBUG_VALIDATE\n") (c!:printf " if (check_env(env)) return aerror(\qenv for %s\q);\n" (cdr argch)) ( c!:printf "#endif\n") (c!:printf "#ifdef CHECK_STACK\n") (c!:printf " if_check_stack;\n") (c!:printf "#endif\n") (cond (does_call (progn ( c!:printf " if (stack >= stackLimit)\n") (c!:printf " {\n") (c!:pushpop (quote push) args) (c!:printf " env = reclaim(env, \qstack\q, GC_STACK, 0);\n") (c!:pushpop (quote pop) (reverse args)) (c!:printf " if (exception_pending()) return nil;\n") (c!:printf " }\n")))) ( cond (reloadenv (c!:printf " push(env);\n"))) (setq n 0) (cond (stacks ( progn (c!:printf "%<// space for vars preserved across procedure calls\n") ( prog (var1346) (setq var1346 stacks) lab1345 (cond ((null var1346) (return nil))) (prog (v) (setq v (car var1346)) (progn (put v (quote c!:location) n) (setq n (plus n 1)))) (setq var1346 (cdr var1346)) (go lab1345)) (setq w n) ( prog nil lab1347 (cond ((null (geq w 5)) (return nil))) (progn (c!:printf " push5(nil, nil, nil, nil, nil);\n") (setq w (difference w 5))) (go lab1347)) (cond ((neq w 0) (progn (cond ((equal w 1) (c!:printf " push(nil);\n")) (t (progn (c!:printf " push%s(nil" w) (prog (i) (setq i 2) lab1348 (cond ((minusp (times 1 (difference w i))) (return nil))) ( c!:printf ", nil") (setq i (plus i 1)) (go lab1348)) (c!:printf ");\n"))))))) ))) (cond (reloadenv (progn (setq reloadenv n) (setq n (plus n 1))))) (cond ( env (c!:printf "%<// copy arguments values to proper place\n"))) (prog ( var1350) (setq var1350 env) lab1349 (cond ((null var1350) (return nil))) ( prog (v) (setq v (car var1350)) (cond ((flagp (cdr v) (quote c!:live_across_call)) (c!:printf " stack[%s] = %s;\n" (minus (get (get ( cdr v) (quote c!:chosen)) (quote c!:location))) (cdr v))) (t (c!:printf " %s = %s;\n" (get (cdr v) (quote c!:chosen)) (cdr v))))) (setq var1350 ( cdr var1350)) (go lab1349)) (c!:printf "%<// end of prologue\n") ( c!:display_flowgraph c!:startpoint n t) (cond (c!:error_labels (progn ( c!:printf "%<// error exit handlers\n") (prog (var1352) (setq var1352 c!:error_labels) lab1351 (cond ((null var1352) (return nil))) (prog (x) (setq x (car var1352)) (progn (c!:printf "%s:\n" (cdr x)) (c!:print_error_return ( caar x) (cadar x) (caddar x)))) (setq var1352 (cdr var1352)) (go lab1351))))) (remflag c!:all_blocks (quote c!:visited)))) (de c!:print_error_return (why env depth) (prog nil (cond ((and reloadenv env ) (c!:printf " env = stack[%s];\n" (minus reloadenv)))) (cond ((null why) (progn (prog (var1354) (setq var1354 env) lab1353 (cond ((null var1354) ( return nil))) (prog (v) (setq v (car var1354)) (c!:printf " qvalue(elt(env, %s)) = %v; %<// %c\n" (c!:find_literal (car v)) (get ( cdr v) (quote c!:chosen)) (car v))) (setq var1354 (cdr var1354)) (go lab1353) ) (cond ((neq depth 0) (c!:printf " popv(%s);\n" depth))) (c!:printf " return nil;\n"))) (t (cond ((flagp (cadr why) (quote c!:live_across_call )) (progn (c!:printf " { LispObject res = %v;\n" (cadr why)) (prog ( var1356) (setq var1356 env) lab1355 (cond ((null var1356) (return nil))) ( prog (v) (setq v (car var1356)) (c!:printf " qvalue(elt(env, %s)) = %v;\n" (c!:find_literal (car v)) (get (cdr v) (quote c!:chosen)))) (setq var1356 (cdr var1356)) (go lab1355)) (cond ((neq depth 0) (c!:printf " popv(%s);\n" depth))) (c!:printf " return error(1, %s, res); }\n" (cond ((eqcar why (quote car)) "err_bad_car") (t (cond ((eqcar why (quote cdr)) "err_bad_cdr") (t (error 0 ( list why "unknown_error"))))))))) (t (progn (prog (var1358) (setq var1358 env ) lab1357 (cond ((null var1358) (return nil))) (prog (v) (setq v (car var1358 )) (c!:printf " qvalue(elt(env, %s)) = %v;\n" (c!:find_literal (car v)) ( get (cdr v) (quote c!:chosen)))) (setq var1358 (cdr var1358)) (go lab1357)) ( cond ((neq depth 0) (c!:printf " popv(%s);\n" depth))) (c!:printf " return error(1, %s, %v);\n" (cond ((eqcar why (quote car)) "err_bad_car" ) (t (cond ((eqcar why (quote cdr)) "err_bad_cdr") (t (error 0 (list why "unknown_error")))))) (cadr why))))))))) (de c!:cand (u env) (prog (w r) (setq w (reverse (cdr u))) (cond ((null w) ( return (c!:cval nil env)))) (setq r (list (list (quote t) (car w)))) (setq w (cdr w)) (prog (var1360) (setq var1360 w) lab1359 (cond ((null var1360) ( return nil))) (prog (z) (setq z (car var1360)) (setq r (cons (list (list ( quote null) z) nil) r))) (setq var1360 (cdr var1360)) (go lab1359)) (setq r ( cons (quote cond) r)) (return (c!:cval r env)))) (put (quote and) (quote c!:code) (function c!:cand)) (de c!:ccatch (u env) (error 0 "catch")) (put (quote catch) (quote c!:code) (function c!:ccatch)) (de c!:ccompile_let (u env) (error 0 "compiler-let")) (put (quote compiler!-let) (quote c!:code) (function c!:ccompiler_let)) (de c!:ccond (u env) (prog (v join) (setq v (c!:newreg)) (setq join ( c!:my_gensym)) (prog (var1362) (setq var1362 (cdr u)) lab1361 (cond ((null var1362) (return nil))) (prog (c) (setq c (car var1362)) (prog (l1 l2) (setq l1 (c!:my_gensym)) (setq l2 (c!:my_gensym)) (cond ((atom (cdr c)) (progn ( c!:outop (quote movr) v nil (c!:cval (car c) env)) (c!:endblock (list (quote ifnull) v) (list l2 join)))) (t (progn (c!:cjumpif (car c) env l1 l2) ( c!:startblock l1) (c!:outop (quote movr) v nil (c!:cval (cons (quote progn) ( cdr c)) env)) (c!:endblock (quote goto) (list join))))) (c!:startblock l2))) (setq var1362 (cdr var1362)) (go lab1361)) (c!:outop (quote movk1) v nil nil) (c!:endblock (quote goto) (list join)) (c!:startblock join) (return v))) (put (quote cond) (quote c!:code) (function c!:ccond)) (de c!:valid_cond (x) (cond ((null x) t) (t (cond ((not (c!:valid_list (car x ))) nil) (t (c!:valid_cond (cdr x))))))) (put (quote cond) (quote c!:valid) (function c!:valid_cond)) (de c!:cdeclare (u env) (error 0 "declare")) (put (quote declare) (quote c!:code) (function c!:cdeclare)) (de c!:cde (u env) (error 0 "de")) (put (quote de) (quote c!:code) (function c!:cde)) (de c!:cdefun (u env) (error 0 "defun")) (put (quote !~defun) (quote c!:code) (function c!:cdefun)) (de c!:ceval_when (u env) (error 0 "eval-when")) (put (quote eval!-when) (quote c!:code) (function c!:ceval_when)) (de c!:cflet (u env) (error 0 "flet")) (put (quote flet) (quote c!:code) (function c!:cflet)) (de c!:cfunction (u env) (prog (v) (setq u (cadr u)) (cond ((not (atom u)) ( progn (cond ((not (eqcar u (quote lambda))) (error 0 (list "lambda expression needed" u)))) (setq v (hashtagged!-name (quote lambda) u)) (setq pending_functions (cons (cons (quote de) (cons v (cdr u))) pending_functions)) (setq u v)))) (setq v (c!:newreg)) (c!:outop (quote movk) v u (c!:find_literal u)) (return v))) (de c!:valid_function (x) (cond ((atom x) nil) (t (cond ((not (null (cdr x))) nil) (t (cond ((idp (car x)) t) (t (cond ((atom (car x)) nil) (t (cond ((not (eqcar (car x) (quote lambda))) nil) (t (cond ((atom (cdar x)) nil) (t ( c!:valid_fndef (cadar x) (cddar x))))))))))))))) (put (quote function) (quote c!:code) (function c!:cfunction)) (put (quote function) (quote c!:valid) (function c!:valid_function)) (de c!:cgo (u env) (prog (w w1) (setq w1 proglabs) (prog nil lab1363 (cond (( null (and (null w) w1)) (return nil))) (progn (setq w (assoc!*!* (cadr u) ( car w1))) (setq w1 (cdr w1))) (go lab1363)) (cond ((null w) (error 0 (list u "label not set")))) (c!:endblock (quote goto) (list (cadr w))) (return nil))) (put (quote go) (quote c!:code) (function c!:cgo)) (put (quote go) (quote c!:valid) (function c!:valid_quote)) (de c!:cif (u env) (prog (v join l1 l2 w) (setq v (c!:newreg)) (setq join ( c!:my_gensym)) (setq l1 (c!:my_gensym)) (setq l2 (c!:my_gensym)) (c!:cjumpif (car (setq u (cdr u))) env l1 l2) (c!:startblock l1) (c!:outop (quote movr) v nil (c!:cval (car (setq u (cdr u))) env)) (c!:endblock (quote goto) (list join)) (c!:startblock l2) (setq u (cdr u)) (cond (u (setq u (car u)))) ( c!:outop (quote movr) v nil (c!:cval u env)) (c!:endblock (quote goto) (list join)) (c!:startblock join) (return v))) (put (quote if) (quote c!:code) (function c!:cif)) (de c!:clabels (u env) (error 0 "labels")) (put (quote labels) (quote c!:code) (function c!:clabels)) (de c!:expand!-let (vl b) (cond ((null vl) (cons (quote progn) b)) (t (cond ( (null (cdr vl)) (c!:expand!-let!* vl b)) (t (prog (vars vals) (prog (var1365) (setq var1365 vl) lab1364 (cond ((null var1365) (return nil))) (prog (v) ( setq v (car var1365)) (cond ((atom v) (progn (setq vars (cons v vars)) (setq vals (cons nil vals)))) (t (cond ((atom (cdr v)) (progn (setq vars (cons (car v) vars)) (setq vals (cons nil vals)))) (t (progn (setq vars (cons (car v) vars)) (setq vals (cons (cadr v) vals)))))))) (setq var1365 (cdr var1365)) ( go lab1364)) (return (cons (cons (quote lambda) (cons vars b)) vals)))))))) (de c!:clet (x env) (c!:cval (c!:expand!-let (cadr x) (cddr x)) env)) (de c!:valid_let (x) (cond ((null x) t) (t (cond ((not (c!:valid_cond (car x) )) nil) (t (c!:valid_list (cdr x))))))) (put (quote !~let) (quote c!:code) (function c!:clet)) (put (quote !~let) (quote c!:valid) (function c!:valid_let)) (de c!:expand!-let!* (vl b) (cond ((null vl) (cons (quote progn) b)) (t (prog (var val) (setq var (car vl)) (cond ((not (atom var)) (progn (setq val (cdr var)) (setq var (car var)) (cond ((not (atom val)) (setq val (car val))))))) (setq b (list (list (quote return) (c!:expand!-let!* (cdr vl) b)))) (cond ( val (setq b (cons (list (quote setq) var val) b)))) (return (cons (quote prog ) (cons (list var) b))))))) (de c!:clet!* (x env) (c!:cval (c!:expand!-let!* (cadr x) (cddr x)) env)) (put (quote let!*) (quote c!:code) (function c!:clet!*)) (put (quote let!*) (quote c!:valid) (function c!:valid_let)) (de c!:clist (u env) (cond ((null (cdr u)) (c!:cval nil env)) (t (cond ((null (cddr u)) (c!:cval (cons (quote ncons) (cdr u)) env)) (t (cond ((eqcar (cadr u) (quote cons)) (c!:cval (list (quote acons) (cadr (cadr u)) (caddr (cadr u )) (cons (quote list) (cddr u))) env)) (t (cond ((null (cdddr u)) (c!:cval ( cons (quote list2) (cdr u)) env)) (t (cond ((null (cddddr u)) (c!:cval (cons (quote list3) (cdr u)) env)) (t (cond ((null (cdr (cddddr u))) (c!:cval (cons (quote list4) (cdr u)) env)) (t (c!:cval (list (quote list3!*) (cadr u) ( caddr u) (cadddr u) (cons (quote list) (cddddr u))) env)))))))))))))) (put (quote list) (quote c!:code) (function c!:clist)) (de c!:clist!* (u env) (prog (v) (setq u (reverse (cdr u))) (setq v (car u)) (prog (var1367) (setq var1367 (cdr u)) lab1366 (cond ((null var1367) (return nil))) (prog (a) (setq a (car var1367)) (setq v (list (quote cons) a v))) ( setq var1367 (cdr var1367)) (go lab1366)) (return (c!:cval v env)))) (put (quote list!*) (quote c!:code) (function c!:clist!*)) (de c!:ccons (u env) (prog (a1 a2) (setq a1 (s!:improve (cadr u))) (setq a2 ( s!:improve (caddr u))) (cond ((or (equal a2 nil) (equal a2 (quote (quote nil) )) (equal a2 (quote (list)))) (return (c!:cval (list (quote ncons) a1) env))) ) (cond ((eqcar a1 (quote cons)) (return (c!:cval (list (quote acons) (cadr a1) (caddr a1) a2) env)))) (cond ((eqcar a2 (quote cons)) (return (c!:cval ( list (quote list2!*) a1 (cadr a2) (caddr a2)) env)))) (cond ((eqcar a2 (quote list)) (return (c!:cval (list (quote cons) a1 (list (quote cons) (cadr a2) ( cons (quote list) (cddr a2)))) env)))) (return (c!:ccall (car u) (cdr u) env) ))) (put (quote cons) (quote c!:code) (function c!:ccons)) (de c!:cget (u env) (prog (a1 a2 w r r1) (setq a1 (s!:improve (cadr u))) ( setq a2 (s!:improve (caddr u))) (cond ((and (eqcar a2 (quote quote)) (idp ( setq w (cadr a2))) (setq w (symbol!-make!-fastget w nil))) (progn (setq r ( c!:newreg)) (c!:outop (quote fastget) r (c!:cval a1 env) (cons w (cadr a2))) (return r))) (t (return (c!:ccall (car u) (cdr u) env)))))) (put (quote get) (quote c!:code) (function c!:cget)) (de c!:cflag (u env) (prog (a1 a2 w r r1) (setq a1 (s!:improve (cadr u))) ( setq a2 (s!:improve (caddr u))) (cond ((and (eqcar a2 (quote quote)) (idp ( setq w (cadr a2))) (setq w (symbol!-make!-fastget w nil))) (progn (setq r ( c!:newreg)) (c!:outop (quote fastflag) r (c!:cval a1 env) (cons w (cadr a2))) (return r))) (t (return (c!:ccall (car u) (cdr u) env)))))) (put (quote flagp) (quote c!:code) (function c!:cflag)) (de c!:cgetv (u env) (cond ((not !*fastvector) (c!:ccall (car u) (cdr u) env) ) (t (c!:cval (cons (quote qgetv) (cdr u)) env)))) (put (quote getv) (quote c!:code) (function c!:cgetv)) (de c!:cputv (u env) (cond ((not !*fastvector) (c!:ccall (car u) (cdr u) env) ) (t (c!:cval (cons (quote qputv) (cdr u)) env)))) (put (quote putv) (quote c!:code) (function c!:cputv)) (de c!:cqputv (x env) (prog (rr) (setq rr (c!:pareval (cdr x) env)) (c!:outop (quote qputv) (caddr rr) (car rr) (cadr rr)) (return (caddr rr)))) (put (quote qputv) (quote c!:code) (function c!:cqputv)) (de c!:cmacrolet (u env) (error 0 "macrolet")) (put (quote macrolet) (quote c!:code) (function c!:cmacrolet)) (de c!:cmultiple_value_call (u env) (error 0 "multiple_value_call")) (put (quote multiple!-value!-call) (quote c!:code) (function c!:cmultiple_value_call)) (de c!:cmultiple_value_prog1 (u env) (error 0 "multiple_value_prog1")) (put (quote multiple!-value!-prog1) (quote c!:code) (function c!:cmultiple_value_prog1)) (de c!:cor (u env) (prog (next done v r) (setq v (c!:newreg)) (setq done ( c!:my_gensym)) (setq u (cdr u)) (prog nil lab1368 (cond ((null (cdr u)) ( return nil))) (progn (setq next (c!:my_gensym)) (c!:outop (quote movr) v nil (c!:cval (car u) env)) (setq u (cdr u)) (c!:endblock (list (quote ifnull) v) (list next done)) (c!:startblock next)) (go lab1368)) (c!:outop (quote movr) v nil (c!:cval (car u) env)) (c!:endblock (quote goto) (list done)) ( c!:startblock done) (return v))) (put (quote or) (quote c!:code) (function c!:cor)) (de c!:cprog (u env) (prog (w w1 bvl local_proglabs progret progexit fluids env1 body decs) (setq env1 (car env)) (setq bvl (cadr u)) (setq w ( s!:find_local_decs (cddr u) t)) (setq body (cdr w)) (setq localdecs (cons ( car w) localdecs)) (prog (var1370) (setq var1370 bvl) lab1369 (cond ((null var1370) (return nil))) (prog (v) (setq v (car var1370)) (progn (cond ((and ( not (globalp v)) (not (fluidp v)) (c!:local_fluidp v localdecs)) (progn ( make!-special v) (setq decs (cons v decs))))))) (setq var1370 (cdr var1370)) (go lab1369)) (prog (var1372) (setq var1372 bvl) lab1371 (cond ((null var1372 ) (return nil))) (prog (v) (setq v (car var1372)) (progn (cond ((globalp v) ( prog (oo) (setq oo (wrs nil)) (princ "+++++ ") (prin v) (princ " converted from GLOBAL to FLUID") (terpri) (wrs oo) (unglobal (list v)) ( fluid (list v))))) (cond ((fluidp v) (progn (setq fluids (cons (cons v ( c!:newreg)) fluids)) (flag (list (cdar fluids)) (quote c!:live_across_call)) (setq env1 (cons (cons (quote c!:dummy!:name) (cdar fluids)) env1)) (c!:outop (quote ldrglob) (cdar fluids) v (c!:find_literal v)) (c!:outop (quote nilglob) nil v (c!:find_literal v)))) (t (progn (setq env1 (cons (cons v ( c!:newreg)) env1)) (c!:outop (quote movk1) (cdar env1) nil nil)))))) (setq var1372 (cdr var1372)) (go lab1371)) (cond (fluids (c!:outop (quote fluidbind ) nil nil fluids))) (setq env (cons env1 (append fluids (cdr env)))) (setq u body) (setq progret (c!:newreg)) (setq progexit (c!:my_gensym)) (setq blockstack (cons (cons nil (cons progret progexit)) blockstack)) (prog ( var1374) (setq var1374 u) lab1373 (cond ((null var1374) (return nil))) (prog (a) (setq a (car var1374)) (cond ((atom a) (cond ((atsoc a local_proglabs) ( progn (cond ((not (null a)) (progn (setq w (wrs nil)) (princ "+++++ multiply defined label: ") (prin a) (terpri) (wrs w)))))) (t (setq local_proglabs (cons (list a (c!:my_gensym)) local_proglabs))))))) (setq var1374 (cdr var1374)) (go lab1373)) (setq proglabs (cons local_proglabs proglabs)) (prog (var1376) (setq var1376 u) lab1375 (cond ((null var1376) ( return nil))) (prog (a) (setq a (car var1376)) (cond ((atom a) (progn (setq w (cdr (assoc!*!* a local_proglabs))) (cond ((null (cdr w)) (progn (rplacd w t ) (c!:endblock (quote goto) (list (car w))) (c!:startblock (car w))))))) (t ( c!:cval a env)))) (setq var1376 (cdr var1376)) (go lab1375)) (c!:outop (quote movk1) progret nil nil) (c!:endblock (quote goto) (list progexit)) ( c!:startblock progexit) (prog (var1378) (setq var1378 fluids) lab1377 (cond ( (null var1378) (return nil))) (prog (v) (setq v (car var1378)) (c!:outop ( quote strglob) (cdr v) (car v) (c!:find_literal (car v)))) (setq var1378 (cdr var1378)) (go lab1377)) (setq blockstack (cdr blockstack)) (setq proglabs ( cdr proglabs)) (unfluid decs) (setq localdecs (cdr localdecs)) (return progret))) (put (quote prog) (quote c!:code) (function c!:cprog)) (de c!:valid_prog (x) (c!:valid_list (cdr x))) (put (quote prog) (quote c!:valid) (function c!:valid_prog)) (de c!:cprog!* (u env) (error 0 "prog*")) (put (quote prog!*) (quote c!:code) (function c!:cprog!*)) (de c!:cprog1 (u env) (prog (g) (setq g (c!:my_gensym)) (setq g (list (quote prog) (list g) (list (quote setq) g (cadr u)) (cons (quote progn) (cddr u)) ( list (quote return) g))) (return (c!:cval g env)))) (put (quote prog1) (quote c!:code) (function c!:cprog1)) (de c!:cprog2 (u env) (prog (g) (setq u (cdr u)) (setq g (c!:my_gensym)) ( setq g (list (quote prog) (list g) (list (quote setq) g (cadr u)) (cons ( quote progn) (cddr u)) (list (quote return) g))) (setq g (list (quote progn) (car u) g)) (return (c!:cval g env)))) (put (quote prog2) (quote c!:code) (function c!:cprog2)) (de c!:cprogn (u env) (prog (r) (setq u (cdr u)) (cond ((equal u nil) (setq u (quote (nil))))) (prog (var1380) (setq var1380 u) lab1379 (cond ((null var1380) (return nil))) (prog (s) (setq s (car var1380)) (setq r (c!:cval s env))) (setq var1380 (cdr var1380)) (go lab1379)) (return r))) (put (quote progn) (quote c!:code) (function c!:cprogn)) (de c!:cprogv (u env) (error 0 "progv")) (put (quote progv) (quote c!:code) (function c!:cprogv)) (de c!:cquote (u env) (prog (v) (setq u (cadr u)) (setq v (c!:newreg)) (cond ((or (null u) (equal u (quote t)) (c!:small_number u)) (c!:outop (quote movk1 ) v nil u)) (t (c!:outop (quote movk) v u (c!:find_literal u)))) (return v))) (de c!:valid_quote (x) t) (put (quote quote) (quote c!:code) (function c!:cquote)) (put (quote quote) (quote c!:valid) (function c!:valid_quote)) (de c!:creturn (u env) (prog (w) (setq w (assoc!*!* nil blockstack)) (cond (( null w) (error 0 "RETURN out of context"))) (c!:outop (quote movr) (cadr w) nil (c!:cval (cadr u) env)) (c!:endblock (quote goto) (list (cddr w))) ( return nil))) (put (quote return) (quote c!:code) (function c!:creturn)) (put (quote return!-from) (quote c!:code) (function c!:creturn_from)) (de c!:csetq (u env) (prog (v w) (setq v (c!:cval (caddr u) env)) (setq u ( cadr u)) (cond ((not (idp u)) (error 0 (list u "bad variable in setq"))) (t ( cond ((setq w (c!:locally_bound u env)) (c!:outop (quote movr) (cdr w) nil v) ) (t (cond ((flagp u (quote c!:constant)) (error 0 (list u "attempt to use setq on a constant"))) (t (c!:outop (quote strglob) v u ( c!:find_literal u)))))))) (return v))) (put (quote setq) (quote c!:code) (function c!:csetq)) (put (quote noisy!-setq) (quote c!:code) (function c!:csetq)) (de c!:cprivate_tagbody (u env) (prog nil (setq u (cdr u)) (c!:endblock ( quote goto) (list (car u))) (c!:startblock (car u)) (setq c!:current_args ( prog (var1382 var1383) (setq var1382 c!:current_args) lab1381 (cond ((null var1382) (return (reversip var1383)))) (prog (v) (setq v (car var1382)) (setq var1383 (cons (prog (z) (setq z (assoc!*!* v (car env))) (return (cond (z ( cdr z)) (t v)))) var1383))) (setq var1382 (cdr var1382)) (go lab1381))) ( return (c!:cval (cadr u) env)))) (put (quote c!:private_tagbody) (quote c!:code) (function c!:cprivate_tagbody )) (de c!:cthe (u env) (c!:cval (caddr u) env)) (put (quote the) (quote c!:code) (function c!:cthe)) (de c!:cunless (u env) (prog (v join l1 l2) (setq v (c!:newreg)) (setq join ( c!:my_gensym)) (setq l1 (c!:my_gensym)) (setq l2 (c!:my_gensym)) (c!:cjumpif (cadr u) env l2 l1) (c!:startblock l1) (c!:outop (quote movr) v nil (c!:cval (cons (quote progn) (cddr u)) env)) (c!:endblock (quote goto) (list join)) ( c!:startblock l2) (c!:outop (quote movk1) v nil nil) (c!:endblock (quote goto ) (list join)) (c!:startblock join) (return v))) (put (quote unless) (quote c!:code) (function c!:cunless)) (de c!:cunwind_protect (u env) (error 0 "unwind_protect")) (put (quote unwind!-protect) (quote c!:code) (function c!:cunwind_protect)) (de c!:cwhen (u env) (prog (v join l1 l2) (setq v (c!:newreg)) (setq join ( c!:my_gensym)) (setq l1 (c!:my_gensym)) (setq l2 (c!:my_gensym)) (c!:cjumpif (cadr u) env l1 l2) (c!:startblock l1) (c!:outop (quote movr) v nil (c!:cval (cons (quote progn) (cddr u)) env)) (c!:endblock (quote goto) (list join)) ( c!:startblock l2) (c!:outop (quote movk1) v nil nil) (c!:endblock (quote goto ) (list join)) (c!:startblock join) (return v))) (put (quote when) (quote c!:code) (function c!:cwhen)) (de c!:expand_map (fnargs) (prog (carp fn fn1 args var avar moveon l1 r s closed) (setq fn (car fnargs)) (cond ((or (equal fn (quote mapc)) (equal fn ( quote mapcar)) (equal fn (quote mapcan))) (setq carp t))) (setq fnargs (cdr fnargs)) (cond ((atom fnargs) (error 0 "bad arguments to map function"))) ( setq fn1 (cadr fnargs)) (prog nil lab1384 (cond ((null (or (eqcar fn1 (quote function)) (and (eqcar fn1 (quote quote)) (eqcar (cadr fn1) (quote lambda)))) ) (return nil))) (progn (setq fn1 (cadr fn1)) (setq closed t)) (go lab1384)) (setq args (car fnargs)) (setq l1 (c!:my_gensym)) (setq r (c!:my_gensym)) ( setq s (c!:my_gensym)) (setq var (c!:my_gensym)) (setq avar var) (cond (carp (setq avar (list (quote car) avar)))) (cond (closed (setq fn1 (list fn1 avar) )) (t (setq fn1 (list (quote apply1) fn1 avar)))) (setq moveon (list (quote setq) var (list (quote cdr) var))) (cond ((or (equal fn (quote map)) (equal fn (quote mapc))) (setq fn (sublis (list (cons (quote l1) l1) (cons (quote var) var) (cons (quote fn) fn1) (cons (quote args) args) (cons (quote moveon) moveon)) (quote (prog (var) (setq var args) l1 (cond ((not var) (return nil) )) fn moveon (go l1)))))) (t (cond ((or (equal fn (quote maplist)) (equal fn (quote mapcar))) (setq fn (sublis (list (cons (quote l1) l1) (cons (quote var ) var) (cons (quote fn) fn1) (cons (quote args) args) (cons (quote moveon) moveon) (cons (quote r) r)) (quote (prog (var r) (setq var args) l1 (cond (( not var) (return (reversip r)))) (setq r (cons fn r)) moveon (go l1)))))) (t (setq fn (sublis (list (cons (quote l1) l1) (cons (quote l2) (c!:my_gensym)) (cons (quote var) var) (cons (quote fn) fn1) (cons (quote args) args) (cons ( quote moveon) moveon) (cons (quote r) (c!:my_gensym)) (cons (quote s) ( c!:my_gensym))) (quote (prog (var r s) (setq var args) (setq r (setq s (list nil))) l1 (cond ((not var) (return (cdr r)))) (rplacd s fn) l2 (cond ((not ( atom (cdr s))) (setq s (cdr s)) (go l2))) moveon (go l1))))))))) (return fn)) ) (put (quote map) (quote c!:compile_macro) (function c!:expand_map)) (put (quote maplist) (quote c!:compile_macro) (function c!:expand_map)) (put (quote mapc) (quote c!:compile_macro) (function c!:expand_map)) (put (quote mapcar) (quote c!:compile_macro) (function c!:expand_map)) (put (quote mapcon) (quote c!:compile_macro) (function c!:expand_map)) (put (quote mapcan) (quote c!:compile_macro) (function c!:expand_map)) (de c!:expand_carcdr (x) (prog (name) (setq name (cdr (reverse (cdr (explode2 (car x)))))) (setq x (cadr x)) (prog (var1386) (setq var1386 name) lab1385 ( cond ((null var1386) (return nil))) (prog (v) (setq v (car var1386)) (setq x (list (cond ((equal v (quote a)) (quote car)) (t (quote cdr))) x))) (setq var1386 (cdr var1386)) (go lab1385)) (return x))) (progn (put (quote caar) (quote c!:compile_macro) (function c!:expand_carcdr) ) (put (quote cadr) (quote c!:compile_macro) (function c!:expand_carcdr)) ( put (quote cdar) (quote c!:compile_macro) (function c!:expand_carcdr)) (put ( quote cddr) (quote c!:compile_macro) (function c!:expand_carcdr)) (put (quote caaar) (quote c!:compile_macro) (function c!:expand_carcdr)) (put (quote caadr) (quote c!:compile_macro) (function c!:expand_carcdr)) (put (quote cadar) (quote c!:compile_macro) (function c!:expand_carcdr)) (put (quote caddr) (quote c!:compile_macro) (function c!:expand_carcdr)) (put (quote cdaar) (quote c!:compile_macro) (function c!:expand_carcdr)) (put (quote cdadr) (quote c!:compile_macro) (function c!:expand_carcdr)) (put (quote cddar) (quote c!:compile_macro) (function c!:expand_carcdr)) (put (quote cdddr) (quote c!:compile_macro) (function c!:expand_carcdr)) (put (quote caaaar) (quote c!:compile_macro) (function c!:expand_carcdr)) (put (quote caaadr) (quote c!:compile_macro) (function c!:expand_carcdr)) (put (quote caadar) (quote c!:compile_macro) (function c!:expand_carcdr)) (put (quote caaddr) (quote c!:compile_macro) (function c!:expand_carcdr)) (put (quote cadaar) (quote c!:compile_macro) (function c!:expand_carcdr)) (put (quote cadadr) (quote c!:compile_macro) (function c!:expand_carcdr)) (put (quote caddar) (quote c!:compile_macro) (function c!:expand_carcdr)) (put (quote cadddr) (quote c!:compile_macro) (function c!:expand_carcdr)) (put (quote cdaaar) (quote c!:compile_macro) (function c!:expand_carcdr)) (put (quote cdaadr) (quote c!:compile_macro) (function c!:expand_carcdr)) (put (quote cdadar) (quote c!:compile_macro) (function c!:expand_carcdr)) (put (quote cdaddr) (quote c!:compile_macro) (function c!:expand_carcdr)) (put (quote cddaar) (quote c!:compile_macro) (function c!:expand_carcdr)) (put (quote cddadr) (quote c!:compile_macro) (function c!:expand_carcdr)) (put (quote cdddar) (quote c!:compile_macro) (function c!:expand_carcdr)) (put (quote cddddr) (quote c!:compile_macro) (function c!:expand_carcdr))) (de c!:builtin_one (x env) (prog (r1 r2) (setq r1 (c!:cval (cadr x) env)) ( c!:outop (car x) (setq r2 (c!:newreg)) (cdr env) r1) (return r2))) (de c!:builtin_two (x env) (prog (a1 a2 r rr) (setq a1 (cadr x)) (setq a2 ( caddr x)) (setq rr (c!:pareval (list a1 a2) env)) (c!:outop (car x) (setq r ( c!:newreg)) (car rr) (cadr rr)) (return r))) (de c!:narg (x env) (c!:cval (expand (cdr x) (get (car x) (quote c!:binary_version))) env)) (prog (var1388) (setq var1388 (quote ((plus plus2) (times times2) (iplus iplus2) (itimes itimes2)))) lab1387 (cond ((null var1388) (return nil))) ( prog (n) (setq n (car var1388)) (progn (put (car n) (quote c!:binary_version) (cadr n)) (put (car n) (quote c!:code) (function c!:narg)))) (setq var1388 ( cdr var1388)) (go lab1387)) (de c!:cplus2 (u env) (prog (a b) (setq a (s!:improve (cadr u))) (setq b ( s!:improve (caddr u))) (return (cond ((and (numberp a) (numberp b)) (c!:cval (plus a b) env)) (t (cond ((equal a 0) (c!:cval b env)) (t (cond ((equal a 1) (c!:cval (list (quote add1) b) env)) (t (cond ((equal b 0) (c!:cval a env)) (t (cond ((equal b 1) (c!:cval (list (quote add1) a) env)) (t (cond ((equal b (minus 1)) (c!:cval (list (quote sub1) a) env)) (t (c!:ccall (car u) (cdr u) env)))))))))))))))) (put (quote plus2) (quote c!:code) (function c!:cplus2)) (de c!:ciplus2 (u env) (prog (a b) (setq a (s!:improve (cadr u))) (setq b ( s!:improve (caddr u))) (return (cond ((and (numberp a) (numberp b)) (c!:cval (plus a b) env)) (t (cond ((equal a 0) (c!:cval b env)) (t (cond ((equal a 1) (c!:cval (list (quote iadd1) b) env)) (t (cond ((equal b 0) (c!:cval a env)) (t (cond ((equal b 1) (c!:cval (list (quote iadd1) a) env)) (t (cond ((equal b (minus 1)) (c!:cval (list (quote isub1) a) env)) (t (c!:builtin_two u env) ))))))))))))))) (put (quote iplus2) (quote c!:code) (function c!:ciplus2)) (de c!:cdifference (u env) (prog (a b) (setq a (s!:improve (cadr u))) (setq b (s!:improve (caddr u))) (return (cond ((and (numberp a) (numberp b)) ( c!:cval (difference a b) env)) (t (cond ((equal a 0) (c!:cval (list (quote minus) b) env)) (t (cond ((equal b 0) (c!:cval a env)) (t (cond ((equal b 1) (c!:cval (list (quote sub1) a) env)) (t (cond ((equal b (minus 1)) (c!:cval ( list (quote add1) a) env)) (t (c!:ccall (car u) (cdr u) env)))))))))))))) (put (quote difference) (quote c!:code) (function c!:cdifference)) (de c!:cidifference (u env) (prog (a b) (setq a (s!:improve (cadr u))) (setq b (s!:improve (caddr u))) (return (cond ((and (numberp a) (numberp b)) ( c!:cval (difference a b) env)) (t (cond ((equal a 0) (c!:cval (list (quote iminus) b) env)) (t (cond ((equal b 0) (c!:cval a env)) (t (cond ((equal b 1) (c!:cval (list (quote isub1) a) env)) (t (cond ((equal b (minus 1)) (c!:cval (list (quote iadd1) a) env)) (t (c!:builtin_two u env)))))))))))))) (put (quote idifference) (quote c!:code) (function c!:cidifference)) (de c!:ctimes2 (u env) (prog (a b) (setq a (s!:improve (cadr u))) (setq b ( s!:improve (caddr u))) (return (cond ((and (numberp a) (numberp b)) (c!:cval (times a b) env)) (t (cond ((or (equal a 0) (equal b 0)) (c!:cval 0 env)) (t (cond ((equal a 1) (c!:cval b env)) (t (cond ((equal b 1) (c!:cval a env)) (t (cond ((equal a (minus 1)) (c!:cval (list (quote minus) b) env)) (t (cond (( equal b (minus 1)) (c!:cval (list (quote minus) a) env)) (t (c!:ccall (car u) (cdr u) env)))))))))))))))) (put (quote times2) (quote c!:code) (function c!:ctimes2)) (de c!:citimes2 (u env) (prog (a b) (setq a (s!:improve (cadr u))) (setq b ( s!:improve (caddr u))) (return (cond ((and (numberp a) (numberp b)) (c!:cval (times a b) env)) (t (cond ((or (equal a 0) (equal b 0)) (c!:cval 0 env)) (t (cond ((equal a 1) (c!:cval b env)) (t (cond ((equal b 1) (c!:cval a env)) (t (cond ((equal a (minus 1)) (c!:cval (list (quote iminus) b) env)) (t (cond ( (equal b (minus 1)) (c!:cval (list (quote iminus) a) env)) (t (c!:builtin_two u env)))))))))))))))) (put (quote itimes2) (quote c!:code) (function c!:citimes2)) (de c!:cminus (u env) (prog (a b) (setq a (s!:improve (cadr u))) (return ( cond ((numberp a) (c!:cval (minus a) env)) (t (cond ((eqcar a (quote minus)) (c!:cval (cadr a) env)) (t (c!:ccall (car u) (cdr u) env)))))))) (put (quote minus) (quote c!:code) (function c!:cminus)) (de c!:ceq (x env) (prog (a1 a2 r rr) (setq a1 (s!:improve (cadr x))) (setq a2 (s!:improve (caddr x))) (cond ((equal a1 nil) (return (c!:cval (list ( quote null) a2) env))) (t (cond ((equal a2 nil) (return (c!:cval (list (quote null) a1) env)))))) (setq rr (c!:pareval (list a1 a2) env)) (c!:outop (quote eq) (setq r (c!:newreg)) (car rr) (cadr rr)) (return r))) (put (quote eq) (quote c!:code) (function c!:ceq)) (de c!:cequal (x env) (prog (a1 a2 r rr) (setq a1 (s!:improve (cadr x))) ( setq a2 (s!:improve (caddr x))) (cond ((equal a1 nil) (return (c!:cval (list (quote null) a2) env))) (t (cond ((equal a2 nil) (return (c!:cval (list ( quote null) a1) env)))))) (setq rr (c!:pareval (list a1 a2) env)) (c!:outop ( cond ((or (c!:eqvalid a1) (c!:eqvalid a2)) (quote eq)) (t (quote equal))) ( setq r (c!:newreg)) (car rr) (cadr rr)) (return r))) (put (quote equal) (quote c!:code) (function c!:cequal)) (de c!:is_fixnum (x) (and (fixp x) (geq x (minus 134217728)) (leq x 134217727 ))) (de c!:certainlyatom (x) (or (null x) (equal x t) (c!:is_fixnum x) (and ( eqcar x (quote quote)) (or (symbolp (cadr x)) (c!:is_fixnum (cadr x)))))) (de c!:atomlist1 (u) (or (atom u) (and (or (symbolp (car u)) (c!:is_fixnum ( car u))) (c!:atomlist1 (cdr u))))) (de c!:atomlist (x) (or (null x) (and (eqcar x (quote quote)) (c!:atomlist1 ( cadr x))) (and (eqcar x (quote list)) (or (null (cdr x)) (and ( c!:certainlyatom (cadr x)) (c!:atomlist (cons (quote list) (cddr x)))))) (and (eqcar x (quote cons)) (c!:certainlyatom (cadr x)) (c!:atomlist (caddr x)))) ) (de c!:atomcar (x) (and (or (eqcar x (quote cons)) (eqcar x (quote list))) ( not (null (cdr x))) (c!:certainlyatom (cadr x)))) (de c!:atomkeys1 (u) (or (atom u) (and (not (atom (car u))) (or (symbolp ( caar u)) (c!:is_fixnum (caar u))) (c!:atomlist1 (cdr u))))) (de c!:atomkeys (x) (or (null x) (and (eqcar x (quote quote)) (c!:atomkeys1 ( cadr x))) (and (eqcar x (quote list)) (or (null (cdr x)) (and (c!:atomcar ( cadr x)) (c!:atomkeys (cons (quote list) (cddr x)))))) (and (eqcar x (quote cons)) (c!:atomcar (cadr x)) (c!:atomkeys (caddr x))))) (de c!:comsublis (x) (cond ((c!:atomkeys (cadr x)) (cons (quote subla) (cdr x ))) (t nil))) (put (quote sublis) (quote c!:compile_macro) (function c!:comsublis)) (de c!:comassoc (x) (cond ((or (c!:certainlyatom (cadr x)) (c!:atomkeys ( caddr x))) (cons (quote atsoc) (cdr x))) (t nil))) (put (quote assoc) (quote c!:compile_macro) (function c!:comassoc)) (put (quote assoc!*!*) (quote c!:compile_macro) (function c!:comassoc)) (de c!:commember (x) (cond ((or (c!:certainlyatom (cadr x)) (c!:atomlist ( caddr x))) (cons (quote memq) (cdr x))) (t nil))) (put (quote member) (quote c!:compile_macro) (function c!:commember)) (de c!:comdelete (x) (cond ((or (c!:certainlyatom (cadr x)) (c!:atomlist ( caddr x))) (cons (quote deleq) (cdr x))) (t nil))) (put (quote delete) (quote c!:compile_macro) (function c!:comdelete)) (de c!:ctestif (x env d1 d2) (prog (l1 l2) (setq l1 (c!:my_gensym)) (setq l2 (c!:my_gensym)) (c!:jumpif (cadr x) l1 l2) (setq x (cddr x)) (c!:startblock l1) (c!:jumpif (car x) d1 d2) (c!:startblock l2) (c!:jumpif (cadr x) d1 d2))) (put (quote if) (quote c!:ctest) (function c!:ctestif)) (de c!:ctestnull (x env d1 d2) (c!:cjumpif (cadr x) env d2 d1)) (put (quote null) (quote c!:ctest) (function c!:ctestnull)) (put (quote not) (quote c!:ctest) (function c!:ctestnull)) (de c!:ctestatom (x env d1 d2) (prog nil (setq x (c!:cval (cadr x) env)) ( c!:endblock (list (quote ifatom) x) (list d1 d2)))) (put (quote atom) (quote c!:ctest) (function c!:ctestatom)) (de c!:ctestconsp (x env d1 d2) (prog nil (setq x (c!:cval (cadr x) env)) ( c!:endblock (list (quote ifatom) x) (list d2 d1)))) (put (quote consp) (quote c!:ctest) (function c!:ctestconsp)) (de c!:ctestsymbol (x env d1 d2) (prog nil (setq x (c!:cval (cadr x) env)) ( c!:endblock (list (quote ifsymbol) x) (list d1 d2)))) (put (quote idp) (quote c!:ctest) (function c!:ctestsymbol)) (de c!:ctestnumberp (x env d1 d2) (prog nil (setq x (c!:cval (cadr x) env)) ( c!:endblock (list (quote ifnumber) x) (list d1 d2)))) (put (quote numberp) (quote c!:ctest) (function c!:ctestnumberp)) (de c!:ctestizerop (x env d1 d2) (prog nil (setq x (c!:cval (cadr x) env)) ( c!:endblock (list (quote ifizerop) x) (list d1 d2)))) (put (quote izerop) (quote c!:ctest) (function c!:ctestizerop)) (de c!:ctesteq (x env d1 d2) (prog (a1 a2 r) (setq a1 (cadr x)) (setq a2 ( caddr x)) (cond ((equal a1 nil) (return (c!:cjumpif a2 env d2 d1))) (t (cond ((equal a2 nil) (return (c!:cjumpif a1 env d2 d1)))))) (setq r (c!:pareval ( list a1 a2) env)) (c!:endblock (cons (quote ifeq) r) (list d1 d2)))) (put (quote eq) (quote c!:ctest) (function c!:ctesteq)) (de c!:ctesteqcar (x env d1 d2) (prog (a1 a2 r d3) (setq a1 (cadr x)) (setq a2 (caddr x)) (setq d3 (c!:my_gensym)) (setq r (c!:pareval (list a1 a2) env)) (c!:endblock (list (quote ifatom) (car r)) (list d2 d3)) (c!:startblock d3) (c!:outop (quote qcar) (car r) nil (car r)) (c!:endblock (cons (quote ifeq) r ) (list d1 d2)))) (put (quote eqcar) (quote c!:ctest) (function c!:ctesteqcar)) (global (quote (least_fixnum greatest_fixnum))) (setq least_fixnum (minus (expt 2 27))) (setq greatest_fixnum (difference (expt 2 27) 1)) (de c!:small_number (x) (and (fixp x) (geq x least_fixnum) (leq x greatest_fixnum))) (de c!:eqvalid (x) (cond ((atom x) (c!:small_number x)) (t (cond ((flagp (car x) (quote c!:fixnum_fn)) t) (t (and (equal (car x) (quote quote)) (or (idp ( cadr x)) (c!:small_number (cadr x))))))))) (flag (quote (iplus iplus2 idifference iminus itimes itimes2)) (quote c!:fixnum_fn)) (de c!:ctestequal (x env d1 d2) (prog (a1 a2 r) (setq a1 (s!:improve (cadr x) )) (setq a2 (s!:improve (caddr x))) (cond ((equal a1 nil) (return (c!:cjumpif a2 env d2 d1))) (t (cond ((equal a2 nil) (return (c!:cjumpif a1 env d2 d1))) ))) (setq r (c!:pareval (list a1 a2) env)) (c!:endblock (cons (cond ((or ( c!:eqvalid a1) (c!:eqvalid a2)) (quote ifeq)) (t (quote ifequal))) r) (list d1 d2)))) (put (quote equal) (quote c!:ctest) (function c!:ctestequal)) (de c!:ctestneq (x env d1 d2) (prog (a1 a2 r) (setq a1 (s!:improve (cadr x))) (setq a2 (s!:improve (caddr x))) (cond ((equal a1 nil) (return (c!:cjumpif a2 env d1 d2))) (t (cond ((equal a2 nil) (return (c!:cjumpif a1 env d1 d2)))) )) (setq r (c!:pareval (list a1 a2) env)) (c!:endblock (cons (cond ((or ( c!:eqvalid a1) (c!:eqvalid a2)) (quote ifeq)) (t (quote ifequal))) r) (list d2 d1)))) (put (quote neq) (quote c!:ctest) (function c!:ctestneq)) (de c!:ctestilessp (x env d1 d2) (prog (r) (setq r (c!:pareval (list (cadr x) (caddr x)) env)) (c!:endblock (cons (quote ifilessp) r) (list d1 d2)))) (put (quote ilessp) (quote c!:ctest) (function c!:ctestilessp)) (de c!:ctestigreaterp (x env d1 d2) (prog (r) (setq r (c!:pareval (list (cadr x) (caddr x)) env)) (c!:endblock (cons (quote ifigreaterp) r) (list d1 d2))) ) (put (quote igreaterp) (quote c!:ctest) (function c!:ctestigreaterp)) (de c!:ctestand (x env d1 d2) (prog (next) (prog (var1390) (setq var1390 (cdr x)) lab1389 (cond ((null var1390) (return nil))) (prog (a) (setq a (car var1390)) (progn (setq next (c!:my_gensym)) (c!:cjumpif a env next d2) ( c!:startblock next))) (setq var1390 (cdr var1390)) (go lab1389)) (c!:endblock (quote goto) (list d1)))) (put (quote and) (quote c!:ctest) (function c!:ctestand)) (de c!:ctestor (x env d1 d2) (prog (next) (prog (var1392) (setq var1392 (cdr x)) lab1391 (cond ((null var1392) (return nil))) (prog (a) (setq a (car var1392)) (progn (setq next (c!:my_gensym)) (c!:cjumpif a env d1 next) ( c!:startblock next))) (setq var1392 (cdr var1392)) (go lab1391)) (c!:endblock (quote goto) (list d2)))) (put (quote or) (quote c!:ctest) (function c!:ctestor)) (fluid (quote (c!:c_entrypoint_list))) (null (setq c!:c_entrypoint_list (quote ((abs c!:c_entrypoint "Labsval") ( apply0 c!:c_entrypoint "Lapply0") (apply1 c!:c_entrypoint "Lapply1") (apply2 c!:c_entrypoint "Lapply2") (apply3 c!:c_entrypoint "Lapply3") (ash1 c!:c_entrypoint "Lash1") (atan c!:c_entrypoint "Latan") (atom c!:c_entrypoint "Latom") (atsoc c!:c_entrypoint "Latsoc") (batchp c!:c_entrypoint "Lbatchp") (boundp c!:c_entrypoint "Lboundp") (bps!-putv c!:c_entrypoint "Lbpsputv") ( caaaar c!:c_entrypoint "Lcaaaar") (caaadr c!:c_entrypoint "Lcaaadr") (caaar c!:c_entrypoint "Lcaaar") (caadar c!:c_entrypoint "Lcaadar") (caaddr c!:c_entrypoint "Lcaaddr") (caadr c!:c_entrypoint "Lcaadr") (caar c!:c_entrypoint "Lcaar") (cadaar c!:c_entrypoint "Lcadaar") (cadadr c!:c_entrypoint "Lcadadr") (cadar c!:c_entrypoint "Lcadar") (caddar c!:c_entrypoint "Lcaddar") (cadddr c!:c_entrypoint "Lcadddr") (caddr c!:c_entrypoint "Lcaddr") (cadr c!:c_entrypoint "Lcadr") (car c!:c_entrypoint "Lcar") (cdaaar c!:c_entrypoint "Lcdaaar") (cdaadr c!:c_entrypoint "Lcdaadr" ) (cdaar c!:c_entrypoint "Lcdaar") (cdadar c!:c_entrypoint "Lcdadar") (cdaddr c!:c_entrypoint "Lcdaddr") (cdadr c!:c_entrypoint "Lcdadr") (cdar c!:c_entrypoint "Lcdar") (cddaar c!:c_entrypoint "Lcddaar") (cddadr c!:c_entrypoint "Lcddadr") (cddar c!:c_entrypoint "Lcddar") (cdddar c!:c_entrypoint "Lcdddar") (cddddr c!:c_entrypoint "Lcddddr") (cdddr c!:c_entrypoint "Lcdddr") (cddr c!:c_entrypoint "Lcddr") (cdr c!:c_entrypoint "Lcdr") (char!-code c!:c_entrypoint "Lchar_code") (close c!:c_entrypoint "Lclose") (codep c!:c_entrypoint "Lcodep") (constantp c!:c_entrypoint "Lconstantp") (date c!:c_entrypoint "Ldate") (deleq c!:c_entrypoint "Ldeleq") (digit c!:c_entrypoint "Ldigitp") (eject c!:c_entrypoint "Leject") (endp c!:c_entrypoint "Lendp") (eq c!:c_entrypoint "Leq") (eqcar c!:c_entrypoint "Leqcar") (eql c!:c_entrypoint "Leql") (eqn c!:c_entrypoint "Leqn") (error1 c!:c_entrypoint "Lerror0") (evenp c!:c_entrypoint "Levenp") (evlis c!:c_entrypoint "Levlis") (explode c!:c_entrypoint "Lexplode") (explode2 c!:c_entrypoint "Lexplodec") (explodec c!:c_entrypoint "Lexplodec") (expt c!:c_entrypoint "Lexpt") (fix c!:c_entrypoint "Ltruncate") (fixp c!:c_entrypoint "Lfixp") (flag c!:c_entrypoint "Lflag") (flagp!*!* c!:c_entrypoint "Lflagp") (flagp c!:c_entrypoint "Lflagp") (flagpcar c!:c_entrypoint "Lflagpcar") (float c!:c_entrypoint "Lfloat") (floatp c!:c_entrypoint "Lfloatp") (fluidp c!:c_entrypoint "Lsymbol_specialp") (gcdn c!:c_entrypoint "Lgcd") (gctime c!:c_entrypoint "Lgctime") (gensym c!:c_entrypoint "Lgensym") (gensym1 c!:c_entrypoint "Lgensym1") (geq c!:c_entrypoint "Lgeq") (get!* c!:c_entrypoint "Lget") (getenv c!:c_entrypoint "Lgetenv") (getv c!:c_entrypoint "Lgetv") (svref c!:c_entrypoint "Lgetv") (globalp c!:c_entrypoint "Lsymbol_globalp") ( greaterp c!:c_entrypoint "Lgreaterp") (iadd1 c!:c_entrypoint "Liadd1") ( idifference c!:c_entrypoint "Lidifference") (idp c!:c_entrypoint "Lsymbolp") (igreaterp c!:c_entrypoint "Ligreaterp") (ilessp c!:c_entrypoint "Lilessp") ( iminus c!:c_entrypoint "Liminus") (iminusp c!:c_entrypoint "Liminusp") ( indirect c!:c_entrypoint "Lindirect") (integerp c!:c_entrypoint "Lintegerp") (iplus2 c!:c_entrypoint "Liplus2") (iquotient c!:c_entrypoint "Liquotient") ( iremainder c!:c_entrypoint "Liremainder") (irightshift c!:c_entrypoint "Lirightshift") (isub1 c!:c_entrypoint "Lisub1") (itimes2 c!:c_entrypoint "Litimes2") (length c!:c_entrypoint "Llength") (lengthc c!:c_entrypoint "Llengthc") (leq c!:c_entrypoint "Lleq") (lessp c!:c_entrypoint "Llessp") ( linelength c!:c_entrypoint "Llinelength") (load!-module c!:c_entrypoint "Lload_module") (lposn c!:c_entrypoint "Llposn") (macro!-function c!:c_entrypoint "Lmacro_function") (macroexpand!-1 c!:c_entrypoint "Lmacroexpand_1") (macroexpand c!:c_entrypoint "Lmacroexpand") (make!-bps c!:c_entrypoint "Lget_bps") (make!-global c!:c_entrypoint "Lmake_global") ( make!-simple!-string c!:c_entrypoint "Lsmkvect") (make!-special c!:c_entrypoint "Lmake_special") (mapstore c!:c_entrypoint "Lmapstore") (max2 c!:c_entrypoint "Lmax2") (memq c!:c_entrypoint "Lmemq") (min2 c!:c_entrypoint "Lmin2") (minus c!:c_entrypoint "Lminus") (minusp c!:c_entrypoint "Lminusp") (mkquote c!:c_entrypoint "Lmkquote") (mkvect c!:c_entrypoint "Lmkvect") (mod c!:c_entrypoint "Lmod") (modular!-difference c!:c_entrypoint "Lmodular_difference") (modular!-expt c!:c_entrypoint "Lmodular_expt") (modular!-minus c!:c_entrypoint "Lmodular_minus") ( modular!-number c!:c_entrypoint "Lmodular_number") (modular!-plus c!:c_entrypoint "Lmodular_plus") (modular!-quotient c!:c_entrypoint "Lmodular_quotient") (modular!-reciprocal c!:c_entrypoint "Lmodular_reciprocal") (modular!-times c!:c_entrypoint "Lmodular_times") ( nconc c!:c_entrypoint "Lnconc") (neq c!:c_entrypoint "Lneq") (not c!:c_entrypoint "Lnull") (null c!:c_entrypoint "Lnull") (numberp c!:c_entrypoint "Lnumberp") (oddp c!:c_entrypoint "Loddp") (onep c!:c_entrypoint "Lonep") (orderp c!:c_entrypoint "Lorderp") (pagelength c!:c_entrypoint "Lpagelength") (pairp c!:c_entrypoint "Lconsp") (plist c!:c_entrypoint "Lplist") (plusp c!:c_entrypoint "Lplusp") (posn c!:c_entrypoint "Lposn") (put c!:c_entrypoint "Lputprop") (putv!-char c!:c_entrypoint "Lsputv") (putv c!:c_entrypoint "Lputv") (qcaar c!:c_entrypoint "Lcaar") (qcadr c!:c_entrypoint "Lcadr") (qcar c!:c_entrypoint "Lcar") (qcdar c!:c_entrypoint "Lcdar") (qcddr c!:c_entrypoint "Lcddr") (qcdr c!:c_entrypoint "Lcdr") (qgetv c!:c_entrypoint "Lgetv") (rds c!:c_entrypoint "Lrds") (reclaim c!:c_entrypoint "Lgc") (remd c!:c_entrypoint "Lremd") (remflag c!:c_entrypoint "Lremflag") (remob c!:c_entrypoint "Lunintern") (remprop c!:c_entrypoint "Lremprop") (reverse c!:c_entrypoint "Lreverse") (reversip c!:c_entrypoint "Lnreverse") (rplaca c!:c_entrypoint "Lrplaca") (rplacd c!:c_entrypoint "Lrplacd") (schar c!:c_entrypoint "Lsgetv") (seprp c!:c_entrypoint "Lwhitespace_char_p") ( set!-small!-modulus c!:c_entrypoint "Lset_small_modulus") (set c!:c_entrypoint "Lset") (smemq c!:c_entrypoint "Lsmemq") (spaces c!:c_entrypoint "Lxtab") (special!-char c!:c_entrypoint "Lspecial_char") ( special!-form!-p c!:c_entrypoint "Lspecial_form_p") (spool c!:c_entrypoint "Lspool") (stop c!:c_entrypoint "Lstop") (stringp c!:c_entrypoint "Lstringp") (subla c!:c_entrypoint "Lsubla") (subst c!:c_entrypoint "Lsubst") ( symbol!-env c!:c_entrypoint "Lsymbol_env") (symbol!-function c!:c_entrypoint "Lsymbol_function") (symbol!-name c!:c_entrypoint "Lsymbol_name") ( symbol!-set!-definition c!:c_entrypoint "Lsymbol_set_definition") ( symbol!-set!-env c!:c_entrypoint "Lsymbol_set_env") (symbol!-value c!:c_entrypoint "Lsymbol_value") (system c!:c_entrypoint "Lsystem") (terpri c!:c_entrypoint "Lterpri") (threevectorp c!:c_entrypoint "Lthreevectorp") ( time c!:c_entrypoint "Ltime") (ttab c!:c_entrypoint "Lttab") (tyo c!:c_entrypoint "Ltyo") (unmake!-global c!:c_entrypoint "Lunmake_global") ( unmake!-special c!:c_entrypoint "Lunmake_special") (upbv c!:c_entrypoint "Lupbv") (verbos c!:c_entrypoint "Lverbos") (wrs c!:c_entrypoint "Lwrs") ( xcons c!:c_entrypoint "Lxcons") (xtab c!:c_entrypoint "Lxtab") (zerop c!:c_entrypoint "Lzerop") (cons c!:direct_entrypoint (2 . "cons")) (ncons c!:direct_entrypoint (1 . "ncons")) (list2 c!:direct_entrypoint (2 . "list2") ) (list2!* c!:direct_entrypoint (3 . "list2star")) (acons c!:direct_entrypoint (3 . "acons")) (list3 c!:direct_entrypoint (3 . "list3") ) (list3!* c!:direct_entrypoint (4 . "list3star")) (list4 c!:direct_entrypoint (4 . "list4")) (plus2 c!:direct_entrypoint (2 . "plus2") ) (difference c!:direct_entrypoint (2 . "difference2")) (add1 c!:direct_entrypoint (1 . "add1")) (sub1 c!:direct_entrypoint (1 . "sub1")) ( lognot c!:direct_entrypoint (1 . "lognot")) (ash c!:direct_entrypoint (2 . "ash")) (quotient c!:direct_entrypoint (2 . "quot2")) (remainder c!:direct_entrypoint (2 . "Cremainder")) (times2 c!:direct_entrypoint (2 . "times2")) (minus c!:direct_entrypoint (1 . "negate")) (lessp c!:direct_predicate (2 . "lessp2")) (leq c!:direct_predicate (2 . "lesseq2")) (greaterp c!:direct_predicate (2 . "greaterp2")) (geq c!:direct_predicate (2 . "geq2")) (zerop c!:direct_predicate (1 . "zerop")))))) (null (setq c!:c_entrypoint_list (append c!:c_entrypoint_list (quote ((append c!:c_entrypoint "Lappend") (assoc c!:c_entrypoint "Lassoc") (compress c!:c_entrypoint "Lcompress") (delete c!:c_entrypoint "Ldelete") (divide c!:c_entrypoint "Ldivide") (equal c!:c_entrypoint "Lequal") (intern c!:c_entrypoint "Lintern") (liter c!:c_entrypoint "Lalpha_char_p") (member c!:c_entrypoint "Lmember") (prin c!:c_entrypoint "Lprin") (prin1 c!:c_entrypoint "Lprin") (prin2 c!:c_entrypoint "Lprinc") (princ c!:c_entrypoint "Lprinc") (print c!:c_entrypoint "Lprint") (printc c!:c_entrypoint "Lprintc") (read c!:c_entrypoint "Lread") (readch c!:c_entrypoint "Lreadch") (sublis c!:c_entrypoint "Lsublis") (vectorp c!:c_entrypoint "Lsimple_vectorp") (get c!:direct_entrypoint (2 . "get")))))) ) (prog (var1394) (setq var1394 c!:c_entrypoint_list) lab1393 (cond ((null var1394) (return nil))) (prog (x) (setq x (car var1394)) (put (car x) (cadr x ) (caddr x))) (setq var1394 (cdr var1394)) (go lab1393)) (flag (quote (atom atsoc codep constantp deleq digit endp eq eqcar evenp eql fixp flagp flagpcar floatp get globalp iadd1 idifference idp igreaterp ilessp iminus iminusp indirect integerp iplus2 irightshift isub1 itimes2 liter memq minusp modular!-difference modular!-expt modular!-minus modular!-number modular!-plus modular!-times not null numberp onep pairp plusp qcaar qcadr qcar qcdar qcddr qcdr remflag remprop reversip seprp special!-form!-p stringp symbol!-env symbol!-name symbol!-value threevectorp vectorp zerop)) (quote c!:no_errors)) % end of file
true
% RLISP to LISP converter. A C PI:NAME:<NAME>END_PI 2004-2020 %% %% Copyright (C) 2020, following the master REDUCE source files. * %% * %% 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 relevant * %% copyright notice, this list of conditions and the following * %% disclaimer. * %% * Redistributions in binary form must reproduce the above * %% copyright notice, this list of conditions and the following * %% disclaimer in the documentation and/or other materials provided * %% with the distribution. * %% * %% THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * %% "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * %% LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * %% FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * %% COPYRIGHT OWNERS 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. * %% (global (quote (s!:opcodelist))) (setq s!:opcodelist (quote (LOADLOC LOADLOC0 LOADLOC1 LOADLOC2 LOADLOC3 LOADLOC4 LOADLOC5 LOADLOC6 LOADLOC7 LOADLOC8 LOADLOC9 LOADLOC10 LOADLOC11 LOC0LOC1 LOC1LOC2 LOC2LOC3 LOC1LOC0 LOC2LOC1 LOC3LOC2 VNIL LOADLIT LOADLIT1 LOADLIT2 LOADLIT3 LOADLIT4 LOADLIT5 LOADLIT6 LOADLIT7 LOADFREE LOADFREE1 LOADFREE2 LOADFREE3 LOADFREE4 STORELOC STORELOC0 STORELOC1 STORELOC2 STORELOC3 STORELOC4 STORELOC5 STORELOC6 STORELOC7 STOREFREE STOREFREE1 STOREFREE2 STOREFREE3 LOADLEX STORELEX CLOSURE CARLOC0 CARLOC1 CARLOC2 CARLOC3 CARLOC4 CARLOC5 CARLOC6 CARLOC7 CARLOC8 CARLOC9 CARLOC10 CARLOC11 CDRLOC0 CDRLOC1 CDRLOC2 CDRLOC3 CDRLOC4 CDRLOC5 CAARLOC0 CAARLOC1 CAARLOC2 CAARLOC3 CALL0 CALL1 CALL2 CALL2R CALL3 CALLN CALL0_0 CALL0_1 CALL0_2 CALL0_3 CALL1_0 CALL1_1 CALL1_2 CALL1_3 CALL1_4 CALL1_5 CALL2_0 CALL2_1 CALL2_2 CALL2_3 CALL2_4 BUILTIN0 BUILTIN1 BUILTIN2 BUILTIN2R BUILTIN3 APPLY1 APPLY2 APPLY3 APPLY4 JCALL JCALLN JUMP JUMP_B JUMP_L JUMP_BL JUMPNIL JUMPNIL_B JUMPNIL_L JUMPNIL_BL JUMPT JUMPT_B JUMPT_L JUMPT_BL JUMPATOM JUMPATOM_B JUMPATOM_L JUMPATOM_BL JUMPNATOM JUMPNATOM_B JUMPNATOM_L JUMPNATOM_BL JUMPEQ JUMPEQ_B JUMPEQ_L JUMPEQ_BL JUMPNE JUMPNE_B JUMPNE_L JUMPNE_BL JUMPEQUAL JUMPEQUAL_B JUMPEQUAL_L JUMPEQUAL_BL JUMPNEQUAL JUMPNEQUAL_B JUMPNEQUAL_L JUMPNEQUAL_BL JUMPL0NIL JUMPL0T JUMPL1NIL JUMPL1T JUMPL2NIL JUMPL2T JUMPL3NIL JUMPL3T JUMPL4NIL JUMPL4T JUMPST0NIL JUMPST0T JUMPST1NIL JUMPST1T JUMPST2NIL JUMPST2T JUMPL0ATOM JUMPL0NATOM JUMPL1ATOM JUMPL1NATOM JUMPL2ATOM JUMPL2NATOM JUMPL3ATOM JUMPL3NATOM JUMPFREE1NIL JUMPFREE1T JUMPFREE2NIL JUMPFREE2T JUMPFREE3NIL JUMPFREE3T JUMPFREE4NIL JUMPFREE4T JUMPFREENIL JUMPFREET JUMPLIT1EQ JUMPLIT1NE JUMPLIT2EQ JUMPLIT2NE JUMPLIT3EQ JUMPLIT3NE JUMPLIT4EQ JUMPLIT4NE JUMPLITEQ JUMPLITNE JUMPB1NIL JUMPB1T JUMPB2NIL JUMPB2T JUMPFLAGP JUMPNFLAGP JUMPEQCAR JUMPNEQCAR CATCH CATCH_B CATCH_L CATCH_BL UNCATCH THROW PROTECT UNPROTECT PVBIND PVRESTORE FREEBIND FREERSTR EXIT NILEXIT LOC0EXIT LOC1EXIT LOC2EXIT PUSH PUSHNIL PUSHNIL2 PUSHNIL3 PUSHNILS POP LOSE LOSE2 LOSE3 LOSES SWOP EQ EQCAR EQUAL NUMBERP CAR CDR CAAR CADR CDAR CDDR CONS NCONS XCONS ACONS LENGTH LIST2 LIST2STAR LIST3 PLUS2 ADD1 DIFFERENCE SUB1 TIMES2 GREATERP LESSP FLAGP GET LITGET GETV QGETV QGETVN BIGSTACK BIGCALL ICASE FASTGET ONEVALUE SPARE))) (prog (n) (setq n 0) (prog (var1001) (setq var1001 s!:opcodelist) lab1000 ( cond ((null var1001) (return nil))) (prog (v) (setq v (car var1001)) (progn ( put v (quote s!:opcode) n) (setq n (plus n 1)))) (setq var1001 (cdr var1001)) (go lab1000)) (return (list n (quote opcodes) (quote allocated)))) (setq s!:opcodelist nil) (fluid (quote (s!:env_alist))) (de s!:vecof (l) (prog (w) (setq w (assoc l s!:env_alist)) (cond (w (return ( cdr w)))) (setq w (s!:vecof1 l)) (setq s!:env_alist (cons (cons l w) s!:env_alist)) (return w))) (de s!:vecof1 (l) (prog (v n) (setq v (mkvect (sub1 (length l)))) (setq n 0) (prog (var1003) (setq var1003 l) lab1002 (cond ((null var1003) (return nil))) (prog (x) (setq x (car var1003)) (progn (putv v n x) (setq n (plus n 1)))) ( setq var1003 (cdr var1003)) (go lab1002)) (return v))) (progn (put (quote batchp) (quote s!:builtin0) 0) (put (quote date) (quote s!:builtin0) 1) (put (quote eject) (quote s!:builtin0) 2) (put (quote error1) (quote s!:builtin0) 3) (put (quote gctime) (quote s!:builtin0) 4) (put ( quote lposn) (quote s!:builtin0) 6) (put (quote posn) (quote s!:builtin0) 8) (put (quote read) (quote s!:builtin0) 9) (put (quote readch) (quote s!:builtin0) 10) (put (quote terpri) (quote s!:builtin0) 11) (put (quote time ) (quote s!:builtin0) 12) (put (quote tyi) (quote s!:builtin0) 13) (put ( quote load!-spid) (quote s!:builtin0) 14) (put (quote abs) (quote s!:builtin1 ) 0) (put (quote add1) (quote s!:builtin1) 1) (put (quote atan) (quote s!:builtin1) 2) (put (quote apply0) (quote s!:builtin1) 3) (put (quote atom) (quote s!:builtin1) 4) (put (quote boundp) (quote s!:builtin1) 5) (put (quote char!-code) (quote s!:builtin1) 6) (put (quote close) (quote s!:builtin1) 7) (put (quote codep) (quote s!:builtin1) 8) (put (quote compress) (quote s!:builtin1) 9) (put (quote constantp) (quote s!:builtin1) 10) (put (quote digit) (quote s!:builtin1) 11) (put (quote endp) (quote s!:builtin1) 12) (put (quote eval) (quote s!:builtin1) 13) (put (quote evenp) (quote s!:builtin1) 14) (put (quote evlis) (quote s!:builtin1) 15) (put (quote explode) (quote s!:builtin1) 16) (put (quote explode2lc) (quote s!:builtin1) 17) (put (quote explode2) (quote s!:builtin1) 18) (put (quote explodec) (quote s!:builtin1) 18) (put (quote fixp) (quote s!:builtin1) 19) (put (quote float) (quote s!:builtin1) 20) (put (quote floatp) (quote s!:builtin1) 21) (put (quote symbol!-specialp) (quote s!:builtin1) 22) (put (quote gc) (quote s!:builtin1) 23) (put (quote gensym1) (quote s!:builtin1) 24) (put (quote getenv) (quote s!:builtin1) 25) (put (quote symbol!-globalp) (quote s!:builtin1) 26) (put ( quote iadd1) (quote s!:builtin1) 27) (put (quote symbolp) (quote s!:builtin1) 28) (put (quote iminus) (quote s!:builtin1) 29) (put (quote iminusp) (quote s!:builtin1) 30) (put (quote indirect) (quote s!:builtin1) 31) (put (quote integerp) (quote s!:builtin1) 32) (put (quote intern) (quote s!:builtin1) 33) (put (quote isub1) (quote s!:builtin1) 34) (put (quote length) (quote s!:builtin1) 35) (put (quote lengthc) (quote s!:builtin1) 36) (put (quote linelength) (quote s!:builtin1) 37) (put (quote liter) (quote s!:builtin1) 38 ) (put (quote load!-module) (quote s!:builtin1) 39) (put (quote lognot) ( quote s!:builtin1) 40) (put (quote macroexpand) (quote s!:builtin1) 41) (put (quote macroexpand!-1) (quote s!:builtin1) 42) (put (quote macro!-function) ( quote s!:builtin1) 43) (put (quote make!-bps) (quote s!:builtin1) 44) (put ( quote make!-global) (quote s!:builtin1) 45) (put (quote make!-simple!-string) (quote s!:builtin1) 46) (put (quote make!-special) (quote s!:builtin1) 47) ( put (quote minus) (quote s!:builtin1) 48) (put (quote minusp) (quote s!:builtin1) 49) (put (quote mkvect) (quote s!:builtin1) 50) (put (quote modular!-minus) (quote s!:builtin1) 51) (put (quote modular!-number) (quote s!:builtin1) 52) (put (quote modular!-reciprocal) (quote s!:builtin1) 53) ( put (quote null) (quote s!:builtin1) 54) (put (quote oddp) (quote s!:builtin1 ) 55) (put (quote onep) (quote s!:builtin1) 56) (put (quote pagelength) ( quote s!:builtin1) 57) (put (quote pairp) (quote s!:builtin1) 58) (put (quote plist) (quote s!:builtin1) 59) (put (quote plusp) (quote s!:builtin1) 60) ( put (quote prin) (quote s!:builtin1) 61) (put (quote princ) (quote s!:builtin1) 62) (put (quote print) (quote s!:builtin1) 63) (put (quote printc) (quote s!:builtin1) 64) (put (quote rds) (quote s!:builtin1) 68) (put (quote remd) (quote s!:builtin1) 69) (put (quote reverse) (quote s!:builtin1 ) 70) (put (quote reversip) (quote s!:builtin1) 71) (put (quote seprp) (quote s!:builtin1) 72) (put (quote set!-small!-modulus) (quote s!:builtin1) 73) ( put (quote spaces) (quote s!:builtin1) 74) (put (quote xtab) (quote s!:builtin1) 74) (put (quote special!-char) (quote s!:builtin1) 75) (put ( quote special!-form!-p) (quote s!:builtin1) 76) (put (quote spool) (quote s!:builtin1) 77) (put (quote stop) (quote s!:builtin1) 78) (put (quote stringp) (quote s!:builtin1) 79) (put (quote sub1) (quote s!:builtin1) 80) ( put (quote symbol!-env) (quote s!:builtin1) 81) (put (quote symbol!-function) (quote s!:builtin1) 82) (put (quote symbol!-name) (quote s!:builtin1) 83) ( put (quote symbol!-value) (quote s!:builtin1) 84) (put (quote system) (quote s!:builtin1) 85) (put (quote fix) (quote s!:builtin1) 86) (put (quote ttab) ( quote s!:builtin1) 87) (put (quote tyo) (quote s!:builtin1) 88) (put (quote remob) (quote s!:builtin1) 89) (put (quote unmake!-global) (quote s!:builtin1 ) 90) (put (quote unmake!-special) (quote s!:builtin1) 91) (put (quote upbv) (quote s!:builtin1) 92) (put (quote vectorp) (quote s!:builtin1) 93) (put ( quote verbos) (quote s!:builtin1) 94) (put (quote wrs) (quote s!:builtin1) 95 ) (put (quote zerop) (quote s!:builtin1) 96) (put (quote car) (quote s!:builtin1) 97) (put (quote cdr) (quote s!:builtin1) 98) (put (quote caar) ( quote s!:builtin1) 99) (put (quote cadr) (quote s!:builtin1) 100) (put (quote cdar) (quote s!:builtin1) 101) (put (quote cddr) (quote s!:builtin1) 102) ( put (quote qcar) (quote s!:builtin1) 103) (put (quote qcdr) (quote s!:builtin1) 104) (put (quote qcaar) (quote s!:builtin1) 105) (put (quote qcadr) (quote s!:builtin1) 106) (put (quote qcdar) (quote s!:builtin1) 107) ( put (quote qcddr) (quote s!:builtin1) 108) (put (quote ncons) (quote s!:builtin1) 109) (put (quote numberp) (quote s!:builtin1) 110) (put (quote is!-spid) (quote s!:builtin1) 111) (put (quote spid!-to!-nil) (quote s!:builtin1) 112) (put (quote append) (quote s!:builtin2) 0) (put (quote ash) (quote s!:builtin2) 1) (put (quote assoc) (quote s!:builtin2) 2) (put (quote assoc!*!*) (quote s!:builtin2) 2) (put (quote atsoc) (quote s!:builtin2) 3) (put (quote deleq) (quote s!:builtin2) 4) (put (quote delete) (quote s!:builtin2) 5) (put (quote divide) (quote s!:builtin2) 6) (put (quote eqcar) (quote s!:builtin2) 7) (put (quote eql) (quote s!:builtin2) 8) (put (quote eqn) (quote s!:builtin2) 9) (put (quote expt) (quote s!:builtin2) 10) (put ( quote flag) (quote s!:builtin2) 11) (put (quote flagpcar) (quote s!:builtin2) 12) (put (quote gcdn) (quote s!:builtin2) 13) (put (quote geq) (quote s!:builtin2) 14) (put (quote getv) (quote s!:builtin2) 15) (put (quote greaterp) (quote s!:builtin2) 16) (put (quote idifference) (quote s!:builtin2 ) 17) (put (quote igreaterp) (quote s!:builtin2) 18) (put (quote ilessp) ( quote s!:builtin2) 19) (put (quote imax) (quote s!:builtin2) 20) (put (quote imin) (quote s!:builtin2) 21) (put (quote iplus2) (quote s!:builtin2) 22) ( put (quote iquotient) (quote s!:builtin2) 23) (put (quote iremainder) (quote s!:builtin2) 24) (put (quote irightshift) (quote s!:builtin2) 25) (put (quote itimes2) (quote s!:builtin2) 26) (put (quote leq) (quote s!:builtin2) 28) ( put (quote lessp) (quote s!:builtin2) 29) (put (quote max2) (quote s!:builtin2) 31) (put (quote member) (quote s!:builtin2) 32) (put (quote member!*!*) (quote s!:builtin2) 32) (put (quote memq) (quote s!:builtin2) 33) (put (quote min2) (quote s!:builtin2) 34) (put (quote mod) (quote s!:builtin2) 35) (put (quote modular!-difference) (quote s!:builtin2) 36) ( put (quote modular!-expt) (quote s!:builtin2) 37) (put (quote modular!-plus) (quote s!:builtin2) 38) (put (quote modular!-quotient) (quote s!:builtin2) 39 ) (put (quote modular!-times) (quote s!:builtin2) 40) (put (quote nconc) ( quote s!:builtin2) 41) (put (quote neq) (quote s!:builtin2) 42) (put (quote orderp) (quote s!:builtin2) 43) (put (quote quotient) (quote s!:builtin2) 44) (put (quote remainder) (quote s!:builtin2) 45) (put (quote remflag) (quote s!:builtin2) 46) (put (quote remprop) (quote s!:builtin2) 47) (put (quote rplaca) (quote s!:builtin2) 48) (put (quote rplacd) (quote s!:builtin2) 49) ( put (quote schar) (quote s!:builtin2) 50) (put (quote set) (quote s!:builtin2 ) 51) (put (quote smemq) (quote s!:builtin2) 52) (put (quote subla) (quote s!:builtin2) 53) (put (quote sublis) (quote s!:builtin2) 54) (put (quote symbol!-set!-definition) (quote s!:builtin2) 55) (put (quote symbol!-set!-env ) (quote s!:builtin2) 56) (put (quote times2) (quote s!:builtin2) 57) (put ( quote xcons) (quote s!:builtin2) 58) (put (quote equal) (quote s!:builtin2) 59) (put (quote eq) (quote s!:builtin2) 60) (put (quote cons) (quote s!:builtin2) 61) (put (quote list2) (quote s!:builtin2) 62) (put (quote get) (quote s!:builtin2) 63) (put (quote qgetv) (quote s!:builtin2) 64) (put ( quote flagp) (quote s!:builtin2) 65) (put (quote apply1) (quote s!:builtin2) 66) (put (quote difference) (quote s!:builtin2) 67) (put (quote plus2) (quote s!:builtin2) 68) (put (quote times2) (quote s!:builtin2) 69) (put (quote equalcar) (quote s!:builtin2) 70) (put (quote iequal) (quote s!:builtin2) 71) (put (quote nreverse) (quote s!:builtin2) 72) (put (quote bps!-putv) (quote s!:builtin3) 0) (put (quote errorset) (quote s!:builtin3) 1) (put (quote list2!*) (quote s!:builtin3) 2) (put (quote list3) (quote s!:builtin3) 3) ( put (quote putprop) (quote s!:builtin3) 4) (put (quote putv) (quote s!:builtin3) 5) (put (quote putv!-char) (quote s!:builtin3) 6) (put (quote subst) (quote s!:builtin3) 7) (put (quote apply2) (quote s!:builtin3) 8) (put (quote acons) (quote s!:builtin3) 9) nil) (de s!:prinhex1 (n) (princ (schar "0123456789abcdef" (logand n 15)))) (de s!:prinhex2 (n) (progn (s!:prinhex1 (truncate n 16)) (s!:prinhex1 n))) (de s!:prinhex4 (n) (progn (s!:prinhex2 (truncate n 256)) (s!:prinhex2 n))) (flag (quote (comp plap pgwd pwrds notailcall ord nocompile carcheckflag savedef r2i native_code save_native strip_native)) (quote switch)) (cond ((not (boundp (quote !*comp))) (progn (fluid (quote (!*comp))) (setq !*comp t)))) (cond ((not (boundp (quote !*nocompile))) (progn (fluid (quote (!*nocompile)) ) (setq !*nocompile nil)))) (cond ((not (boundp (quote !*plap))) (progn (fluid (quote (!*plap))) (setq !*plap nil)))) (cond ((not (boundp (quote !*pgwd))) (progn (fluid (quote (!*pgwd))) (setq !*pgwd nil)))) (cond ((not (boundp (quote !*pwrds))) (progn (fluid (quote (!*pwrds))) (setq !*pwrds t)))) (cond ((not (boundp (quote !*notailcall))) (progn (fluid (quote (!*notailcall ))) (setq !*notailcall nil)))) (cond ((not (boundp (quote !*ord))) (progn (fluid (quote (!*ord))) (setq !*ord t)))) (cond ((not (boundp (quote !*savedef))) (progn (fluid (quote (!*savedef))) ( setq !*savedef nil)))) (cond ((not (boundp (quote !*carcheckflag))) (progn (fluid (quote ( !*carcheckflag))) (setq !*carcheckflag t)))) (cond ((not (boundp (quote !*r2i))) (progn (fluid (quote (!*r2i))) (setq !*r2i t)))) (cond ((not (boundp (quote !*native_code))) (progn (fluid (quote ( !*native_code))) (setq !*native_code nil)))) (cond ((not (boundp (quote !*save_native))) (progn (fluid (quote ( !*save_native))) (setq !*save_native nil)))) (cond ((not (boundp (quote !*strip_native))) (progn (fluid (quote ( !*strip_native))) (setq !*strip_native t)))) (global (quote (s!:native_file))) (fluid (quote (s!:current_function s!:current_label s!:current_block s!:current_size s!:current_procedure s!:other_defs s!:lexical_env s!:has_closure s!:recent_literals s!:used_lexicals s!:a_reg_values s!:current_count s!:maybe_values))) (de s!:start_procedure (nargs nopts restarg) (progn (setq s!:current_procedure nil) (setq s!:current_label (gensym)) (setq s!:a_reg_values nil) (cond ((or (not (zerop nopts)) restarg) (progn (setq s!:current_block (list (list (quote OPTARGS) nopts) nopts (list (quote ARGCOUNT) nargs) nargs)) (setq s!:current_size 2))) (t (cond ((greaterp nargs 3) (progn (setq s!:current_block (list (list (quote ARGCOUNT) nargs) nargs)) (setq s!:current_size 1))) (t (progn (setq s!:current_block nil) (setq s!:current_size 0)))))))) (de s!:set_label (x) (progn (cond (s!:current_label (prog (w) (setq w (cons s!:current_size s!:current_block)) (prog (var1005) (setq var1005 s!:recent_literals) lab1004 (cond ((null var1005) (return nil))) (prog (x) ( setq x (car var1005)) (rplaca x w)) (setq var1005 (cdr var1005)) (go lab1004) ) (setq s!:recent_literals nil) (setq s!:current_procedure (cons (cons s!:current_label (cons (list (quote JUMP) x) w)) s!:current_procedure)) (setq s!:current_block nil) (setq s!:current_size 0)))) (setq s!:current_label x) (setq s!:a_reg_values nil))) (de s!:outjump (op lab) (prog (g w) (cond ((not (flagp op (quote s!:preserves_a))) (setq s!:a_reg_values nil))) (cond ((null s!:current_label) (return nil))) (cond ((equal op (quote JUMP)) (setq op (list op lab))) (t ( cond ((equal op (quote ICASE)) (setq op (cons op lab))) (t (setq op (list op lab (setq g (gensym)))))))) (setq w (cons s!:current_size s!:current_block)) (prog (var1007) (setq var1007 s!:recent_literals) lab1006 (cond ((null var1007) (return nil))) (prog (x) (setq x (car var1007)) (rplaca x w)) (setq var1007 (cdr var1007)) (go lab1006)) (setq s!:recent_literals nil) (setq s!:current_procedure (cons (cons s!:current_label (cons op w)) s!:current_procedure)) (setq s!:current_block nil) (setq s!:current_size 0) ( setq s!:current_label g) (return op))) (de s!:outexit nil (prog (w op) (setq op (quote (EXIT))) (cond ((null s!:current_label) (return nil))) (setq w (cons s!:current_size s!:current_block)) (prog (var1009) (setq var1009 s!:recent_literals) lab1008 (cond ((null var1009) (return nil))) (prog (x) (setq x (car var1009)) (rplaca x w)) (setq var1009 (cdr var1009)) (go lab1008)) (setq s!:recent_literals nil) (setq s!:current_procedure (cons (cons s!:current_label (cons op w)) s!:current_procedure)) (setq s!:current_block nil) (setq s!:current_size 0) ( setq s!:current_label nil))) (flag (quote (PUSH PUSHNIL PUSHNIL2 PUSHNIL3 LOSE LOSE2 LOSE3 LOSES STORELOC STORELOC0 STORELOC1 STORELOC2 STORELOC3 STORELOC4 STORELOC5 STORELOC6 STORELOC7 JUMP JUMPT JUMPNIL JUMPEQ JUMPEQUAL JUMPNE JUMPNEQUAL JUMPATOM JUMPNATOM)) (quote s!:preserves_a)) (de s!:outopcode0 (op doc) (prog nil (cond ((not (flagp op (quote s!:preserves_a))) (setq s!:a_reg_values nil))) (cond ((null s!:current_label) (return nil))) (setq s!:current_block (cons op s!:current_block)) (setq s!:current_size (plus s!:current_size 1)) (cond ((or !*plap !*pgwd) (setq s!:current_block (cons doc s!:current_block)))))) (de s!:outopcode1 (op arg doc) (prog nil (cond ((not (flagp op (quote s!:preserves_a))) (setq s!:a_reg_values nil))) (cond ((null s!:current_label) (return nil))) (setq s!:current_block (cons arg (cons op s!:current_block))) (setq s!:current_size (plus s!:current_size 2)) (cond ((or !*plap !*pgwd) ( setq s!:current_block (cons (list op doc) s!:current_block)))))) (deflist (quote ((LOADLIT 1) (LOADFREE 2) (CALL0 2) (CALL1 2) (LITGET 2) ( JUMPLITEQ 2) (JUMPLITNE 2) (JUMPLITEQ!* 2) (JUMPLITNE!* 2) (JUMPFREET 2) ( JUMPFREENIL 2))) (quote s!:short_form_bonus)) (de s!:record_literal (env) (prog (w extra) (setq w (gethash (car s!:current_block) (car env))) (cond ((null w) (setq w (cons 0 nil)))) (setq extra (get (cadr s!:current_block) (quote s!:short_form_bonus))) (cond ((null extra) (setq extra 10)) (t (setq extra (plus extra 10)))) (setq s!:recent_literals (cons (cons nil s!:current_block) s!:recent_literals)) ( puthash (car s!:current_block) (car env) (cons (plus (car w) extra) (cons ( car s!:recent_literals) (cdr w)))))) (de s!:record_literal_for_jump (x env lab) (prog (w extra) (cond ((null s!:current_label) (return nil))) (setq w (gethash (cadr x) (car env))) (cond ((null w) (setq w (cons 0 nil)))) (setq extra (get (car x) (quote s!:short_form_bonus))) (cond ((null extra) (setq extra 10)) (t (setq extra ( plus extra 10)))) (setq x (s!:outjump x lab)) (puthash (cadar x) (car env) ( cons (plus (car w) extra) (cons (cons nil x) (cdr w)))))) (de s!:outopcode1lit (op arg env) (prog nil (cond ((not (flagp op (quote s!:preserves_a))) (setq s!:a_reg_values nil))) (cond ((null s!:current_label) (return nil))) (setq s!:current_block (cons arg (cons op s!:current_block))) (s!:record_literal env) (setq s!:current_size (plus s!:current_size 2)) ( cond ((or !*plap !*pgwd) (setq s!:current_block (cons (list op arg) s!:current_block)))))) (de s!:outopcode2 (op arg1 arg2 doc) (prog nil (cond ((not (flagp op (quote s!:preserves_a))) (setq s!:a_reg_values nil))) (cond ((null s!:current_label) (return nil))) (setq s!:current_block (cons arg2 (cons arg1 (cons op s!:current_block)))) (setq s!:current_size (plus s!:current_size 3)) (cond (( or !*plap !*pgwd) (setq s!:current_block (cons (cons op doc) s!:current_block )))))) (de s!:outopcode2lit (op arg1 arg2 doc env) (prog nil (cond ((not (flagp op ( quote s!:preserves_a))) (setq s!:a_reg_values nil))) (cond ((null s!:current_label) (return nil))) (setq s!:current_block (cons arg1 (cons op s!:current_block))) (s!:record_literal env) (setq s!:current_block (cons arg2 s!:current_block)) (setq s!:current_size (plus s!:current_size 3)) (cond (( or !*plap !*pgwd) (setq s!:current_block (cons (cons op doc) s!:current_block )))))) (de s!:outlexref (op arg1 arg2 arg3 doc) (prog (arg4) (cond ((null s!:current_label) (return nil))) (cond ((or (greaterp arg1 255) (greaterp arg2 255) (greaterp arg3 255)) (progn (cond ((or (greaterp arg1 2047) ( greaterp arg2 31) (greaterp arg3 2047)) (error 0 "stack frame > 2047 or > 31 deep nesting"))) (setq doc (list op doc)) (setq arg4 (logand arg3 255)) (setq arg3 (plus (truncate arg3 256) (times 16 ( logand arg1 15)))) (cond ((equal op (quote LOADLEX)) (setq op (plus 192 arg2) )) (t (setq op (plus 224 arg2)))) (setq arg2 (truncate arg1 16)) (setq arg1 op) (setq op (quote BIGSTACK)))) (t (setq doc (list doc)))) (setq s!:current_block (cons arg3 (cons arg2 (cons arg1 (cons op s!:current_block)) ))) (setq s!:current_size (plus s!:current_size 4)) (cond (arg4 (progn (setq s!:current_block (cons arg4 s!:current_block)) (setq s!:current_size (plus s!:current_size 1))))) (cond ((or !*plap !*pgwd) (setq s!:current_block (cons (cons op doc) s!:current_block)))))) (put (quote LOADLIT) (quote s!:shortform) (cons (quote (1 . 7)) (s!:vecof ( quote (!- LOADLIT1 LOADLIT2 LOADLIT3 LOADLIT4 LOADLIT5 LOADLIT6 LOADLIT7))))) (put (quote LOADFREE) (quote s!:shortform) (cons (quote (1 . 4)) (s!:vecof ( quote (!- LOADFREE1 LOADFREE2 LOADFREE3 LOADFREE4))))) (put (quote STOREFREE) (quote s!:shortform) (cons (quote (1 . 3)) (s!:vecof ( quote (!- STOREFREE1 STOREFREE2 STOREFREE3))))) (put (quote CALL0) (quote s!:shortform) (cons (quote (0 . 3)) (s!:vecof ( quote (CALL0_0 CALL0_1 CALL0_2 CALL0_3))))) (put (quote CALL1) (quote s!:shortform) (cons (quote (0 . 5)) (s!:vecof ( quote (CALL1_0 CALL1_1 CALL1_2 CALL1_3 CALL1_4 CALL1_5))))) (put (quote CALL2) (quote s!:shortform) (cons (quote (0 . 4)) (s!:vecof ( quote (CALL2_0 CALL2_1 CALL2_2 CALL2_3 CALL2_4))))) (put (quote JUMPFREET) (quote s!:shortform) (cons (quote (1 . 4)) (s!:vecof ( quote (!- JUMPFREE1T JUMPFREE2T JUMPFREE3T JUMPFREE4T))))) (put (quote JUMPFREENIL) (quote s!:shortform) (cons (quote (1 . 4)) (s!:vecof (quote (!- JUMPFREE1NIL JUMPFREE2NIL JUMPFREE3NIL JUMPFREE4NIL))))) (put (quote JUMPLITEQ) (quote s!:shortform) (cons (quote (1 . 4)) (s!:vecof ( quote (!- JUMPLIT1EQ JUMPLIT2EQ JUMPLIT3EQ JUMPLIT4EQ))))) (put (quote JUMPLITNE) (quote s!:shortform) (cons (quote (1 . 4)) (s!:vecof ( quote (!- JUMPLIT1NE JUMPLIT2NE JUMPLIT3NE JUMPLIT4NE))))) (put (quote JUMPLITEQ!*) (quote s!:shortform) (get (quote JUMPLITEQ) (quote s!:shortform))) (put (quote JUMPLITNE!*) (quote s!:shortform) (get (quote JUMPLITNE) (quote s!:shortform))) (put (quote CALL0) (quote s!:longform) 0) (put (quote CALL1) (quote s!:longform) 16) (put (quote CALL2) (quote s!:longform) 32) (put (quote CALL3) (quote s!:longform) 48) (put (quote CALLN) (quote s!:longform) 64) (put (quote CALL2R) (quote s!:longform) 80) (put (quote LOADFREE) (quote s!:longform) 96) (put (quote STOREFREE) (quote s!:longform) 112) (put (quote JCALL0) (quote s!:longform) 128) (put (quote JCALL1) (quote s!:longform) 144) (put (quote JCALL2) (quote s!:longform) 160) (put (quote JCALL3) (quote s!:longform) 176) (put (quote JCALLN) (quote s!:longform) 192) (put (quote FREEBIND) (quote s!:longform) 208) (put (quote LITGET) (quote s!:longform) 224) (put (quote LOADLIT) (quote s!:longform) 240) (de s!:literal_order (a b) (cond ((equal (cadr a) (cadr b)) (orderp (car a) ( car b))) (t (greaterp (cadr a) (cadr b))))) (de s!:resolve_literals (env checksum) (prog (w op opspec n litbytes) (setq w (hashcontents (car env))) (setq w (sort w (function s!:literal_order))) ( setq w (append w (list (list checksum 0)))) (setq n (length w)) (setq litbytes (times 4 n)) (cond ((greaterp n 4096) (setq w (s!:too_many_literals w n)))) (setq n 0) (prog (var1011) (setq var1011 w) lab1010 (cond ((null var1011) (return nil))) (prog (x) (setq x (car var1011)) (progn (rplaca (cdr x) n) (setq n (plus n 1)))) (setq var1011 (cdr var1011)) (go lab1010)) (prog (var1015) (setq var1015 w) lab1014 (cond ((null var1015) (return nil))) (prog (x) (setq x (car var1015)) (progn (setq n (cadr x)) (prog (var1013) (setq var1013 (cddr x)) lab1012 (cond ((null var1013) (return nil))) (prog (y) ( setq y (car var1013)) (progn (cond ((null (car y)) (progn (setq op (caadr y)) (setq opspec (get op (quote s!:shortform))) (cond ((and opspec (leq (caar opspec) n) (leq n (cdar opspec))) (rplaca (cdr y) (getv (cdr opspec) n))) (t (rplaca (cdadr y) n))))) (t (progn (setq op (caddr y)) (cond ((greaterp n 255 ) (progn (rplaca (car y) (plus (caar y) 1)) (setq op (plus (get op (quote s!:longform)) (truncate n 256))) (rplaca (cdr y) (ilogand n 255)) (rplaca ( cddr y) (quote BIGCALL)) (rplacd (cdr y) (cons op (cddr y))))) (t (cond ((and (setq opspec (get op (quote s!:shortform))) (leq (caar opspec) n) (leq n ( cdar opspec))) (progn (rplaca (car y) (difference (caar y) 1)) (rplaca (cdr y ) (getv (cdr opspec) n)) (rplacd (cdr y) (cdddr y)))) (t (rplaca (cdr y) n))) ))))))) (setq var1013 (cdr var1013)) (go lab1012)))) (setq var1015 (cdr var1015)) (go lab1014)) (prog (var1017) (setq var1017 w) lab1016 (cond ((null var1017) (return nil))) (prog (x) (setq x (car var1017)) (rplacd x (cadr x)) ) (setq var1017 (cdr var1017)) (go lab1016)) (rplaca env (cons (reversip w) litbytes)))) (de s!:only_loadlit (l) (cond ((null l) t) (t (cond ((null (caar l)) nil) (t (cond ((not (eqcar (cddar l) (quote LOADLIT))) nil) (t (s!:only_loadlit (cdr l))))))))) (de s!:too_many_literals (w n) (prog (k xvecs l r newrefs uses z1) (setq k 0) (setq n (plus n 1)) (prog nil lab1018 (cond ((null (and (greaterp n 4096) ( not (null w)))) (return nil))) (progn (cond ((and (not (equal (cadar w) 10000000)) (s!:only_loadlit (cddar w))) (progn (setq l (cons (car w) l)) ( setq n (difference n 1)) (setq k (plus k 1)) (cond ((equal k 256) (progn ( setq xvecs (cons l xvecs)) (setq l nil) (setq k 0) (setq n (plus n 1))))))) ( t (setq r (cons (car w) r)))) (setq w (cdr w))) (go lab1018)) (cond (( greaterp n 4096) (error 0 "function uses too many literals (4096 is limit)")) ) (setq xvecs (cons l xvecs)) (prog nil lab1019 (cond ((null r) (return nil)) ) (progn (setq w (cons (car r) w)) (setq r (cdr r))) (go lab1019)) (prog ( var1025) (setq var1025 xvecs) lab1024 (cond ((null var1025) (return nil))) ( prog (v) (setq v (car var1025)) (progn (setq newrefs nil) (setq uses 0) (setq r nil) (setq k 0) (prog (var1023) (setq var1023 v) lab1022 (cond ((null var1023) (return nil))) (prog (q) (setq q (car var1023)) (progn (prog ( var1021) (setq var1021 (cddr q)) lab1020 (cond ((null var1021) (return nil))) (prog (z) (setq z (car var1021)) (progn (cond ((car z) (rplaca (car z) (plus (caar z) 2)))) (setq z1 (cons (quote QGETVN) (cons nil (cddr z)))) (rplaca ( cdr z) k) (rplacd (cdr z) z1) (rplacd z (cdr z1)) (setq newrefs (cons z newrefs)) (setq uses (plus uses 11)))) (setq var1021 (cdr var1021)) (go lab1020)) (setq r (cons (car q) r)) (setq k (plus k 1)))) (setq var1023 (cdr var1023)) (go lab1022)) (setq newrefs (cons uses newrefs)) (setq newrefs ( cons (s!:vecof (reversip r)) newrefs)) (setq w (cons newrefs w)))) (setq var1025 (cdr var1025)) (go lab1024)) (return (sort w (function s!:literal_order))))) (fluid (quote (s!:into_c))) (de s!:endprocedure (name env checksum) (prog (pc labelvals w vec) ( s!:outexit) (cond (s!:into_c (return (cons s!:current_procedure env)))) ( s!:resolve_literals env checksum) (setq s!:current_procedure ( s!:tidy_flowgraph s!:current_procedure)) (cond ((and (not !*notailcall) (not s!:has_closure)) (setq s!:current_procedure (s!:try_tailcall s!:current_procedure)))) (setq s!:current_procedure (s!:tidy_exits s!:current_procedure)) (setq labelvals (s!:resolve_labels)) (setq pc (car labelvals)) (setq labelvals (cdr labelvals)) (setq vec (make!-bps pc)) (setq pc 0) (cond ((or !*plap !*pgwd) (progn (terpri) (ttab 23) (princ "+++ ") ( prin name) (princ " +++") (terpri)))) (prog (var1027) (setq var1027 s!:current_procedure) lab1026 (cond ((null var1027) (return nil))) (prog (b) (setq b (car var1027)) (progn (cond ((and (car b) (flagp (car b) (quote used_label)) (or !*plap !*pgwd)) (progn (ttab 20) (prin (car b)) (princ ":") (terpri)))) (setq pc (s!:plant_basic_block vec pc (reverse (cdddr b)))) (setq b (cadr b)) (cond ((and b (neq (car b) (quote ICASE)) (cdr b) (cddr b)) ( setq b (list (car b) (cadr b))))) (setq pc (s!:plant_exit_code vec pc b labelvals)))) (setq var1027 (cdr var1027)) (go lab1026)) (cond (!*pwrds ( progn (cond ((neq (posn) 0) (terpri))) (princ "+++ ") (prin name) (princ " compiled, ") (princ pc) (princ " + ") (princ (cdar env)) (princ " bytes") ( terpri)))) (setq env (caar env)) (cond ((null env) (setq w nil)) (t (progn ( setq w (mkvect (cdar env))) (prog nil lab1028 (cond ((null env) (return nil)) ) (progn (putv w (cdar env) (caar env)) (setq env (cdr env))) (go lab1028)))) ) (return (cons vec w)))) (de s!:add_pending (lab pend blocks) (prog (w) (cond ((not (atom lab)) ( return (cons (list (gensym) lab 0) pend)))) (setq w (atsoc lab pend)) (cond ( w (return (cons w (deleq w pend)))) (t (return (cons (atsoc lab blocks) pend) ))))) (de s!:invent_exit (x blocks) (prog (w) (setq w blocks) scan (cond ((null w) (go not_found)) (t (cond ((and (eqcar (cadar w) x) (equal (caddar w) 0)) ( return (cons (caar w) blocks))) (t (setq w (cdr w)))))) (go scan) not_found ( setq w (gensym)) (return (cons w (cons (list w (list x) 0) blocks))))) (de s!:destination_label (lab blocks) (prog (n w x) (setq w (atsoc lab blocks )) (cond ((s!:is_lose_and_exit w blocks) (return (quote (EXIT))))) (setq x ( cadr w)) (setq n (caddr w)) (setq w (cdddr w)) (cond ((neq n 0) (return lab)) ) (cond ((or (null x) (null (cdr x))) (return x)) (t (cond ((equal (cadr x) lab) (return lab)) (t (cond ((null (cddr x)) (return (s!:destination_label ( cadr x) blocks))) (t (return lab))))))))) (de s!:remlose (b) (prog (w) (setq w b) (prog nil lab1029 (cond ((null (and w (not (atom (car w))))) (return nil))) (setq w (cdr w)) (go lab1029)) (cond ( (null w) (return (cons 0 b)))) (cond ((and (numberp (car w)) (eqcar (cdr w) ( quote LOSES))) (setq w (cons 2 (cddr w)))) (t (cond ((or (equal (car w) ( quote LOSE)) (equal (car w) (quote LOSE2)) (equal (car w) (quote LOSE3))) ( setq w (cons 1 (cdr w)))) (t (return (cons 0 b)))))) (setq b (s!:remlose (cdr w))) (return (cons (plus (car w) (car b)) (cdr b))))) (put (quote CALL0_0) (quote s!:shortcall) (quote (0 . 0))) (put (quote CALL0_1) (quote s!:shortcall) (quote (0 . 1))) (put (quote CALL0_2) (quote s!:shortcall) (quote (0 . 2))) (put (quote CALL0_3) (quote s!:shortcall) (quote (0 . 3))) (put (quote CALL1_0) (quote s!:shortcall) (quote (1 . 0))) (put (quote CALL1_1) (quote s!:shortcall) (quote (1 . 1))) (put (quote CALL1_2) (quote s!:shortcall) (quote (1 . 2))) (put (quote CALL1_3) (quote s!:shortcall) (quote (1 . 3))) (put (quote CALL1_4) (quote s!:shortcall) (quote (1 . 4))) (put (quote CALL1_5) (quote s!:shortcall) (quote (1 . 5))) (put (quote CALL2_0) (quote s!:shortcall) (quote (2 . 0))) (put (quote CALL2_1) (quote s!:shortcall) (quote (2 . 1))) (put (quote CALL2_2) (quote s!:shortcall) (quote (2 . 2))) (put (quote CALL2_3) (quote s!:shortcall) (quote (2 . 3))) (put (quote CALL2_4) (quote s!:shortcall) (quote (2 . 4))) (de s!:remcall (b) (prog (w p q r s) (prog nil lab1030 (cond ((null (and b ( not (atom (car b))))) (return nil))) (progn (setq p (car b)) (setq b (cdr b)) ) (go lab1030)) (cond ((null b) (return nil)) (t (cond ((numberp (car b)) ( progn (setq r (car b)) (setq s 2) (setq b (cdr b)) (cond ((null b) (return nil)) (t (cond ((numberp (car b)) (progn (setq q r) (setq r (car b)) (setq s 3) (setq b (cdr b)) (cond ((and b (numberp (setq w (car b))) (eqcar (cdr b) ( quote BIGCALL)) (equal (truncate w 16) 4)) (progn (setq r (plus (times 256 ( logand w 15)) r)) (setq s 4) (setq b (cdr b)))) (t (cond ((eqcar b (quote BIGCALL)) (progn (setq w (truncate r 16)) (setq r (plus (times 256 (logand r 15)) q)) (setq q w) (cond ((equal q 5) (progn (setq q 2) (setq s (difference s 1)) (setq b (cons (quote BIGCALL) (cons (quote SWOP) (cdr b))))))) (cond (( greaterp q 4) (return nil))))) (t (cond ((not (eqcar b (quote CALLN))) ( return nil))))))))) (t (cond ((equal (car b) (quote CALL0)) (setq q 0)) (t ( cond ((equal (car b) (quote CALL1)) (setq q 1)) (t (cond ((equal (car b) ( quote CALL2)) (setq q 2)) (t (cond ((equal (car b) (quote CALL2R)) (progn ( setq q 2) (setq s (difference s 1)) (setq b (cons (quote CALL2) (cons (quote SWOP) (cdr b)))))) (t (cond ((equal (car b) (quote CALL3)) (setq q 3)) (t ( return nil))))))))))))))) (setq b (cdr b)))) (t (cond ((setq q (get (car b) ( quote s!:shortcall))) (progn (setq r (cdr q)) (setq q (car q)) (setq s 1) ( setq b (cdr b)))) (t (return nil))))))) (return (cons p (cons q (cons r (cons s b))))))) (de s!:is_lose_and_exit (b blocks) (prog (lab exit) (setq lab (car b)) (setq exit (cadr b)) (setq b (cdddr b)) (cond ((null exit) (return nil))) (setq b ( s!:remlose b)) (setq b (cdr b)) (prog nil lab1031 (cond ((null (and b (not ( atom (car b))))) (return nil))) (setq b (cdr b)) (go lab1031)) (cond (b ( return nil)) (t (cond ((equal (car exit) (quote EXIT)) (return t)) (t (cond ( (equal (car exit) (quote JUMP)) (progn (cond ((equal (cadr exit) lab) nil) (t (return (s!:is_lose_and_exit (atsoc (cadr exit) blocks) blocks)))))) (t ( return nil))))))))) (de s!:try_tail_1 (b blocks) (prog (exit size body w w0 w1 w2 op) (setq exit (cadr b)) (cond ((null exit) (return b)) (t (cond ((not (equal (car exit) ( quote EXIT))) (progn (cond ((equal (car exit) (quote JUMP)) (progn (cond (( not (s!:is_lose_and_exit (atsoc (cadr exit) blocks) blocks)) (return b))))) ( t (return b)))))))) (setq size (caddr b)) (setq body (cdddr b)) (setq body ( s!:remlose body)) (setq size (difference size (car body))) (setq body (cdr body)) (setq w (s!:remcall body)) (cond ((null w) (return b))) (setq w0 (cadr w)) (setq w1 (caddr w)) (setq body (cddddr w)) (cond ((and (leq w0 7) (leq w1 31)) (progn (setq body (cons (quote JCALL) body)) (setq body (cons (plus ( times 32 w0) w1) body)) (setq size (difference size 1)))) (t (cond ((lessp w1 256) (setq body (cons w0 (cons w1 (cons (quote JCALLN) body))))) (t (progn ( setq body (cons (quote BIGCALL) body)) (setq w2 (logand w1 255)) (setq w1 ( truncate w1 256)) (cond ((lessp w0 4) (setq body (cons w2 (cons (plus w1 ( times 16 w0) 128) body)))) (t (progn (setq body (cons w0 (cons w2 (cons (plus w1 (plus (times 16 4) 128)) body)))) (setq size (plus size 1)))))))))) (cond ((car w) (setq body (cons (append (car w) (list (quote TAIL))) body)))) ( rplaca (cdr b) nil) (rplaca (cddr b) (plus (difference size (cadddr w)) 3)) ( rplacd (cddr b) body) (return b))) (de s!:try_tailcall (b) (prog (var1033 var1034) (setq var1033 b) lab1032 ( cond ((null var1033) (return (reversip var1034)))) (prog (v) (setq v (car var1033)) (setq var1034 (cons (s!:try_tail_1 v b) var1034))) (setq var1033 ( cdr var1033)) (go lab1032))) (de s!:tidy_exits_1 (b blocks) (prog (exit size body comm w w0 w1 w2 op) ( setq exit (cadr b)) (cond ((null exit) (return b)) (t (cond ((not (equal (car exit) (quote EXIT))) (progn (cond ((equal (car exit) (quote JUMP)) (progn ( cond ((not (s!:is_lose_and_exit (atsoc (cadr exit) blocks) blocks)) (return b ))))) (t (return b)))))))) (setq size (caddr b)) (setq body (cdddr b)) (setq body (s!:remlose body)) (setq size (difference size (car body))) (setq body ( cdr body)) (prog nil lab1035 (cond ((null (and body (not (atom (car body))))) (return nil))) (progn (setq comm (car body)) (setq body (cdr body))) (go lab1035)) (cond ((eqcar body (quote VNIL)) (setq w (quote NILEXIT))) (t (cond ((eqcar body (quote LOADLOC0)) (setq w (quote LOC0EXIT))) (t (cond ((eqcar body (quote LOADLOC1)) (setq w (quote LOC1EXIT))) (t (cond ((eqcar body ( quote LOADLOC2)) (setq w (quote LOC2EXIT))) (t (setq w nil))))))))) (cond (w (progn (rplaca (cdr b) (list w)) (setq body (cdr body)) (setq size ( difference size 1)))) (t (cond (comm (setq body (cons comm body)))))) (rplaca (cddr b) size) (rplacd (cddr b) body) (return b))) (de s!:tidy_exits (b) (prog (var1037 var1038) (setq var1037 b) lab1036 (cond ((null var1037) (return (reversip var1038)))) (prog (v) (setq v (car var1037) ) (setq var1038 (cons (s!:tidy_exits_1 v b) var1038))) (setq var1037 (cdr var1037)) (go lab1036))) (de s!:tidy_flowgraph (b) (prog (r pending) (setq b (reverse b)) (setq pending (list (car b))) (prog nil lab1040 (cond ((null pending) (return nil)) ) (prog (c x l1 l2 done1 done2) (setq c (car pending)) (setq pending (cdr pending)) (flag (list (car c)) (quote coded)) (setq x (cadr c)) (cond ((or ( null x) (null (cdr x))) (setq r (cons c r))) (t (cond ((equal (car x) (quote ICASE)) (progn (rplacd x (reversip (cdr x))) (prog (ll) (setq ll (cdr x)) lab1039 (cond ((null ll) (return nil))) (progn (setq l1 (s!:destination_label (car ll) b)) (cond ((not (atom l1)) (progn (setq l1 (s!:invent_exit (car l1) b)) (setq b (cdr l1)) (setq l1 (cadr l1))))) (rplaca ll l1) (setq done1 ( flagp l1 (quote coded))) (flag (list l1) (quote used_label)) (cond ((not done1) (setq pending (s!:add_pending l1 pending b))))) (setq ll (cdr ll)) (go lab1039)) (rplacd x (reversip (cdr x))) (setq r (cons c r)))) (t (cond (( null (cddr x)) (progn (setq l1 (s!:destination_label (cadr x) b)) (cond ((not (atom l1)) (setq c (cons (car c) (cons l1 (cddr c))))) (t (cond ((flagp l1 ( quote coded)) (progn (flag (list l1) (quote used_label)) (setq c (cons (car c ) (cons (list (car x) l1) (cddr c)))))) (t (progn (setq c (cons (car c) (cons nil (cddr c)))) (setq pending (s!:add_pending l1 pending b))))))) (setq r ( cons c r)))) (t (progn (setq l1 (s!:destination_label (cadr x) b)) (setq l2 ( s!:destination_label (caddr x) b)) (setq done1 (and (atom l1) (flagp l1 ( quote coded)))) (setq done2 (and (atom l2) (flagp l2 (quote coded)))) (cond ( done1 (progn (cond (done2 (progn (flag (list l1) (quote used_label)) (rplaca (cdadr c) l1) (setq pending (cons (list (gensym) (list (quote JUMP) l2) 0) pending)))) (t (progn (flag (list l1) (quote used_label)) (rplaca (cdadr c) l1) (setq pending (s!:add_pending l2 pending b))))))) (t (progn (cond (done2 (progn (flag (list l2) (quote used_label)) (rplaca (cadr c) (s!:negate_jump ( car x))) (rplaca (cdadr c) l2) (setq pending (s!:add_pending l1 pending b)))) (t (progn (cond ((not (atom l1)) (progn (setq l1 (s!:invent_exit (car l1) b) ) (setq b (cdr l1)) (setq l1 (car l1))))) (flag (list l1) (quote used_label)) (rplaca (cdadr c) l1) (cond ((not (flagp l1 (quote coded))) (setq pending ( s!:add_pending l1 pending b)))) (setq pending (s!:add_pending l2 pending b))) ))))) (setq r (cons c r)))))))))) (go lab1040)) (return (reverse r)))) (deflist (quote ((JUMPNIL JUMPT) (JUMPT JUMPNIL) (JUMPATOM JUMPNATOM) ( JUMPNATOM JUMPATOM) (JUMPEQ JUMPNE) (JUMPNE JUMPEQ) (JUMPEQUAL JUMPNEQUAL) ( JUMPNEQUAL JUMPEQUAL) (JUMPL0NIL JUMPL0T) (JUMPL0T JUMPL0NIL) (JUMPL1NIL JUMPL1T) (JUMPL1T JUMPL1NIL) (JUMPL2NIL JUMPL2T) (JUMPL2T JUMPL2NIL) ( JUMPL3NIL JUMPL3T) (JUMPL3T JUMPL3NIL) (JUMPL4NIL JUMPL4T) (JUMPL4T JUMPL4NIL ) (JUMPL0ATOM JUMPL0NATOM) (JUMPL0NATOM JUMPL0ATOM) (JUMPL1ATOM JUMPL1NATOM) (JUMPL1NATOM JUMPL1ATOM) (JUMPL2ATOM JUMPL2NATOM) (JUMPL2NATOM JUMPL2ATOM) ( JUMPL3ATOM JUMPL3NATOM) (JUMPL3NATOM JUMPL3ATOM) (JUMPST0NIL JUMPST0T) ( JUMPST0T JUMPST0NIL) (JUMPST1NIL JUMPST1T) (JUMPST1T JUMPST1NIL) (JUMPST2NIL JUMPST2T) (JUMPST2T JUMPST2NIL) (JUMPFREE1NIL JUMPFREE1T) (JUMPFREE1T JUMPFREE1NIL) (JUMPFREE2NIL JUMPFREE2T) (JUMPFREE2T JUMPFREE2NIL) ( JUMPFREE3NIL JUMPFREE3T) (JUMPFREE3T JUMPFREE3NIL) (JUMPFREE4NIL JUMPFREE4T) (JUMPFREE4T JUMPFREE4NIL) (JUMPFREENIL JUMPFREET) (JUMPFREET JUMPFREENIL) ( JUMPLIT1EQ JUMPLIT1NE) (JUMPLIT1NE JUMPLIT1EQ) (JUMPLIT2EQ JUMPLIT2NE) ( JUMPLIT2NE JUMPLIT2EQ) (JUMPLIT3EQ JUMPLIT3NE) (JUMPLIT3NE JUMPLIT3EQ) ( JUMPLIT4EQ JUMPLIT4NE) (JUMPLIT4NE JUMPLIT4EQ) (JUMPLITEQ JUMPLITNE) ( JUMPLITNE JUMPLITEQ) (JUMPLITEQ!* JUMPLITNE!*) (JUMPLITNE!* JUMPLITEQ!*) ( JUMPB1NIL JUMPB1T) (JUMPB1T JUMPB1NIL) (JUMPB2NIL JUMPB2T) (JUMPB2T JUMPB2NIL ) (JUMPFLAGP JUMPNFLAGP) (JUMPNFLAGP JUMPFLAGP) (JUMPEQCAR JUMPNEQCAR) ( JUMPNEQCAR JUMPEQCAR))) (quote negjump)) (de s!:negate_jump (x) (cond ((atom x) (get x (quote negjump))) (t (rplaca x (get (car x) (quote negjump)))))) (de s!:resolve_labels nil (prog (w labelvals converged pc x) (prog nil lab1043 (progn (setq converged t) (setq pc 0) (prog (var1042) (setq var1042 s!:current_procedure) lab1041 (cond ((null var1042) (return nil))) (prog (b) (setq b (car var1042)) (progn (setq w (assoc!*!* (car b) labelvals)) (cond (( null w) (progn (setq converged nil) (setq w (cons (car b) pc)) (setq labelvals (cons w labelvals)))) (t (cond ((neq (cdr w) pc) (progn (rplacd w pc) (setq converged nil)))))) (setq pc (plus pc (caddr b))) (setq x (cadr b)) (cond ((null x) nil) (t (cond ((null (cdr x)) (setq pc (plus pc 1))) (t ( cond ((equal (car x) (quote ICASE)) (setq pc (plus pc (times 2 (length x))))) (t (progn (setq w (assoc!*!* (cadr x) labelvals)) (cond ((null w) (progn ( setq w 128) (setq converged nil))) (t (setq w (difference (cdr w) pc)))) ( setq w (s!:expand_jump (car x) w)) (setq pc (plus pc (length w)))))))))))) ( setq var1042 (cdr var1042)) (go lab1041))) (cond ((null converged) (go lab1043)))) (return (cons pc labelvals)))) (de s!:plant_basic_block (vec pc b) (prog (tagged) (prog (var1047) (setq var1047 b) lab1046 (cond ((null var1047) (return nil))) (prog (i) (setq i ( car var1047)) (progn (cond ((atom i) (progn (cond ((symbolp i) (setq i (get i (quote s!:opcode))))) (cond ((and (not tagged) (or !*plap !*pgwd)) (progn ( s!:prinhex4 pc) (princ ":") (ttab 8) (setq tagged t)))) (cond ((or (not (fixp i)) (lessp i 0) (greaterp i 255)) (error "bad byte to put" i))) (bps!-putv vec pc i) (cond ((or !*plap !*pgwd) (progn (s!:prinhex2 i) (princ " ")))) ( setq pc (plus pc 1)))) (t (cond ((or !*plap !*pgwd) (progn (ttab 23) (princ ( car i)) (prog (var1045) (setq var1045 (cdr i)) lab1044 (cond ((null var1045) (return nil))) (prog (w) (setq w (car var1045)) (progn (princ " ") (prin w))) (setq var1045 (cdr var1045)) (go lab1044)) (terpri) (setq tagged nil)))))))) (setq var1047 (cdr var1047)) (go lab1046)) (return pc))) (de s!:plant_bytes (vec pc bytelist doc) (prog nil (cond ((or !*plap !*pgwd) (progn (s!:prinhex4 pc) (princ ":") (ttab 8)))) (prog (var1049) (setq var1049 bytelist) lab1048 (cond ((null var1049) (return nil))) (prog (v) (setq v ( car var1049)) (progn (cond ((symbolp v) (setq v (get v (quote s!:opcode))))) (cond ((or (not (fixp v)) (lessp v 0) (greaterp v 255)) (error "bad byte to put" v))) (bps!-putv vec pc v) (cond ((or !*plap !*pgwd) (progn (cond ((greaterp (posn) 50) (progn (terpri) (ttab 8)))) (s!:prinhex2 v) ( princ " ")))) (setq pc (plus pc 1)))) (setq var1049 (cdr var1049)) (go lab1048)) (cond ((or !*plap !*pgwd) (progn (cond ((greaterp (posn) 23) ( terpri))) (ttab 23) (princ (car doc)) (prog (var1051) (setq var1051 (cdr doc) ) lab1050 (cond ((null var1051) (return nil))) (prog (w) (setq w (car var1051 )) (progn (cond ((greaterp (posn) 65) (progn (terpri) (ttab 23)))) (princ " " ) (prin w))) (setq var1051 (cdr var1051)) (go lab1050)) (terpri)))) (return pc))) (de s!:plant_exit_code (vec pc b labelvals) (prog (w loc low high r) (cond (( null b) (return pc)) (t (cond ((null (cdr b)) (return (s!:plant_bytes vec pc (list (get (car b) (quote s!:opcode))) b))) (t (cond ((equal (car b) (quote ICASE)) (progn (setq loc (plus pc 3)) (prog (var1053) (setq var1053 (cdr b)) lab1052 (cond ((null var1053) (return nil))) (prog (ll) (setq ll (car var1053 )) (progn (setq w (difference (cdr (assoc!*!* ll labelvals)) loc)) (setq loc (plus loc 2)) (cond ((lessp w 0) (progn (setq w (minus w)) (setq low (ilogand w 255)) (setq high (plus 128 (truncate (difference w low) 256))))) (t (progn (setq low (ilogand w 255)) (setq high (truncate (difference w low) 256))))) (setq r (cons low (cons high r))))) (setq var1053 (cdr var1053)) (go lab1052) ) (setq r (cons (get (quote ICASE) (quote s!:opcode)) (cons (length (cddr b)) (reversip r)))) (return (s!:plant_bytes vec pc r b))))))))) (setq w ( difference (cdr (assoc!*!* (cadr b) labelvals)) pc)) (setq w (s!:expand_jump (car b) w)) (return (s!:plant_bytes vec pc w b)))) (deflist (quote ((JUMPL0NIL ((LOADLOC0) JUMPNIL)) (JUMPL0T ((LOADLOC0) JUMPT) ) (JUMPL1NIL ((LOADLOC1) JUMPNIL)) (JUMPL1T ((LOADLOC1) JUMPT)) (JUMPL2NIL (( LOADLOC2) JUMPNIL)) (JUMPL2T ((LOADLOC2) JUMPT)) (JUMPL3NIL ((LOADLOC3) JUMPNIL)) (JUMPL3T ((LOADLOC3) JUMPT)) (JUMPL4NIL ((LOADLOC4) JUMPNIL)) ( JUMPL4T ((LOADLOC4) JUMPT)) (JUMPL0ATOM ((LOADLOC0) JUMPATOM)) (JUMPL0NATOM ( (LOADLOC0) JUMPNATOM)) (JUMPL1ATOM ((LOADLOC1) JUMPATOM)) (JUMPL1NATOM (( LOADLOC1) JUMPNATOM)) (JUMPL2ATOM ((LOADLOC2) JUMPATOM)) (JUMPL2NATOM (( LOADLOC2) JUMPNATOM)) (JUMPL3ATOM ((LOADLOC3) JUMPATOM)) (JUMPL3NATOM (( LOADLOC3) JUMPNATOM)) (JUMPST0NIL ((STORELOC0) JUMPNIL)) (JUMPST0T (( STORELOC0) JUMPT)) (JUMPST1NIL ((STORELOC1) JUMPNIL)) (JUMPST1T ((STORELOC1) JUMPT)) (JUMPST2NIL ((STORELOC2) JUMPNIL)) (JUMPST2T ((STORELOC2) JUMPT)) ( JUMPFREE1NIL ((LOADFREE1) JUMPNIL)) (JUMPFREE1T ((LOADFREE1) JUMPT)) ( JUMPFREE2NIL ((LOADFREE2) JUMPNIL)) (JUMPFREE2T ((LOADFREE2) JUMPT)) ( JUMPFREE3NIL ((LOADFREE3) JUMPNIL)) (JUMPFREE3T ((LOADFREE3) JUMPT)) ( JUMPFREE4NIL ((LOADFREE4) JUMPNIL)) (JUMPFREE4T ((LOADFREE4) JUMPT)) ( JUMPFREENIL ((LOADFREE !*) JUMPNIL)) (JUMPFREET ((LOADFREE !*) JUMPT)) ( JUMPLIT1EQ ((LOADLIT1) JUMPEQ)) (JUMPLIT1NE ((LOADLIT1) JUMPNE)) (JUMPLIT2EQ ((LOADLIT2) JUMPEQ)) (JUMPLIT2NE ((LOADLIT2) JUMPNE)) (JUMPLIT3EQ ((LOADLIT3) JUMPEQ)) (JUMPLIT3NE ((LOADLIT3) JUMPNE)) (JUMPLIT4EQ ((LOADLIT4) JUMPEQ)) ( JUMPLIT4NE ((LOADLIT4) JUMPNE)) (JUMPLITEQ ((LOADLIT !*) JUMPEQ)) (JUMPLITNE ((LOADLIT !*) JUMPNE)) (JUMPLITEQ!* ((LOADLIT !* SWOP) JUMPEQ)) (JUMPLITNE!* ((LOADLIT !* SWOP) JUMPNE)) (JUMPB1NIL ((BUILTIN1 !*) JUMPNIL)) (JUMPB1T (( BUILTIN1 !*) JUMPT)) (JUMPB2NIL ((BUILTIN2 !*) JUMPNIL)) (JUMPB2T ((BUILTIN2 !*) JUMPT)) (JUMPFLAGP ((LOADLIT !* FLAGP) JUMPT)) (JUMPNFLAGP ((LOADLIT !* FLAGP) JUMPNIL)) (JUMPEQCAR ((LOADLIT !* EQCAR) JUMPT)) (JUMPNEQCAR ((LOADLIT !* EQCAR) JUMPNIL)))) (quote s!:expand_jump)) (fluid (quote (s!:backwards_jump s!:longer_jump))) (progn (setq s!:backwards_jump (make!-simple!-string 256)) (setq s!:longer_jump (make!-simple!-string 256)) nil) (prog (var1055) (setq var1055 (quote ((JUMP JUMP_B JUMP_L JUMP_BL) (JUMPNIL JUMPNIL_B JUMPNIL_L JUMPNIL_BL) (JUMPT JUMPT_B JUMPT_L JUMPT_BL) (JUMPATOM JUMPATOM_B JUMPATOM_L JUMPATOM_BL) (JUMPNATOM JUMPNATOM_B JUMPNATOM_L JUMPNATOM_BL) (JUMPEQ JUMPEQ_B JUMPEQ_L JUMPEQ_BL) (JUMPNE JUMPNE_B JUMPNE_L JUMPNE_BL) (JUMPEQUAL JUMPEQUAL_B JUMPEQUAL_L JUMPEQUAL_BL) (JUMPNEQUAL JUMPNEQUAL_B JUMPNEQUAL_L JUMPNEQUAL_BL) (CATCH CATCH_B CATCH_L CATCH_BL)))) lab1054 (cond ((null var1055) (return nil))) (prog (op) (setq op (car var1055 )) (progn (putv!-char s!:backwards_jump (get (car op) (quote s!:opcode)) (get (cadr op) (quote s!:opcode))) (putv!-char s!:backwards_jump (get (caddr op) (quote s!:opcode)) (get (cadddr op) (quote s!:opcode))) (putv!-char s!:longer_jump (get (car op) (quote s!:opcode)) (get (caddr op) (quote s!:opcode))) (putv!-char s!:longer_jump (get (cadr op) (quote s!:opcode)) ( get (cadddr op) (quote s!:opcode))))) (setq var1055 (cdr var1055)) (go lab1054)) (de s!:expand_jump (op offset) (prog (arg low high opcode expanded) (cond (( not (atom op)) (progn (setq arg (cadr op)) (setq op (car op)) (setq offset ( difference offset 1))))) (setq expanded (get op (quote s!:expand_jump))) ( cond ((and expanded (not (and (leq 2 offset) (lessp offset (plus 256 2)) (or (null arg) (lessp arg 256))))) (progn (setq op (cadr expanded)) (setq expanded (car expanded)) (cond (arg (progn (cond ((greaterp arg 2047) (error 0 "function uses too many literals (2048 limit)")) (t (cond ((greaterp arg 255) (prog (high low) (setq low (ilogand arg 255)) (setq high (truncate ( difference arg low) 256)) (setq expanded (cons (quote BIGCALL) (cons (plus ( get (car expanded) (quote s!:longform)) high) (cons low (cddr expanded))))))) (t (setq expanded (subst arg (quote !*) expanded)))))) (setq offset (plus offset 1))))) (setq offset (difference offset (length expanded))) (setq arg nil))) (t (setq expanded nil))) (setq opcode (get op (quote s!:opcode))) ( cond ((null opcode) (error 0 (list op offset "invalid block exit")))) (cond ( (and (lessp (plus (minus 256) 2) offset) (lessp offset (plus 256 2))) (setq offset (difference offset 2))) (t (progn (setq high t) (setq offset ( difference offset 3))))) (cond ((lessp offset 0) (progn (setq opcode ( byte!-getv s!:backwards_jump opcode)) (setq offset (minus offset))))) (cond ( high (progn (setq low (logand offset 255)) (setq high (truncate (difference offset low) 256)))) (t (cond ((greaterp (setq low offset) 255) (error 0 "Bad offset in expand_jump"))))) (cond (arg (return (list opcode arg low))) ( t (cond ((not high) (return (append expanded (list opcode low)))) (t (return (append expanded (list (byte!-getv s!:longer_jump opcode) high low))))))))) (de s!:comval (x env context) (prog (helper) (setq x (s!:improve x)) (cond (( atom x) (return (s!:comatom x env context))) (t (cond ((eqcar (car x) (quote lambda)) (return (s!:comlambda (cadar x) (cddar x) (cdr x) env context))) (t (cond ((eq (car x) s!:current_function) (s!:comcall x env context)) (t (cond ((and (setq helper (get (car x) (quote s!:compilermacro))) (setq helper ( funcall helper x env context))) (return (s!:comval helper env context))) (t ( cond ((setq helper (get (car x) (quote s!:newname))) (return (s!:comval (cons helper (cdr x)) env context))) (t (cond ((setq helper (get (car x) (quote s!:compfn))) (return (funcall helper x env context))) (t (cond ((setq helper (macro!-function (car x))) (return (s!:comval (funcall helper x) env context) )) (t (return (s!:comcall x env context)))))))))))))))))) (de s!:comspecform (x env context) (error 0 (list "special form" x))) (cond ((null (get (quote and) (quote s!:compfn))) (progn (put (quote compiler!-let) (quote s!:compfn) (function s!:comspecform)) (put (quote de) ( quote s!:compfn) (function s!:comspecform)) (put (quote defun) (quote s!:compfn) (function s!:comspecform)) (put (quote eval!-when) (quote s!:compfn) (function s!:comspecform)) (put (quote flet) (quote s!:compfn) ( function s!:comspecform)) (put (quote labels) (quote s!:compfn) (function s!:comspecform)) (put (quote macrolet) (quote s!:compfn) (function s!:comspecform)) (put (quote multiple!-value!-call) (quote s!:compfn) ( function s!:comspecform)) (put (quote multiple!-value!-prog1) (quote s!:compfn) (function s!:comspecform)) (put (quote prog!*) (quote s!:compfn) ( function s!:comspecform)) (put (quote progv) (quote s!:compfn) (function s!:comspecform)) nil))) (de s!:improve (u) (prog (w) (cond ((atom u) (return u)) (t (cond ((setq w ( get (car u) (quote s!:tidy_fn))) (return (funcall w u))) (t (cond ((setq w ( get (car u) (quote s!:newname))) (return (s!:improve (cons w (cdr u))))) (t ( return u))))))))) (de s!:imp_minus (u) (prog (a) (setq a (s!:improve (cadr u))) (return (cond ( (numberp a) (minus a)) (t (cond ((or (eqcar a (quote minus)) (eqcar a (quote iminus))) (cadr a)) (t (cond ((eqcar a (quote difference)) (s!:improve (list (quote difference) (caddr a) (cadr a)))) (t (cond ((eqcar a (quote idifference)) (s!:improve (list (quote idifference) (caddr a) (cadr a)))) (t (list (car u) a)))))))))))) (put (quote minus) (quote s!:tidy_fn) (quote s!:imp_minus)) (put (quote iminus) (quote s!:tidy_fn) (quote s!:imp_minus)) (de s!:imp_times (u) (prog (a b) (cond ((not (equal (length u) 3)) (return ( cons (car u) (prog (var1057 var1058) (setq var1057 (cdr u)) lab1056 (cond (( null var1057) (return (reversip var1058)))) (prog (v) (setq v (car var1057)) (setq var1058 (cons (s!:improve v) var1058))) (setq var1057 (cdr var1057)) ( go lab1056)))))) (setq a (s!:improve (cadr u))) (setq b (s!:improve (caddr u) )) (return (cond ((equal a 1) b) (t (cond ((equal b 1) a) (t (cond ((equal a (minus 1)) (s!:imp_minus (list (quote minus) b))) (t (cond ((equal b (minus 1 )) (s!:imp_minus (list (quote minus) a))) (t (list (car u) a b)))))))))))) (put (quote times) (quote s!:tidy_fn) (quote s!:imp_times)) (de s!:imp_itimes (u) (prog (a b) (cond ((not (equal (length u) 3)) (return ( cons (car u) (prog (var1060 var1061) (setq var1060 (cdr u)) lab1059 (cond (( null var1060) (return (reversip var1061)))) (prog (v) (setq v (car var1060)) (setq var1061 (cons (s!:improve v) var1061))) (setq var1060 (cdr var1060)) ( go lab1059)))))) (setq a (s!:improve (cadr u))) (setq b (s!:improve (caddr u) )) (return (cond ((equal a 1) b) (t (cond ((equal b 1) a) (t (cond ((equal a (minus 1)) (s!:imp_minus (list (quote iminus) b))) (t (cond ((equal b (minus 1)) (s!:imp_minus (list (quote iminus) a))) (t (list (car u) a b)))))))))))) (put (quote itimes) (quote s!:tidy_fn) (quote s!:imp_itimes)) (de s!:imp_difference (u) (prog (a b) (setq a (s!:improve (cadr u))) (setq b (s!:improve (caddr u))) (return (cond ((equal a 0) (s!:imp_minus (list (quote minus) b))) (t (cond ((equal b 0) a) (t (list (car u) a b)))))))) (put (quote difference) (quote s!:tidy_fn) (quote s!:imp_difference)) (de s!:imp_idifference (u) (prog (a b) (setq a (s!:improve (cadr u))) (setq b (s!:improve (caddr u))) (return (cond ((equal a 0) (s!:imp_minus (list ( quote iminus) b))) (t (cond ((equal b 0) a) (t (list (car u) a b)))))))) (put (quote idifference) (quote s!:tidy_fn) (quote s!:imp_idifference)) (de s!:boolean_jumpable (u) (or (null u) (equal u t) (and (not (atom u)) ( atom (car u)) (or (flagp (car u) (quote s!:bool_opcode)) (and (or (equal (car u) (quote and)) (equal (car u) (quote or))) (s!:boolean_jumpable_list (cdr u ))))))) (de s!:boolean_jumpable_list (u) (or (atom u) (and (s!:boolean_jumpable (car u)) (s!:boolean_jumpable_list (cdr u))))) (flag (quote (null not eq equal neq eqcar atom flagp)) (quote s!:bool_opcode) ) (de s!:imp_or (u) (prog (w x) (setq w (cdr u)) (cond ((atom w) (return nil))) (setq x (car w)) (cond ((atom (cdr w)) (return (s!:improve x))) (t (cond (( s!:boolean_jumpable x) (return (list (quote cond) (list x t) (list t ( s!:imp_or (cons (quote or) (cdr w))))))) (t (return (list (quote or) ( s!:improve x) (s!:imp_or (cons (quote or) (cdr w))))))))))) (put (quote or) (quote s!:tidy_fn) (quote s!:imp_or)) (de s!:imp_and (u) (prog (w x) (setq w (cdr u)) (cond ((atom w) (return t))) (setq x (car w)) (cond ((atom (cdr w)) (return x)) (t (cond (( s!:boolean_jumpable x) (return (list (quote cond) (list x (s!:imp_and (cons ( quote and) (cdr w)))) (list t nil)))) (t (return (list (quote and) ( s!:improve x) (s!:imp_and (cons (quote and) (cdr w))))))))))) (put (quote and) (quote s!:tidy_fn) (quote s!:imp_and)) (de s!:alwayseasy (x) t) (put (quote quote) (quote s!:helpeasy) (function s!:alwayseasy)) (put (quote function) (quote s!:helpeasy) (function s!:alwayseasy)) (de s!:easyifarg (x) (or (null (cdr x)) (and (null (cddr x)) (s!:iseasy (cadr x))))) (put (quote ncons) (quote s!:helpeasy) (function s!:easyifarg)) (put (quote car) (quote s!:helpeasy) (function s!:easyifarg)) (put (quote cdr) (quote s!:helpeasy) (function s!:easyifarg)) (put (quote caar) (quote s!:helpeasy) (function s!:easyifarg)) (put (quote cadr) (quote s!:helpeasy) (function s!:easyifarg)) (put (quote cdar) (quote s!:helpeasy) (function s!:easyifarg)) (put (quote cddr) (quote s!:helpeasy) (function s!:easyifarg)) (put (quote caaar) (quote s!:helpeasy) (function s!:easyifarg)) (put (quote caadr) (quote s!:helpeasy) (function s!:easyifarg)) (put (quote cadar) (quote s!:helpeasy) (function s!:easyifarg)) (put (quote caddr) (quote s!:helpeasy) (function s!:easyifarg)) (put (quote cdaar) (quote s!:helpeasy) (function s!:easyifarg)) (put (quote cdadr) (quote s!:helpeasy) (function s!:easyifarg)) (put (quote cddar) (quote s!:helpeasy) (function s!:easyifarg)) (put (quote cdddr) (quote s!:helpeasy) (function s!:easyifarg)) (put (quote caaaar) (quote s!:helpeasy) (function s!:easyifarg)) (put (quote caaadr) (quote s!:helpeasy) (function s!:easyifarg)) (put (quote caadar) (quote s!:helpeasy) (function s!:easyifarg)) (put (quote caaddr) (quote s!:helpeasy) (function s!:easyifarg)) (put (quote cadaar) (quote s!:helpeasy) (function s!:easyifarg)) (put (quote cadadr) (quote s!:helpeasy) (function s!:easyifarg)) (put (quote caddar) (quote s!:helpeasy) (function s!:easyifarg)) (put (quote cadddr) (quote s!:helpeasy) (function s!:easyifarg)) (put (quote cdaaar) (quote s!:helpeasy) (function s!:easyifarg)) (put (quote cdaadr) (quote s!:helpeasy) (function s!:easyifarg)) (put (quote cdadar) (quote s!:helpeasy) (function s!:easyifarg)) (put (quote cdaddr) (quote s!:helpeasy) (function s!:easyifarg)) (put (quote cddaar) (quote s!:helpeasy) (function s!:easyifarg)) (put (quote cddadr) (quote s!:helpeasy) (function s!:easyifarg)) (put (quote cdddar) (quote s!:helpeasy) (function s!:easyifarg)) (put (quote cddddr) (quote s!:helpeasy) (function s!:easyifarg)) (de s!:easygetv (x) (prog (a2) (setq a2 (caddr x)) (cond ((and (null !*carcheckflag) (fixp a2) (geq a2 0) (lessp a2 256)) (return (s!:iseasy (cadr x)))) (t (return nil))))) (put (quote getv) (quote s!:helpeasy) (function s!:easygetv)) (de s!:easyqgetv (x) (prog (a2) (setq a2 (caddr x)) (cond ((and (fixp a2) ( geq a2 0) (lessp a2 256)) (return (s!:iseasy (cadr x)))) (t (return nil))))) (put (quote qgetv) (quote s!:helpeasy) (function s!:easyqgetv)) (de s!:iseasy (x) (prog (h) (cond ((atom x) (return t))) (cond ((not (atom ( car x))) (return nil))) (cond ((setq h (get (car x) (quote s!:helpeasy))) ( return (funcall h x))) (t (return nil))))) (de s!:instate_local_decs (v d w) (prog (fg) (cond ((fluidp v) (return w))) ( prog (var1063) (setq var1063 d) lab1062 (cond ((null var1063) (return nil))) (prog (z) (setq z (car var1063)) (cond ((and (eqcar z (quote special)) (memq v (cdr z))) (setq fg t)))) (setq var1063 (cdr var1063)) (go lab1062)) (cond ( fg (progn (make!-special v) (setq w (cons v w))))) (return w))) (de s!:residual_local_decs (d w) (prog nil (prog (var1067) (setq var1067 d) lab1066 (cond ((null var1067) (return nil))) (prog (z) (setq z (car var1067)) (cond ((eqcar z (quote special)) (prog (var1065) (setq var1065 (cdr z)) lab1064 (cond ((null var1065) (return nil))) (prog (v) (setq v (car var1065)) (cond ((and (not (fluidp v)) (not (globalp v))) (progn (make!-special v) ( setq w (cons v w)))))) (setq var1065 (cdr var1065)) (go lab1064))))) (setq var1067 (cdr var1067)) (go lab1066)) (return w))) (de s!:cancel_local_decs (w) (unfluid w)) (de s!:find_local_decs (body isprog) (prog (w local_decs) (cond ((and (not isprog) body (null (cdr body)) (eqcar (car body) (quote progn))) (setq body ( cdar body)))) (prog nil lab1068 (cond ((null (and body (or (eqcar (car body) (quote declare)) (stringp (car body))))) (return nil))) (progn (cond (( stringp (car body)) (setq w (cons (car body) w))) (t (setq local_decs (append local_decs (cdar body))))) (setq body (cdr body))) (go lab1068)) (prog nil lab1069 (cond ((null w) (return nil))) (progn (setq body (cons (car w) body)) (setq w (cdr w))) (go lab1069)) (return (cons local_decs body)))) (de s!:comlambda (bvl body args env context) (prog (s nbvl fluids fl1 w local_decs) (cond ((and (equal context 0) s!:maybe_values) (s!:outopcode0 ( quote ONEVALUE) (quote (onevalue))))) (setq nbvl (setq s (cdr env))) (setq body (s!:find_local_decs body nil)) (setq local_decs (car body)) (setq body ( cdr body)) (cond ((atom body) (setq body nil)) (t (cond ((atom (cdr body)) ( setq body (car body))) (t (setq body (cons (quote progn) body)))))) (setq w nil) (prog (var1071) (setq var1071 bvl) lab1070 (cond ((null var1071) (return nil))) (prog (v) (setq v (car var1071)) (setq w (s!:instate_local_decs v local_decs w))) (setq var1071 (cdr var1071)) (go lab1070)) (prog (var1073) ( setq var1073 bvl) lab1072 (cond ((null var1073) (return nil))) (prog (v) ( setq v (car var1073)) (progn (cond ((or (fluidp v) (globalp v)) (prog (g) ( setq g (gensym)) (setq nbvl (cons g nbvl)) (setq fl1 (cons v fl1)) (setq fluids (cons (cons v g) fluids)))) (t (setq nbvl (cons v nbvl)))) (cond (( equal (car args) nil) (s!:outstack 1)) (t (progn (s!:comval (car args) env 1) (s!:outopcode0 (quote PUSH) (quote (PUSH)))))) (rplacd env (cons 0 (cdr env) )) (setq args (cdr args)))) (setq var1073 (cdr var1073)) (go lab1072)) ( rplacd env nbvl) (cond (fluids (progn (setq fl1 (s!:vecof fl1)) ( s!:outopcode1lit (quote FREEBIND) fl1 env) (prog (var1075) (setq var1075 ( cons nil fluids)) lab1074 (cond ((null var1075) (return nil))) (prog (v) ( setq v (car var1075)) (rplacd env (cons 0 (cdr env)))) (setq var1075 (cdr var1075)) (go lab1074)) (rplacd env (cons (plus 2 (length fluids)) (cdr env)) ) (prog (var1077) (setq var1077 fluids) lab1076 (cond ((null var1077) (return nil))) (prog (v) (setq v (car var1077)) (s!:comval (list (quote setq) (car v ) (cdr v)) env 2)) (setq var1077 (cdr var1077)) (go lab1076))))) (setq w ( s!:residual_local_decs local_decs w)) (s!:comval body env 1) ( s!:cancel_local_decs w) (cond (fluids (s!:outopcode0 (quote FREERSTR) (quote (FREERSTR))))) (s!:outlose (length bvl)) (rplacd env s))) (de s!:loadliteral (x env) (cond ((member!*!* (list (quote quote) x) s!:a_reg_values) nil) (t (progn (cond ((equal x nil) (s!:outopcode0 (quote VNIL) (quote (loadlit nil)))) (t (s!:outopcode1lit (quote LOADLIT) x env))) ( setq s!:a_reg_values (list (list (quote quote) x))))))) (de s!:comquote (x env context) (progn (cond ((and (equal context 0) s!:maybe_values) (s!:outopcode0 (quote ONEVALUE) (quote (onevalue))))) (cond ((leq context 1) (s!:loadliteral (cadr x) env))))) (put (quote quote) (quote s!:compfn) (function s!:comquote)) (fluid (quote (s!:current_exitlab s!:current_proglabels s!:local_macros))) (de s!:comfunction (x env context) (progn (cond ((and (equal context 0) s!:maybe_values) (s!:outopcode0 (quote ONEVALUE) (quote (onevalue))))) (cond ((leq context 1) (progn (setq x (cadr x)) (cond ((eqcar x (quote lambda)) ( prog (g w s!:used_lexicals) (setq s!:has_closure t) (setq g (hashtagged!-name (quote lambda) (cdr x))) (setq w (s!:compile1 g (cadr x) (cddr x) (cons ( list (cdr env) s!:current_exitlab s!:current_proglabels s!:local_macros) s!:lexical_env))) (cond (s!:used_lexicals (setq w (s!:compile1 g (cons ( gensym) (cadr x)) (cddr x) (cons (list (cdr env) s!:current_exitlab s!:current_proglabels s!:local_macros) s!:lexical_env))))) (setq s!:other_defs (append w s!:other_defs)) (s!:loadliteral g env) (setq w ( length (cdr env))) (cond (s!:used_lexicals (progn (setq s!:has_closure t) ( cond ((greaterp w 4095) (error 0 "stack frame > 4095")) (t (cond ((greaterp w 255) (s!:outopcode2 (quote BIGSTACK) (plus 128 (truncate w 256)) (logand w 255) (list (quote CLOSURE) w))) (t (s!:outopcode1 (quote CLOSURE) w x)))))))) )) (t (s!:loadliteral x env)))))))) (put (quote function) (quote s!:compfn) (function s!:comfunction)) (de s!:should_be_fluid (x) (cond ((not (or (fluidp x) (globalp x))) (progn ( cond (!*pwrds (progn (cond ((neq (posn) 0) (terpri))) (princ "+++ ") (prin x) (princ " declared fluid") (terpri)))) (fluid (list x)) nil)))) (de s!:find_lexical (x lex n) (prog (p) (cond ((null lex) (return nil))) ( setq p (memq x (caar lex))) (cond (p (progn (cond ((not (memq x s!:used_lexicals)) (setq s!:used_lexicals (cons x s!:used_lexicals)))) ( return (list n (length p))))) (t (return (s!:find_lexical x (cdr lex) (plus n 1))))))) (global (quote (s!:loadlocs))) (setq s!:loadlocs (s!:vecof (quote (LOADLOC0 LOADLOC1 LOADLOC2 LOADLOC3 LOADLOC4 LOADLOC5 LOADLOC6 LOADLOC7 LOADLOC8 LOADLOC9 LOADLOC10 LOADLOC11)))) (de s!:comatom (x env context) (prog (n w) (cond ((and (equal context 0) s!:maybe_values) (s!:outopcode0 (quote ONEVALUE) (quote (onevalue))))) (cond ((greaterp context 1) (return nil)) (t (cond ((or (null x) (not (symbolp x))) (return (s!:loadliteral x env)))))) (setq n 0) (setq w (cdr env)) (prog nil lab1078 (cond ((null (and w (not (eqcar w x)))) (return nil))) (progn (setq n (add1 n)) (setq w (cdr w))) (go lab1078)) (cond (w (progn (setq w (cons ( quote loc) w)) (cond ((member!*!* w s!:a_reg_values) (return nil)) (t (progn (cond ((lessp n 12) (s!:outopcode0 (getv s!:loadlocs n) (list (quote LOADLOC) x))) (t (cond ((greaterp n 4095) (error 0 "stack frame > 4095")) (t (cond (( greaterp n 255) (s!:outopcode2 (quote BIGSTACK) (truncate n 256) (logand n 255) (list (quote LOADLOC) x))) (t (s!:outopcode1 (quote LOADLOC) n x))))))) (setq s!:a_reg_values (list w)) (return nil))))))) (cond ((setq w ( s!:find_lexical x s!:lexical_env 0)) (progn (cond ((member!*!* (cons (quote lex) w) s!:a_reg_values) (return nil))) (s!:outlexref (quote LOADLEX) (length (cdr env)) (car w) (cadr w) x) (setq s!:a_reg_values (list (cons (quote lex) w))) (return nil)))) (s!:should_be_fluid x) (cond ((flagp x (quote constant!?)) (return (s!:loadliteral (eval x) env)))) (setq w (cons (quote free) x)) (cond ((member!*!* w s!:a_reg_values) (return nil))) ( s!:outopcode1lit (quote LOADFREE) x env) (setq s!:a_reg_values (list w)))) (flag (quote (t !$EOL!$ !$EOF!$)) (quote constant!?)) (de s!:islocal (x env) (prog (n w) (cond ((or (null x) (not (symbolp x)) (eq x t)) (return 99999))) (setq n 0) (setq w (cdr env)) (prog nil lab1079 (cond ((null (and w (not (eqcar w x)))) (return nil))) (progn (setq n (add1 n)) ( setq w (cdr w))) (go lab1079)) (cond (w (return n)) (t (return 99999))))) (de s!:load2 (a b env) (progn (cond ((s!:iseasy b) (prog (wa wb w) (setq wa ( s!:islocal a env)) (setq wb (s!:islocal b env)) (cond ((and (lessp wa 4) ( lessp wb 4)) (progn (cond ((and (equal wa 0) (equal wb 1)) (setq w (quote LOC0LOC1))) (t (cond ((and (equal wa 1) (equal wb 2)) (setq w (quote LOC1LOC2 ))) (t (cond ((and (equal wa 2) (equal wb 3)) (setq w (quote LOC2LOC3))) (t ( cond ((and (equal wa 1) (equal wb 0)) (setq w (quote LOC1LOC0))) (t (cond (( and (equal wa 2) (equal wb 1)) (setq w (quote LOC2LOC1))) (t (cond ((and ( equal wa 3) (equal wb 2)) (setq w (quote LOC3LOC2)))))))))))))) (cond (w ( progn (s!:outopcode0 w (list (quote LOCLOC) a b)) (return nil))))))) ( s!:comval a env 1) (setq s!:a_reg_values nil) (s!:comval b env 1) (return nil ))) (t (cond (!*ord (progn (s!:comval a env 1) (s!:outopcode0 (quote PUSH) ( quote (PUSH))) (rplacd env (cons 0 (cdr env))) (setq s!:a_reg_values nil) ( s!:comval b env 1) (s!:outopcode0 (quote POP) (quote (POP))) (rplacd env ( cddr env)) t)) (t (cond ((s!:iseasy a) (progn (s!:comval b env 1) (setq s!:a_reg_values nil) (s!:comval a env 1) t)) (t (progn (s!:comval b env 1) ( s!:outopcode0 (quote PUSH) (quote (PUSH))) (rplacd env (cons 0 (cdr env))) ( setq s!:a_reg_values nil) (s!:comval a env 1) (s!:outopcode0 (quote POP) ( quote (POP))) (rplacd env (cddr env)) nil))))))))) (global (quote (s!:carlocs s!:cdrlocs s!:caarlocs))) (setq s!:carlocs (s!:vecof (quote (CARLOC0 CARLOC1 CARLOC2 CARLOC3 CARLOC4 CARLOC5 CARLOC6 CARLOC7 CARLOC8 CARLOC9 CARLOC10 CARLOC11)))) (setq s!:cdrlocs (s!:vecof (quote (CDRLOC0 CDRLOC1 CDRLOC2 CDRLOC3 CDRLOC4 CDRLOC5)))) (setq s!:caarlocs (s!:vecof (quote (CAARLOC0 CAARLOC1 CAARLOC2 CAARLOC3)))) (flag (quote (plus2 times2 eq equal)) (quote s!:symmetric)) (flag (quote (car cdr caar cadr cdar cddr ncons add1 sub1 numberp length)) ( quote s!:onearg)) (flag (quote (cons xcons list2 get flagp plus2 difference times2 greaterp lessp apply1 eq equal getv qgetv eqcar)) (quote s!:twoarg)) (flag (quote (apply2 list2!* list3 acons)) (quote s!:threearg)) (de s!:comcall (x env context) (prog (fn args nargs op s w1 w2 w3 sw) (setq fn (car x)) (cond ((not (symbolp fn)) (error 0 "non-symbol used in function position"))) (setq args (prog (var1081 var1082) (setq var1081 (cdr x)) lab1080 (cond ((null var1081) (return (reversip var1082)))) (prog (v) (setq v (car var1081)) (setq var1082 (cons (s!:improve v) var1082))) (setq var1081 (cdr var1081)) (go lab1080))) (setq nargs (length args)) (cond ((and (greaterp nargs 15) !*pwrds) (progn (cond ((neq (posn) 0) (terpri))) (princ "+++ ") (prin fn) (princ " called with ") (prin nargs) ( princ " from function ") (prin s!:current_function) (terpri)))) (setq s (cdr env)) (cond ((and (equal context 0) s!:maybe_values) (s!:outopcode0 (quote ONEVALUE) (quote (onevalue))))) (cond ((equal nargs 0) (cond ((setq w2 (get fn (quote s!:builtin0))) (s!:outopcode1 (quote BUILTIN0) w2 fn)) (t (progn ( s!:outopcode1lit (quote CALL0) fn env) (cond ((neq fn s!:current_function) ( setq s!:maybe_values t))))))) (t (cond ((equal nargs 1) (progn (cond ((and ( equal fn (quote car)) (lessp (setq w2 (s!:islocal (car args) env)) 12)) ( s!:outopcode0 (getv s!:carlocs w2) (list (quote carloc) (car args)))) (t ( cond ((and (equal fn (quote cdr)) (lessp (setq w2 (s!:islocal (car args) env) ) 6)) (s!:outopcode0 (getv s!:cdrlocs w2) (list (quote cdrloc) (car args)))) (t (cond ((and (equal fn (quote caar)) (lessp (setq w2 (s!:islocal (car args) env)) 4)) (s!:outopcode0 (getv s!:caarlocs w2) (list (quote caarloc) (car args)))) (t (progn (s!:comval (car args) env 1) (cond ((flagp fn (quote s!:onearg)) (s!:outopcode0 fn (list fn))) (t (cond ((setq w2 (get fn (quote s!:builtin1))) (s!:outopcode1 (quote BUILTIN1) w2 fn)) (t (progn (cond ((and (equal context 0) s!:maybe_values) (s!:outopcode0 (quote ONEVALUE) (quote ( onevalue))))) (s!:outopcode1lit (quote CALL1) fn env) (cond ((neq fn s!:current_function) (setq s!:maybe_values t))))))))))))))))) (t (cond (( equal nargs 2) (progn (setq sw (s!:load2 (car args) (cadr args) env)) (cond ( (flagp fn (quote s!:symmetric)) (setq sw nil))) (cond ((flagp fn (quote s!:twoarg)) (progn (cond (sw (s!:outopcode0 (quote SWOP) (quote (SWOP))))) ( s!:outopcode0 fn (list fn)))) (t (progn (setq w3 (get fn (quote s!:builtin2)) ) (cond (sw (progn (cond (w3 (s!:outopcode1 (quote BUILTIN2R) w3 fn)) (t ( s!:outopcode1lit (quote CALL2R) fn env))))) (t (cond (w3 (s!:outopcode1 ( quote BUILTIN2) w3 fn)) (t (progn (cond ((and (equal context 0) s!:maybe_values) (s!:outopcode0 (quote ONEVALUE) (quote (onevalue))))) ( s!:outopcode1lit (quote CALL2) fn env) (cond ((neq fn s!:current_function) ( setq s!:maybe_values t))))))))))))) (t (cond ((equal nargs 3) (progn (cond (( equal (car args) nil) (s!:outstack 1)) (t (progn (s!:comval (car args) env 1) (s!:outopcode0 (quote PUSH) (quote (PUSHA3)))))) (rplacd env (cons 0 (cdr env))) (setq s!:a_reg_values nil) (cond ((s!:load2 (cadr args) (caddr args) env) (s!:outopcode0 (quote SWOP) (quote (SWOP))))) (cond ((flagp fn (quote s!:threearg)) (s!:outopcode0 (cond ((equal fn (quote list2!*)) (quote list2star)) (t fn)) (list fn))) (t (cond ((setq w2 (get fn (quote s!:builtin3 ))) (s!:outopcode1 (quote BUILTIN3) w2 fn)) (t (progn (cond ((and (equal context 0) s!:maybe_values) (s!:outopcode0 (quote ONEVALUE) (quote (onevalue) )))) (s!:outopcode1lit (quote CALL3) fn env) (cond ((neq fn s!:current_function) (setq s!:maybe_values t)))))))) (rplacd env (cddr env))) ) (t (prog (largs) (setq largs (reverse args)) (prog (var1084) (setq var1084 (reverse (cddr largs))) lab1083 (cond ((null var1084) (return nil))) (prog (a ) (setq a (car var1084)) (progn (cond ((null a) (s!:outstack 1)) (t (progn ( s!:comval a env 1) (cond ((equal nargs 4) (s!:outopcode0 (quote PUSH) (quote (PUSHA4)))) (t (s!:outopcode0 (quote PUSH) (quote (PUSHARG)))))))) (rplacd env (cons 0 (cdr env))) (setq s!:a_reg_values nil))) (setq var1084 (cdr var1084)) (go lab1083)) (cond ((s!:load2 (cadr largs) (car largs) env) ( s!:outopcode0 (quote SWOP) (quote (SWOP))))) (cond ((and (equal fn (quote apply3)) (equal nargs 4)) (s!:outopcode0 (quote APPLY3) (quote (APPLY3)))) (t (cond ((greaterp nargs 255) (error 0 "Over 255 args in a function call")) (t (progn (cond ((and (equal context 0) s!:maybe_values) (s!:outopcode0 (quote ONEVALUE) (quote (onevalue))))) (s!:outopcode2lit (quote CALLN) fn nargs ( list nargs fn) env) (cond ((neq fn s!:current_function) (setq s!:maybe_values t)))))))) (rplacd env s)))))))))))) (de s!:ad_name (l) (cond ((equal (car l) (quote a)) (cond ((equal (cadr l) ( quote a)) (quote caar)) (t (quote cadr)))) (t (cond ((equal (cadr l) (quote a )) (quote cdar)) (t (quote cddr)))))) (de s!:comcarcdr3 (x env context) (prog (name outer c1 c2) (setq name (cdr ( explode2 (car x)))) (setq x (list (s!:ad_name name) (list (cond ((equal ( caddr name) (quote a)) (quote car)) (t (quote cdr))) (cadr x)))) (return ( s!:comval x env context)))) (put (quote caaar) (quote s!:compfn) (function s!:comcarcdr3)) (put (quote caadr) (quote s!:compfn) (function s!:comcarcdr3)) (put (quote cadar) (quote s!:compfn) (function s!:comcarcdr3)) (put (quote caddr) (quote s!:compfn) (function s!:comcarcdr3)) (put (quote cdaar) (quote s!:compfn) (function s!:comcarcdr3)) (put (quote cdadr) (quote s!:compfn) (function s!:comcarcdr3)) (put (quote cddar) (quote s!:compfn) (function s!:comcarcdr3)) (put (quote cdddr) (quote s!:compfn) (function s!:comcarcdr3)) (de s!:comcarcdr4 (x env context) (prog (name outer c1 c2) (setq name (cdr ( explode2 (car x)))) (setq x (list (s!:ad_name name) (list (s!:ad_name (cddr name)) (cadr x)))) (return (s!:comval x env context)))) (put (quote caaaar) (quote s!:compfn) (function s!:comcarcdr4)) (put (quote caaadr) (quote s!:compfn) (function s!:comcarcdr4)) (put (quote caadar) (quote s!:compfn) (function s!:comcarcdr4)) (put (quote caaddr) (quote s!:compfn) (function s!:comcarcdr4)) (put (quote cadaar) (quote s!:compfn) (function s!:comcarcdr4)) (put (quote cadadr) (quote s!:compfn) (function s!:comcarcdr4)) (put (quote caddar) (quote s!:compfn) (function s!:comcarcdr4)) (put (quote cadddr) (quote s!:compfn) (function s!:comcarcdr4)) (put (quote cdaaar) (quote s!:compfn) (function s!:comcarcdr4)) (put (quote cdaadr) (quote s!:compfn) (function s!:comcarcdr4)) (put (quote cdadar) (quote s!:compfn) (function s!:comcarcdr4)) (put (quote cdaddr) (quote s!:compfn) (function s!:comcarcdr4)) (put (quote cddaar) (quote s!:compfn) (function s!:comcarcdr4)) (put (quote cddadr) (quote s!:compfn) (function s!:comcarcdr4)) (put (quote cdddar) (quote s!:compfn) (function s!:comcarcdr4)) (put (quote cddddr) (quote s!:compfn) (function s!:comcarcdr4)) (de s!:comgetv (x env context) (cond (!*carcheckflag (s!:comcall x env context)) (t (s!:comval (cons (quote qgetv) (cdr x)) env context)))) (put (quote getv) (quote s!:compfn) (function s!:comgetv)) (de s!:comqgetv (x env context) (cond ((and (fixp (caddr x)) (geq (caddr x) 0 ) (lessp (caddr x) 256)) (progn (s!:comval (cadr x) env 1) (s!:outopcode1 ( quote QGETVN) (caddr x) (caddr x)))) (t (s!:comcall x env context)))) (put (quote qgetv) (quote s!:compfn) (function s!:comqgetv)) (de s!:comget (x env context) (prog (a b c w) (setq a (cadr x)) (setq b ( caddr x)) (setq c (cdddr x)) (cond ((eqcar b (quote quote)) (progn (setq b ( cadr b)) (setq w (symbol!-make!-fastget b nil)) (cond (c (progn (cond (w ( progn (cond ((s!:load2 a b env) (s!:outopcode0 (quote SWOP) (quote (SWOP))))) (s!:outopcode1 (quote FASTGET) (logor w 64) b))) (t (s!:comcall x env context))))) (t (progn (s!:comval a env 1) (cond (w (s!:outopcode1 (quote FASTGET) w b)) (t (s!:outopcode1lit (quote LITGET) b env)))))))) (t ( s!:comcall x env context))))) (put (quote get) (quote s!:compfn) (function s!:comget)) (de s!:comflagp (x env context) (prog (a b) (setq a (cadr x)) (setq b (caddr x)) (cond ((eqcar b (quote quote)) (progn (setq b (cadr b)) (s!:comval a env 1) (setq a (symbol!-make!-fastget b nil)) (cond (a (s!:outopcode1 (quote FASTGET) (logor a 128) b)) (t (s!:comcall x env context))))) (t (s!:comcall x env context))))) (put (quote flagp) (quote s!:compfn) (function s!:comflagp)) (de s!:complus (x env context) (s!:comval (expand (cdr x) (quote plus2)) env context)) (put (quote plus) (quote s!:compfn) (function s!:complus)) (de s!:comtimes (x env context) (s!:comval (expand (cdr x) (quote times2)) env context)) (put (quote times) (quote s!:compfn) (function s!:comtimes)) (de s!:comiplus (x env context) (s!:comval (expand (cdr x) (quote iplus2)) env context)) (put (quote iplus) (quote s!:compfn) (function s!:comiplus)) (de s!:comitimes (x env context) (s!:comval (expand (cdr x) (quote itimes2)) env context)) (put (quote itimes) (quote s!:compfn) (function s!:comitimes)) (de s!:complus2 (x env context) (prog (a b) (setq a (s!:improve (cadr x))) ( setq b (s!:improve (caddr x))) (return (cond ((and (numberp a) (numberp b)) ( s!:comval (plus a b) env context)) (t (cond ((equal a 0) (s!:comval b env context)) (t (cond ((equal a 1) (s!:comval (list (quote add1) b) env context) ) (t (cond ((equal b 0) (s!:comval a env context)) (t (cond ((equal b 1) ( s!:comval (list (quote add1) a) env context)) (t (cond ((equal b (minus 1)) ( s!:comval (list (quote sub1) a) env context)) (t (s!:comcall x env context))) ))))))))))))) (put (quote plus2) (quote s!:compfn) (function s!:complus2)) (de s!:comdifference (x env context) (prog (a b) (setq a (s!:improve (cadr x) )) (setq b (s!:improve (caddr x))) (return (cond ((and (numberp a) (numberp b )) (s!:comval (difference a b) env context)) (t (cond ((equal a 0) (s!:comval (list (quote minus) b) env context)) (t (cond ((equal b 0) (s!:comval a env context)) (t (cond ((equal b 1) (s!:comval (list (quote sub1) a) env context) ) (t (cond ((equal b (minus 1)) (s!:comval (list (quote add1) a) env context) ) (t (s!:comcall x env context)))))))))))))) (put (quote difference) (quote s!:compfn) (function s!:comdifference)) (de s!:comiplus2 (x env context) (prog (a b) (setq a (s!:improve (cadr x))) ( setq b (s!:improve (caddr x))) (return (cond ((and (numberp a) (numberp b)) ( s!:comval (plus a b) env context)) (t (cond ((equal a 1) (s!:comval (list ( quote iadd1) b) env context)) (t (cond ((equal b 1) (s!:comval (list (quote iadd1) a) env context)) (t (cond ((equal b (minus 1)) (s!:comval (list (quote isub1) a) env context)) (t (s!:comcall x env context)))))))))))) (put (quote iplus2) (quote s!:compfn) (function s!:comiplus2)) (de s!:comidifference (x env context) (prog (a b) (setq a (s!:improve (cadr x ))) (setq b (s!:improve (caddr x))) (return (cond ((and (numberp a) (numberp b)) (s!:comval (difference a b) env context)) (t (cond ((equal b 1) ( s!:comval (list (quote isub1) a) env context)) (t (cond ((equal b (minus 1)) (s!:comval (list (quote iadd1) a) env context)) (t (s!:comcall x env context) ))))))))) (put (quote idifference) (quote s!:compfn) (function s!:comidifference)) (de s!:comtimes2 (x env context) (prog (a b) (setq a (s!:improve (cadr x))) ( setq b (s!:improve (caddr x))) (return (cond ((and (numberp a) (numberp b)) ( s!:comval (times a b) env context)) (t (cond ((equal a 1) (s!:comval b env context)) (t (cond ((equal a (minus 1)) (s!:comval (list (quote minus) b) env context)) (t (cond ((equal b 1) (s!:comval a env context)) (t (cond ((equal b (minus 1)) (s!:comval (list (quote minus) a) env context)) (t (s!:comcall x env context)))))))))))))) (put (quote times2) (quote s!:compfn) (function s!:comtimes2)) (put (quote itimes2) (quote s!:compfn) (function s!:comtimes2)) (de s!:comminus (x env context) (prog (a b) (setq a (s!:improve (cadr x))) ( return (cond ((numberp a) (s!:comval (minus a) env context)) (t (cond ((eqcar a (quote minus)) (s!:comval (cadr a) env context)) (t (s!:comcall x env context)))))))) (put (quote minus) (quote s!:compfn) (function s!:comminus)) (de s!:comminusp (x env context) (prog (a) (setq a (s!:improve (cadr x))) ( cond ((eqcar a (quote difference)) (return (s!:comval (cons (quote lessp) ( cdr a)) env context))) (t (return (s!:comcall x env context)))))) (put (quote minusp) (quote s!:compfn) (function s!:comminusp)) (de s!:comlessp (x env context) (prog (a b) (setq a (s!:improve (cadr x))) ( setq b (s!:improve (caddr x))) (cond ((equal b 0) (return (s!:comval (list ( quote minusp) a) env context))) (t (return (s!:comcall x env context)))))) (put (quote lessp) (quote s!:compfn) (function s!:comlessp)) (de s!:comiminusp (x env context) (prog (a) (setq a (s!:improve (cadr x))) ( cond ((eqcar a (quote difference)) (return (s!:comval (cons (quote ilessp) ( cdr a)) env context))) (t (return (s!:comcall x env context)))))) (put (quote iminusp) (quote s!:compfn) (function s!:comiminusp)) (de s!:comilessp (x env context) (prog (a b) (setq a (s!:improve (cadr x))) ( setq b (s!:improve (caddr x))) (cond ((equal b 0) (return (s!:comval (list ( quote iminusp) a) env context))) (t (return (s!:comcall x env context)))))) (put (quote ilessp) (quote s!:compfn) (function s!:comilessp)) (de s!:comprogn (x env context) (progn (setq x (cdr x)) (cond ((null x) ( s!:comval nil env context)) (t (prog (a) (setq a (car x)) (prog nil lab1085 ( cond ((null (setq x (cdr x))) (return nil))) (progn (s!:comval a env (cond (( geq context 4) context) (t 2))) (setq a (car x))) (go lab1085)) (s!:comval a env context)))))) (put (quote progn) (quote s!:compfn) (function s!:comprogn)) (de s!:comprog1 (x env context) (prog nil (setq x (cdr x)) (cond ((null x) ( return (s!:comval nil env context)))) (s!:comval (car x) env context) (cond ( (null (setq x (cdr x))) (return nil))) (s!:outopcode0 (quote PUSH) (quote ( PUSH))) (rplacd env (cons 0 (cdr env))) (prog (var1087) (setq var1087 x) lab1086 (cond ((null var1087) (return nil))) (prog (a) (setq a (car var1087)) (s!:comval a env (cond ((geq context 4) context) (t 2)))) (setq var1087 (cdr var1087)) (go lab1086)) (s!:outopcode0 (quote POP) (quote (POP))) (rplacd env (cddr env)))) (put (quote prog1) (quote s!:compfn) (function s!:comprog1)) (de s!:comprog2 (x env context) (prog (a) (setq x (cdr x)) (cond ((null x) ( return (s!:comval nil env context)))) (setq a (car x)) (s!:comval a env (cond ((geq context 4) context) (t 2))) (s!:comprog1 x env context))) (put (quote prog2) (quote s!:compfn) (function s!:comprog2)) (de s!:outstack (n) (prog (w a) (setq w s!:current_block) (prog nil lab1088 ( cond ((null (and w (not (atom (car w))))) (return nil))) (setq w (cdr w)) (go lab1088)) (cond ((eqcar w (quote PUSHNIL)) (setq a 1)) (t (cond ((eqcar w ( quote PUSHNIL2)) (setq a 2)) (t (cond ((eqcar w (quote PUSHNIL3)) (setq a 3)) (t (cond ((and w (numberp (setq a (car w))) (not (equal a 255)) (eqcar (cdr w) (quote PUSHNILS))) (progn (setq w (cdr w)) (setq s!:current_size ( difference s!:current_size 1)))) (t (setq a nil))))))))) (cond (a (progn ( setq s!:current_block (cdr w)) (setq s!:current_size (difference s!:current_size 1)) (setq n (plus n a))))) (cond ((equal n 1) (s!:outopcode0 (quote PUSHNIL) (quote (PUSHNIL)))) (t (cond ((equal n 2) (s!:outopcode0 ( quote PUSHNIL2) (quote (PUSHNIL2)))) (t (cond ((equal n 3) (s!:outopcode0 ( quote PUSHNIL3) (quote (PUSHNIL3)))) (t (cond ((greaterp n 255) (progn ( s!:outopcode1 (quote PUSHNILS) 255 255) (s!:outstack (difference n 255)))) (t (cond ((greaterp n 3) (s!:outopcode1 (quote PUSHNILS) n n))))))))))))) (de s!:outlose (n) (prog (w a) (setq w s!:current_block) (prog nil lab1089 ( cond ((null (and w (not (atom (car w))))) (return nil))) (setq w (cdr w)) (go lab1089)) (cond ((eqcar w (quote LOSE)) (setq a 1)) (t (cond ((eqcar w ( quote LOSE2)) (setq a 2)) (t (cond ((eqcar w (quote LOSE3)) (setq a 3)) (t ( cond ((and w (numberp (setq a (car w))) (not (equal a 255)) (eqcar (cdr w) ( quote LOSES))) (progn (setq w (cdr w)) (setq s!:current_size (difference s!:current_size 1)))) (t (setq a nil))))))))) (cond (a (progn (setq s!:current_block (cdr w)) (setq s!:current_size (difference s!:current_size 1 )) (setq n (plus n a))))) (cond ((equal n 1) (s!:outopcode0 (quote LOSE) ( quote (LOSE)))) (t (cond ((equal n 2) (s!:outopcode0 (quote LOSE2) (quote ( LOSE2)))) (t (cond ((equal n 3) (s!:outopcode0 (quote LOSE3) (quote (LOSE3))) ) (t (cond ((greaterp n 255) (progn (s!:outopcode1 (quote LOSES) 255 255) ( s!:outlose (difference n 255)))) (t (cond ((greaterp n 3) (s!:outopcode1 ( quote LOSES) n n))))))))))))) (de s!:comprog (x env context) (prog (labs s bvl fluids n body local_decs w) (setq body (s!:find_local_decs (cddr x) t)) (setq local_decs (car body)) ( setq body (cdr body)) (setq n 0) (prog (var1091) (setq var1091 (cadr x)) lab1090 (cond ((null var1091) (return nil))) (prog (v) (setq v (car var1091)) (setq w (s!:instate_local_decs v local_decs w))) (setq var1091 (cdr var1091) ) (go lab1090)) (prog (var1093) (setq var1093 (cadr x)) lab1092 (cond ((null var1093) (return nil))) (prog (v) (setq v (car var1093)) (progn (cond (( globalp v) (progn (cond (!*pwrds (progn (cond ((neq (posn) 0) (terpri))) ( princ "+++++ global ") (prin v) (princ " converted to fluid") (terpri)))) ( unglobal (list v)) (fluid (list v))))) (cond ((fluidp v) (setq fluids (cons v fluids))) (t (progn (setq n (plus n 1)) (setq bvl (cons v bvl))))))) (setq var1093 (cdr var1093)) (go lab1092)) (setq s (cdr env)) (setq s!:current_exitlab (cons (cons nil (cons (gensym) s)) s!:current_exitlab)) ( s!:outstack n) (rplacd env (append bvl (cdr env))) (cond (fluids (prog (fl1) (setq fl1 (s!:vecof fluids)) (s!:outopcode1lit (quote FREEBIND) fl1 env) ( prog (var1095) (setq var1095 (cons nil fluids)) lab1094 (cond ((null var1095) (return nil))) (prog (v) (setq v (car var1095)) (rplacd env (cons 0 (cdr env )))) (setq var1095 (cdr var1095)) (go lab1094)) (rplacd env (cons (plus 2 ( length fluids)) (cdr env))) (cond ((equal context 0) (setq context 1)))))) ( prog (var1097) (setq var1097 body) lab1096 (cond ((null var1097) (return nil) )) (prog (a) (setq a (car var1097)) (cond ((atom a) (progn (cond ((atsoc a labs) (progn (cond ((not (null a)) (progn (cond ((neq (posn) 0) (terpri))) ( princ "+++++ label ") (prin a) (princ " multiply defined") (terpri)))))) (t ( setq labs (cons (cons a (cons (cons (gensym) (cdr env)) nil)) labs)))))))) ( setq var1097 (cdr var1097)) (go lab1096)) (setq s!:current_proglabels (cons labs s!:current_proglabels)) (setq w (s!:residual_local_decs local_decs w)) ( prog (var1099) (setq var1099 body) lab1098 (cond ((null var1099) (return nil) )) (prog (a) (setq a (car var1099)) (cond ((not (atom a)) (s!:comval a env ( plus context 4))) (t (prog (d) (setq d (atsoc a labs)) (cond ((null (cddr d)) (progn (rplacd (cdr d) t) (s!:set_label (caadr d))))))))) (setq var1099 (cdr var1099)) (go lab1098)) (s!:cancel_local_decs w) (s!:comval nil env context) (cond (fluids (s!:outopcode0 (quote FREERSTR) (quote (FREERSTR))))) ( s!:outlose n) (rplacd env s) (s!:set_label (cadar s!:current_exitlab)) (setq s!:current_exitlab (cdr s!:current_exitlab)) (setq s!:current_proglabels (cdr s!:current_proglabels)))) (put (quote prog) (quote s!:compfn) (function s!:comprog)) (de s!:comtagbody (x env context) (prog (labs) (prog (var1101) (setq var1101 (cdr x)) lab1100 (cond ((null var1101) (return nil))) (prog (a) (setq a (car var1101)) (cond ((atom a) (progn (cond ((atsoc a labs) (progn (cond ((not ( null a)) (progn (cond ((neq (posn) 0) (terpri))) (princ "+++++ label ") (prin a) (princ " multiply defined") (terpri)))))) (t (setq labs (cons (cons a ( cons (cons (gensym) (cdr env)) nil)) labs)))))))) (setq var1101 (cdr var1101) ) (go lab1100)) (setq s!:current_proglabels (cons labs s!:current_proglabels) ) (prog (var1103) (setq var1103 (cdr x)) lab1102 (cond ((null var1103) ( return nil))) (prog (a) (setq a (car var1103)) (cond ((not (atom a)) ( s!:comval a env (plus context 4))) (t (prog (d) (setq d (atsoc a labs)) (cond ((null (cddr d)) (progn (rplacd (cdr d) t) (s!:set_label (caadr d))))))))) ( setq var1103 (cdr var1103)) (go lab1102)) (s!:comval nil env context) (setq s!:current_proglabels (cdr s!:current_proglabels)))) (put (quote tagbody) (quote s!:compfn) (function s!:comtagbody)) (de s!:comblock (x env context) (prog nil (setq s!:current_exitlab (cons ( cons (cadr x) (cons (gensym) (cdr env))) s!:current_exitlab)) (s!:comval ( cons (quote progn) (cddr x)) env context) (s!:set_label (cadar s!:current_exitlab)) (setq s!:current_exitlab (cdr s!:current_exitlab)))) (put (quote !~block) (quote s!:compfn) (function s!:comblock)) (de s!:comcatch (x env context) (prog (g) (setq g (gensym)) (s!:comval (cadr x) env 1) (s!:outjump (quote CATCH) g) (rplacd env (cons (quote (catch)) ( cons 0 (cons 0 (cdr env))))) (s!:comval (cons (quote progn) (cddr x)) env context) (s!:outopcode0 (quote UNCATCH) (quote (UNCATCH))) (rplacd env ( cddddr env)) (s!:set_label g))) (put (quote catch) (quote s!:compfn) (quote s!:comcatch)) (de s!:comthrow (x env context) (prog nil (s!:comval (cadr x) env 1) ( s!:outopcode0 (quote PUSH) (quote (PUSH))) (rplacd env (cons 0 (cdr env))) ( s!:comval (caddr x) env 1) (s!:outopcode0 (quote THROW) (quote (THROW))) ( rplacd env (cddr env)))) (put (quote throw) (quote s!:compfn) (quote s!:comthrow)) (de s!:comunwind!-protect (x env context) (prog (g) (setq g (gensym)) ( s!:comval (quote (load!-spid)) env 1) (s!:outjump (quote CATCH) g) (rplacd env (cons (list (quote unwind!-protect) (cddr x)) (cons 0 (cons 0 (cdr env))) )) (s!:comval (cadr x) env context) (s!:outopcode0 (quote PROTECT) (quote ( PROTECT))) (s!:set_label g) (rplaca (cdr env) 0) (s!:comval (cons (quote progn) (cddr x)) env context) (s!:outopcode0 (quote UNPROTECT) (quote ( UNPROTECT))) (rplacd env (cddddr env)))) (put (quote unwind!-protect) (quote s!:compfn) (quote s!:comunwind!-protect)) (de s!:comdeclare (x env context) (prog nil (cond (!*pwrds (progn (princ "+++ ") (prin x) (princ " ignored") (terpri)))))) (put (quote declare) (quote s!:compfn) (function s!:comdeclare)) (de s!:expand_let (vl b) (prog (vars vals) (prog (var1105) (setq var1105 vl) lab1104 (cond ((null var1105) (return nil))) (prog (v) (setq v (car var1105)) (cond ((atom v) (progn (setq vars (cons v vars)) (setq vals (cons nil vals)) )) (t (cond ((atom (cdr v)) (progn (setq vars (cons (car v) vars)) (setq vals (cons nil vals)))) (t (progn (setq vars (cons (car v) vars)) (setq vals ( cons (cadr v) vals)))))))) (setq var1105 (cdr var1105)) (go lab1104)) (return (list (cons (cons (quote lambda) (cons vars b)) vals))))) (de s!:comlet (x env context) (s!:comval (cons (quote progn) (s!:expand_let ( cadr x) (cddr x))) env context)) (put (quote !~let) (quote s!:compfn) (function s!:comlet)) (de s!:expand_let!* (vl local_decs b) (prog (r var val) (setq r (cons (cons ( quote declare) local_decs) b)) (prog (var1109) (setq var1109 (reverse vl)) lab1108 (cond ((null var1109) (return nil))) (prog (x) (setq x (car var1109)) (progn (setq val nil) (cond ((atom x) (setq var x)) (t (cond ((atom (cdr x)) (setq var (car x))) (t (progn (setq var (car x)) (setq val (cadr x))))))) ( prog (var1107) (setq var1107 local_decs) lab1106 (cond ((null var1107) ( return nil))) (prog (z) (setq z (car var1107)) (cond ((eqcar z (quote special )) (cond ((memq var (cdr z)) (setq r (cons (list (quote declare) (list (quote special) var)) r))))))) (setq var1107 (cdr var1107)) (go lab1106)) (setq r ( list (list (cons (quote lambda) (cons (list var) r)) val))))) (setq var1109 ( cdr var1109)) (go lab1108)) (cond ((eqcar (car r) (quote declare)) (setq r ( list (cons (quote lambda) (cons nil r))))) (t (setq r (cons (quote progn) r)) )) (return r))) (de s!:comlet!* (x env context) (prog (b) (setq b (s!:find_local_decs (cddr x ) nil)) (return (s!:comval (s!:expand_let!* (cadr x) (car b) (cdr b)) env context)))) (put (quote let!*) (quote s!:compfn) (function s!:comlet!*)) (de s!:restore_stack (e1 e2) (prog (n) (setq n 0) (prog nil lab1111 (cond (( null (not (equal e1 e2))) (return nil))) (progn (cond ((null e1) (error 0 "bad block nesting with GO or RETURN-FROM"))) (cond ((and (numberp (car e1)) (greaterp (car e1) 2)) (progn (cond ((not (zerop n)) (s!:outlose n))) (setq n (car e1)) (s!:outopcode0 (quote FREERSTR) (quote (FREERSTR))) (prog (i) ( setq i 1) lab1110 (cond ((minusp (times 1 (difference n i))) (return nil))) ( setq e1 (cdr e1)) (setq i (plus i 1)) (go lab1110)) (setq n 0))) (t (cond (( equal (car e1) (quote (catch))) (progn (cond ((not (zerop n)) (s!:outlose n)) ) (s!:outopcode0 (quote UNCATCH) (quote (UNCATCH))) (setq e1 (cdddr e1)) ( setq n 0))) (t (cond ((eqcar (car e1) (quote unwind!-protect)) (progn (cond ( (not (zerop n)) (s!:outlose n))) (s!:outopcode0 (quote PROTECT) (quote ( PROTECT))) (s!:comval (cons (quote progn) (cadar e1)) e1 2) (s!:outopcode0 ( quote UNPROTECT) (quote (UNPROTECT))) (setq e1 (cdddr e1)) (setq n 0))) (t ( progn (setq e1 (cdr e1)) (setq n (plus n 1)))))))))) (go lab1111)) (cond (( not (zerop n)) (s!:outlose n))))) (de s!:comgo (x env context) (prog (pl d) (cond ((lessp context 4) (progn ( princ "go not in program context") (terpri)))) (setq pl s!:current_proglabels ) (prog nil lab1112 (cond ((null (and pl (null d))) (return nil))) (progn ( setq d (atsoc (cadr x) (car pl))) (cond ((null d) (setq pl (cdr pl))))) (go lab1112)) (cond ((null d) (progn (cond ((neq (posn) 0) (terpri))) (princ "+++++ label ") (prin (cadr x)) (princ " not set") (terpri) (return nil)))) ( setq d (cadr d)) (s!:restore_stack (cdr env) (cdr d)) (s!:outjump (quote JUMP ) (car d)))) (put (quote go) (quote s!:compfn) (function s!:comgo)) (de s!:comreturn!-from (x env context) (prog (tag) (cond ((lessp context 4) ( progn (princ "+++++ return or return-from not in prog context") (terpri)))) ( setq x (cdr x)) (setq tag (car x)) (cond ((cdr x) (setq x (cadr x))) (t (setq x nil))) (s!:comval x env (difference context 4)) (setq x (atsoc tag s!:current_exitlab)) (cond ((null x) (error 0 (list "invalid return-from" tag )))) (setq x (cdr x)) (s!:restore_stack (cdr env) (cdr x)) (s!:outjump (quote JUMP) (car x)))) (put (quote return!-from) (quote s!:compfn) (function s!:comreturn!-from)) (de s!:comreturn (x env context) (s!:comreturn!-from (cons (quote return!-from) (cons nil (cdr x))) env context)) (put (quote return) (quote s!:compfn) (function s!:comreturn)) (global (quote (s!:jumplts s!:jumplnils s!:jumpatoms s!:jumpnatoms))) (setq s!:jumplts (s!:vecof (quote (JUMPL0T JUMPL1T JUMPL2T JUMPL3T JUMPL4T))) ) (setq s!:jumplnils (s!:vecof (quote (JUMPL0NIL JUMPL1NIL JUMPL2NIL JUMPL3NIL JUMPL4NIL)))) (setq s!:jumpatoms (s!:vecof (quote (JUMPL0ATOM JUMPL1ATOM JUMPL2ATOM JUMPL3ATOM)))) (setq s!:jumpnatoms (s!:vecof (quote (JUMPL0NATOM JUMPL1NATOM JUMPL2NATOM JUMPL3NATOM)))) (de s!:jumpif (neg x env lab) (prog (w w1 j) top (cond ((null x) (progn (cond ((not neg) (s!:outjump (quote JUMP) lab))) (return nil))) (t (cond ((or (eq x t) (and (eqcar x (quote quote)) (cadr x)) (and (atom x) (not (symbolp x)))) (progn (cond (neg (s!:outjump (quote JUMP) lab))) (return nil))) (t (cond (( lessp (setq w (s!:islocal x env)) 5) (return (s!:outjump (getv (cond (neg s!:jumplts) (t s!:jumplnils)) w) lab))) (t (cond ((and (equal w 99999) ( symbolp x)) (progn (s!:should_be_fluid x) (setq w (list (cond (neg (quote JUMPFREET)) (t (quote JUMPFREENIL))) x x)) (return ( s!:record_literal_for_jump w env lab))))))))))) (cond ((and (not (atom x)) ( atom (car x)) (setq w (get (car x) (quote s!:testfn)))) (return (funcall w neg x env lab)))) (cond ((not (atom x)) (progn (setq w (s!:improve x)) (cond ((or (atom w) (not (eqcar x (car w)))) (progn (setq x w) (go top)))) (cond (( and (setq w1 (get (car w) (quote s!:compilermacro))) (setq w1 (funcall w1 w env 1))) (progn (setq x w1) (go top))))))) remacro (cond ((and (not (atom w)) (setq w1 (macro!-function (car w)))) (progn (setq w (funcall w1 w)) (cond (( or (atom w) (eqcar w (quote quote)) (get (car w) (quote s!:testfn)) (get (car w) (quote s!:compilermacro))) (progn (setq x w) (go top)))) (go remacro)))) (s!:comval x env 1) (setq w s!:current_block) (prog nil lab1113 (cond ((null (and w (not (atom (car w))))) (return nil))) (setq w (cdr w)) (go lab1113)) ( setq j (quote (JUMPNIL . JUMPT))) (cond (w (progn (setq w1 (car w)) (setq w ( cdr w)) (cond ((equal w1 (quote STORELOC0)) (progn (setq s!:current_block w) (setq s!:current_size (difference s!:current_size 1)) (setq j (quote ( JUMPST0NIL . JUMPST0T))))) (t (cond ((equal w1 (quote STORELOC1)) (progn ( setq s!:current_block w) (setq s!:current_size (difference s!:current_size 1) ) (setq j (quote (JUMPST1NIL . JUMPST1T))))) (t (cond ((equal w1 (quote STORELOC2)) (progn (setq s!:current_block w) (setq s!:current_size ( difference s!:current_size 1)) (setq j (quote (JUMPST2NIL . JUMPST2T))))) (t (cond ((eqcar w (quote BUILTIN1)) (progn (setq s!:current_block (cdr w)) ( setq s!:current_size (difference s!:current_size 2)) (setq j (cons (list ( quote JUMPB1NIL) w1) (list (quote JUMPB1T) w1))))) (t (cond ((eqcar w (quote BUILTIN2)) (progn (setq s!:current_block (cdr w)) (setq s!:current_size ( difference s!:current_size 2)) (setq j (cons (list (quote JUMPB2NIL) w1) ( list (quote JUMPB2T) w1))))))))))))))))) (return (s!:outjump (cond (neg (cdr j)) (t (car j))) lab)))) (de s!:testnot (neg x env lab) (s!:jumpif (not neg) (cadr x) env lab)) (put (quote null) (quote s!:testfn) (function s!:testnot)) (put (quote not) (quote s!:testfn) (function s!:testnot)) (de s!:testatom (neg x env lab) (prog (w) (cond ((lessp (setq w (s!:islocal ( cadr x) env)) 4) (return (s!:outjump (getv (cond (neg s!:jumpatoms) (t s!:jumpnatoms)) w) lab)))) (s!:comval (cadr x) env 1) (cond (neg (s!:outjump (quote JUMPATOM) lab)) (t (s!:outjump (quote JUMPNATOM) lab))))) (put (quote atom) (quote s!:testfn) (function s!:testatom)) (de s!:testconsp (neg x env lab) (prog (w) (cond ((lessp (setq w (s!:islocal (cadr x) env)) 4) (return (s!:outjump (getv (cond (neg s!:jumpnatoms) (t s!:jumpatoms)) w) lab)))) (s!:comval (cadr x) env 1) (cond (neg (s!:outjump ( quote JUMPNATOM) lab)) (t (s!:outjump (quote JUMPATOM) lab))))) (put (quote consp) (quote s!:testfn) (function s!:testconsp)) (de s!:comcond (x env context) (prog (l1 l2 w) (setq l1 (gensym)) (prog nil lab1114 (cond ((null (setq x (cdr x))) (return nil))) (progn (setq w (car x)) (cond ((atom (cdr w)) (progn (s!:comval (car w) env 1) (s!:outjump (quote JUMPT) l1) (setq l2 nil))) (t (progn (cond ((equal (car w) t) (setq l2 nil)) (t (progn (setq l2 (gensym)) (s!:jumpif nil (car w) env l2)))) (setq w (cdr w )) (cond ((null (cdr w)) (setq w (car w))) (t (setq w (cons (quote progn) w)) )) (s!:comval w env context) (cond (l2 (progn (s!:outjump (quote JUMP) l1) ( s!:set_label l2))) (t (setq x (quote (nil))))))))) (go lab1114)) (cond (l2 ( s!:comval nil env context))) (s!:set_label l1))) (put (quote cond) (quote s!:compfn) (function s!:comcond)) (de s!:comif (x env context) (prog (l1 l2) (setq l2 (gensym)) (s!:jumpif nil (cadr x) env l2) (setq x (cddr x)) (s!:comval (car x) env context) (setq x ( cdr x)) (cond ((or x (and (lessp context 2) (setq x (quote (nil))))) (progn ( setq l1 (gensym)) (s!:outjump (quote JUMP) l1) (s!:set_label l2) (s!:comval ( car x) env context) (s!:set_label l1))) (t (s!:set_label l2))))) (put (quote if) (quote s!:compfn) (function s!:comif)) (de s!:comwhen (x env context) (prog (l2) (setq l2 (gensym)) (cond ((lessp context 2) (progn (s!:comval (cadr x) env 1) (s!:outjump (quote JUMPNIL) l2)) ) (t (s!:jumpif nil (cadr x) env l2))) (s!:comval (cons (quote progn) (cddr x )) env context) (s!:set_label l2))) (put (quote when) (quote s!:compfn) (function s!:comwhen)) (de s!:comunless (x env context) (s!:comwhen (list!* (quote when) (list ( quote not) (cadr x)) (cddr x)) env context)) (put (quote unless) (quote s!:compfn) (function s!:comunless)) (de s!:comicase (x env context) (prog (l1 labs labassoc w) (setq x (cdr x)) ( prog (var1116) (setq var1116 (cdr x)) lab1115 (cond ((null var1116) (return nil))) (prog (v) (setq v (car var1116)) (progn (setq w (assoc!*!* v labassoc) ) (cond (w (setq l1 (cons (cdr w) l1))) (t (progn (setq l1 (gensym)) (setq labs (cons l1 labs)) (setq labassoc (cons (cons v l1) labassoc))))))) (setq var1116 (cdr var1116)) (go lab1115)) (s!:comval (car x) env 1) (s!:outjump ( quote ICASE) (reversip labs)) (setq l1 (gensym)) (prog (var1118) (setq var1118 labassoc) lab1117 (cond ((null var1118) (return nil))) (prog (v) ( setq v (car var1118)) (progn (s!:set_label (cdr v)) (s!:comval (car v) env context) (s!:outjump (quote JUMP) l1))) (setq var1118 (cdr var1118)) (go lab1117)) (s!:set_label l1))) (put (quote s!:icase) (quote s!:compfn) (function s!:comicase)) (put (quote JUMPLITEQ!*) (quote s!:opcode) (get (quote JUMPLITEQ) (quote s!:opcode))) (put (quote JUMPLITNE!*) (quote s!:opcode) (get (quote JUMPLITNE) (quote s!:opcode))) (de s!:jumpliteql (val lab env) (prog (w) (cond ((or (idp val) (eq!-safe val) ) (progn (setq w (list (quote JUMPLITEQ!*) val val)) ( s!:record_literal_for_jump w env lab))) (t (progn (s!:outopcode0 (quote PUSH) (quote (PUSH))) (s!:loadliteral val env) (s!:outopcode1 (quote BUILTIN2) ( get (quote eql) (quote s!:builtin2)) (quote eql)) (s!:outjump (quote JUMPT) lab) (flag (list lab) (quote s!:jumpliteql)) (s!:outopcode0 (quote POP) ( quote (POP)))))))) (de s!:casebranch (sw env dflt) (prog (size w w1 r g) (setq size (plus 4 ( truncate (length sw) 2))) (prog nil lab1119 (cond ((null (or (equal ( remainder size 2) 0) (equal (remainder size 3) 0) (equal (remainder size 5) 0 ) (equal (remainder size 13) 0))) (return nil))) (setq size (plus size 1)) ( go lab1119)) (prog (var1121) (setq var1121 sw) lab1120 (cond ((null var1121) (return nil))) (prog (p) (setq p (car var1121)) (progn (setq w (remainder ( eqlhash (car p)) size)) (setq w1 (assoc!*!* w r)) (cond (w1 (rplacd (cdr w1) (cons p (cddr w1)))) (t (setq r (cons (list w (gensym) p) r)))))) (setq var1121 (cdr var1121)) (go lab1120)) (s!:outopcode0 (quote PUSH) (quote (PUSH ))) (rplacd env (cons 0 (cdr env))) (s!:outopcode1lit (quote CALL1) (quote eqlhash) env) (s!:loadliteral size env) (setq g (gensym)) (s!:outopcode1 ( quote BUILTIN2) (get (quote iremainder) (quote s!:builtin2)) (quote iremainder)) (s!:outjump (quote ICASE) (cons g (prog (i var1123) (setq i 0) lab1122 (cond ((minusp (times 1 (difference (difference size 1) i))) (return (reversip var1123)))) (setq var1123 (cons (progn (setq w (assoc!*!* i r)) ( cond (w (cadr w)) (t g))) var1123)) (setq i (plus i 1)) (go lab1122)))) (prog (var1127) (setq var1127 r) lab1126 (cond ((null var1127) (return nil))) ( prog (p) (setq p (car var1127)) (progn (s!:set_label (cadr p)) (s!:outopcode0 (quote POP) (quote (POP))) (prog (var1125) (setq var1125 (cddr p)) lab1124 ( cond ((null var1125) (return nil))) (prog (q) (setq q (car var1125)) ( s!:jumpliteql (car q) (cdr q) env)) (setq var1125 (cdr var1125)) (go lab1124) ) (s!:outjump (quote JUMP) dflt))) (setq var1127 (cdr var1127)) (go lab1126)) (s!:set_label g) (s!:outopcode0 (quote POP) (quote (POP))) (s!:outjump ( quote JUMP) dflt) (rplacd env (cddr env)))) (de s!:comcase (x env context) (prog (keyform blocks v w g dflt sw keys nonnum) (setq x (cdr x)) (setq keyform (car x)) (prog (y) (setq y (cdr x)) lab1130 (cond ((null y) (return nil))) (progn (setq w (assoc!*!* (cdar y) blocks)) (cond (w (setq g (cdr w))) (t (progn (setq g (gensym)) (setq blocks (cons (cons (cdar y) g) blocks))))) (setq w (caar y)) (cond ((and (null (cdr y)) (or (equal w t) (equal w (quote otherwise)))) (setq dflt g)) (t (progn ( cond ((atom w) (setq w (list w)))) (prog (var1129) (setq var1129 w) lab1128 ( cond ((null var1129) (return nil))) (prog (n) (setq n (car var1129)) (progn ( cond ((or (idp n) (numberp n)) (progn (cond ((not (fixp n)) (setq nonnum t))) (setq keys (cons n keys)) (setq sw (cons (cons n g) sw)))) (t (error 0 (list "illegal case label" n)))))) (setq var1129 (cdr var1129)) (go lab1128)))))) (setq y (cdr y)) (go lab1130)) (cond ((null dflt) (progn (cond ((setq w ( assoc!*!* nil blocks)) (setq dflt (cdr w))) (t (setq blocks (cons (cons nil ( setq dflt (gensym))) blocks))))))) (cond ((not nonnum) (progn (setq keys ( sort keys (function lessp))) (setq nonnum (car keys)) (setq g (lastcar keys)) (cond ((lessp (difference g nonnum) (times 2 (length keys))) (progn (cond (( not (equal nonnum 0)) (progn (setq keyform (list (quote xdifference) keyform nonnum)) (setq sw (prog (var1132 var1133) (setq var1132 sw) lab1131 (cond (( null var1132) (return (reversip var1133)))) (prog (y) (setq y (car var1132)) (setq var1133 (cons (cons (difference (car y) nonnum) (cdr y)) var1133))) ( setq var1132 (cdr var1132)) (go lab1131)))))) (s!:comval keyform env 1) (setq w nil) (prog (i) (setq i 0) lab1134 (cond ((minusp (times 1 (difference g i) )) (return nil))) (cond ((setq v (assoc!*!* i sw)) (setq w (cons (cdr v) w))) (t (setq w (cons dflt w)))) (setq i (plus i 1)) (go lab1134)) (setq w (cons dflt (reversip w))) (s!:outjump (quote ICASE) w) (setq nonnum nil))) (t (setq nonnum t)))))) (cond (nonnum (progn (s!:comval keyform env 1) (cond ((lessp (length sw) 7) (progn (prog (var1136) (setq var1136 sw) lab1135 (cond ((null var1136) (return nil))) (prog (y) (setq y (car var1136)) (s!:jumpliteql (car y) (cdr y) env)) (setq var1136 (cdr var1136)) (go lab1135)) (s!:outjump ( quote JUMP) dflt))) (t (s!:casebranch sw env dflt)))))) (setq g (gensym)) ( prog (var1138) (setq var1138 blocks) lab1137 (cond ((null var1138) (return nil))) (prog (v) (setq v (car var1138)) (progn (s!:set_label (cdr v)) (cond ( (flagp (cdr v) (quote s!:jumpliteql)) (s!:outlose 1))) (s!:comval (cons ( quote progn) (car v)) env context) (s!:outjump (quote JUMP) g))) (setq var1138 (cdr var1138)) (go lab1137)) (s!:set_label g))) (put (quote case) (quote s!:compfn) (function s!:comcase)) (fluid (quote (!*defn dfprint!* s!:dfprintsave s!:faslmod_name))) (de s!:comeval!-when (x env context) (prog (y) (setq x (cdr x)) (setq y (car x)) (princ "COMPILING eval-when: ") (print y) (print x) (setq x (cons (quote progn) (cdr x))) (cond ((memq (quote compile) y) (eval x))) (cond ((memq ( quote load) y) (progn (cond (dfprint!* (apply1 dfprint!* x)))))) (cond ((memq (quote eval) y) (s!:comval x env context)) (t (s!:comval nil env context)))) ) (put (quote eval!-when) (quote s!:compfn) (function s!:comeval!-when)) (de s!:comthe (x env context) (s!:comval (caddr x) env context)) (put (quote the) (quote s!:compfn) (function s!:comthe)) (de s!:comand (x env context) (prog (l) (setq l (gensym)) (setq x (cdr x)) ( s!:comval (car x) env 1) (prog nil lab1139 (cond ((null (setq x (cdr x))) ( return nil))) (progn (s!:outjump (quote JUMPNIL) l) (s!:comval (car x) env 1) ) (go lab1139)) (s!:set_label l))) (put (quote and) (quote s!:compfn) (function s!:comand)) (de s!:comor (x env context) (prog (l) (setq l (gensym)) (setq x (cdr x)) ( s!:comval (car x) env 1) (prog nil lab1140 (cond ((null (setq x (cdr x))) ( return nil))) (progn (s!:outjump (quote JUMPT) l) (s!:comval (car x) env 1)) (go lab1140)) (s!:set_label l))) (put (quote or) (quote s!:compfn) (function s!:comor)) (de s!:combool (neg x env lab) (prog (fn) (setq fn (eqcar x (quote or))) ( cond ((eq fn neg) (prog nil lab1141 (cond ((null (setq x (cdr x))) (return nil))) (s!:jumpif fn (car x) env lab) (go lab1141))) (t (progn (setq neg ( gensym)) (prog nil lab1142 (cond ((null (setq x (cdr x))) (return nil))) ( s!:jumpif fn (car x) env neg) (go lab1142)) (s!:outjump (quote JUMP) lab) ( s!:set_label neg)))))) (put (quote and) (quote s!:testfn) (function s!:combool)) (put (quote or) (quote s!:testfn) (function s!:combool)) (de s!:testeq (neg x env lab) (prog (a b) (setq a (s!:improve (cadr x))) ( setq b (s!:improve (caddr x))) (cond ((or (s!:eval_to_eq_unsafe a) ( s!:eval_to_eq_unsafe b)) (progn (cond ((neq (posn) 0) (terpri))) (princ "++++ EQ on number upgraded to EQUAL in ") (prin s!:current_function) (princ " : ") (prin a) (princ " ") (print b) (return (s!:testequal neg (cons (quote equal) (cdr x)) env lab))))) (cond ((null a) (s!:jumpif (not neg) b env lab)) (t (cond ((null b) (s!:jumpif (not neg) a env lab)) (t (cond ((or (eqcar a ( quote quote)) (and (atom a) (not (symbolp a)))) (progn (s!:comval b env 1) ( cond ((eqcar a (quote quote)) (setq a (cadr a)))) (setq b (list (cond (neg ( quote JUMPLITEQ)) (t (quote JUMPLITNE))) a a)) (s!:record_literal_for_jump b env lab))) (t (cond ((or (eqcar b (quote quote)) (and (atom b) (not (symbolp b)))) (progn (s!:comval a env 1) (cond ((eqcar b (quote quote)) (setq b (cadr b)))) (setq a (list (cond (neg (quote JUMPLITEQ)) (t (quote JUMPLITNE))) b b )) (s!:record_literal_for_jump a env lab))) (t (progn (s!:load2 a b env) ( cond (neg (s!:outjump (quote JUMPEQ) lab)) (t (s!:outjump (quote JUMPNE) lab) ))))))))))))) (de s!:testeq1 (neg x env lab) (prog (a b) (setq a (s!:improve (cadr x))) ( setq b (s!:improve (caddr x))) (cond ((null a) (s!:jumpif (not neg) b env lab )) (t (cond ((null b) (s!:jumpif (not neg) a env lab)) (t (cond ((or (eqcar a (quote quote)) (and (atom a) (not (symbolp a)))) (progn (s!:comval b env 1) (cond ((eqcar a (quote quote)) (setq a (cadr a)))) (setq b (list (cond (neg ( quote JUMPLITEQ)) (t (quote JUMPLITNE))) a a)) (s!:record_literal_for_jump b env lab))) (t (cond ((or (eqcar b (quote quote)) (and (atom b) (not (symbolp b)))) (progn (s!:comval a env 1) (cond ((eqcar b (quote quote)) (setq b (cadr b)))) (setq a (list (cond (neg (quote JUMPLITEQ)) (t (quote JUMPLITNE))) b b )) (s!:record_literal_for_jump a env lab))) (t (progn (s!:load2 a b env) ( cond (neg (s!:outjump (quote JUMPEQ) lab)) (t (s!:outjump (quote JUMPNE) lab) ))))))))))))) (put (quote eq) (quote s!:testfn) (function s!:testeq)) (cond ((eq!-safe 0) (put (quote iequal) (quote s!:testfn) (function s!:testeq1))) (t (put (quote iequal) (quote s!:testfn) (function s!:testequal )))) (de s!:testequal (neg x env lab) (prog (a b) (setq a (cadr x)) (setq b (caddr x)) (cond ((null a) (s!:jumpif (not neg) b env lab)) (t (cond ((null b) ( s!:jumpif (not neg) a env lab)) (t (cond ((or (and (eqcar a (quote quote)) ( or (symbolp (cadr a)) (eq!-safe (cadr a)))) (and (eqcar b (quote quote)) (or (symbolp (cadr b)) (eq!-safe (cadr b)))) (and (not (idp a)) (eq!-safe a)) ( and (not (idp b)) (eq!-safe b))) (s!:testeq1 neg (cons (quote eq) (cdr x)) env lab)) (t (progn (s!:load2 a b env) (cond (neg (s!:outjump (quote JUMPEQUAL) lab)) (t (s!:outjump (quote JUMPNEQUAL) lab)))))))))))) (put (quote equal) (quote s!:testfn) (function s!:testequal)) (de s!:testneq (neg x env lab) (s!:testequal (not neg) (cons (quote equal) ( cdr x)) env lab)) (put (quote neq) (quote s!:testfn) (function s!:testneq)) (de s!:testeqcar (neg x env lab) (prog (a b sw promote) (setq a (cadr x)) ( setq b (s!:improve (caddr x))) (cond ((s!:eval_to_eq_unsafe b) (progn (cond ( (neq (posn) 0) (terpri))) (princ "++++ EQCAR on number upgraded to EQUALCAR in ") (prin s!:current_function) ( princ " : ") (print b) (setq promote t)))) (cond ((and (not promote) (eqcar b (quote quote))) (progn (s!:comval a env 1) (setq b (cadr b)) (setq a (list ( cond (neg (quote JUMPEQCAR)) (t (quote JUMPNEQCAR))) b b)) ( s!:record_literal_for_jump a env lab))) (t (cond ((or (equal b nil) (equal b t) (and (not (symbolp b)) (eq!-safe b))) (progn (s!:comval a env 1) (setq a ( list (cond (neg (quote JUMPEQCAR)) (t (quote JUMPNEQCAR))) b b)) ( s!:record_literal_for_jump a env lab))) (t (progn (setq sw (s!:load2 a b env) ) (cond (sw (s!:outopcode0 (quote SWOP) (quote (SWOP))))) (cond (promote ( s!:outopcode1 (quote BUILTIN2) (get (quote equalcar) (quote s!:builtin2)) ( quote equalcar))) (t (s!:outopcode0 (quote EQCAR) (quote (EQCAR))))) ( s!:outjump (cond (neg (quote JUMPT)) (t (quote JUMPNIL))) lab)))))))) (put (quote eqcar) (quote s!:testfn) (function s!:testeqcar)) (de s!:testflagp (neg x env lab) (prog (a b sw) (setq a (cadr x)) (setq b ( caddr x)) (cond ((eqcar b (quote quote)) (progn (s!:comval a env 1) (setq b ( cadr b)) (setq sw (symbol!-make!-fastget b nil)) (cond (sw (progn ( s!:outopcode1 (quote FASTGET) (logor sw 128) b) (s!:outjump (cond (neg (quote JUMPT)) (t (quote JUMPNIL))) lab))) (t (progn (setq a (list (cond (neg ( quote JUMPFLAGP)) (t (quote JUMPNFLAGP))) b b)) (s!:record_literal_for_jump a env lab)))))) (t (progn (setq sw (s!:load2 a b env)) (cond (sw ( s!:outopcode0 (quote SWOP) (quote (SWOP))))) (s!:outopcode0 (quote FLAGP) ( quote (FLAGP))) (s!:outjump (cond (neg (quote JUMPT)) (t (quote JUMPNIL))) lab)))))) (put (quote flagp) (quote s!:testfn) (function s!:testflagp)) (global (quote (s!:storelocs))) (setq s!:storelocs (s!:vecof (quote (STORELOC0 STORELOC1 STORELOC2 STORELOC3 STORELOC4 STORELOC5 STORELOC6 STORELOC7)))) (de s!:comsetq (x env context) (prog (n w var) (setq x (cdr x)) (cond ((null x) (return nil))) (cond ((or (not (symbolp (car x))) (null (cdr x))) (return (error 0 (list "bad args for setq" x))))) (s!:comval (cadr x) env 1) (setq var (car x)) (setq n 0) (setq w (cdr env)) (prog nil lab1143 (cond ((null ( and w (not (eqcar w var)))) (return nil))) (progn (setq n (add1 n)) (setq w ( cdr w))) (go lab1143)) (cond (w (progn (cond ((not (member!*!* (cons (quote loc) w) s!:a_reg_values)) (setq s!:a_reg_values (cons (cons (quote loc) w) s!:a_reg_values)))) (cond ((lessp n 8) (s!:outopcode0 (getv s!:storelocs n) ( list (quote storeloc) var))) (t (cond ((greaterp n 4095) (error 0 "stack frame > 4095")) (t (cond ((greaterp n 255) (s!:outopcode2 (quote BIGSTACK) (plus 64 (truncate n 256)) (logand n 255) (list (quote STORELOC) var))) (t (s!:outopcode1 (quote STORELOC) n var))))))))) (t (cond ((setq w ( s!:find_lexical var s!:lexical_env 0)) (progn (cond ((not (member!*!* (cons ( quote lex) w) s!:a_reg_values)) (setq s!:a_reg_values (cons (cons (quote lex) w) s!:a_reg_values)))) (s!:outlexref (quote STORELEX) (length (cdr env)) ( car w) (cadr w) var))) (t (progn (cond ((or (null var) (eq var t)) (error 0 ( list "bad variable in setq" var))) (t (s!:should_be_fluid var))) (setq w ( cons (quote free) var)) (cond ((not (member!*!* w s!:a_reg_values)) (setq s!:a_reg_values (cons w s!:a_reg_values)))) (s!:outopcode1lit (quote STOREFREE) var env)))))) (cond ((cddr x) (return (s!:comsetq (cdr x) env context)))))) (put (quote setq) (quote s!:compfn) (function s!:comsetq)) (put (quote noisy!-setq) (quote s!:compfn) (function s!:comsetq)) (de s!:comlist (x env context) (prog (w) (cond ((null (setq x (cdr x))) ( return (s!:comval nil env context)))) (setq s!:a_reg_values nil) (cond ((null (setq w (cdr x))) (s!:comval (list (quote ncons) (car x)) env context)) (t ( cond ((null (setq w (cdr w))) (s!:comval (list (quote list2) (car x) (cadr x) ) env context)) (t (cond ((null (cdr w)) (s!:comval (list (quote list3) (car x) (cadr x) (car w)) env context)) (t (s!:comval (list (quote list2!*) (car x ) (cadr x) (cons (quote list) w)) env context))))))))) (put (quote list) (quote s!:compfn) (function s!:comlist)) (de s!:comlist!* (x env context) (prog (w) (cond ((null (setq x (cdr x))) ( return (s!:comval nil env context)))) (setq s!:a_reg_values nil) (cond ((null (setq w (cdr x))) (s!:comval (car x) env context)) (t (cond ((null (setq w ( cdr w))) (s!:comval (list (quote cons) (car x) (cadr x)) env context)) (t ( cond ((null (cdr w)) (s!:comval (list (quote list2!*) (car x) (cadr x) (car w )) env context)) (t (s!:comval (list (quote list2!*) (car x) (cadr x) (cons ( quote list!*) w)) env context))))))))) (put (quote list!*) (quote s!:compfn) (function s!:comlist!*)) (de s!:comcons (x env context) (prog (a b) (setq a (cadr x)) (setq b (caddr x )) (cond ((or (equal b nil) (equal b (quote (quote nil)))) (s!:comval (list ( quote ncons) a) env context)) (t (cond ((eqcar a (quote cons)) (s!:comval ( list (quote acons) (cadr a) (caddr a) b) env context)) (t (cond ((eqcar b ( quote cons)) (cond ((null (caddr b)) (s!:comval (list (quote list2) a (cadr b )) env context)) (t (s!:comval (list (quote list2!*) a (cadr b) (caddr b)) env context)))) (t (cond ((and (not !*ord) (s!:iseasy a) (not (s!:iseasy b))) (s!:comval (list (quote xcons) b a) env context)) (t (s!:comcall x env context))))))))))) (put (quote cons) (quote s!:compfn) (function s!:comcons)) (de s!:comapply (x env context) (prog (a b n) (setq a (cadr x)) (setq b ( caddr x)) (cond ((and (null (cdddr x)) (eqcar b (quote list))) (progn (cond ( (eqcar a (quote quote)) (return (progn (setq n s!:current_function) (prog ( s!:current_function) (setq s!:current_function (compress (append (explode n) (cons (quote !!) (cons (quote !.) (explodec (setq s!:current_count (plus s!:current_count 1)))))))) (return (s!:comval (cons (cadr a) (cdr b)) env context))))))) (setq n (length (setq b (cdr b)))) (return (s!:comval (cons ( quote funcall) (cons a b)) env context)))) (t (cond ((and (null b) (null ( cdddr x))) (return (s!:comval (list (quote funcall) a) env context))) (t ( return (s!:comcall x env context)))))))) (put (quote apply) (quote s!:compfn) (function s!:comapply)) (de s!:imp_funcall (u) (prog (n) (setq u (cdr u)) (cond ((eqcar (car u) ( quote function)) (return (s!:improve (cons (cadar u) (cdr u)))))) (setq n ( length (cdr u))) (setq u (cond ((equal n 0) (cons (quote apply0) u)) (t (cond ((equal n 1) (cons (quote apply1) u)) (t (cond ((equal n 2) (cons (quote apply2) u)) (t (cond ((equal n 3) (cons (quote apply3) u)) (t (cons (quote funcall!*) u)))))))))) (return u))) (put (quote funcall) (quote s!:tidy_fn) (quote s!:imp_funcall)) (de s!:eval_to_eq_safe (x) (or (equal x nil) (equal x t) (and (not (symbolp x )) (eq!-safe x)) (and (not (atom x)) (flagp (car x) (quote eq!-safe))) (and ( eqcar x (quote quote)) (or (symbolp (cadr x)) (eq!-safe (cadr x)))))) (de s!:eval_to_eq_unsafe (x) (or (and (atom x) (not (symbolp x)) (not ( eq!-safe x))) (and (not (atom x)) (flagp (car x) (quote eq!-unsafe))) (and ( eqcar x (quote quote)) (or (not (atom (cadr x))) (and (not (symbolp (cadr x)) ) (not (eq!-safe (cadr x)))))))) (de s!:list_all_eq_safe (u) (or (atom u) (and (or (symbolp (car u)) (eq!-safe (car u))) (s!:list_all_eq_safe (cdr u))))) (de s!:eval_to_list_all_eq_safe (x) (or (null x) (and (eqcar x (quote quote)) (s!:list_all_eq_safe (cadr x))) (and (eqcar x (quote list)) (or (null (cdr x )) (and (s!:eval_to_eq_safe (cadr x)) (s!:eval_to_list_all_eq_safe (cons ( quote list) (cddr x)))))) (and (eqcar x (quote cons)) (s!:eval_to_eq_safe ( cadr x)) (s!:eval_to_list_all_eq_safe (caddr x))))) (de s!:list_some_eq_unsafe (u) (and (not (atom u)) (or (s!:eval_to_eq_unsafe (car u)) (s!:list_some_eq_unsafe (cdr u))))) (de s!:eval_to_list_some_eq_unsafe (x) (cond ((atom x) nil) (t (cond ((eqcar x (quote quote)) (s!:list_some_eq_unsafe (cadr x))) (t (cond ((and (eqcar x ( quote list)) (cdr x)) (or (s!:eval_to_eq_unsafe (cadr x)) ( s!:eval_to_list_some_eq_unsafe (cons (quote list) (cddr x))))) (t (cond (( eqcar x (quote cons)) (or (s!:eval_to_eq_unsafe (cadr x)) ( s!:eval_to_list_some_eq_unsafe (caddr x)))) (t nil))))))))) (de s!:eval_to_car_eq_safe (x) (and (or (eqcar x (quote cons)) (eqcar x ( quote list))) (not (null (cdr x))) (s!:eval_to_eq_safe (cadr x)))) (de s!:eval_to_car_eq_unsafe (x) (and (or (eqcar x (quote cons)) (eqcar x ( quote list))) (not (null (cdr x))) (s!:eval_to_eq_unsafe (cadr x)))) (de s!:alist_eq_safe (u) (or (atom u) (and (not (atom (car u))) (or (symbolp (caar u)) (eq!-safe (caar u))) (s!:alist_eq_safe (cdr u))))) (de s!:eval_to_alist_eq_safe (x) (or (null x) (and (eqcar x (quote quote)) ( s!:alist_eq_safe (cadr x))) (and (eqcar x (quote list)) (or (null (cdr x)) ( and (s!:eval_to_car_eq_safe (cadr x)) (s!:eval_to_alist_eq_safe (cons (quote list) (cddr x)))))) (and (eqcar x (quote cons)) (s!:eval_to_car_eq_safe (cadr x)) (s!:eval_to_alist_eq_safe (caddr x))))) (de s!:alist_eq_unsafe (u) (and (not (atom u)) (not (atom (car u))) (or (not (atom (caar u))) (and (not (symbolp (caar u))) (not (eq!-safe (caar u)))) ( s!:alist_eq_unsafe (cdr u))))) (de s!:eval_to_alist_eq_unsafe (x) (cond ((null x) nil) (t (cond ((eqcar x ( quote quote)) (s!:alist_eq_unsafe (cadr x))) (t (cond ((eqcar x (quote list)) (and (cdr x) (or (s!:eval_to_car_eq_unsafe (cadr x)) ( s!:eval_to_alist_eq_unsafe (cons (quote list) (cddr x)))))) (t (cond ((eqcar x (quote cons)) (or (s!:eval_to_car_eq_unsafe (cadr x)) ( s!:eval_to_alist_eq_safe (caddr x)))) (t nil))))))))) (flag (quote (eq eqcar null not greaterp lessp geq leq minusp atom numberp consp)) (quote eq!-safe)) (cond ((not (eq!-safe 1)) (flag (quote (length plus minus difference times quotient plus2 times2 expt fix float)) (quote eq!-unsafe)))) (de s!:comequal (x env context) (cond ((or (s!:eval_to_eq_safe (cadr x)) ( s!:eval_to_eq_safe (caddr x))) (s!:comcall (cons (quote eq) (cdr x)) env context)) (t (s!:comcall x env context)))) (put (quote equal) (quote s!:compfn) (function s!:comequal)) (de s!:comeq (x env context) (cond ((or (s!:eval_to_eq_unsafe (cadr x)) ( s!:eval_to_eq_unsafe (caddr x))) (progn (cond ((neq (posn) 0) (terpri))) ( princ "++++ EQ on number upgraded to EQUAL in ") (prin s!:current_function) ( princ " : ") (prin (cadr x)) (princ " ") (print (caddr x)) (s!:comcall (cons (quote equal) (cdr x)) env context))) (t (s!:comcall x env context)))) (put (quote eq) (quote s!:compfn) (function s!:comeq)) (de s!:comeqcar (x env context) (cond ((s!:eval_to_eq_unsafe (caddr x)) ( progn (cond ((neq (posn) 0) (terpri))) (princ "++++ EQCAR on number upgraded to EQUALCAR in ") (prin s!:current_function) ( princ " : ") (prin (caddr x)) (s!:comcall (cons (quote equalcar) (cdr x)) env context))) (t (s!:comcall x env context)))) (put (quote eqcar) (quote s!:compfn) (function s!:comeqcar)) (de s!:comsublis (x env context) (cond ((s!:eval_to_alist_eq_safe (cadr x)) ( s!:comval (cons (quote subla) (cdr x)) env context)) (t (s!:comcall x env context)))) (put (quote sublis) (quote s!:compfn) (function s!:comsublis)) (de s!:comsubla (x env context) (cond ((s!:eval_to_alist_eq_unsafe (cadr x)) (progn (cond ((neq (posn) 0) (terpri))) (princ "++++ SUBLA on number upgraded to SUBLIS in ") (prin s!:current_function) ( princ " : ") (print (cadr x)) (s!:comval (cons (quote sublis) (cdr x)) env context))) (t (s!:comcall x env context)))) (put (quote subla) (quote s!:compfn) (function s!:comsubla)) (de s!:comassoc (x env context) (cond ((and (or (s!:eval_to_eq_safe (cadr x)) (s!:eval_to_alist_eq_safe (caddr x))) (equal (length x) 3)) (s!:comval (cons (quote atsoc) (cdr x)) env context)) (t (cond ((equal (length x) 3) ( s!:comcall (cons (quote assoc!*!*) (cdr x)) env context)) (t (s!:comcall x env context)))))) (put (quote assoc) (quote s!:compfn) (function s!:comassoc)) (put (quote assoc!*!*) (quote s!:compfn) (function s!:comassoc)) (de s!:comatsoc (x env context) (cond ((or (s!:eval_to_eq_unsafe (cadr x)) ( s!:eval_to_alist_eq_unsafe (caddr x))) (progn (cond ((neq (posn) 0) (terpri)) ) (princ "++++ ATSOC on number upgraded to ASSOC in ") (prin s!:current_function) (princ " : ") (prin (cadr x)) (princ " ") (print (caddr x)) (s!:comval (cons (quote assoc) (cdr x)) env context))) (t (s!:comcall x env context)))) (put (quote atsoc) (quote s!:compfn) (function s!:comatsoc)) (de s!:commember (x env context) (cond ((and (or (s!:eval_to_eq_safe (cadr x) ) (s!:eval_to_list_all_eq_safe (caddr x))) (equal (length x) 3)) (s!:comval ( cons (quote memq) (cdr x)) env context)) (t (s!:comcall x env context)))) (put (quote member) (quote s!:compfn) (function s!:commember)) (put (quote member!*!*) (quote s!:compfn) (function s!:commember)) (de s!:commemq (x env context) (cond ((or (s!:eval_to_eq_unsafe (cadr x)) ( s!:eval_to_list_some_eq_unsafe (caddr x))) (progn (cond ((neq (posn) 0) ( terpri))) (princ "++++ MEMQ on number upgraded to MEMBER in ") (prin s!:current_function) (princ " : ") (prin (cadr x)) (princ " ") (print (caddr x)) (s!:comval (cons (quote member) (cdr x)) env context))) (t (s!:comcall x env context)))) (put (quote memq) (quote s!:compfn) (function s!:commemq)) (de s!:comdelete (x env context) (cond ((and (or (s!:eval_to_eq_safe (cadr x) ) (s!:eval_to_list_all_eq_safe (caddr x))) (equal (length x) 3)) (s!:comval ( cons (quote deleq) (cdr x)) env context)) (t (s!:comcall x env context)))) (put (quote delete) (quote s!:compfn) (function s!:comdelete)) (de s!:comdeleq (x env context) (cond ((or (s!:eval_to_eq_unsafe (cadr x)) ( s!:eval_to_list_some_eq_unsafe (caddr x))) (progn (cond ((neq (posn) 0) ( terpri))) (princ "++++ DELEQ on number upgraded to DELETE in ") (prin s!:current_function) (princ " : ") (prin (cadr x)) (princ " ") (print (caddr x)) (s!:comval (cons (quote delete) (cdr x)) env context))) (t (s!:comcall x env context)))) (put (quote deleq) (quote s!:compfn) (function s!:comdeleq)) (de s!:commap (fnargs env context) (prog (carp fn fn1 args var avar moveon l1 r s closed) (setq fn (car fnargs)) (cond ((greaterp context 1) (progn (cond ((equal fn (quote mapcar)) (setq fn (quote mapc))) (t (cond ((equal fn (quote maplist)) (setq fn (quote map))))))))) (cond ((or (equal fn (quote mapc)) ( equal fn (quote mapcar)) (equal fn (quote mapcan))) (setq carp t))) (setq fnargs (cdr fnargs)) (cond ((atom fnargs) (error 0 "bad arguments to map function"))) (setq fn1 (cadr fnargs)) (prog nil lab1144 (cond ((null (or (eqcar fn1 (quote function)) (and (eqcar fn1 (quote quote)) (eqcar (cadr fn1) (quote lambda))))) (return nil))) (progn (setq fn1 (cadr fn1)) (setq closed t)) (go lab1144)) (setq args (car fnargs)) (setq l1 ( gensym)) (setq r (gensym)) (setq s (gensym)) (setq var (gensym)) (setq avar var) (cond (carp (setq avar (list (quote car) avar)))) (cond (closed (setq fn1 (list fn1 avar))) (t (setq fn1 (list (quote funcall) fn1 avar)))) (setq moveon (list (quote setq) var (list (quote cdr) var))) (cond ((or (equal fn ( quote map)) (equal fn (quote mapc))) (setq fn (sublis (list (cons (quote l1) l1) (cons (quote var) var) (cons (quote fn) fn1) (cons (quote args) args) ( cons (quote moveon) moveon)) (quote (prog (var) (setq var args) l1 (cond (( not var) (return nil))) fn moveon (go l1)))))) (t (cond ((or (equal fn (quote maplist)) (equal fn (quote mapcar))) (setq fn (sublis (list (cons (quote l1) l1) (cons (quote var) var) (cons (quote fn) fn1) (cons (quote args) args) ( cons (quote moveon) moveon) (cons (quote r) r)) (quote (prog (var r) (setq var args) l1 (cond ((not var) (return (reversip r)))) (setq r (cons fn r)) moveon (go l1)))))) (t (setq fn (sublis (list (cons (quote l1) l1) (cons ( quote l2) (gensym)) (cons (quote var) var) (cons (quote fn) fn1) (cons (quote args) args) (cons (quote moveon) moveon) (cons (quote r) (gensym)) (cons ( quote s) (gensym))) (quote (prog (var r s) (setq var args) (setq r (setq s ( list nil))) l1 (cond ((not var) (return (cdr r)))) (rplacd s fn) l2 (cond (( not (atom (cdr s))) (setq s (cdr s)) (go l2))) moveon (go l1))))))))) ( s!:comval fn env context))) (put (quote map) (quote s!:compfn) (function s!:commap)) (put (quote maplist) (quote s!:compfn) (function s!:commap)) (put (quote mapc) (quote s!:compfn) (function s!:commap)) (put (quote mapcar) (quote s!:compfn) (function s!:commap)) (put (quote mapcon) (quote s!:compfn) (function s!:commap)) (put (quote mapcan) (quote s!:compfn) (function s!:commap)) (de s!:nilargs (use) (cond ((null use) t) (t (cond ((or (equal (car use) ( quote nil)) (equal (car use) (quote (quote nil)))) (s!:nilargs (cdr use))) (t nil))))) (de s!:subargs (args use) (cond ((null use) t) (t (cond ((null args) ( s!:nilargs use)) (t (cond ((not (equal (car args) (car use))) nil) (t ( s!:subargs (cdr args) (cdr use))))))))) (fluid (quote (!*where_defined!*))) (de clear_source_database nil (progn (setq !*where_defined!* (mkhash 10 2 1.5 )) nil)) (de load_source_database (filename) (prog (a b) (clear_source_database) (setq a (open filename (quote input))) (cond ((null a) (return nil))) (setq a (rds a)) (prog nil lab1145 (cond ((null (setq b (read))) (return nil))) (puthash (car b) !*where_defined!* (cdr b)) (go lab1145)) (close (rds a)) (return nil) )) (de save_source_database (filename) (prog (a) (setq a (open filename (quote output))) (cond ((null a) (return nil))) (setq a (wrs a)) (prog (var1147) ( setq var1147 (sort (hashcontents !*where_defined!*) (function orderp))) lab1146 (cond ((null var1147) (return nil))) (prog (z) (setq z (car var1147)) (progn (prin z) (terpri))) (setq var1147 (cdr var1147)) (go lab1146)) (princ nil) (terpri) (wrs a) (setq !*where_defined!* nil) (return nil))) (de display_source_database nil (prog (w) (cond ((null !*where_defined!*) ( return nil))) (setq w (hashcontents !*where_defined!*)) (setq w (sort w ( function orderp))) (terpri) (prog (var1149) (setq var1149 w) lab1148 (cond (( null var1149) (return nil))) (prog (x) (setq x (car var1149)) (progn (princ ( car x)) (ttab 40) (prin (cdr x)) (terpri))) (setq var1149 (cdr var1149)) (go lab1148)))) (fluid (quote (s!:r2i_simple_recurse s!:r2i_cons_recurse))) (de s!:r2i (name args body) (prog (lab v b1 s!:r2i_simple_recurse s!:r2i_cons_recurse) (setq lab (gensym)) (setq v (list (gensym))) (setq b1 ( s!:r2i1 name args body lab v)) (cond (s!:r2i_cons_recurse (progn (setq b1 ( list (quote prog) v lab b1)) (return b1))) (t (cond (s!:r2i_simple_recurse ( progn (setq v (list (gensym))) (setq b1 (s!:r2i2 name args body lab v)) (setq b1 (list (quote prog) (cdr v) lab b1)) (return b1))) (t (return (s!:r2i3 name args body lab v)))))))) (de s!:r2i1 (name args body lab v) (cond ((or (null body) (equal body (quote (progn)))) (list (quote return) (list (quote nreverse) (car v)))) (t (cond (( and (eqcar body name) (equal (length (cdr body)) (length args))) (progn (setq s!:r2i_simple_recurse t) (cons (quote progn) (append (s!:r2isteps args (cdr body) v) (list (list (quote go) lab)))))) (t (cond ((eqcar body (quote cond)) (cons (quote cond) (s!:r2icond name args (cdr body) lab v))) (t (cond (( eqcar body (quote if)) (cons (quote if) (s!:r2iif name args (cdr body) lab v) )) (t (cond ((eqcar body (quote when)) (cons (quote when) (s!:r2iwhen name args (cdr body) lab v))) (t (cond ((eqcar body (quote cons)) (s!:r2icons name args (cadr body) (caddr body) lab v)) (t (cond ((or (eqcar body (quote progn )) (eqcar body (quote prog2))) (cons (quote progn) (s!:r2iprogn name args ( cdr body) lab v))) (t (cond ((eqcar body (quote and)) (s!:r2i1 name args ( s!:r2iand (cdr body)) lab v)) (t (cond ((eqcar body (quote or)) (s!:r2i1 name args (s!:r2ior (cdr body)) lab v)) (t (list (quote return) (list (quote nreverse) (car v) body))))))))))))))))))))) (de s!:r2iand (l) (cond ((null l) t) (t (cond ((null (cdr l)) (car l)) (t ( list (quote cond) (list (car l) (s!:r2iand (cdr l))))))))) (de s!:r2ior (l) (cond ((null l) nil) (t (cons (quote cond) (prog (var1151 var1152) (setq var1151 l) lab1150 (cond ((null var1151) (return (reversip var1152)))) (prog (x) (setq x (car var1151)) (setq var1152 (cons (list x) var1152))) (setq var1151 (cdr var1151)) (go lab1150)))))) (de s!:r2icond (name args b lab v) (cond ((null b) (list (list t (list (quote return) (list (quote nreverse) (car v)))))) (t (cond ((null (cdar b)) (progn (cond ((null (cdr v)) (rplacd v (list (gensym))))) (cons (list (list (quote setq) (cadr v) (caar b)) (list (quote return) (list (quote nreverse) (car v) (cadr v)))) (s!:r2icond name args (cdr b) lab v)))) (t (cond ((eqcar (car b) t) (list (cons t (s!:r2iprogn name args (cdar b) lab v)))) (t (cons (cons ( caar b) (s!:r2iprogn name args (cdar b) lab v)) (s!:r2icond name args (cdr b) lab v))))))))) (de s!:r2iif (name args b lab v) (cond ((null (cddr b)) (list (car b) ( s!:r2i1 name args (cadr b) lab v))) (t (list (car b) (s!:r2i1 name args (cadr b) lab v) (s!:r2i1 name args (caddr b) lab v))))) (de s!:r2iwhen (name args b lab v) (cons (car b) (s!:r2iprogn name args (cdr b) lab v))) (de s!:r2iprogn (name args b lab v) (cond ((null (cdr b)) (list (s!:r2i1 name args (car b) lab v))) (t (cons (car b) (s!:r2iprogn name args (cdr b) lab v) )))) (de s!:r2icons (name args a d lab v) (cond ((eqcar d (quote cons)) ( s!:r2icons2 name args a (cadr d) (caddr d) lab v)) (t (cond ((and (eqcar d name) (equal (length (cdr d)) (length args))) (progn (setq s!:r2i_cons_recurse t) (cons (quote progn) (cons (list (quote setq) (car v) ( list (quote cons) a (car v))) (append (s!:r2isteps args (cdr d) v) (list ( list (quote go) lab))))))) (t (list (quote return) (list (quote nreverse) ( car v) (list (quote cons) a d)))))))) (de s!:r2icons2 (name args a ad dd lab v) (cond ((and (eqcar dd name) (equal (length (cdr dd)) (length args))) (progn (setq s!:r2i_cons_recurse t) (cons ( quote progn) (cons (list (quote setq) (car v) (list (quote cons) a (car v))) (cons (list (quote setq) (car v) (list (quote cons) ad (car v))) (append ( s!:r2isteps args (cdr dd) v) (list (list (quote go) lab)))))))) (t (list ( quote return) (list (quote nreverse) (car v) (list (quote cons) a (list ( quote cons) ad dd))))))) (de s!:r2isteps (vars vals v) (cond ((null vars) (cond ((null vals) nil) (t ( error 0 "too many args in recursive call to self")))) (t (cond ((null vals) ( error 0 "not enough args in recursive call to self")) (t (cond ((equal (car vars) (car vals)) (s!:r2isteps (cdr vars) (cdr vals) v)) (t (cond (( s!:r2i_safestep (car vars) (cdr vars) (cdr vals)) (cons (list (quote setq) ( car vars) (car vals)) (s!:r2isteps (cdr vars) (cdr vals) v))) (t (prog (w) ( cond ((null (cdr v)) (rplacd v (list (gensym))))) (setq v (cdr v)) (setq w ( s!:r2isteps (cdr vars) (cdr vals) v)) (return (cons (list (quote setq) (car v ) (car vals)) (append w (list (list (quote setq) (car vars) (car v))))))))))) ))))) (de s!:r2i_safestep (x vars vals) (cond ((and (null vars) (null vals)) t) (t (cond ((s!:r2i_dependson (car vals) x) nil) (t (s!:r2i_safestep x (cdr vars) (cdr vals))))))) (de s!:r2i_dependson (e x) (cond ((equal e x) t) (t (cond ((or (atom e) ( eqcar e (quote quote))) nil) (t (cond ((not (atom (car e))) t) (t (cond (( flagp (car e) (quote s!:r2i_safe)) (s!:r2i_list_dependson (cdr e) x)) (t ( cond ((or (fluidp x) (globalp x)) t) (t (cond ((or (flagp (car e) (quote s!:r2i_unsafe)) (macro!-function (car e))) t) (t (s!:r2i_list_dependson (cdr e) x)))))))))))))) (flag (quote (car cdr caar cadr cdar cddr caaar caadr cadar caddr cdaar cdadr cddar cdddr cons ncons rcons acons list list2 list3 list!* add1 sub1 plus plus2 times times2 difference minus quotient append reverse nreverse null not assoc atsoc member memq subst sublis subla pair prog1 prog2 progn)) (quote s!:r2i_safe)) (flag (quote (cond if when case de defun dm defmacro prog let let!* flet and or)) (quote s!:r2i_unsafe)) (de s!:r2i_list_dependson (l x) (cond ((null l) nil) (t (cond (( s!:r2i_dependson (car l) x) t) (t (s!:r2i_list_dependson (cdr l) x)))))) (de s!:r2i2 (name args body lab v) (cond ((or (null body) (equal body (quote (progn)))) (list (quote return) nil)) (t (cond ((and (eqcar body name) (equal (length (cdr body)) (length args))) (progn (cons (quote progn) (append ( s!:r2isteps args (cdr body) v) (list (list (quote go) lab)))))) (t (cond (( eqcar body (quote cond)) (cons (quote cond) (s!:r2i2cond name args (cdr body) lab v))) (t (cond ((eqcar body (quote if)) (cons (quote if) (s!:r2i2if name args (cdr body) lab v))) (t (cond ((eqcar body (quote when)) (cons (quote when) (s!:r2i2when name args (cdr body) lab v))) (t (cond ((or (eqcar body ( quote progn)) (eqcar body (quote prog2))) (cons (quote progn) (s!:r2i2progn name args (cdr body) lab v))) (t (cond ((eqcar body (quote and)) (s!:r2i2 name args (s!:r2iand (cdr body)) lab v)) (t (cond ((eqcar body (quote or)) ( s!:r2i2 name args (s!:r2ior (cdr body)) lab v)) (t (list (quote return) body) ))))))))))))))))) (de s!:r2i2cond (name args b lab v) (cond ((null b) (list (list t (list ( quote return) nil)))) (t (cond ((null (cdar b)) (progn (cond ((null (cdr v)) (rplacd v (list (gensym))))) (cons (list (list (quote setq) (cadr v) (caar b) ) (list (quote return) (cadr v))) (s!:r2i2cond name args (cdr b) lab v)))) (t (cond ((eqcar (car b) t) (list (cons t (s!:r2i2progn name args (cdar b) lab v)))) (t (cons (cons (caar b) (s!:r2i2progn name args (cdar b) lab v)) ( s!:r2i2cond name args (cdr b) lab v))))))))) (de s!:r2i2if (name args b lab v) (cond ((null (cddr b)) (list (car b) ( s!:r2i2 name args (cadr b) lab v))) (t (list (car b) (s!:r2i2 name args (cadr b) lab v) (s!:r2i2 name args (caddr b) lab v))))) (de s!:r2i2when (name args b lab v) (cons (car b) (s!:r2i2progn name args ( cdr b) lab v))) (de s!:r2i2progn (name args b lab v) (cond ((null (cdr b)) (list (s!:r2i2 name args (car b) lab v))) (t (cons (car b) (s!:r2i2progn name args (cdr b) lab v))))) (de s!:r2i3 (name args body lab v) (prog (v v1 v2 lab1 lab2 lab3 w P Q g R) ( cond ((s!:any_fluid args) (return body))) (cond ((eqcar body (quote cond)) ( progn (cond ((not (setq w (cdr body))) (return body))) (setq P (car w)) (setq w (cdr w)) (cond ((null P) (return body))) (setq Q (cdr P)) (setq P (car P)) (cond ((or (null Q) (cdr Q)) (return body))) (setq Q (car Q)) (cond ((or ( null w) (cdr w)) (return body))) (setq w (car w)) (cond ((not (eqcar w t)) ( return body))) (setq w (cdr w)) (cond ((or (not w) (cdr w)) (return body))) ( setq w (car w)))) (t (cond ((eqcar body (quote if)) (progn (setq w (cdr body) ) (setq P (car w)) (setq w (cdr w)) (setq Q (car w)) (setq w (cdr w)) (cond ( (null w) (return body))) (setq w (car w)))) (t (return body))))) (cond ((or ( atom w) (atom (cdr w)) (atom (cddr w)) (cdddr w)) (return body))) (setq g ( car w)) (setq R (cadr w)) (setq w (caddr w)) (cond ((not (atom g)) (return body))) (cond ((member g (quote (and or progn prog1 prog2 cond if when))) ( return body))) (cond ((not (eqcar w name)) (return body))) (setq w (cdr w)) ( cond ((not (equal (length w) (length args))) (return body))) (setq v1 (gensym )) (setq v2 (gensym)) (setq v (list v2)) (setq lab1 (gensym)) (setq lab2 ( gensym)) (setq lab3 (gensym)) (setq w (s!:r2isteps args w v)) (setq w (list ( quote prog) (cons v1 v) lab1 (list (quote cond) (list P (list (quote go) lab2 ))) (list (quote setq) v1 (list (quote cons) R v1)) (cons (quote progn) w) ( list (quote go) lab1) lab2 (list (quote setq) v2 Q) lab3 (list (quote cond) ( list (list (quote null) v1) (list (quote return) v2))) (list (quote setq) v2 (list g (list (quote car) v1) v2)) (list (quote setq) v1 (list (quote cdr) v1 )) (list (quote go) lab3))) (return w))) (de s!:any_fluid (l) (cond ((null l) nil) (t (cond ((fluidp (car l)) t) (t ( s!:any_fluid (cdr l))))))) (de s!:compile1 (name args body s!:lexical_env) (prog (w aargs oargs oinit restarg svars nargs nopts env fluids s!:current_function s!:current_label s!:current_block s!:current_size s!:current_procedure s!:current_exitlab s!:current_proglabels s!:other_defs local_decs s!:has_closure s!:local_macros s!:recent_literals s!:a_reg_values w1 w2 s!:current_count s!:env_alist s!:maybe_values checksum) (cond (s!:lexical_env (setq checksum 0)) (t (setq checksum (md60 (cons name (cons args body)))))) (setq s!:current_function name) (setq s!:current_count 0) (cond (!*where_defined!* (progn (setq w name) (puthash w !*where_defined!* (where!-was!-that))))) (setq body ( s!:find_local_decs body nil)) (setq local_decs (car body)) (setq body (cdr body)) (cond ((atom body) (setq body nil)) (t (cond ((null (cdr body)) (setq body (car body))) (t (setq body (cons (quote progn) body)))))) (setq nargs ( setq nopts 0)) (prog nil lab1153 (cond ((null (and args (not (eqcar args ( quote !&optional))) (not (eqcar args (quote !&rest))))) (return nil))) (progn (cond ((or (equal (car args) (quote !&key)) (equal (car args) (quote !&aux)) ) (error 0 "&key/&aux"))) (setq aargs (cons (car args) aargs)) (setq nargs ( plus nargs 1)) (setq args (cdr args))) (go lab1153)) (cond ((eqcar args ( quote !&optional)) (progn (setq args (cdr args)) (prog nil lab1155 (cond (( null (and args (not (eqcar args (quote !&rest))))) (return nil))) (progn ( cond ((or (equal (car args) (quote !&key)) (equal (car args) (quote !&aux))) (error 0 "&key/&aux"))) (setq w (car args)) (prog nil lab1154 (cond ((null ( and (not (atom w)) (or (atom (cdr w)) (equal (cdr w) (quote (nil)))))) ( return nil))) (setq w (car w)) (go lab1154)) (setq args (cdr args)) (setq oargs (cons w oargs)) (setq nopts (plus nopts 1)) (cond ((atom w) (setq aargs (cons w aargs))) (t (progn (setq oinit t) (setq aargs (cons (car w) aargs)) (cond ((not (atom (cddr w))) (setq svars (cons (caddr w) svars)))))))) (go lab1155))))) (cond ((eqcar args (quote !&rest)) (progn (setq w (cadr args)) ( setq aargs (cons w aargs)) (setq restarg w) (setq args (cddr args)) (cond ( args (error 0 "&rest arg not at end")))))) (setq args (reverse aargs)) (setq oargs (reverse oargs)) (prog (var1157) (setq var1157 (append svars args)) lab1156 (cond ((null var1157) (return nil))) (prog (v) (setq v (car var1157)) (progn (cond ((globalp v) (progn (cond (!*pwrds (progn (cond ((neq (posn) 0) (terpri))) (princ "+++++ global ") (prin v) (princ " converted to fluid") ( terpri)))) (unglobal (list v)) (fluid (list v))))))) (setq var1157 (cdr var1157)) (go lab1156)) (cond (oinit (return (s!:compile2 name nargs nopts args oargs restarg body local_decs checksum)))) (setq w nil) (prog (var1159) (setq var1159 args) lab1158 (cond ((null var1159) (return nil))) (prog (v) ( setq v (car var1159)) (setq w (s!:instate_local_decs v local_decs w))) (setq var1159 (cdr var1159)) (go lab1158)) (cond ((and !*r2i (null oargs) (null restarg)) (setq body (s!:r2i name args body)))) (prog (v) (setq v args) lab1160 (cond ((null v) (return nil))) (progn (cond ((fluidp (car v)) (prog ( g) (setq g (gensym)) (setq fluids (cons (cons (car v) g) fluids)) (rplaca v g ))))) (setq v (cdr v)) (go lab1160)) (cond (fluids (progn (setq body (list ( list (quote return) body))) (prog (var1162) (setq var1162 fluids) lab1161 ( cond ((null var1162) (return nil))) (prog (v) (setq v (car var1162)) (setq body (cons (list (quote setq) (car v) (cdr v)) body))) (setq var1162 (cdr var1162)) (go lab1161)) (setq body (cons (quote prog) (cons (prog (var1164 var1165) (setq var1164 fluids) lab1163 (cond ((null var1164) (return ( reversip var1165)))) (prog (v) (setq v (car var1164)) (setq var1165 (cons ( car v) var1165))) (setq var1164 (cdr var1164)) (go lab1163)) body)))))) (setq env (cons (mkhash 10 2 1.5) (reverse args))) (puthash name (car env) (cons 10000000 nil)) (setq w (s!:residual_local_decs local_decs w)) ( s!:start_procedure nargs nopts restarg) (setq w1 body) more (cond ((atom w1) nil) (t (cond ((and (equal (car w1) (quote block)) (equal (length w1) 3)) ( progn (setq w1 (caddr w1)) (go more))) (t (cond ((and (equal (car w1) (quote progn)) (equal (length w1) 2)) (progn (setq w1 (cadr w1)) (go more))) (t ( cond ((and (atom (setq w2 (car w1))) (setq w2 (get w2 (quote s!:newname)))) ( progn (setq w1 (cons w2 (cdr w1))) (go more))) (t (cond ((and (atom (setq w2 (car w1))) (setq w2 (macro!-function w2))) (progn (setq w1 (funcall w2 w1)) ( go more)))))))))))) (cond ((not (equal (setq w2 (s!:improve w1)) w1)) (progn (setq w1 w2) (go more)))) (cond ((and (not (atom w1)) (atom (car w1)) (not ( special!-form!-p (car w1))) (s!:subargs args (cdr w1)) (leq nargs 3) (equal nopts 0) (not restarg) (leq (length (cdr w1)) nargs)) (progn ( s!:cancel_local_decs w) (cond (restarg (setq nopts (plus nopts 512)))) (setq nopts (plus nopts (times 1024 (length w1)))) (setq nargs (plus nargs (times 256 nopts))) (cond (!*pwrds (progn (cond ((neq (posn) 0) (terpri))) (princ "+++ ") (prin name) (princ " compiled as link to ") (princ (car w1)) (terpri) ))) (return (cons (cons name (cons nargs (cons nil (car w1)))) s!:other_defs) )))) (s!:comval body env 0) (s!:cancel_local_decs w) (cond (restarg (setq nopts (plus nopts 512)))) (setq nargs (plus nargs (times 256 nopts))) (return (cons (cons name (cons nargs (s!:endprocedure name env checksum))) s!:other_defs)))) (de s!:compile2 (name nargs nopts args oargs restarg body local_decs checksum ) (prog (fluids env penv g v init atend w) (prog (var1167) (setq var1167 args ) lab1166 (cond ((null var1167) (return nil))) (prog (v) (setq v (car var1167 )) (progn (setq env (cons 0 env)) (setq penv (cons env penv)))) (setq var1167 (cdr var1167)) (go lab1166)) (setq env (cons (mkhash 10 2 1.5) env)) ( puthash name (car env) (cons 10000000 nil)) (setq penv (reversip penv)) (cond (restarg (setq oargs (append oargs (quote (0)))))) (prog (i) (setq i 1) lab1168 (cond ((minusp (times 1 (difference nargs i))) (return nil))) (setq oargs (cons 0 oargs)) (setq i (plus i 1)) (go lab1168)) (s!:start_procedure nargs nopts restarg) (prog nil lab1169 (cond ((null args) (return nil))) ( progn (setq v (car args)) (setq init (car oargs)) (cond ((equal init 0) ( progn (setq w (s!:instate_local_decs v local_decs w)) (cond ((fluidp v) ( progn (setq g (gensym)) (rplaca (car penv) g) (s!:outopcode1lit (quote FREEBIND) (s!:vecof (list v)) env) (rplacd env (cons 3 (cons 0 (cons 0 (cdr env))))) (setq atend (cons (quote FREERSTR) atend)) (s!:comval (list (quote setq) v g) env 2))) (t (rplaca (car penv) v))))) (t (prog (ival sp l1 l2) ( cond ((not (atom init)) (progn (setq init (cdr init)) (setq ival (car init)) (cond ((not (atom (cdr init))) (setq sp (cadr init))))))) (setq l1 (gensym)) (setq g (gensym)) (rplaca (car penv) g) (cond ((and (null ival) (null sp)) ( s!:comval (list (quote setq) g (list (quote spid!-to!-nil) g)) env 1)) (t ( progn (s!:jumpif nil (list (quote is!-spid) g) env l1) (s!:comval (list ( quote setq) g ival) env 1) (cond (sp (progn (cond ((fluidp sp) (progn ( s!:outopcode1lit (quote FREEBIND) (s!:vecof (list sp)) env) (s!:outjump ( quote JUMP) (setq l2 (gensym))) (s!:set_label l1) (s!:outopcode1lit (quote FREEBIND) (s!:vecof (list sp)) env) (rplacd env (cons 3 (cons 0 (cons 0 (cdr env))))) (s!:comval (list (quote setq) sp t) env 1) (s!:set_label l2) (setq atend (cons (quote FREERSTR) atend)))) (t (progn (s!:outopcode0 (quote PUSHNIL) (quote (PUSHNIL))) (s!:outjump (quote JUMP) (setq l2 (gensym))) ( s!:set_label l1) (s!:loadliteral t env) (s!:outopcode0 (quote PUSH) (quote ( PUSH))) (s!:set_label l2) (rplacd env (cons sp (cdr env))) (setq atend (cons (quote LOSE) atend))))))) (t (s!:set_label l1)))))) (setq w ( s!:instate_local_decs v local_decs w)) (cond ((fluidp v) (progn ( s!:outopcode1lit (quote FREEBIND) (s!:vecof (list v)) env) (rplacd env (cons 3 (cons 0 (cons 0 (cdr env))))) (s!:comval (list (quote setq) v g) env 1) ( setq atend (cons (quote FREERSTR) atend)))) (t (rplaca (car penv) v)))))) ( setq args (cdr args)) (setq oargs (cdr oargs)) (setq penv (cdr penv))) (go lab1169)) (setq w (s!:residual_local_decs local_decs w)) (s!:comval body env 0) (prog nil lab1170 (cond ((null atend) (return nil))) (progn (s!:outopcode0 (car atend) (list (car atend))) (setq atend (cdr atend))) (go lab1170)) ( s!:cancel_local_decs w) (setq nopts (plus nopts 256)) (cond (restarg (setq nopts (plus nopts 512)))) (setq nargs (plus nargs (times 256 nopts))) (return (cons (cons name (cons nargs (s!:endprocedure name env checksum))) s!:other_defs)))) (de compile!-all nil (prog (var1172) (setq var1172 (oblist)) lab1171 (cond (( null var1172) (return nil))) (prog (x) (setq x (car var1172)) (prog (w) (setq w (getd x)) (cond ((and (or (eqcar w (quote expr)) (eqcar w (quote macro))) (eqcar (cdr w) (quote lambda))) (progn (princ "Compile: ") (prin x) (terpri) (errorset (list (quote compile) (mkquote (list x))) t t)))))) (setq var1172 ( cdr var1172)) (go lab1171))) (flag (quote (rds deflist flag fluid global remprop remflag unfluid unglobal dm defmacro carcheck faslend c_end)) (quote eval)) (flag (quote (rds)) (quote ignore)) (fluid (quote (!*backtrace))) (de s!:fasl_supervisor nil (prog (u w !*echo) top (setq u (errorset (quote ( read)) t !*backtrace)) (cond ((atom u) (return nil))) (setq u (car u)) (cond ((equal u !$eof!$) (return nil))) (cond ((not (atom u)) (setq u (macroexpand u)))) (cond ((atom u) (go top)) (t (cond ((eqcar u (quote faslend)) (return ( apply (quote faslend) nil))) (t (cond ((eqcar u (quote rdf)) (progn (setq w ( open (setq u (eval (cadr u))) (quote input))) (cond (w (progn (terpri) (princ "Reading file ") (prin u) (terpri) (setq w (rds w)) (s!:fasl_supervisor) ( princ "End of file ") (prin u) (terpri) (close (rds w)))) (t (progn (princ "Failed to open file ") (prin u) (terpri)))))) (t (s!:fslout0 u))))))) (go top))) (de s!:fslout0 (u) (s!:fslout1 u nil)) (de s!:fslout1 (u loadonly) (prog (w) (cond ((not (atom u)) (setq u ( macroexpand u)))) (cond ((atom u) (return nil)) (t (cond ((eqcar u (quote progn)) (progn (prog (var1174) (setq var1174 (cdr u)) lab1173 (cond ((null var1174) (return nil))) (prog (v) (setq v (car var1174)) (s!:fslout1 v loadonly)) (setq var1174 (cdr var1174)) (go lab1173)) (return nil))) (t (cond ((eqcar u (quote eval!-when)) (return (prog nil (setq w (cadr u)) (setq u ( cons (quote progn) (cddr u))) (cond ((and (memq (quote compile) w) (not loadonly)) (eval u))) (cond ((memq (quote load) w) (s!:fslout1 u t))) (return nil)))) (t (cond ((or (flagp (car u) (quote eval)) (and (equal (car u) ( quote setq)) (not (atom (caddr u))) (flagp (caaddr u) (quote eval)))) (cond ( (not loadonly) (errorset u t !*backtrace))))))))))) (cond ((eqcar u (quote rdf)) (prog nil (setq w (open (setq u (eval (cadr u))) (quote input))) (cond (w (progn (princ "Reading file ") (prin u) (terpri) (setq w (rds w)) ( s!:fasl_supervisor) (princ "End of file ") (prin u) (terpri) (close (rds w))) ) (t (progn (princ "Failed to open file ") (prin u) (terpri)))))) (t (cond ( !*nocompile (progn (cond ((and (not (eqcar u (quote faslend))) (not (eqcar u (quote carcheck)))) (write!-module u))))) (t (cond ((or (eqcar u (quote de)) (eqcar u (quote defun))) (progn (cond ((and !*native_code (not (memq (quote win64) lispsystem!*))) (progn (cond ((c!:valid_fndef (caddr u) (cdddr u)) ( prog (pending_functions u1) (c!:ccmpout1a u) (prog nil lab1175 (cond ((null pending_functions) (return nil))) (progn (setq u1 (car pending_functions)) ( setq pending_functions (cdr pending_functions)) (s!:fslout0 u1)) (go lab1175) ))) (t (progn (princ "+++ ") (prin (cadr u)) (printc " can not be compiled into native code"))))))) (setq u (cdr u)) (cond ((and ( setq w (get (car u) (quote c!-version))) (equal w (md60 (cons (car u) (cons ( cadr u) (s!:fully_macroexpand_list (cddr u))))))) (progn (princ "+++ ") (prin (car u)) (printc " not compiled (C version available)") (write!-module (list (quote restore!-c!-code) (mkquote (car u)))))) (t (cond ((flagp (car u) ( quote lose)) (progn (princ "+++ ") (prin (car u)) (printc " not compiled (LOSE flag)"))) (t (progn (cond ((setq w (get (car u) (quote c!-version))) (progn (princ "+++ ") (prin (car u)) (princ " reports C version with checksum ") (print w) (print "+++ differing from this version:") (setq w (cons (car u) (cons (cadr u) ( s!:fully_macroexpand_list (cddr u))))) (princ "::: ") (prettyprint w) (princ "+++ which has checksum ") (print (md60 w))))) (prog (var1177) (setq var1177 (s!:compile1 (car u) (cadr u) (cddr u) nil)) lab1176 (cond ((null var1177) ( return nil))) (prog (p) (setq p (car var1177)) (s!:fslout2 p u)) (setq var1177 (cdr var1177)) (go lab1176))))))))) (t (cond ((or (eqcar u (quote dm) ) (eqcar u (quote defmacro))) (prog (g) (setq g (hashtagged!-name (cadr u) ( cddr u))) (setq u (cdr u)) (cond ((flagp (car u) (quote lose)) (progn (princ "+++ ") (prin (car u)) (printc " not compiled (LOSE flag)") (return nil)))) ( setq w (cadr u)) (cond ((and w (null (cdr w))) (setq w (cons (car w) (cons ( quote !&optional) (cons (gensym) nil)))))) (prog (var1179) (setq var1179 ( s!:compile1 g w (cddr u) nil)) lab1178 (cond ((null var1179) (return nil))) ( prog (p) (setq p (car var1179)) (s!:fslout2 p u)) (setq var1179 (cdr var1179) ) (go lab1178)) (write!-module (list (quote dm) (car u) (quote (u !&optional e)) (list g (quote u) (quote e)))))) (t (cond ((eqcar u (quote putd)) (prog ( a1 a2 a3) (setq a1 (cadr u)) (setq a2 (caddr u)) (setq a3 (cadddr u)) (cond ( (and (eqcar a1 (quote quote)) (or (equal a2 (quote (quote expr))) (equal a2 ( quote (quote macro)))) (or (eqcar a3 (quote quote)) (eqcar a3 (quote function ))) (eqcar (cadr a3) (quote lambda))) (progn (setq a1 (cadr a1)) (setq a2 ( cadr a2)) (setq a3 (cadr a3)) (setq u (cons (cond ((equal a2 (quote expr)) ( quote de)) (t (quote dm))) (cons a1 (cdr a3)))) (s!:fslout1 u loadonly))) (t (write!-module u))))) (t (cond ((and (not (eqcar u (quote faslend))) (not ( eqcar u (quote carcheck)))) (write!-module u))))))))))))))) (de s!:fslout2 (p u) (prog (name nargs code env w) (setq name (car p)) (setq nargs (cadr p)) (setq code (caddr p)) (setq env (cdddr p)) (cond ((and !*savedef (equal name (car u))) (progn (define!-in!-module (minus 1)) ( write!-module (cons (quote lambda) (cons (cadr u) (s!:fully_macroexpand_list (cddr u)))))))) (setq w (irightshift nargs 18)) (setq nargs (logand nargs 262143)) (cond ((not (equal w 0)) (setq code (difference w 1)))) ( define!-in!-module nargs) (write!-module name) (write!-module code) ( write!-module env))) (remprop (quote faslend) (quote stat)) (de faslend nil (prog (copysrc copydest) (cond ((null s!:faslmod_name) ( return nil))) (princ "Completed FASL files for ") (print (car s!:faslmod_name )) (cond ((and !*native_code (not (memq (quote win64) lispsystem!*))) (prog ( cmnd w w1 obj deff) (setq w (C!-end1 nil)) (close C_file) (setq cmnd (append (explodec s!:native_file) (quote (!")))) (cond ((memq (quote win32) lispsystem!*) (setq obj "dll")) (t (setq obj "so"))) (setq obj (tmpnam obj)) (cond ((memq (quote win32) lispsystem!*) (prog (nn) (setq nn (car s!:faslmod_name)) (setq nn (list2string (prog (var1181 var1182) (setq var1181 (explodec nn)) lab1180 (cond ((null var1181) (return (reversip var1182)))) ( prog (c) (setq c (car var1181)) (setq var1182 (cons (cond ((equal c (quote !- )) (quote !_)) (t c)) var1182))) (setq var1181 (cdr var1181)) (go lab1180)))) (setq deff (tmpnam "def")) (setq w1 (open deff (quote output))) (setq w1 ( wrs w1)) (princ "LIBRARY ") (princ (car s!:faslmod_name)) (printc ".dll") ( printc "EXPORTS") (printc " init") (princ " ") (princ nn) (printc "_setup") ( printc "IMPORTS") (print!-imports) (close (wrs w1)) (setq cmnd (append ( explodec deff) (cons (quote ! ) cmnd)))))) (setq cmnd (append (explodec obj) (cons (quote ! ) cmnd))) (setq cmnd (append (explodec " -o ") cmnd)) (prog ( var1184) (setq var1184 (reverse (cdr (assoc (quote compiler!-command) lispsystem!*)))) lab1183 (cond ((null var1184) (return nil))) (prog (x) (setq x (car var1184)) (setq cmnd (append (explodec x) (cons (quote ! ) cmnd)))) ( setq var1184 (cdr var1184)) (go lab1183)) (setq cmnd (compress (cons (quote !") cmnd))) (print cmnd) (cond ((not (zerop (silent!-system cmnd))) (progn ( princ "+++ C compilation for ") (prin (car s!:faslmod_name)) (printc " failed"))) (t (progn (cond (!*strip_native (progn (setq cmnd (compress ( cons (quote !") (append (explodec "strip ") (append (explodec obj) (quote (!" ))))))) (print cmnd) (silent!-system cmnd)))) (setq copysrc obj) (setq copydest (list2string (append (explodec (car s!:faslmod_name)) (cons (quote !.) (explodec (cdr (assoc (quote linker) lispsystem!*))))))) (cond ((not !*save_native) (progn (delete!-file s!:native_file) (cond ((memq (quote win32 ) lispsystem!*) (delete!-file deff)))))) (write!-module (list (quote instate!-c!-code) (mkquote (car s!:faslmod_name)) (mkquote w))))))))) ( start!-module nil) (cond (copysrc (progn (copy!-native copysrc copydest) ( cond ((not !*save_native) (delete!-file copysrc)))))) (setq dfprint!* s!:dfprintsave) (setq !*defn nil) (setq !*comp (cdr s!:faslmod_name)) (setq s!:faslmod_name nil) (return nil))) (put (quote faslend) (quote stat) (quote endstat)) (de s!:file (s) (prog (r) (setq s (reverse (explodec s))) (prog nil lab1185 ( cond ((null (and s (not (or (eqcar s (quote !/)) (eqcar s (quote !\)))))) ( return nil))) (progn (setq r (cons (car s) r)) (setq s (cdr s))) (go lab1185) ) (return (list2string r)))) (de s!:trim!.c (s) (prog (r) (setq s (reverse (explodec s))) (cond ((eqcar s (quote c)) (progn (setq s (cdr s)) (cond ((eqcar s (quote !.)) (setq s (cdr s ))))))) (return (list2string (reverse s))))) (de s!:dir (s) (prog nil (setq s (reverse (explodec s))) (prog nil lab1186 ( cond ((null (and s (not (or (eqcar s (quote !/)) (eqcar s (quote !\)))))) ( return nil))) (setq s (cdr s)) (go lab1186)) (cond (s (setq s (cdr s)))) ( cond ((null s) (return ".")) (t (return (list2string (reverse s))))))) (de faslout (u) (prog nil (terpri) (princ "FASLOUT ") (prin u) (princ ": IN files; or type in expressions") (terpri) (princ "When all done, execute FASLEND;") (terpri) (cond ((not (atom u)) (setq u ( car u)))) (cond ((not (start!-module u)) (progn (cond ((neq (posn) 0) (terpri ))) (princ "+++ Failed to open FASL output file") (terpri) (return nil)))) ( cond ((and !*native_code (not (memq (quote win64) lispsystem!*))) (progn ( setq s!:native_file (tmpnam "c")) (c!:ccompilestart (s!:trim!.c (s!:file s!:native_file)) u (s!:dir s!:native_file) t)))) (setq s!:faslmod_name (cons u !*comp)) (setq s!:dfprintsave dfprint!*) (setq dfprint!* (quote s!:fslout0) ) (setq !*defn t) (setq !*comp nil) (cond ((getd (quote begin)) (return nil)) ) (s!:fasl_supervisor))) (put (quote faslout) (quote stat) (quote rlis)) (de s!:c_supervisor nil (prog (u w !*echo) top (setq u (errorset (quote (read )) t !*backtrace)) (cond ((atom u) (return nil))) (setq u (car u)) (cond (( equal u !$eof!$) (return nil))) (cond ((not (atom u)) (setq u (macroexpand u) ))) (cond ((atom u) (go top)) (t (cond ((eqcar u (quote c_end)) (return ( apply (quote c_end) nil))) (t (cond ((eqcar u (quote rdf)) (progn (setq w ( open (setq u (eval (cadr u))) (quote input))) (cond (w (progn (terpri) (princ "Reading file ") (prin u) (terpri) (setq w (rds w)) (s!:c_supervisor) (princ "End of file ") (prin u) (terpri) (close (rds w)))) (t (progn (princ "Failed to open file ") (prin u) (terpri)))))) (t (s!:cout0 u))))))) (go top) )) (de s!:cout0 (u) (s!:cout1 u nil)) (de s!:cout1 (u loadonly) (prog (s!:into_c) (setq s!:into_c t) (cond ((not ( atom u)) (setq u (macroexpand u)))) (cond ((atom u) (return nil)) (t (cond (( eqcar u (quote progn)) (progn (prog (var1188) (setq var1188 (cdr u)) lab1187 (cond ((null var1188) (return nil))) (prog (v) (setq v (car var1188)) ( s!:cout1 v loadonly)) (setq var1188 (cdr var1188)) (go lab1187)) (return nil) )) (t (cond ((eqcar u (quote eval!-when)) (return (prog (w) (setq w (cadr u)) (setq u (cons (quote progn) (cddr u))) (cond ((and (memq (quote compile) w) (not loadonly)) (eval u))) (cond ((memq (quote load) w) (s!:cout1 u t))) ( return nil)))) (t (cond ((or (flagp (car u) (quote eval)) (and (equal (car u) (quote setq)) (not (atom (caddr u))) (flagp (caaddr u) (quote eval)))) (cond ((not loadonly) (errorset u t !*backtrace))))))))))) (cond ((eqcar u (quote rdf)) (prog (w) (setq w (open (setq u (eval (cadr u))) (quote input))) (cond (w (progn (princ "Reading file ") (prin u) (terpri) (setq w (rds w)) ( s!:c_supervisor) (princ "End of file ") (prin u) (terpri) (close (rds w)))) ( t (progn (princ "Failed to open file ") (prin u) (terpri)))))) (t (cond ((or (eqcar u (quote de)) (eqcar u (quote defun))) (prog (w) (setq u (cdr u)) ( setq w (s!:compile1 (car u) (cadr u) (cddr u) nil)) (prog (var1190) (setq var1190 w) lab1189 (cond ((null var1190) (return nil))) (prog (p) (setq p ( car var1190)) (s!:cgen (car p) (cadr p) (caddr p) (cdddr p))) (setq var1190 ( cdr var1190)) (go lab1189)))) (t (cond ((or (eqcar u (quote dm)) (eqcar u ( quote defmacro))) (prog (w g) (setq g (hashtagged!-name (cadr u) (cddr u))) ( setq u (cdr u)) (setq w (cadr u)) (cond ((and w (null (cdr w))) (setq w (cons (car w) (cons (quote !&optional) (cons (gensym) nil)))))) (setq w ( s!:compile1 g w (cddr u) nil)) (prog (var1192) (setq var1192 w) lab1191 (cond ((null var1192) (return nil))) (prog (p) (setq p (car var1192)) (s!:cgen ( car p) (cadr p) (caddr p) (cdddr p))) (setq var1192 (cdr var1192)) (go lab1191)) (s!:cinit (list (quote dm) (car u) (quote (u !&optional e)) (list g (quote u) (quote e)))))) (t (cond ((eqcar u (quote putd)) (prog (a1 a2 a3) ( setq a1 (cadr u)) (setq a2 (caddr u)) (setq a3 (cadddr u)) (cond ((and (eqcar a1 (quote quote)) (or (equal a2 (quote (quote expr))) (equal a2 (quote ( quote macro)))) (or (eqcar a3 (quote quote)) (eqcar a3 (quote function))) ( eqcar (cadr a3) (quote lambda))) (progn (setq a1 (cadr a1)) (setq a2 (cadr a2 )) (setq a3 (cadr a3)) (setq u (cons (cond ((equal a2 (quote expr)) (quote de )) (t (quote dm))) (cons a1 (cdr a3)))) (s!:cout1 u loadonly))) (t (s!:cinit u))))) (t (cond ((and (not (eqcar u (quote c_end))) (not (eqcar u (quote carcheck)))) (s!:cinit u))))))))))))) (fluid (quote (s!:cmod_name))) (de c_end nil (prog nil (cond ((null s!:cmod_name) (return nil))) (s!:cend) ( setq dfprint!* s!:dfprintsave) (setq !*defn nil) (setq !*comp (cdr s!:cmod_name)) (setq s!:cmod_name nil) (return nil))) (put (quote c_end) (quote stat) (quote endstat)) (de c_out (u) (prog nil (terpri) (princ "C_OUT ") (prin u) (princ ": IN files; or type in expressions") (terpri) (princ "When all done, execute C_END;") (terpri) (cond ((not (atom u)) (setq u (car u)))) (cond ((null (s!:cstart u)) (progn (cond ((neq (posn) 0) (terpri))) ( princ "+++ Failed to open C output file") (terpri) (return nil)))) (setq s!:cmod_name (cons u !*comp)) (setq s!:dfprintsave dfprint!*) (setq dfprint!* (quote s!:cout0)) (setq !*defn t) (setq !*comp nil) (cond ((getd (quote begin)) (return nil))) (s!:c_supervisor))) (put (quote c_out) (quote stat) (quote rlis)) (de s!:compile!-file!* (fromfile !&optional tofile verbose !*pwrds) (prog ( !*comp w save) (cond ((null tofile) (setq tofile fromfile))) (cond (verbose ( progn (cond ((neq (posn) 0) (terpri))) (princ "+++ Compiling file ") (prin fromfile) (terpri) (setq save (verbos nil)) (verbos (ilogand save 4))))) ( cond ((not (start!-module tofile)) (progn (cond ((neq (posn) 0) (terpri))) ( princ "+++ Failed to open FASL output file") (terpri) (cond (save (verbos save))) (return nil)))) (setq w (open fromfile (quote input))) (cond (w ( progn (setq w (rds w)) (s!:fasl_supervisor) (close (rds w)))) (t (progn ( princ "Failed to open file ") (prin fromfile) (terpri)))) (cond (save (verbos save))) (start!-module nil) (cond (verbose (progn (cond ((neq (posn) 0) ( terpri))) (princ "+++ Compilation complete") (terpri)))) (return t))) (de compile!-file!* (fromfile !&optional tofile) (s!:compile!-file!* fromfile tofile t t)) (de compd (name type defn) (prog (g !*comp) (setq !*comp t) (cond ((eqcar defn (quote lambda)) (progn (setq g (dated!-name type)) ( symbol!-set!-definition g defn) (compile (list g)) (setq defn g)))) (put name type defn) (return name))) (de s!:compile0 (name) (prog (w args defn) (setq defn (getd name)) (cond (( and (eqcar defn (quote macro)) (eqcar (cdr defn) (quote lambda))) (prog ( !*comp lx vx bx) (setq lx (cdr defn)) (cond ((not (or (and (equal (length lx) 3) (not (atom (setq bx (caddr lx)))) (equal (cadr lx) (cdr bx))) (and (equal (length lx) 3) (not (atom (setq bx (caddr lx)))) (not (atom (cadr lx))) ( eqcar (cdadr lx) (quote !&optional)) (not (atom (setq bx (cdr bx)))) (equal ( caadr lx) (car bx)) (equal (cddadr lx) (cdr bx))))) (progn (setq w ( hashtagged!-name name defn)) (symbol!-set!-definition w (cdr defn)) ( s!:compile0 w) (cond ((equal 1 (length (cadr lx))) (symbol!-set!-env name ( list (quote (u !&optional env)) (list w (quote u))))) (t (symbol!-set!-env name (list (quote (u !&optional env)) (list w (quote u) (quote env))))))))))) (t (cond ((or (not (eqcar defn (quote expr))) (not (eqcar (cdr defn) (quote lambda)))) (progn (cond (!*pwrds (progn (cond ((neq (posn) 0) (terpri))) ( princ "+++ ") (prin name) (princ " not compilable") (terpri)))))) (t (progn ( setq args (cddr defn)) (setq defn (cdr args)) (setq args (car args)) (cond (( stringp args) (progn (cond (!*pwrds (progn (cond ((neq (posn) 0) (terpri))) ( princ "+++ ") (prin name) (princ " was already compiled") (terpri)))))) (t ( progn (cond (!*savedef (put name (quote !*savedef) (cons (quote lambda) (cons args (s!:fully_macroexpand_list defn)))))) (setq w (s!:compile1 name args defn nil)) (prog (var1194) (setq var1194 w) lab1193 (cond ((null var1194) ( return nil))) (prog (p) (setq p (car var1194)) (symbol!-set!-definition (car p) (cdr p))) (setq var1194 (cdr var1194)) (go lab1193)))))))))))) (de s!:fully_macroexpand_list (l) (cond ((atom l) l) (t (prog (var1196 var1197) (setq var1196 l) lab1195 (cond ((null var1196) (return (reversip var1197)))) (prog (u) (setq u (car var1196)) (setq var1197 (cons ( s!:fully_macroexpand u) var1197))) (setq var1196 (cdr var1196)) (go lab1195)) ))) (de s!:fully_macroexpand (x) (prog (helper) (cond ((or (atom x) (eqcar x ( quote quote))) (return x)) (t (cond ((eqcar (car x) (quote lambda)) (return ( cons (cons (quote lambda) (cons (cadar x) (s!:fully_macroexpand_list (cddar x )))) (s!:fully_macroexpand_list (cdr x))))) (t (cond ((setq helper (get (car x) (quote s!:newname))) (return (s!:fully_macroexpand (cons helper (cdr x)))) ) (t (cond ((setq helper (get (car x) (quote s!:expandfn))) (return (funcall helper x))) (t (cond ((setq helper (macro!-function (car x))) (return ( s!:fully_macroexpand (funcall helper x)))) (t (return (cons (car x) ( s!:fully_macroexpand_list (cdr x)))))))))))))))) (de s!:expandfunction (u) u) (de s!:expandflet (u) (cons (car u) (cons (prog (var1199 var1200) (setq var1199 (cadr u)) lab1198 (cond ((null var1199) (return (reversip var1200)))) (prog (b) (setq b (car var1199)) (setq var1200 (cons (s!:expandfletvars b) var1200))) (setq var1199 (cdr var1199)) (go lab1198)) ( s!:fully_macroexpand_list (cddr u))))) (de s!:expandfletvars (b) (cons (car b) (cons (cadr b) ( s!:fully_macroexpand_list (cddr b))))) (de s!:expandlabels (u) (s!:expandflet u)) (de s!:expandmacrolet (u) (s!:expandflet u)) (de s!:expandprog (u) (cons (car u) (cons (cadr u) (s!:fully_macroexpand_list (cddr u))))) (de s!:expandtagbody (u) (s!:fully_macroexpand_list u)) (de s!:expandprogv (u) (cons (car u) (cons (cadr u) (cons (caddr u) ( s!:fully_macroexpand_list (cadddr u)))))) (de s!:expandblock (u) (cons (car u) (cons (cadr u) ( s!:fully_macroexpand_list (cddr u))))) (de s!:expanddeclare (u) u) (de s!:expandlet (u) (cons (car u) (cons (prog (var1202 var1203) (setq var1202 (cadr u)) lab1201 (cond ((null var1202) (return (reversip var1203)))) (prog (x) (setq x (car var1202)) (setq var1203 (cons ( s!:fully_macroexpand_list x) var1203))) (setq var1202 (cdr var1202)) (go lab1201)) (s!:fully_macroexpand_list (cddr u))))) (de s!:expandlet!* (u) (s!:expandlet u)) (de s!:expandgo (u) u) (de s!:expandreturn!-from (u) (cons (car u) (cons (cadr u) ( s!:fully_macroexpand_list (cddr u))))) (de s!:expandcond (u) (cons (car u) (prog (var1205 var1206) (setq var1205 ( cdr u)) lab1204 (cond ((null var1205) (return (reversip var1206)))) (prog (x) (setq x (car var1205)) (setq var1206 (cons (s!:fully_macroexpand_list x) var1206))) (setq var1205 (cdr var1205)) (go lab1204)))) (de s!:expandcase (u) (cons (car u) (cons (s!:fully_macroexpand (cadr u)) ( prog (var1208 var1209) (setq var1208 (cddr u)) lab1207 (cond ((null var1208) (return (reversip var1209)))) (prog (x) (setq x (car var1208)) (setq var1209 (cons (cons (car x) (s!:fully_macroexpand_list (cdr x))) var1209))) (setq var1208 (cdr var1208)) (go lab1207))))) (de s!:expandeval!-when (u) (cons (car u) (cons (cadr u) ( s!:fully_macroexpand_list (cddr u))))) (de s!:expandthe (u) (cons (car u) (cons (cadr u) (s!:fully_macroexpand_list (cddr u))))) (de s!:expandmv!-call (u) (cons (car u) (cons (cadr u) ( s!:fully_macroexpand_list (cddr u))))) (put (quote function) (quote s!:expandfn) (function s!:expandfunction)) (put (quote flet) (quote s!:expandfn) (function s!:expandflet)) (put (quote labels) (quote s!:expandfn) (function s!:expandlabels)) (put (quote macrolet) (quote s!:expandfn) (function s!:expandmacrolet)) (put (quote prog) (quote s!:expandfn) (function s!:expandprog)) (put (quote tagbody) (quote s!:expandfn) (function s!:expandtagbody)) (put (quote progv) (quote s!:expandfn) (function s!:expandprogv)) (put (quote !~block) (quote s!:expandfn) (function s!:expandblock)) (put (quote declare) (quote s!:expandfn) (function s!:expanddeclare)) (put (quote !~let) (quote s!:expandfn) (function s!:expandlet)) (put (quote let!*) (quote s!:expandfn) (function s!:expandlet!*)) (put (quote go) (quote s!:expandfn) (function s!:expandgo)) (put (quote return!-from) (quote s!:expandfn) (function s!:expandreturn!-from )) (put (quote cond) (quote s!:expandfn) (function s!:expandcond)) (put (quote case) (quote s!:expandfn) (function s!:expandcase)) (put (quote eval!-when) (quote s!:expandfn) (function s!:expandeval!-when)) (put (quote the) (quote s!:expandfn) (function s!:expandthe)) (put (quote multiple!-value!-call) (quote s!:expandfn) (function s!:expandmv!-call)) (de compile (l) (prog nil (cond ((and (atom l) (not (null l))) (setq l (list l)))) (prog (var1211) (setq var1211 l) lab1210 (cond ((null var1211) (return nil))) (prog (name) (setq name (car var1211)) (errorset (list (quote s!:compile0) (mkquote name)) t t)) (setq var1211 (cdr var1211)) (go lab1210)) (return l))) (global (quote (!*fastvector !*unsafecar))) (flag (quote (fastvector unsafecar)) (quote switch)) (fluid (quote (C_file L_file O_file L_contents Setup_name File_name))) (dm c!:printf (u !&optional env) (list (quote c!:printf1) (cadr u) (cons ( quote list) (cddr u)))) (de c!:printf1 (fmt args) (prog (a c) (setq fmt (explode2 fmt)) (prog nil lab1212 (cond ((null fmt) (return nil))) (progn (setq c (car fmt)) (setq fmt (cdr fmt)) (cond ((and (equal c (quote !\)) (or (equal (car fmt) (quote !n)) (equal (car fmt) (quote !N)))) (progn (terpri) (setq fmt (cdr fmt)))) (t ( cond ((and (equal c (quote !\)) (or (equal (car fmt) (quote !q)) (equal (car fmt) (quote !Q)))) (progn (princ (quote !")) (setq fmt (cdr fmt)))) (t (cond ((equal c (quote !%)) (progn (setq c (car fmt)) (cond ((null args) (setq a ( quote missing_arg))) (t (setq a (car args)))) (cond ((or (equal c (quote !v)) (equal c (quote !V))) (cond ((flagp a (quote c!:live_across_call)) (progn ( princ "stack[") (princ (minus (get a (quote c!:location)))) (princ "]"))) (t (princ a)))) (t (cond ((or (equal c (quote !c)) (equal c (quote !C))) ( c!:safeprin a)) (t (cond ((or (equal c (quote !a)) (equal c (quote !A))) ( prin a)) (t (cond ((or (equal c (quote !t)) (equal c (quote !T))) (ttab a)) ( t (cond ((equal c (quote !<)) (progn (setq args (cons nil args)) (cond (( greaterp (posn) 70) (terpri))))) (t (princ a))))))))))) (cond (args (setq args (cdr args)))) (setq fmt (cdr fmt)))) (t (princ c)))))))) (go lab1212)))) (de c!:safeprin (x) (prog (n lastc) (setq n 0) (prog (var1214) (setq var1214 (explode x)) lab1213 (cond ((null var1214) (return nil))) (prog (c) (setq c ( car var1214)) (progn (cond ((and (greaterp n 120) (equal c (quote ! ))) ( progn (terpri) (prin2 "//") (setq n 2))) (t (cond ((and (greaterp n 150) (neq c !$eol!$)) (progn (terpri) (prin2 "// ") (setq n 3))) (t (setq n (plus n 1) ))))) (cond ((and (equal lastc (quote !\)) (equal c !$eol!$)) (princ " (backslash)"))) (setq lastc c) (princ c) (cond ((equal c !$eol!$) (progn ( princ "//") (setq n 2)))))) (setq var1214 (cdr var1214)) (go lab1213)) (cond ((equal lastc (quote !\)) (princ " (backslash)"))))) (de c!:valid_fndef (args body) (cond ((or (memq (quote !&optional) args) ( memq (quote !&rest) args)) nil) (t (c!:valid_list body)))) (de c!:valid_list (x) (cond ((null x) t) (t (cond ((atom x) nil) (t (cond (( not (c!:valid_expr (car x))) nil) (t (c!:valid_list (cdr x))))))))) (de c!:valid_expr (x) (cond ((atom x) t) (t (cond ((not (atom (car x))) ( progn (cond ((not (c!:valid_list (cdr x))) nil) (t (cond ((not (eqcar (car x) (quote lambda))) nil) (t (cond ((atom (cdar x)) nil) (t (c!:valid_fndef ( cadar x) (cddar x)))))))))) (t (cond ((not (idp (car x))) nil) (t (cond (( eqcar x (quote quote)) t) (t (prog (h) (setq h (get (car x) (quote c!:valid)) ) (cond ((null h) (return (c!:valid_list (cdr x))))) (return (funcall h (cdr x))))))))))))) (de c!:cspecform (x env) (error 0 (list "special form" x))) (de c!:valid_specform (x) nil) (progn (put (quote and) (quote c!:code) (function c!:cspecform)) (put (quote catch) (quote c!:code) (function c!:cspecform)) (put (quote compiler!-let) ( quote c!:code) (function c!:cspecform)) (put (quote cond) (quote c!:code) ( function c!:cspecform)) (put (quote declare) (quote c!:code) (function c!:cspecform)) (put (quote de) (quote c!:code) (function c!:cspecform)) (put (quote eval!-when) (quote c!:code) (function c!:cspecform)) (put (quote flet) (quote c!:code) (function c!:cspecform)) (put (quote function) (quote c!:code) (function c!:cspecform)) (put (quote go) (quote c!:code) (function c!:cspecform)) (put (quote if) (quote c!:code) (function c!:cspecform)) (put (quote labels) (quote c!:code) (function c!:cspecform)) (put (quote !~let) ( quote c!:code) (function c!:cspecform)) (put (quote let!*) (quote c!:code) ( function c!:cspecform)) (put (quote list) (quote c!:code) (function c!:cspecform)) (put (quote list!*) (quote c!:code) (function c!:cspecform)) ( put (quote macrolet) (quote c!:code) (function c!:cspecform)) (put (quote multiple!-value!-call) (quote c!:code) (function c!:cspecform)) (put (quote multiple!-value!-prog1) (quote c!:code) (function c!:cspecform)) (put (quote or) (quote c!:code) (function c!:cspecform)) (put (quote prog) (quote c!:code ) (function c!:cspecform)) (put (quote prog!*) (quote c!:code) (function c!:cspecform)) (put (quote prog1) (quote c!:code) (function c!:cspecform)) ( put (quote prog2) (quote c!:code) (function c!:cspecform)) (put (quote progn) (quote c!:code) (function c!:cspecform)) (put (quote progv) (quote c!:code) (function c!:cspecform)) (put (quote quote) (quote c!:code) (function c!:cspecform)) (put (quote return) (quote c!:code) (function c!:cspecform)) ( put (quote return!-from) (quote c!:code) (function c!:cspecform)) (put (quote setq) (quote c!:code) (function c!:cspecform)) (put (quote tagbody) (quote c!:code) (function c!:cspecform)) (put (quote the) (quote c!:code) (function c!:cspecform)) (put (quote unless) (quote c!:code) (function c!:cspecform)) ( put (quote unwind!-protect) (quote c!:code) (function c!:cspecform)) (put ( quote when) (quote c!:code) (function c!:cspecform)) (put (quote catch) ( quote c!:valid) (function c!:valid_specform)) (put (quote compiler!-let) ( quote c!:valid) (function c!:valid_specform)) (put (quote cond) (quote c!:valid) (function c!:valid_specform)) (put (quote declare) (quote c!:valid) (function c!:valid_specform)) (put (quote de) (quote c!:valid) (function c!:valid_specform)) (put (quote eval!-when) (quote c!:valid) (function c!:valid_specform)) (put (quote flet) (quote c!:valid) (function c!:valid_specform)) (put (quote function) (quote c!:valid) (function c!:valid_specform)) (put (quote labels) (quote c!:valid) (function c!:valid_specform)) (put (quote !~let) (quote c!:valid) (function c!:valid_specform)) (put (quote let!*) (quote c!:valid) (function c!:valid_specform)) (put (quote macrolet) (quote c!:valid) (function c!:valid_specform)) (put (quote multiple!-value!-call) (quote c!:valid) ( function c!:valid_specform)) (put (quote multiple!-value!-prog1) (quote c!:valid) (function c!:valid_specform)) (put (quote prog) (quote c!:valid) ( function c!:valid_specform)) (put (quote prog!*) (quote c!:valid) (function c!:valid_specform)) (put (quote progv) (quote c!:valid) (function c!:valid_specform)) (put (quote quote) (quote c!:valid) (function c!:valid_specform)) (put (quote the) (quote c!:valid) (function c!:valid_specform)) (put (quote unwind!-protect) (quote c!:valid) (function c!:valid_specform))) (fluid (quote (c!:current_procedure c!:current_args c!:current_block c!:current_contents c!:all_blocks c!:registers c!:stacklocs))) (fluid (quote (c!:available c!:used))) (setq c!:available (setq c!:used nil)) (de c!:reset_gensyms nil (progn (remflag c!:used (quote c!:live_across_call)) (remflag c!:used (quote c!:visited)) (prog nil lab1215 (cond ((null c!:used) (return nil))) (progn (remprop (car c!:used) (quote c!:contents)) (remprop ( car c!:used) (quote c!:why)) (remprop (car c!:used) (quote c!:where_to)) ( remprop (car c!:used) (quote c!:count)) (remprop (car c!:used) (quote c!:live )) (remprop (car c!:used) (quote c!:clash)) (remprop (car c!:used) (quote c!:chosen)) (remprop (car c!:used) (quote c!:location)) (cond ((plist (car c!:used)) (prog (o) (setq o (wrs nil)) (princ "+++++ ") (prin (car c!:used)) (princ " ") (prin (plist (car c!:used))) (terpri) (wrs o)))) (setq c!:available (cons (car c!:used) c!:available)) (setq c!:used (cdr c!:used))) (go lab1215)))) (de c!:my_gensym nil (prog (w) (cond (c!:available (progn (setq w (car c!:available)) (setq c!:available (cdr c!:available)))) (t (setq w (gensym1 "v")))) (setq c!:used (cons w c!:used)) (cond ((plist w) (progn (princ "????? ") (prin w) (princ " => ") (prin (plist w)) (terpri)))) (return w))) (de c!:newreg nil (prog (r) (setq r (c!:my_gensym)) (setq c!:registers (cons r c!:registers)) (return r))) (de c!:startblock (s) (progn (setq c!:current_block s) (setq c!:current_contents nil))) (de c!:outop (a b c d) (cond (c!:current_block (setq c!:current_contents ( cons (list a b c d) c!:current_contents))))) (de c!:endblock (why where_to) (cond (c!:current_block (progn (put c!:current_block (quote c!:contents) c!:current_contents) (put c!:current_block (quote c!:why) why) (put c!:current_block (quote c!:where_to ) where_to) (setq c!:all_blocks (cons c!:current_block c!:all_blocks)) (setq c!:current_contents nil) (setq c!:current_block nil))))) (de c!:cval_inner (x env) (prog (helper) (setq x (s!:improve x)) (cond ((atom x) (return (c!:catom x env))) (t (cond ((eqcar (car x) (quote lambda)) ( return (c!:clambda (cadar x) (cddar x) (cdr x) env))) (t (cond ((setq helper (get (car x) (quote c!:code))) (return (funcall helper x env))) (t (cond (( and (setq helper (get (car x) (quote c!:compile_macro))) (setq helper ( funcall helper x))) (return (c!:cval helper env))) (t (cond ((and (idp (car x )) (setq helper (macro!-function (car x)))) (return (c!:cval (funcall helper x) env))) (t (return (c!:ccall (car x) (cdr x) env)))))))))))))) (de c!:cval (x env) (prog (r) (setq r (c!:cval_inner x env)) (cond ((and r ( not (member!*!* r c!:registers))) (error 0 (list r "not a register" x)))) ( return r))) (de c!:clambda (bvl body args env) (prog (w w1 fluids env1 decs) (setq env1 ( car env)) (setq w (prog (var1217 var1218) (setq var1217 args) lab1216 (cond ( (null var1217) (return (reversip var1218)))) (prog (a) (setq a (car var1217)) (setq var1218 (cons (c!:cval a env) var1218))) (setq var1217 (cdr var1217)) (go lab1216))) (setq w1 (s!:find_local_decs body nil)) (setq localdecs (cons (car w1) localdecs)) (setq w1 (cdr w1)) (cond ((null w1) (setq body nil)) (t (cond ((null (cdr w1)) (setq body (car w1))) (t (setq body (cons (quote progn ) w1)))))) (prog (var1220) (setq var1220 bvl) lab1219 (cond ((null var1220) ( return nil))) (prog (x) (setq x (car var1220)) (cond ((and (not (fluidp x)) ( not (globalp x)) (c!:local_fluidp x localdecs)) (progn (make!-special x) ( setq decs (cons x decs)))))) (setq var1220 (cdr var1220)) (go lab1219)) (prog (var1222) (setq var1222 bvl) lab1221 (cond ((null var1222) (return nil))) ( prog (v) (setq v (car var1222)) (progn (cond ((globalp v) (prog (oo) (setq oo (wrs nil)) (princ "+++++ ") (prin v) (princ " converted from GLOBAL to FLUID") (terpri) (wrs oo) (unglobal (list v)) ( fluid (list v))))) (cond ((fluidp v) (progn (setq fluids (cons (cons v ( c!:newreg)) fluids)) (flag (list (cdar fluids)) (quote c!:live_across_call)) (setq env1 (cons (cons (quote c!:dummy!:name) (cdar fluids)) env1)) (c!:outop (quote ldrglob) (cdar fluids) v (c!:find_literal v)) (c!:outop (quote strglob) (car w) v (c!:find_literal v)))) (t (progn (setq env1 (cons (cons v (c!:newreg)) env1)) (c!:outop (quote movr) (cdar env1) nil (car w))))) (setq w (cdr w)))) (setq var1222 (cdr var1222)) (go lab1221)) (cond (fluids ( c!:outop (quote fluidbind) nil nil fluids))) (setq env (cons env1 (append fluids (cdr env)))) (setq w (c!:cval body env)) (prog (var1224) (setq var1224 fluids) lab1223 (cond ((null var1224) (return nil))) (prog (v) (setq v (car var1224)) (c!:outop (quote strglob) (cdr v) (car v) (c!:find_literal (car v)) )) (setq var1224 (cdr var1224)) (go lab1223)) (unfluid decs) (setq localdecs (cdr localdecs)) (return w))) (de c!:locally_bound (x env) (atsoc x (car env))) (flag (quote (nil t)) (quote c!:constant)) (fluid (quote (literal_vector))) (de c!:find_literal (x) (prog (n w) (setq w literal_vector) (setq n 0) (prog nil lab1225 (cond ((null (and w (not (equal (car w) x)))) (return nil))) ( progn (setq n (plus n 1)) (setq w (cdr w))) (go lab1225)) (cond ((null w) ( setq literal_vector (append literal_vector (list x))))) (return n))) (de c!:catom (x env) (prog (v w) (setq v (c!:newreg)) (cond ((and (idp x) (or (fluidp x) (globalp x))) (c!:outop (quote ldrglob) v x (c!:find_literal x))) (t (cond ((and (idp x) (setq w (c!:locally_bound x env))) (c!:outop (quote movr) v nil (cdr w))) (t (cond ((or (null x) (equal x (quote t)) ( c!:small_number x)) (c!:outop (quote movk1) v nil x)) (t (cond ((or (not (idp x)) (flagp x (quote c!:constant))) (c!:outop (quote movk) v x ( c!:find_literal x))) (t (c!:outop (quote ldrglob) v x (c!:find_literal x))))) ))))) (return v))) (de c!:cjumpif (x env d1 d2) (prog (helper r) (setq x (s!:improve x)) (cond ( (and (atom x) (or (not (idp x)) (and (flagp x (quote c!:constant)) (not ( c!:locally_bound x env))))) (c!:endblock (quote goto) (list (cond (x d1) (t d2))))) (t (cond ((and (not (atom x)) (setq helper (get (car x) (quote c!:ctest)))) (return (funcall helper x env d1 d2))) (t (progn (setq r ( c!:cval x env)) (c!:endblock (list (quote ifnull) r) (list d2 d1))))))))) (fluid (quote (c!:current))) (de c!:ccall (fn args env) (c!:ccall1 fn args env)) (fluid (quote (c!:visited))) (de c!:has_calls (a b) (prog (c!:visited) (return (c!:has_calls_1 a b)))) (de c!:has_calls_1 (a b) (cond ((or (equal a b) (not (atom a)) (memq a c!:visited)) nil) (t (prog (has_call) (setq c!:visited (cons a c!:visited)) ( prog (var1227) (setq var1227 (get a (quote c!:contents))) lab1226 (cond (( null var1227) (return nil))) (prog (z) (setq z (car var1227)) (cond ((eqcar z (quote call)) (setq has_call t)))) (setq var1227 (cdr var1227)) (go lab1226) ) (cond (has_call (return (prog (c!:visited) (return (c!:can_reach a b)))))) (prog (var1229) (setq var1229 (get a (quote c!:where_to))) lab1228 (cond (( null var1229) (return nil))) (prog (d) (setq d (car var1229)) (cond (( c!:has_calls_1 d b) (setq has_call t)))) (setq var1229 (cdr var1229)) (go lab1228)) (return has_call))))) (de c!:can_reach (a b) (cond ((equal a b) t) (t (cond ((or (not (atom a)) ( memq a c!:visited)) nil) (t (progn (setq c!:visited (cons a c!:visited)) ( c!:any_can_reach (get a (quote c!:where_to)) b))))))) (de c!:any_can_reach (l b) (cond ((null l) nil) (t (cond ((c!:can_reach (car l) b) t) (t (c!:any_can_reach (cdr l) b)))))) (de c!:pareval (args env) (prog (tasks tasks1 merge split r) (setq tasks ( prog (var1231 var1232) (setq var1231 args) lab1230 (cond ((null var1231) ( return (reversip var1232)))) (prog (a) (setq a (car var1231)) (setq var1232 ( cons (cons (c!:my_gensym) (c!:my_gensym)) var1232))) (setq var1231 (cdr var1231)) (go lab1230))) (setq split (c!:my_gensym)) (c!:endblock (quote goto ) (list split)) (prog (var1234) (setq var1234 args) lab1233 (cond ((null var1234) (return nil))) (prog (a) (setq a (car var1234)) (prog (s) (setq s ( car tasks)) (setq tasks (cdr tasks)) (c!:startblock (car s)) (setq r (cons ( c!:cval a env) r)) (c!:endblock (quote goto) (list (cdr s))) (cond ((or t ( c!:has_calls (car s) (cdr s))) (setq tasks1 (cons s tasks1))) (t (setq merge (cons s merge)))))) (setq var1234 (cdr var1234)) (go lab1233)) (prog (var1236 ) (setq var1236 tasks1) lab1235 (cond ((null var1236) (return nil))) (prog (z ) (setq z (car var1236)) (setq merge (cons z merge))) (setq var1236 (cdr var1236)) (go lab1235)) (prog (var1238) (setq var1238 merge) lab1237 (cond (( null var1238) (return nil))) (prog (v) (setq v (car var1238)) (progn ( c!:startblock split) (c!:endblock (quote goto) (list (car v))) (setq split ( cdr v)))) (setq var1238 (cdr var1238)) (go lab1237)) (c!:startblock split) ( return (reversip r)))) (de c!:ccall1 (fn args env) (prog (tasks merge r val) (setq fn (list fn (cdr env))) (setq val (c!:newreg)) (cond ((null args) (c!:outop (quote call) val nil fn)) (t (cond ((null (cdr args)) (c!:outop (quote call) val (list ( c!:cval (car args) env)) fn)) (t (progn (setq r (c!:pareval args env)) ( c!:outop (quote call) val r fn)))))) (c!:outop (quote reloadenv) (quote env) nil nil) (return val))) (fluid (quote (restart_label reloadenv does_call c!:current_c_name))) (de c!:local_fluidp1 (v decs) (and decs (or (and (eqcar (car decs) (quote special)) (memq v (cdar decs))) (c!:local_fluidp1 v (cdr decs))))) (de c!:local_fluidp (v decs) (and decs (or (c!:local_fluidp1 v (car decs)) ( c!:local_fluidp v (cdr decs))))) (fluid (quote (proglabs blockstack localdecs))) (de c!:cfndef (c!:current_procedure c!:current_c_name argsbody checksum) ( prog (env n w c!:current_args c!:current_block restart_label c!:current_contents c!:all_blocks entrypoint exitpoint args1 c!:registers c!:stacklocs literal_vector reloadenv does_call blockstack proglabs args body localdecs varargs) (setq args (car argsbody)) (setq body (cdr argsbody)) ( setq w (s!:find_local_decs body nil)) (setq body (cdr w)) (cond ((atom body) (setq body nil)) (t (cond ((atom (cdr body)) (setq body (car body))) (t (setq body (cons (quote progn) body)))))) (setq localdecs (list (car w))) ( c!:reset_gensyms) (wrs C_file) (linelength 200) (c!:printf "\n\n// Code for %a\n\n" c!:current_procedure) (c!:find_literal c!:current_procedure) (setq c!:current_args args) (setq varargs (or (null args) (geq (length args) 3))) (prog (var1240) (setq var1240 args) lab1239 ( cond ((null var1240) (return nil))) (prog (v) (setq v (car var1240)) (cond (( or (equal v (quote !&optional)) (equal v (quote !&rest))) (error 0 "&optional and &rest not supported by this compiler (yet)")) (t (cond (( globalp v) (prog (oo) (setq oo (wrs nil)) (princ "+++++ ") (prin v) (princ " converted from GLOBAL to FLUID") (terpri) (wrs oo) (unglobal (list v)) ( fluid (list v)) (setq n (cons (cons v (c!:my_gensym)) n)))) (t (cond ((or ( fluidp v) (c!:local_fluidp v localdecs)) (setq n (cons (cons v (c!:my_gensym) ) n))))))))) (setq var1240 (cdr var1240)) (go lab1239)) (cond (!*r2i (setq body (s!:r2i c!:current_procedure args body)))) (setq restart_label ( c!:my_gensym)) (setq body (list (quote c!:private_tagbody) restart_label body )) (cond (n (progn (setq body (list (list (quote return) body))) (setq args ( subla n args)) (prog (var1242) (setq var1242 n) lab1241 (cond ((null var1242) (return nil))) (prog (v) (setq v (car var1242)) (setq body (cons (list ( quote setq) (car v) (cdr v)) body))) (setq var1242 (cdr var1242)) (go lab1241 )) (setq body (cons (quote prog) (cons (prog (var1244 var1245) (setq var1244 (reverse n)) lab1243 (cond ((null var1244) (return (reversip var1245)))) ( prog (v) (setq v (car var1244)) (setq var1245 (cons (car v) var1245))) (setq var1244 (cdr var1244)) (go lab1243)) body)))))) (c!:printf "static LispObject %s(LispObject env" c!:current_c_name) (setq env nil) (cond (varargs (c!:printf ", int nargs, ...")) (t (progn (setq n t) (prog (var1247 ) (setq var1247 args) lab1246 (cond ((null var1247) (return nil))) (prog (x) (setq x (car var1247)) (prog (aa) (c!:printf ",") (cond (n (progn (c!:printf "\n ") (setq n nil))) (t (setq n t))) (setq aa ( c!:my_gensym)) (setq env (cons (cons x aa) env)) (setq c!:registers (cons aa c!:registers)) (setq args1 (cons aa args1)) (c!:printf " LispObject %s" aa))) (setq var1247 (cdr var1247)) (go lab1246))))) (c!:printf ")\n{\n") (cond (( and varargs args) (prog (var1249) (setq var1249 args) lab1248 (cond ((null var1249) (return nil))) (prog (x) (setq x (car var1249)) (prog (aa) (setq aa (c!:my_gensym)) (setq env (cons (cons x aa) env)) (setq c!:registers (cons aa c!:registers)) (setq args1 (cons aa args1)))) (setq var1249 (cdr var1249)) ( go lab1248)))) (c!:startblock (setq entrypoint (c!:my_gensym))) (setq exitpoint c!:current_block) (c!:endblock (quote goto) (list (list (c!:cval body (cons env nil))))) (c!:optimise_flowgraph entrypoint c!:all_blocks env ( cons (length args) c!:current_procedure) args1 varargs) (c!:printf "}\n\n") ( wrs O_file) (setq L_contents (cons (cons c!:current_procedure (cons literal_vector checksum)) L_contents)) (return nil))) (flag (quote (rds deflist flag fluid global remprop remflag unfluid unglobal dm carcheck C!-end)) (quote eval)) (flag (quote (rds)) (quote ignore)) (fluid (quote (!*backtrace))) (de c!:ccompilesupervisor nil (prog (u w) top (setq u (errorset (quote (read) ) t !*backtrace)) (cond ((atom u) (return nil))) (setq u (car u)) (cond (( equal u !$eof!$) (return nil))) (cond ((atom u) (go top)) (t (cond ((eqcar u (quote C!-end)) (return (apply (quote C!-end) nil))) (t (cond ((eqcar u ( quote rdf)) (progn (setq w (open (setq u (eval (cadr u))) (quote input))) ( cond (w (progn (terpri) (princ "Reading file ") (print u) (setq w (rds w)) ( c!:ccompilesupervisor) (princ "End of file ") (print u) (close (rds w)))) (t (progn (princ "Failed to open file ") (print u)))))) (t (c!:ccmpout1 u))))))) (go top))) (global (quote (c!:char_mappings))) (setq c!:char_mappings (quote ((! . !A) (!! . !B) (!# . !C) (!$ . !D) (!% . !E) (!^ . !F) (!& . !G) (!* . !H) (!( . !I) (!) . !J) (!- . !K) (!+ . !L) (!= . !M) (!\ . !N) (!| . !O) (!, . !P) (!. . !Q) (!< . !R) (!> . !S) (!: . !T) (!; . !U) (!/ . !V) (!? . !W) (!~ . !X) (!` . !Y)))) (fluid (quote (c!:names_so_far))) (de c!:inv_name (n) (prog (r w) (cond ((setq w (assoc n c!:names_so_far)) ( setq w (plus (cdr w) 1))) (t (setq w 0))) (setq c!:names_so_far (cons (cons n w) c!:names_so_far)) (setq r (quote (!C !C !"))) (cond ((not (zerop w)) ( setq r (append (reverse (explodec w)) r)))) (setq r (cons (quote !_) r)) ( prog (var1251) (setq var1251 (explode2 n)) lab1250 (cond ((null var1251) ( return nil))) (prog (c) (setq c (car var1251)) (progn (cond ((equal c (quote _)) (setq r (cons (quote _) r))) (t (cond ((or (liter c) (digit c)) (setq r ( cons c r))) (t (cond ((setq w (atsoc c c!:char_mappings)) (setq r (cons (cdr w) r))) (t (setq r (cons (quote !Z) r)))))))))) (setq var1251 (cdr var1251)) (go lab1250)) (setq r (cons (quote !") r)) (return (compress (reverse r))))) (fluid (quote (c!:defnames pending_functions))) (de c!:ccmpout1 (u) (prog (pending_functions) (setq pending_functions (list u )) (prog nil lab1252 (cond ((null pending_functions) (return nil))) (progn ( setq u (car pending_functions)) (setq pending_functions (cdr pending_functions)) (c!:ccmpout1a u)) (go lab1252)))) (de c!:ccmpout1a (u) (prog (w checksum) (cond ((atom u) (return nil)) (t ( cond ((eqcar u (quote progn)) (progn (prog (var1254) (setq var1254 (cdr u)) lab1253 (cond ((null var1254) (return nil))) (prog (v) (setq v (car var1254)) (c!:ccmpout1a v)) (setq var1254 (cdr var1254)) (go lab1253)) (return nil))) (t (cond ((eqcar u (quote C!-end)) nil) (t (cond ((or (flagp (car u) (quote eval)) (and (equal (car u) (quote setq)) (not (atom (caddr u))) (flagp ( caaddr u) (quote eval)))) (errorset u t !*backtrace))))))))) (cond ((eqcar u (quote rdf)) (prog nil (setq w (open (setq u (eval (cadr u))) (quote input))) (cond (w (progn (princ "Reading file ") (print u) (setq w (rds w)) ( c!:ccompilesupervisor) (princ "End of file ") (print u) (close (rds w)))) (t (progn (princ "Failed to open file ") (print u)))))) (t (cond ((eqcar u ( quote de)) (progn (setq u (cdr u)) (setq checksum (md60 u)) (setq c!:defnames (cons (list (car u) (c!:inv_name (car u)) (length (cadr u)) checksum) c!:defnames)) (princ "Compiling ") (prin (caar c!:defnames)) (princ " ... ") (c!:cfndef (caar c!:defnames) (cadar c!:defnames) (cdr u) checksum) (terpri)) )))))) (fluid (quote (!*defn dfprint!* dfprintsave))) (de c!:concat (a b) (compress (cons (quote !") (append (explode2 a) (append ( explode2 b) (quote (!"))))))) (de c!:ccompilestart (name setupname dir hdrnow) (prog (o d w) (reset!-gensym 0) (setq c!:registers (setq c!:available (setq c!:used nil))) (setq File_name (list2string (explodec name))) (setq Setup_name (explodec setupname )) (setq Setup_name (subst (quote !_) (quote !-) Setup_name)) (setq Setup_name (list2string Setup_name)) (cond (dir (progn (cond ((memq (quote win32) lispsystem!*) (setq name (c!:concat dir (c!:concat "\" name)))) (t ( setq name (c!:concat dir (c!:concat "/" name)))))))) (princ "C file = ") ( print name) (setq C_file (open (c!:concat name ".cpp") (quote output))) (setq L_file (c!:concat name ".lsp")) (setq L_contents nil) (setq c!:names_so_far nil) (setq o (reverse (explode (date!-and!-time)))) (prog (i) (setq i 1) lab1255 (cond ((minusp (times 1 (difference 5 i))) (return nil))) (progn ( setq d (cons (car o) d)) (setq o (cdr o))) (setq i (plus i 1)) (go lab1255)) (setq d (cons (quote !-) d)) (setq o (cdddr (cdddr (cddddr o)))) (setq w o) ( setq o (cdddr o)) (setq d (cons (caddr o) (cons (cadr o) (cons (car o) d)))) (setq d (compress (cons (quote !") (cons (cadr w) (cons (car w) (cons (quote !-) d)))))) (setq O_file (wrs C_file)) (setq c!:defnames nil) (cond (hdrnow ( c!:printf "\n// Module: %s %tMachine generated C code\n\n" setupname 25)) (t (c!:printf "\n// %s.c %tMachine generated C code\n\n" name 25))) (c!:printf "// $I") (c!:printf "d: $\n\n") (c!:printf "#include <cstdio>\n") (c!:printf "#include <cstdlib>\n") (c!:printf "#include <cstring>\n") (c!:printf "#include <cctype>\n") (c!:printf "#include <cstdarg>\n") (c!:printf "#include <ctime>\n") (c!:printf "#ifndef _cplusplus\n") (c!:printf "#include <csetjmp>\n") (c!:printf "#endif\n\n") (cond (hdrnow ( print!-config!-header)) (t (c!:printf "#include \qconfig.h\q\n\n"))) ( print!-csl!-headers) (cond (hdrnow (c!:print!-init))) (wrs O_file) (return nil))) (de c!:print!-init nil (progn (c!:printf "\n") (c!:printf "LispObject *nilp;\n") (c!:printf "LispObject **C_stackp;\n") (c!:printf "LispObject * volatile * stackLimitp;\n") (c!:printf "\n") (c!:printf "void init(LispObject *a, LispObject **b, LispObject * volatile *c)\n") ( c!:printf "{\n") (c!:printf " nilp = a;\n") (c!:printf " C_stackp = b;\n") (c!:printf " stackLimitp = c;\n") (c!:printf "}\n") (c!:printf "\n") (c!:printf "#define nil (*nilp)\n") (c!:printf "#define C_stack (*C_stackp)\n") (c!:printf "#define stackLimit (*stackLimitp)\n") (c!:printf "\n"))) (de C!-end nil (C!-end1 t)) (de C!-end1 (create_lfile) (prog (checksum c1 c2 c3) (wrs C_file) (cond ( create_lfile (c!:printf "\n\nsetup_type const %s_setup[] =\n{\n" Setup_name)) (t (c!:printf "\n\nsetup_type_1 const %s_setup[] =\n{\n" Setup_name))) (setq c!:defnames (reverse c!:defnames)) (prog nil lab1256 (cond ((null c!:defnames) (return nil))) (prog (name nargs f1 f2 cast fn) (setq name (caar c!:defnames)) (setq checksum (cadddr (car c!:defnames))) (setq f1 (cadar c!:defnames)) (setq nargs (caddar c!:defnames)) (setq cast "(n_args *)") ( cond ((equal nargs 1) (progn (setq f2 (quote !t!o!o_!m!a!n!y_1)) (setq cast "") (setq fn (quote !w!r!o!n!g_!n!o_1)))) (t (cond ((equal nargs 2) (progn ( setq f2 f1) (setq f1 (quote !t!o!o_!f!e!w_2)) (setq cast "") (setq fn (quote !w!r!o!n!g_!n!o_2)))) (t (progn (setq fn f1) (setq f1 (quote !w!r!o!n!g_!n!o_!n!a)) (setq f2 (quote !w!r!o!n!g_!n!o_!n!b))))))) (cond ( create_lfile (c!:printf " {\q%s\q,%t%s,%t%s,%t%s%s},\n" name 32 f1 48 f2 63 cast fn)) (t (prog (c1 c2) (setq c1 (divide checksum (expt 2 31))) (setq c2 (cdr c1)) (setq c1 (car c1)) (c!:printf " {\q%s\q, %t%s, %t%s, %t%s%s, %t%s, %t%s},\n" name 24 f1 40 f2 52 cast fn 64 c1 76 c2)))) (setq c!:defnames (cdr c!:defnames))) (go lab1256)) (setq c3 (setq checksum (md60 L_contents))) (setq c1 (remainder c3 10000000)) (setq c3 (quotient c3 10000000)) (setq c2 (remainder c3 10000000)) (setq c3 ( quotient c3 10000000)) (setq checksum (list2string (append (explodec c3) ( cons (quote ! ) (append (explodec c2) (cons (quote ! ) (explodec c1))))))) ( c!:printf " {NULL, (one_args *)%a, (two_args *)%a, 0}\n};\n\n" Setup_name checksum) (c!:printf "%<// end of generated code\n") (close C_file) (cond ( create_lfile (progn (setq L_file (open L_file (quote output))) (wrs L_file) ( linelength 72) (terpri) (princ "% ") (princ Setup_name) (princ ".lsp") (ttab 20) (princ "Machine generated Lisp") (terpri) (terpri) (princ "(c!:install ") (princ (quote !")) (princ Setup_name) (princ (quote !")) (princ " ") (princ checksum) (printc ")") (terpri) (prog (var1258) (setq var1258 (reverse L_contents)) lab1257 (cond ((null var1258) (return nil))) (prog (x) (setq x ( car var1258)) (progn (princ "(c!:install '") (prin (car x)) (princ " '") ( prin (cadr x)) (princ " ") (prin (cddr x)) (princ ")") (terpri) (terpri))) ( setq var1258 (cdr var1258)) (go lab1257)) (terpri) (princ "% End of generated Lisp code") (terpri) (terpri) (setq L_contents nil) (wrs O_file) (close L_file) (setq !*defn nil) (setq dfprint!* dfprintsave))) (t ( progn (setq checksum (cons checksum (reverse L_contents))) (setq L_contents nil) (return checksum)))))) (put (quote C!-end) (quote stat) (quote endstat)) (de C!-compile (u) (prog nil (terpri) (princ "C!-COMPILE ") (prin u) (princ ": IN files; or type in expressions") (terpri) (princ "When all done, execute C!-END;") (terpri) (verbos nil) (c!:ccompilestart ( car u) (car u) nil nil) (setq dfprintsave dfprint!*) (setq dfprint!* (quote c!:ccmpout1)) (setq !*defn t) (cond ((getd (quote begin)) (return nil))) ( c!:ccompilesupervisor))) (put (quote C!-compile) (quote stat) (quote rlis)) (de c!:print_opcode (s depth) (prog (op r1 r2 r3 helper) (setq op (car s)) ( setq r1 (cadr s)) (setq r2 (caddr s)) (setq r3 (cadddr s)) (setq helper (get op (quote c!:opcode_printer))) (cond (helper (funcall helper op r1 r2 r3 depth)) (t (progn (prin s) (terpri)))))) (de c!:print_exit_condition (why where_to depth) (prog (helper lab1 drop1 lab2 drop2 negate) (cond ((equal why (quote goto)) (progn (setq where_to (car where_to)) (cond ((atom where_to) (progn (c!:printf " goto %s;\n" where_to) (c!:display_flowgraph where_to depth t))) (t (progn (c!:printf " ") (c!:pgoto where_to depth)))) (return nil))) (t (cond ((eqcar (car why ) (quote call)) (return (prog (args locs g w) (cond ((setq w (get (cadar why) (quote c!:direct_entrypoint))) (progn (prog (var1260) (setq var1260 (cdr why )) lab1259 (cond ((null var1260) (return nil))) (prog (a) (setq a (car var1260)) (cond ((flagp a (quote c!:live_across_call)) (progn (cond ((null g) (c!:printf " {\n"))) (setq g (c!:my_gensym)) (c!:printf " LispObject %s = %v;\n" g a) (setq args (cons g args)))) (t (setq args (cons a args))))) (setq var1260 (cdr var1260)) (go lab1259)) (cond ((neq depth 0) (progn (cond (g (c!:printf " "))) (c!:printf " popv(%s);\n" depth)))) (cond (g (c!:printf " "))) (c!:printf " return %s(" (cdr w)) (setq args (reversip args)) (cond (args (progn (c!:printf "%v" (car args)) ( prog (var1262) (setq var1262 (cdr args)) lab1261 (cond ((null var1262) ( return nil))) (prog (a) (setq a (car var1262)) (c!:printf ", %v" a)) (setq var1262 (cdr var1262)) (go lab1261))))) (c!:printf ");\n") (cond (g ( c!:printf " }\n"))))) (t (cond ((setq w (get (cadar why) (quote c!:c_entrypoint))) (progn (prog (var1264) (setq var1264 (cdr why)) lab1263 ( cond ((null var1264) (return nil))) (prog (a) (setq a (car var1264)) (cond (( flagp a (quote c!:live_across_call)) (progn (cond ((null g) (c!:printf " {\n"))) (setq g (c!:my_gensym)) (c!:printf " LispObject %s = %v;\n" g a) (setq args (cons g args)))) (t (setq args (cons a args))))) (setq var1264 (cdr var1264)) (go lab1263)) (cond ((neq depth 0) (c!:printf " popv(%s);\n" depth))) (c!:printf " return %s(nil" w) (cond ((or (null args) (geq (length args) 3)) ( c!:printf ", %s" (length args)))) (prog (var1266) (setq var1266 (reversip args)) lab1265 (cond ((null var1266) (return nil))) (prog (a) (setq a (car var1266)) (c!:printf ", %v" a)) (setq var1266 (cdr var1266)) (go lab1265)) ( c!:printf ");\n") (cond (g (c!:printf " }\n"))))) (t (prog (nargs) (setq nargs (length (cdr why))) (c!:printf " {\n") (prog (var1268) (setq var1268 (cdr why)) lab1267 (cond ((null var1268) (return nil))) (prog (a) (setq a ( car var1268)) (cond ((flagp a (quote c!:live_across_call)) (progn (setq g ( c!:my_gensym)) (c!:printf " LispObject %s = %v;\n" g a) (setq args ( cons g args)))) (t (setq args (cons a args))))) (setq var1268 (cdr var1268)) (go lab1267)) (cond ((neq depth 0) (c!:printf " popv(%s);\n" depth))) (c!:printf " fn = elt(env, %s); %<// %c\n" (c!:find_literal (cadar why )) (cadar why)) (cond ((equal nargs 1) (c!:printf " return (*qfn1(fn))(qenv(fn)")) (t (cond ((equal nargs 2) (c!:printf " return (*qfn2(fn))(qenv(fn)")) (t (c!:printf " return (*qfnn(fn))(qenv(fn), %s" nargs))))) (prog (var1270) (setq var1270 (reversip args)) lab1269 (cond ((null var1270) (return nil))) (prog ( a) (setq a (car var1270)) (c!:printf ", %s" a)) (setq var1270 (cdr var1270)) (go lab1269)) (c!:printf ");\n }\n")))))) (return nil))))))) (setq lab1 ( car where_to)) (setq drop1 (and (atom lab1) (not (flagp lab1 (quote c!:visited))))) (setq lab2 (cadr where_to)) (setq drop2 (and (atom lab2) (not (flagp drop2 (quote c!:visited))))) (cond ((and drop2 (equal (get lab2 ( quote c!:count)) 1)) (progn (setq where_to (list lab2 lab1)) (setq drop1 t))) (t (cond (drop1 (setq negate t))))) (setq helper (get (car why) (quote c!:exit_helper))) (cond ((null helper) (error 0 (list "Bad exit condition" why)))) (c!:printf " if (") (cond (negate (progn (c!:printf "!(") (funcall helper (cdr why) depth) (c!:printf ")"))) (t (funcall helper (cdr why) depth ))) (c!:printf ") ") (cond ((not drop1) (progn (c!:pgoto (car where_to) depth ) (c!:printf " else ")))) (c!:pgoto (cadr where_to) depth) (cond ((atom ( car where_to)) (c!:display_flowgraph (car where_to) depth drop1))) (cond (( atom (cadr where_to)) (c!:display_flowgraph (cadr where_to) depth nil))))) (de c!:pmovr (op r1 r2 r3 depth) (c!:printf " %v = %v;\n" r1 r3)) (put (quote movr) (quote c!:opcode_printer) (function c!:pmovr)) (de c!:pmovk (op r1 r2 r3 depth) (c!:printf " %v = elt(env, %s); %<// %c\n" r1 r3 r2)) (put (quote movk) (quote c!:opcode_printer) (function c!:pmovk)) (de c!:pmovk1 (op r1 r2 r3 depth) (cond ((null r3) (c!:printf " %v = nil;\n" r1)) (t (cond ((equal r3 (quote t)) (c!:printf " %v = lisp_true;\n" r1)) (t (c!:printf " %v = (LispObject)%s+TAG_FIXNUM; %<// %c\n" r1 (times 16 r3) r3)))))) (put (quote movk1) (quote c!:opcode_printer) (function c!:pmovk1)) (flag (quote (movk1)) (quote c!:uses_nil)) (de c!:preloadenv (op r1 r2 r3 depth) (c!:printf " env = stack[%s];\n" ( minus reloadenv))) (put (quote reloadenv) (quote c!:opcode_printer) (function c!:preloadenv)) (de c!:pldrglob (op r1 r2 r3 depth) (c!:printf " %v = qvalue(elt(env, %s)); %<// %c\n" r1 r3 r2)) (put (quote ldrglob) (quote c!:opcode_printer) (function c!:pldrglob)) (de c!:pstrglob (op r1 r2 r3 depth) (c!:printf " qvalue(elt(env, %s)) = %v; %<// %c\n" r3 r1 r2)) (put (quote strglob) (quote c!:opcode_printer) (function c!:pstrglob)) (de c!:pnilglob (op r1 r2 r3 depth) (c!:printf " qvalue(elt(env, %s)) = nil; %<// %c\n" r3 r2)) (put (quote nilglob) (quote c!:opcode_printer) (function c!:pnilglob)) (flag (quote (nilglob)) (quote c!:uses_nil)) (de c!:pnull (op r1 r2 r3 depth) (c!:printf " %v = (%v == nil ? lisp_true : nil);\n" r1 r3)) (put (quote null) (quote c!:opcode_printer) (function c!:pnull)) (put (quote not) (quote c!:opcode_printer) (function c!:pnull)) (flag (quote (null not)) (quote c!:uses_nil)) (de c!:pfastget (op r1 r2 r3 depth) (progn (c!:printf " if (!symbolp(%v)) %v = nil;\n" r2 r1) (c!:printf " else { %v = qfastgets(%v);\n" r1 r2) (c!:printf " if (%v != nil) { %v = elt(%v, %s); %<// %c\n" r1 r1 r1 (car r3) ( cdr r3)) (c!:printf "#ifdef RECORD_GET\n") (c!:printf " if (%v != SPID_NOPROP)\n" r1) (c!:printf " record_get(elt(fastget_names, %s), 1);\n" (car r3)) ( c!:printf " else record_get(elt(fastget_names, %s), 0),\n" (car r3)) (c!:printf " %v = nil; }\n" r1) (c!:printf " else record_get(elt(fastget_names, %s), 0); }\n" (car r3)) ( c!:printf "#else\n") (c!:printf " if (%v == SPID_NOPROP) %v = nil; }}\n" r1 r1) (c!:printf "#endif\n"))) (put (quote fastget) (quote c!:opcode_printer) (function c!:pfastget)) (flag (quote (fastget)) (quote c!:uses_nil)) (de c!:pfastflag (op r1 r2 r3 depth) (progn (c!:printf " if (!symbolp(%v)) %v = nil;\n" r2 r1) (c!:printf " else { %v = qfastgets(%v);\n" r1 r2) (c!:printf " if (%v != nil) { %v = elt(%v, %s); %<// %c\n" r1 r1 r1 (car r3) ( cdr r3)) (c!:printf "#ifdef RECORD_GET\n") (c!:printf " if (%v == SPID_NOPROP)\n" r1) (c!:printf " record_get(elt(fastget_names, %s), 0),\n" (car r3)) ( c!:printf " %v = nil;\n" r1) (c!:printf " else record_get(elt(fastget_names, %s), 1),\n" (car r3)) ( c!:printf " %v = lisp_true; }\n" r1) (c!:printf " else record_get(elt(fastget_names, %s), 0); }\n" (car r3)) ( c!:printf "#else\n") (c!:printf " if (%v == SPID_NOPROP) %v = nil; else %v = lisp_true; }}\n" r1 r1 r1) (c!:printf "#endif\n"))) (put (quote fastflag) (quote c!:opcode_printer) (function c!:pfastflag)) (flag (quote (fastflag)) (quote c!:uses_nil)) (de c!:pcar (op r1 r2 r3 depth) (prog nil (cond ((not !*unsafecar) (progn ( c!:printf " if (!car_legal(%v)) " r3) (c!:pgoto (c!:find_error_label (list (quote car) r3) r2 depth) depth)))) (c!:printf " %v = qcar(%v);\n" r1 r3) )) (put (quote car) (quote c!:opcode_printer) (function c!:pcar)) (de c!:pcdr (op r1 r2 r3 depth) (prog nil (cond ((not !*unsafecar) (progn ( c!:printf " if (!car_legal(%v)) " r3) (c!:pgoto (c!:find_error_label (list (quote cdr) r3) r2 depth) depth)))) (c!:printf " %v = qcdr(%v);\n" r1 r3) )) (put (quote cdr) (quote c!:opcode_printer) (function c!:pcdr)) (de c!:pqcar (op r1 r2 r3 depth) (c!:printf " %v = qcar(%v);\n" r1 r3)) (put (quote qcar) (quote c!:opcode_printer) (function c!:pqcar)) (de c!:pqcdr (op r1 r2 r3 depth) (c!:printf " %v = qcdr(%v);\n" r1 r3)) (put (quote qcdr) (quote c!:opcode_printer) (function c!:pqcdr)) (de c!:patom (op r1 r2 r3 depth) (c!:printf " %v = (consp(%v) ? nil : lisp_true);\n" r1 r3)) (put (quote atom) (quote c!:opcode_printer) (function c!:patom)) (flag (quote (atom)) (quote c!:uses_nil)) (de c!:pnumberp (op r1 r2 r3 depth) (c!:printf " %v = (is_number(%v) ? lisp_true : nil);\n" r1 r3)) (put (quote numberp) (quote c!:opcode_printer) (function c!:pnumberp)) (flag (quote (numberp)) (quote c!:uses_nil)) (de c!:pfixp (op r1 r2 r3 depth) (c!:printf " %v = integerp(%v);\n" r1 r3) ) (put (quote fixp) (quote c!:opcode_printer) (function c!:pfixp)) (flag (quote (fixp)) (quote c!:uses_nil)) (de c!:piminusp (op r1 r2 r3 depth) (c!:printf " %v = ((intptr_t)(%v) < 0 ? lisp_true : nil);\n" r1 r3)) (put (quote iminusp) (quote c!:opcode_printer) (function c!:piminusp)) (flag (quote (iminusp)) (quote c!:uses_nil)) (de c!:pilessp (op r1 r2 r3 depth) (c!:printf " %v = ((intptr_t)%v < (intptr_t)%v) ? lisp_true : nil;\n" r1 r2 r3)) (put (quote ilessp) (quote c!:opcode_printer) (function c!:pilessp)) (flag (quote (ilessp)) (quote c!:uses_nil)) (de c!:pigreaterp (op r1 r2 r3 depth) (c!:printf " %v = ((intptr_t)%v > (intptr_t)%v) ? lisp_true : nil;\n" r1 r2 r3)) (put (quote igreaterp) (quote c!:opcode_printer) (function c!:pigreaterp)) (flag (quote (igreaterp)) (quote c!:uses_nil)) (de c!:piminus (op r1 r2 r3 depth) (c!:printf " %v = (LispObject)(2-((intptr_t)(%v)));\n" r1 r3)) (put (quote iminus) (quote c!:opcode_printer) (function c!:piminus)) (de c!:piadd1 (op r1 r2 r3 depth) (c!:printf " %v = (LispObject)((intptr_t)(%v) + 0x10);\n" r1 r3)) (put (quote iadd1) (quote c!:opcode_printer) (function c!:piadd1)) (de c!:pisub1 (op r1 r2 r3 depth) (c!:printf " %v = (LispObject)((intptr_t)(%v) - 0x10);\n" r1 r3)) (put (quote isub1) (quote c!:opcode_printer) (function c!:pisub1)) (de c!:piplus2 (op r1 r2 r3 depth) (progn (c!:printf " %v = (LispObject)(intptr_t)((intptr_t)%v +" r1 r2) (c!:printf " (intptr_t)%v - TAG_FIXNUM);\n" r3))) (put (quote iplus2) (quote c!:opcode_printer) (function c!:piplus2)) (de c!:pidifference (op r1 r2 r3 depth) (progn (c!:printf " %v = (LispObject)(intptr_t)((intptr_t)%v - (intptr_t)%v" r1 r2 r3) ( c!:printf " + TAG_FIXNUM);\n"))) (put (quote idifference) (quote c!:opcode_printer) (function c!:pidifference) ) (de c!:pitimes2 (op r1 r2 r3 depth) (progn (c!:printf " %v = fixnum_of_int((intptr_t)(int_of_fixnum(%v) *" r1 r2) (c!:printf " int_of_fixnum(%v)));\n" r3))) (put (quote itimes2) (quote c!:opcode_printer) (function c!:pitimes2)) (de c!:pmodular_plus (op r1 r2 r3 depth) (progn (c!:printf " { intptr_t w = int_of_fixnum(%v) + int_of_fixnum(%v);\n" r2 r3) ( c!:printf " if (w >= current_modulus) w -= current_modulus;\n") ( c!:printf " %v = fixnum_of_int(w);\n" r1) (c!:printf " }\n"))) (put (quote modular!-plus) (quote c!:opcode_printer) (function c!:pmodular_plus)) (de c!:pmodular_difference (op r1 r2 r3 depth) (progn (c!:printf " { intptr_t w = int_of_fixnum(%v) - int_of_fixnum(%v);\n" r2 r3) ( c!:printf " if (w < 0) w += current_modulus;\n") (c!:printf " %v = fixnum_of_int(w);\n" r1) (c!:printf " }\n"))) (put (quote modular!-difference) (quote c!:opcode_printer) (function c!:pmodular_difference)) (de c!:pmodular_minus (op r1 r2 r3 depth) (progn (c!:printf " { intptr_t w = int_of_fixnum(%v);\n" r3) (c!:printf " if (w != 0) w = current_modulus - w;\n") (c!:printf " %v = fixnum_of_int(w);\n" r1) (c!:printf " }\n"))) (put (quote modular!-minus) (quote c!:opcode_printer) (function c!:pmodular_minus)) (de c!:passoc (op r1 r2 r3 depth) (c!:printf " %v = Lassoc(nil, %v, %v);\n" r1 r2 r3)) (put (quote assoc) (quote c!:opcode_printer) (function c!:passoc)) (flag (quote (assoc)) (quote c!:uses_nil)) (de c!:patsoc (op r1 r2 r3 depth) (c!:printf " %v = Latsoc(nil, %v, %v);\n" r1 r2 r3)) (put (quote atsoc) (quote c!:opcode_printer) (function c!:patsoc)) (flag (quote (atsoc)) (quote c!:uses_nil)) (de c!:pmember (op r1 r2 r3 depth) (c!:printf " %v = Lmember(nil, %v, %v);\n" r1 r2 r3)) (put (quote member) (quote c!:opcode_printer) (function c!:pmember)) (flag (quote (member)) (quote c!:uses_nil)) (de c!:pmemq (op r1 r2 r3 depth) (c!:printf " %v = Lmemq(nil, %v, %v);\n" r1 r2 r3)) (put (quote memq) (quote c!:opcode_printer) (function c!:pmemq)) (flag (quote (memq)) (quote c!:uses_nil)) (de c!:pget (op r1 r2 r3 depth) (c!:printf " %v = get(%v, %v);\n" r1 r2 r3 )) (put (quote get) (quote c!:opcode_printer) (function c!:pget)) (de c!:pqgetv (op r1 r2 r3 depth) (progn (c!:printf " %v = *(LispObject *)((char *)%v + (CELL-TAG_VECTOR) +" r1 r2) (c!:printf " (((intptr_t)%v-TAG_FIXNUM)/(16/CELL)));\n" r3))) (put (quote qgetv) (quote c!:opcode_printer) (function c!:pqgetv)) (de c!:pqputv (op r1 r2 r3 depth) (progn (c!:printf " *(LispObject *)((char *)%v + (CELL-TAG_VECTOR) +" r2) (c!:printf " (((intptr_t)%v-TAG_FIXNUM)/(16/CELL))) = %v;\n" r3 r1))) (put (quote qputv) (quote c!:opcode_printer) (function c!:pqputv)) (de c!:peq (op r1 r2 r3 depth) (c!:printf " %v = (%v == %v ? lisp_true : nil);\n" r1 r2 r3)) (put (quote eq) (quote c!:opcode_printer) (function c!:peq)) (flag (quote (eq)) (quote c!:uses_nil)) (de c!:pequal (op r1 r2 r3 depth) (c!:printf " %v = (equal(%v, %v) ? lisp_true : nil);\n" r1 r2 r3 r2 r3)) (put (quote equal) (quote c!:opcode_printer) (function c!:pequal)) (flag (quote (equal)) (quote c!:uses_nil)) (de c!:pfluidbind (op r1 r2 r3 depth) nil) (put (quote fluidbind) (quote c!:opcode_printer) (function c!:pfluidbind)) (de c!:pcall (op r1 r2 r3 depth) (prog (w boolfn) (cond ((setq w (get (car r3 ) (quote c!:direct_entrypoint))) (progn (c!:printf " %v = %s(" r1 (cdr w)) (cond (r2 (progn (c!:printf "%v" (car r2)) (prog (var1272) (setq var1272 ( cdr r2)) lab1271 (cond ((null var1272) (return nil))) (prog (a) (setq a (car var1272)) (c!:printf ", %v" a)) (setq var1272 (cdr var1272)) (go lab1271))))) (c!:printf ");\n"))) (t (cond ((setq w (get (car r3) (quote c!:direct_predicate))) (progn (setq boolfn t) (c!:printf " %v = (LispObject)%s(" r1 (cdr w)) (cond (r2 (progn (c!:printf "%v" (car r2)) (prog (var1274) (setq var1274 (cdr r2)) lab1273 (cond ((null var1274) ( return nil))) (prog (a) (setq a (car var1274)) (c!:printf ", %v" a)) (setq var1274 (cdr var1274)) (go lab1273))))) (c!:printf ");\n"))) (t (cond ((equal (car r3) c!:current_procedure) (progn (setq r2 (c!:fix_nargs r2 c!:current_args)) (c!:printf " %v = %s(env" r1 c!:current_c_name) (cond (( or (null r2) (geq (length r2) 3)) (c!:printf ", %s" (length r2)))) (prog ( var1276) (setq var1276 r2) lab1275 (cond ((null var1276) (return nil))) (prog (a) (setq a (car var1276)) (c!:printf ", %v" a)) (setq var1276 (cdr var1276) ) (go lab1275)) (c!:printf ");\n"))) (t (cond ((setq w (get (car r3) (quote c!:c_entrypoint))) (progn (c!:printf " %v = %s(nil" r1 w) (cond ((or (null r2) (geq (length r2) 3)) (c!:printf ", %s" (length r2)))) (prog (var1278) ( setq var1278 r2) lab1277 (cond ((null var1278) (return nil))) (prog (a) (setq a (car var1278)) (c!:printf ", %v" a)) (setq var1278 (cdr var1278)) (go lab1277)) (c!:printf ");\n"))) (t (prog (nargs) (setq nargs (length r2)) ( c!:printf " fn = elt(env, %s); %<// %c\n" (c!:find_literal (car r3)) (car r3)) (cond ((equal nargs 1) (c!:printf " %v = (*qfn1(fn))(qenv(fn)" r1)) ( t (cond ((equal nargs 2) (c!:printf " %v = (*qfn2(fn))(qenv(fn)" r1)) (t ( c!:printf " %v = (*qfnn(fn))(qenv(fn), %s" r1 nargs))))) (prog (var1280) ( setq var1280 r2) lab1279 (cond ((null var1280) (return nil))) (prog (a) (setq a (car var1280)) (c!:printf ", %v" a)) (setq var1280 (cdr var1280)) (go lab1279)) (c!:printf ");\n")))))))))) (cond ((not (flagp (car r3) (quote c!:no_errors))) (progn (cond ((and (null (cadr r3)) (equal depth 0)) ( c!:printf " errexit();\n")) (t (progn ( c!:printf " if (exception_pending()) ") (c!:pgoto (c!:find_error_label nil (cadr r3) depth) depth))))))) (cond (boolfn (c!:printf " %v = %v ? lisp_true : nil;\n" r1 r1))))) (de c!:fix_nargs (r2 act) (cond ((null act) nil) (t (cond ((null r2) (cons nil (c!:fix_nargs nil (cdr act)))) (t (cons (car r2) (c!:fix_nargs (cdr r2) ( cdr act)))))))) (put (quote call) (quote c!:opcode_printer) (function c!:pcall)) (de c!:pgoto (lab depth) (prog nil (cond ((atom lab) (return (c!:printf "goto %s;\n" lab)))) (setq lab (get (car lab) (quote c!:chosen))) (cond (( zerop depth) (c!:printf "return onevalue(%v);\n" lab)) (t (cond ((flagp lab ( quote c!:live_across_call)) (c!:printf "{ LispObject res = %v; popv(%s); return onevalue(res); }\n" lab depth)) (t ( c!:printf "{ popv(%s); return onevalue(%v); }\n" depth lab))))))) (de c!:pifnull (s depth) (c!:printf "%v == nil" (car s))) (put (quote ifnull) (quote c!:exit_helper) (function c!:pifnull)) (de c!:pifatom (s depth) (c!:printf "!consp(%v)" (car s))) (put (quote ifatom) (quote c!:exit_helper) (function c!:pifatom)) (de c!:pifsymbol (s depth) (c!:printf "symbolp(%v)" (car s))) (put (quote ifsymbol) (quote c!:exit_helper) (function c!:pifsymbol)) (de c!:pifnumber (s depth) (c!:printf "is_number(%v)" (car s))) (put (quote ifnumber) (quote c!:exit_helper) (function c!:pifnumber)) (de c!:pifizerop (s depth) (c!:printf "(%v) == 1" (car s))) (put (quote ifizerop) (quote c!:exit_helper) (function c!:pifizerop)) (de c!:pifeq (s depth) (c!:printf "%v == %v" (car s) (cadr s))) (put (quote ifeq) (quote c!:exit_helper) (function c!:pifeq)) (de c!:pifequal (s depth) (c!:printf "equal(%v, %v)" (car s) (cadr s) (car s) (cadr s))) (put (quote ifequal) (quote c!:exit_helper) (function c!:pifequal)) (de c!:pifilessp (s depth) (c!:printf "((intptr_t)(%v)) < ((intptr_t)(%v))" ( car s) (cadr s))) (put (quote ifilessp) (quote c!:exit_helper) (function c!:pifilessp)) (de c!:pifigreaterp (s depth) (c!:printf "((intptr_t)(%v)) > ((intptr_t)(%v))" (car s) (cadr s))) (put (quote ifigreaterp) (quote c!:exit_helper) (function c!:pifigreaterp)) (de c!:display_flowgraph (s depth dropping_through) (cond ((not (atom s)) ( progn (c!:printf " ") (c!:pgoto s depth))) (t (cond ((not (flagp s (quote c!:visited))) (prog (why where_to) (flag (list s) (quote c!:visited)) (cond ( (or (not dropping_through) (not (equal (get s (quote c!:count)) 1))) ( c!:printf "\n%s:\n" s))) (prog (var1282) (setq var1282 (reverse (get s (quote c!:contents)))) lab1281 (cond ((null var1282) (return nil))) (prog (k) (setq k (car var1282)) (c!:print_opcode k depth)) (setq var1282 (cdr var1282)) (go lab1281)) (setq why (get s (quote c!:why))) (setq where_to (get s (quote c!:where_to))) (cond ((and (equal why (quote goto)) (or (not (atom (car where_to))) (and (not (flagp (car where_to) (quote c!:visited))) (equal (get (car where_to) (quote c!:count)) 1)))) (c!:display_flowgraph (car where_to) depth t)) (t (c!:print_exit_condition why where_to depth))))))))) (fluid (quote (c!:startpoint))) (de c!:branch_chain (s count) (prog (contents why where_to n) (cond ((not ( atom s)) (return s)) (t (cond ((flagp s (quote c!:visited)) (progn (setq n ( get s (quote c!:count))) (cond ((null n) (setq n 1)) (t (setq n (plus n 1)))) (put s (quote c!:count) n) (return s)))))) (flag (list s) (quote c!:visited) ) (setq contents (get s (quote c!:contents))) (setq why (get s (quote c!:why) )) (setq where_to (prog (var1284 var1285) (setq var1284 (get s (quote c!:where_to))) lab1283 (cond ((null var1284) (return (reversip var1285)))) ( prog (z) (setq z (car var1284)) (setq var1285 (cons (c!:branch_chain z count) var1285))) (setq var1284 (cdr var1284)) (go lab1283))) (prog nil lab1286 ( cond ((null (and contents (eqcar (car contents) (quote movr)) (equal why ( quote goto)) (not (atom (car where_to))) (equal (caar where_to) (cadr (car contents))))) (return nil))) (progn (setq where_to (list (list (cadddr (car contents))))) (setq contents (cdr contents))) (go lab1286)) (put s (quote c!:contents) contents) (put s (quote c!:where_to) where_to) (cond ((and (null contents) (equal why (quote goto))) (progn (remflag (list s) (quote c!:visited)) (return (car where_to))))) (cond (count (progn (setq n (get s ( quote c!:count))) (cond ((null n) (setq n 1)) (t (setq n (plus n 1)))) (put s (quote c!:count) n)))) (return s))) (de c!:one_operand (op) (progn (flag (list op) (quote c!:set_r1)) (flag (list op) (quote c!:read_r3)) (put op (quote c!:code) (function c!:builtin_one)))) (de c!:two_operands (op) (progn (flag (list op) (quote c!:set_r1)) (flag ( list op) (quote c!:read_r2)) (flag (list op) (quote c!:read_r3)) (put op ( quote c!:code) (function c!:builtin_two)))) (prog (var1288) (setq var1288 (quote (car cdr qcar qcdr null not atom numberp fixp iminusp iminus iadd1 isub1 modular!-minus))) lab1287 (cond ((null var1288) (return nil))) (prog (n) (setq n (car var1288)) (c!:one_operand n)) (setq var1288 (cdr var1288)) (go lab1287)) (prog (var1290) (setq var1290 (quote (eq equal atsoc memq iplus2 idifference assoc member itimes2 ilessp igreaterp qgetv get modular!-plus modular!-difference))) lab1289 (cond ((null var1290) (return nil))) (prog (n) (setq n (car var1290)) (c!:two_operands n)) (setq var1290 (cdr var1290)) (go lab1289)) (flag (quote (movr movk movk1 ldrglob call reloadenv fastget fastflag)) ( quote c!:set_r1)) (flag (quote (strglob qputv)) (quote c!:read_r1)) (flag (quote (qputv fastget fastflag)) (quote c!:read_r2)) (flag (quote (movr qputv)) (quote c!:read_r3)) (flag (quote (ldrglob strglob nilglob movk call)) (quote c!:read_env)) (fluid (quote (fn_used nil_used nilbase_used))) (de c!:live_variable_analysis (c!:all_blocks) (prog (changed z) (prog nil lab1297 (progn (setq changed nil) (prog (var1296) (setq var1296 c!:all_blocks ) lab1295 (cond ((null var1296) (return nil))) (prog (b) (setq b (car var1296 )) (prog (w live) (prog (var1292) (setq var1292 (get b (quote c!:where_to))) lab1291 (cond ((null var1292) (return nil))) (prog (x) (setq x (car var1292)) (cond ((atom x) (setq live (union live (get x (quote c!:live))))) (t (setq live (union live x))))) (setq var1292 (cdr var1292)) (go lab1291)) (setq w ( get b (quote c!:why))) (cond ((not (atom w)) (progn (cond ((or (eqcar w ( quote ifnull)) (eqcar w (quote ifequal))) (setq nil_used t))) (setq live ( union live (cdr w))) (cond ((and (eqcar (car w) (quote call)) (or (flagp ( cadar w) (quote c!:direct_predicate)) (and (flagp (cadar w) (quote c!:c_entrypoint)) (not (flagp (cadar w) (quote c!:direct_entrypoint)))))) ( setq nil_used t))) (cond ((and (eqcar (car w) (quote call)) (not (equal ( cadar w) c!:current_procedure)) (not (get (cadar w) (quote c!:direct_entrypoint))) (not (get (cadar w) (quote c!:c_entrypoint)))) (progn (setq fn_used t) (setq live (union (quote (env)) live)))))))) (prog (var1294 ) (setq var1294 (get b (quote c!:contents))) lab1293 (cond ((null var1294) ( return nil))) (prog (s) (setq s (car var1294)) (prog (op r1 r2 r3) (setq op ( car s)) (setq r1 (cadr s)) (setq r2 (caddr s)) (setq r3 (cadddr s)) (cond (( equal op (quote movk1)) (progn (cond ((equal r3 nil) (setq nil_used t)) (t ( cond ((equal r3 (quote t)) (setq nilbase_used t))))))) (t (cond ((and (atom op) (flagp op (quote c!:uses_nil))) (setq nil_used t))))) (cond ((flagp op ( quote c!:set_r1)) (cond ((memq r1 live) (setq live (delete r1 live))) (t ( cond ((equal op (quote call)) nil) (t (setq op (quote nop)))))))) (cond (( flagp op (quote c!:read_r1)) (setq live (union live (list r1))))) (cond (( flagp op (quote c!:read_r2)) (setq live (union live (list r2))))) (cond (( flagp op (quote c!:read_r3)) (setq live (union live (list r3))))) (cond (( equal op (quote call)) (progn (cond ((or (not (flagp (car r3) (quote c!:no_errors))) (flagp (car r3) (quote c!:c_entrypoint)) (get (car r3) (quote c!:direct_predicate))) (setq nil_used t))) (setq does_call t) (cond ((and ( not (eqcar r3 c!:current_procedure)) (not (get (car r3) (quote c!:direct_entrypoint))) (not (get (car r3) (quote c!:c_entrypoint)))) (setq fn_used t))) (cond ((not (flagp (car r3) (quote c!:no_errors))) (flag live ( quote c!:live_across_call)))) (setq live (union live r2))))) (cond ((flagp op (quote c!:read_env)) (setq live (union live (quote (env)))))))) (setq var1294 (cdr var1294)) (go lab1293)) (setq live (sort live (function orderp)) ) (cond ((not (equal live (get b (quote c!:live)))) (progn (put b (quote c!:live) live) (setq changed t)))))) (setq var1296 (cdr var1296)) (go lab1295 ))) (cond ((null (not changed)) (go lab1297)))) (setq z c!:registers) (setq c!:registers (setq c!:stacklocs nil)) (prog (var1299) (setq var1299 z) lab1298 (cond ((null var1299) (return nil))) (prog (r) (setq r (car var1299)) (cond ((flagp r (quote c!:live_across_call)) (setq c!:stacklocs (cons r c!:stacklocs))) (t (setq c!:registers (cons r c!:registers))))) (setq var1299 (cdr var1299)) (go lab1298)))) (de c!:insert1 (a b) (cond ((memq a b) b) (t (cons a b)))) (de c!:clash (a b) (cond ((equal (flagp a (quote c!:live_across_call)) (flagp b (quote c!:live_across_call))) (progn (put a (quote c!:clash) (c!:insert1 b (get a (quote c!:clash)))) (put b (quote c!:clash) (c!:insert1 a (get b ( quote c!:clash)))))))) (de c!:build_clash_matrix (c!:all_blocks) (prog nil (prog (var1307) (setq var1307 c!:all_blocks) lab1306 (cond ((null var1307) (return nil))) (prog (b) (setq b (car var1307)) (prog (live w) (prog (var1301) (setq var1301 (get b ( quote c!:where_to))) lab1300 (cond ((null var1301) (return nil))) (prog (x) ( setq x (car var1301)) (cond ((atom x) (setq live (union live (get x (quote c!:live))))) (t (setq live (union live x))))) (setq var1301 (cdr var1301)) ( go lab1300)) (setq w (get b (quote c!:why))) (cond ((not (atom w)) (progn ( setq live (union live (cdr w))) (cond ((and (eqcar (car w) (quote call)) (not (get (cadar w) (quote c!:direct_entrypoint))) (not (get (cadar w) (quote c!:c_entrypoint)))) (setq live (union (quote (env)) live))))))) (prog ( var1305) (setq var1305 (get b (quote c!:contents))) lab1304 (cond ((null var1305) (return nil))) (prog (s) (setq s (car var1305)) (prog (op r1 r2 r3) (setq op (car s)) (setq r1 (cadr s)) (setq r2 (caddr s)) (setq r3 (cadddr s)) (cond ((flagp op (quote c!:set_r1)) (cond ((memq r1 live) (progn (setq live (delete r1 live)) (cond ((equal op (quote reloadenv)) (setq reloadenv t))) ( prog (var1303) (setq var1303 live) lab1302 (cond ((null var1303) (return nil) )) (prog (v) (setq v (car var1303)) (c!:clash r1 v)) (setq var1303 (cdr var1303)) (go lab1302)))) (t (cond ((equal op (quote call)) nil) (t (progn ( setq op (quote nop)) (rplacd s (cons (car s) (cdr s))) (rplaca s op)))))))) ( cond ((flagp op (quote c!:read_r1)) (setq live (union live (list r1))))) ( cond ((flagp op (quote c!:read_r2)) (setq live (union live (list r2))))) ( cond ((flagp op (quote c!:read_r3)) (setq live (union live (list r3))))) ( cond ((equal op (quote call)) (setq live (union live r2)))) (cond ((flagp op (quote c!:read_env)) (setq live (union live (quote (env)))))))) (setq var1305 (cdr var1305)) (go lab1304)))) (setq var1307 (cdr var1307)) (go lab1306)) ( return nil))) (de c!:allocate_registers (rl) (prog (schedule neighbours allocation) (setq neighbours 0) (prog nil lab1311 (cond ((null rl) (return nil))) (prog (w x) ( setq w rl) (prog nil lab1308 (cond ((null (and w (greaterp (length (setq x ( get (car w) (quote c!:clash)))) neighbours))) (return nil))) (setq w (cdr w)) (go lab1308)) (cond (w (progn (setq schedule (cons (car w) schedule)) (setq rl (deleq (car w) rl)) (prog (var1310) (setq var1310 x) lab1309 (cond ((null var1310) (return nil))) (prog (r) (setq r (car var1310)) (put r (quote c!:clash) (deleq (car w) (get r (quote c!:clash))))) (setq var1310 (cdr var1310)) (go lab1309)))) (t (setq neighbours (plus neighbours 1))))) (go lab1311)) (prog (var1315) (setq var1315 schedule) lab1314 (cond ((null var1315) (return nil))) (prog (r) (setq r (car var1315)) (prog (poss) (setq poss allocation) (prog (var1313) (setq var1313 (get r (quote c!:clash))) lab1312 (cond ((null var1313) (return nil))) (prog (x) (setq x (car var1313)) (setq poss (deleq (get x (quote c!:chosen)) poss))) (setq var1313 (cdr var1313)) (go lab1312)) (cond ((null poss) (progn (setq poss (c!:my_gensym)) (setq allocation (append allocation (list poss))))) (t (setq poss (car poss)) )) (put r (quote c!:chosen) poss))) (setq var1315 (cdr var1315)) (go lab1314) ) (return allocation))) (de c!:remove_nops (c!:all_blocks) (prog (var1325) (setq var1325 c!:all_blocks) lab1324 (cond ((null var1325) (return nil))) (prog (b) (setq b (car var1325)) (prog (r) (prog (var1320) (setq var1320 (get b (quote c!:contents))) lab1319 (cond ((null var1320) (return nil))) (prog (s) (setq s (car var1320)) (cond ((not (eqcar s (quote nop))) (prog (op r1 r2 r3) (setq op (car s)) (setq r1 (cadr s)) (setq r2 (caddr s)) (setq r3 (cadddr s)) (cond ((or (flagp op (quote c!:set_r1)) (flagp op (quote c!:read_r1))) (setq r1 ( get r1 (quote c!:chosen))))) (cond ((flagp op (quote c!:read_r2)) (setq r2 ( get r2 (quote c!:chosen))))) (cond ((flagp op (quote c!:read_r3)) (setq r3 ( get r3 (quote c!:chosen))))) (cond ((equal op (quote call)) (setq r2 (prog ( var1317 var1318) (setq var1317 r2) lab1316 (cond ((null var1317) (return ( reversip var1318)))) (prog (v) (setq v (car var1317)) (setq var1318 (cons ( get v (quote c!:chosen)) var1318))) (setq var1317 (cdr var1317)) (go lab1316) )))) (cond ((not (and (equal op (quote movr)) (equal r1 r3))) (setq r (cons ( list op r1 r2 r3) r)))))))) (setq var1320 (cdr var1320)) (go lab1319)) (put b (quote c!:contents) (reversip r)) (setq r (get b (quote c!:why))) (cond (( not (atom r)) (put b (quote c!:why) (cons (car r) (prog (var1322 var1323) ( setq var1322 (cdr r)) lab1321 (cond ((null var1322) (return (reversip var1323 )))) (prog (v) (setq v (car var1322)) (setq var1323 (cons (get v (quote c!:chosen)) var1323))) (setq var1322 (cdr var1322)) (go lab1321)))))))) (setq var1325 (cdr var1325)) (go lab1324))) (fluid (quote (c!:error_labels))) (de c!:find_error_label (why env depth) (prog (w z) (setq z (list why env depth)) (setq w (assoc!*!* z c!:error_labels)) (cond ((null w) (progn (setq w (cons z (c!:my_gensym))) (setq c!:error_labels (cons w c!:error_labels))))) (return (cdr w)))) (de c!:assign (u v c) (cond ((flagp u (quote fluid)) (cons (list (quote strglob) v u (c!:find_literal u)) c)) (t (cons (list (quote movr) u nil v) c) ))) (de c!:insert_tailcall (b) (prog (why dest contents fcall res w) (setq why ( get b (quote c!:why))) (setq dest (get b (quote c!:where_to))) (setq contents (get b (quote c!:contents))) (prog nil lab1326 (cond ((null (and contents ( not (eqcar (car contents) (quote call))))) (return nil))) (progn (setq w ( cons (car contents) w)) (setq contents (cdr contents))) (go lab1326)) (cond ( (null contents) (return nil))) (setq fcall (car contents)) (setq contents ( cdr contents)) (setq res (cadr fcall)) (prog nil lab1327 (cond ((null w) ( return nil))) (progn (cond ((eqcar (car w) (quote reloadenv)) (setq w (cdr w) )) (t (cond ((and (eqcar (car w) (quote movr)) (equal (cadddr (car w)) res)) (progn (setq res (cadr (car w))) (setq w (cdr w)))) (t (setq res (setq w nil) )))))) (go lab1327)) (cond ((null res) (return nil))) (cond ((c!:does_return res why dest) (cond ((equal (car (cadddr fcall)) c!:current_procedure) (progn (prog (var1329) (setq var1329 (pair c!:current_args (caddr fcall))) lab1328 (cond ((null var1329) (return nil))) (prog (p) (setq p (car var1329)) (setq contents (c!:assign (car p) (cdr p) contents))) (setq var1329 (cdr var1329)) (go lab1328)) (put b (quote c!:contents) contents) (put b (quote c!:why) ( quote goto)) (put b (quote c!:where_to) (list restart_label)))) (t (progn ( setq nil_used t) (put b (quote c!:contents) contents) (put b (quote c!:why) ( cons (list (quote call) (car (cadddr fcall))) (caddr fcall))) (put b (quote c!:where_to) nil)))))))) (de c!:does_return (res why where_to) (cond ((not (equal why (quote goto))) nil) (t (cond ((not (atom (car where_to))) (equal res (caar where_to))) (t ( prog (contents) (setq where_to (car where_to)) (setq contents (reverse (get where_to (quote c!:contents)))) (setq why (get where_to (quote c!:why))) ( setq where_to (get where_to (quote c!:where_to))) (prog nil lab1330 (cond (( null contents) (return nil))) (cond ((eqcar (car contents) (quote reloadenv)) (setq contents (cdr contents))) (t (cond ((and (eqcar (car contents) (quote movr)) (equal (cadddr (car contents)) res)) (progn (setq res (cadr (car contents))) (setq contents (cdr contents)))) (t (setq res (setq contents nil) ))))) (go lab1330)) (cond ((null res) (return nil)) (t (return ( c!:does_return res why where_to)))))))))) (de c!:pushpop (op v) (prog (n w) (cond ((null v) (return nil))) (setq n ( length v)) (prog nil lab1332 (cond ((null (greaterp n 0)) (return nil))) ( progn (setq w n) (cond ((greaterp w 6) (setq w 6))) (setq n (difference n w)) (cond ((equal w 1) (c!:printf " %s(%s);\n" op (car v))) (t (progn ( c!:printf " %s%d(%s" op w (car v)) (setq v (cdr v)) (prog (i) (setq i 2) lab1331 (cond ((minusp (times 1 (difference w i))) (return nil))) (progn ( c!:printf ",%s" (car v)) (setq v (cdr v))) (setq i (plus i 1)) (go lab1331)) (c!:printf ");\n"))))) (go lab1332)))) (de c!:optimise_flowgraph (c!:startpoint c!:all_blocks env argch args varargs ) (prog (w n locs stacks c!:error_labels fn_used nil_used nilbase_used) (prog (var1334) (setq var1334 c!:all_blocks) lab1333 (cond ((null var1334) (return nil))) (prog (b) (setq b (car var1334)) (c!:insert_tailcall b)) (setq var1334 (cdr var1334)) (go lab1333)) (setq c!:startpoint (c!:branch_chain c!:startpoint nil)) (remflag c!:all_blocks (quote c!:visited)) ( c!:live_variable_analysis c!:all_blocks) (c!:build_clash_matrix c!:all_blocks ) (cond ((and c!:error_labels env) (setq reloadenv t))) (prog (var1338) (setq var1338 env) lab1337 (cond ((null var1338) (return nil))) (prog (u) (setq u (car var1338)) (prog (var1336) (setq var1336 env) lab1335 (cond ((null var1336) (return nil))) (prog (v) (setq v (car var1336)) (c!:clash (cdr u) ( cdr v))) (setq var1336 (cdr var1336)) (go lab1335))) (setq var1338 (cdr var1338)) (go lab1337)) (setq locs (c!:allocate_registers c!:registers)) ( setq stacks (c!:allocate_registers c!:stacklocs)) (flag stacks (quote c!:live_across_call)) (c!:remove_nops c!:all_blocks) (setq c!:startpoint ( c!:branch_chain c!:startpoint nil)) (remflag c!:all_blocks (quote c!:visited) ) (setq c!:startpoint (c!:branch_chain c!:startpoint t)) (remflag c!:all_blocks (quote c!:visited)) (cond (does_call (setq nil_used t))) (cond (locs (progn (c!:printf " LispObject %s" (car locs)) (prog (var1340) (setq var1340 (cdr locs)) lab1339 (cond ((null var1340) (return nil))) (prog (v) (setq v (car var1340)) (c!:printf ", %s" v)) (setq var1340 (cdr var1340)) (go lab1339)) (c!:printf ";\n")))) (cond (fn_used (c!:printf " LispObject fn;\n"))) (cond ((and varargs args) (progn (setq w " ") (c!:printf " LispObject") (prog (var1342 ) (setq var1342 args) lab1341 (cond ((null var1342) (return nil))) (prog (v) (setq v (car var1342)) (progn (c!:printf "%s%s" w v) (setq w ", "))) (setq var1342 (cdr var1342)) (go lab1341)) (c!:printf ";\n va_list aa;\n") ( c!:printf " va_start(aa, nargs);\n")))) (cond ((or (equal (car argch) 0) ( geq (car argch) 3)) (c!:printf " argcheck(nargs, %s, \q%s\q);\n" (car argch) (cdr argch)))) (cond ((and varargs args) (progn (c!:printf " va_start(aa, nargs);\n") (prog (var1344) (setq var1344 (reverse args)) lab1343 (cond ((null var1344) (return nil))) (prog (v) (setq v (car var1344)) (c!:printf " %s = va_arg(aa, LispObject);\n" v)) (setq var1344 (cdr var1344)) (go lab1343)) (c!:printf " va_end(aa);\n")))) (c!:printf "#ifdef DEBUG_VALIDATE\n") (c!:printf " if (check_env(env)) return aerror(\qenv for %s\q);\n" (cdr argch)) ( c!:printf "#endif\n") (c!:printf "#ifdef CHECK_STACK\n") (c!:printf " if_check_stack;\n") (c!:printf "#endif\n") (cond (does_call (progn ( c!:printf " if (stack >= stackLimit)\n") (c!:printf " {\n") (c!:pushpop (quote push) args) (c!:printf " env = reclaim(env, \qstack\q, GC_STACK, 0);\n") (c!:pushpop (quote pop) (reverse args)) (c!:printf " if (exception_pending()) return nil;\n") (c!:printf " }\n")))) ( cond (reloadenv (c!:printf " push(env);\n"))) (setq n 0) (cond (stacks ( progn (c!:printf "%<// space for vars preserved across procedure calls\n") ( prog (var1346) (setq var1346 stacks) lab1345 (cond ((null var1346) (return nil))) (prog (v) (setq v (car var1346)) (progn (put v (quote c!:location) n) (setq n (plus n 1)))) (setq var1346 (cdr var1346)) (go lab1345)) (setq w n) ( prog nil lab1347 (cond ((null (geq w 5)) (return nil))) (progn (c!:printf " push5(nil, nil, nil, nil, nil);\n") (setq w (difference w 5))) (go lab1347)) (cond ((neq w 0) (progn (cond ((equal w 1) (c!:printf " push(nil);\n")) (t (progn (c!:printf " push%s(nil" w) (prog (i) (setq i 2) lab1348 (cond ((minusp (times 1 (difference w i))) (return nil))) ( c!:printf ", nil") (setq i (plus i 1)) (go lab1348)) (c!:printf ");\n"))))))) ))) (cond (reloadenv (progn (setq reloadenv n) (setq n (plus n 1))))) (cond ( env (c!:printf "%<// copy arguments values to proper place\n"))) (prog ( var1350) (setq var1350 env) lab1349 (cond ((null var1350) (return nil))) ( prog (v) (setq v (car var1350)) (cond ((flagp (cdr v) (quote c!:live_across_call)) (c!:printf " stack[%s] = %s;\n" (minus (get (get ( cdr v) (quote c!:chosen)) (quote c!:location))) (cdr v))) (t (c!:printf " %s = %s;\n" (get (cdr v) (quote c!:chosen)) (cdr v))))) (setq var1350 ( cdr var1350)) (go lab1349)) (c!:printf "%<// end of prologue\n") ( c!:display_flowgraph c!:startpoint n t) (cond (c!:error_labels (progn ( c!:printf "%<// error exit handlers\n") (prog (var1352) (setq var1352 c!:error_labels) lab1351 (cond ((null var1352) (return nil))) (prog (x) (setq x (car var1352)) (progn (c!:printf "%s:\n" (cdr x)) (c!:print_error_return ( caar x) (cadar x) (caddar x)))) (setq var1352 (cdr var1352)) (go lab1351))))) (remflag c!:all_blocks (quote c!:visited)))) (de c!:print_error_return (why env depth) (prog nil (cond ((and reloadenv env ) (c!:printf " env = stack[%s];\n" (minus reloadenv)))) (cond ((null why) (progn (prog (var1354) (setq var1354 env) lab1353 (cond ((null var1354) ( return nil))) (prog (v) (setq v (car var1354)) (c!:printf " qvalue(elt(env, %s)) = %v; %<// %c\n" (c!:find_literal (car v)) (get ( cdr v) (quote c!:chosen)) (car v))) (setq var1354 (cdr var1354)) (go lab1353) ) (cond ((neq depth 0) (c!:printf " popv(%s);\n" depth))) (c!:printf " return nil;\n"))) (t (cond ((flagp (cadr why) (quote c!:live_across_call )) (progn (c!:printf " { LispObject res = %v;\n" (cadr why)) (prog ( var1356) (setq var1356 env) lab1355 (cond ((null var1356) (return nil))) ( prog (v) (setq v (car var1356)) (c!:printf " qvalue(elt(env, %s)) = %v;\n" (c!:find_literal (car v)) (get (cdr v) (quote c!:chosen)))) (setq var1356 (cdr var1356)) (go lab1355)) (cond ((neq depth 0) (c!:printf " popv(%s);\n" depth))) (c!:printf " return error(1, %s, res); }\n" (cond ((eqcar why (quote car)) "err_bad_car") (t (cond ((eqcar why (quote cdr)) "err_bad_cdr") (t (error 0 ( list why "unknown_error"))))))))) (t (progn (prog (var1358) (setq var1358 env ) lab1357 (cond ((null var1358) (return nil))) (prog (v) (setq v (car var1358 )) (c!:printf " qvalue(elt(env, %s)) = %v;\n" (c!:find_literal (car v)) ( get (cdr v) (quote c!:chosen)))) (setq var1358 (cdr var1358)) (go lab1357)) ( cond ((neq depth 0) (c!:printf " popv(%s);\n" depth))) (c!:printf " return error(1, %s, %v);\n" (cond ((eqcar why (quote car)) "err_bad_car" ) (t (cond ((eqcar why (quote cdr)) "err_bad_cdr") (t (error 0 (list why "unknown_error")))))) (cadr why))))))))) (de c!:cand (u env) (prog (w r) (setq w (reverse (cdr u))) (cond ((null w) ( return (c!:cval nil env)))) (setq r (list (list (quote t) (car w)))) (setq w (cdr w)) (prog (var1360) (setq var1360 w) lab1359 (cond ((null var1360) ( return nil))) (prog (z) (setq z (car var1360)) (setq r (cons (list (list ( quote null) z) nil) r))) (setq var1360 (cdr var1360)) (go lab1359)) (setq r ( cons (quote cond) r)) (return (c!:cval r env)))) (put (quote and) (quote c!:code) (function c!:cand)) (de c!:ccatch (u env) (error 0 "catch")) (put (quote catch) (quote c!:code) (function c!:ccatch)) (de c!:ccompile_let (u env) (error 0 "compiler-let")) (put (quote compiler!-let) (quote c!:code) (function c!:ccompiler_let)) (de c!:ccond (u env) (prog (v join) (setq v (c!:newreg)) (setq join ( c!:my_gensym)) (prog (var1362) (setq var1362 (cdr u)) lab1361 (cond ((null var1362) (return nil))) (prog (c) (setq c (car var1362)) (prog (l1 l2) (setq l1 (c!:my_gensym)) (setq l2 (c!:my_gensym)) (cond ((atom (cdr c)) (progn ( c!:outop (quote movr) v nil (c!:cval (car c) env)) (c!:endblock (list (quote ifnull) v) (list l2 join)))) (t (progn (c!:cjumpif (car c) env l1 l2) ( c!:startblock l1) (c!:outop (quote movr) v nil (c!:cval (cons (quote progn) ( cdr c)) env)) (c!:endblock (quote goto) (list join))))) (c!:startblock l2))) (setq var1362 (cdr var1362)) (go lab1361)) (c!:outop (quote movk1) v nil nil) (c!:endblock (quote goto) (list join)) (c!:startblock join) (return v))) (put (quote cond) (quote c!:code) (function c!:ccond)) (de c!:valid_cond (x) (cond ((null x) t) (t (cond ((not (c!:valid_list (car x ))) nil) (t (c!:valid_cond (cdr x))))))) (put (quote cond) (quote c!:valid) (function c!:valid_cond)) (de c!:cdeclare (u env) (error 0 "declare")) (put (quote declare) (quote c!:code) (function c!:cdeclare)) (de c!:cde (u env) (error 0 "de")) (put (quote de) (quote c!:code) (function c!:cde)) (de c!:cdefun (u env) (error 0 "defun")) (put (quote !~defun) (quote c!:code) (function c!:cdefun)) (de c!:ceval_when (u env) (error 0 "eval-when")) (put (quote eval!-when) (quote c!:code) (function c!:ceval_when)) (de c!:cflet (u env) (error 0 "flet")) (put (quote flet) (quote c!:code) (function c!:cflet)) (de c!:cfunction (u env) (prog (v) (setq u (cadr u)) (cond ((not (atom u)) ( progn (cond ((not (eqcar u (quote lambda))) (error 0 (list "lambda expression needed" u)))) (setq v (hashtagged!-name (quote lambda) u)) (setq pending_functions (cons (cons (quote de) (cons v (cdr u))) pending_functions)) (setq u v)))) (setq v (c!:newreg)) (c!:outop (quote movk) v u (c!:find_literal u)) (return v))) (de c!:valid_function (x) (cond ((atom x) nil) (t (cond ((not (null (cdr x))) nil) (t (cond ((idp (car x)) t) (t (cond ((atom (car x)) nil) (t (cond ((not (eqcar (car x) (quote lambda))) nil) (t (cond ((atom (cdar x)) nil) (t ( c!:valid_fndef (cadar x) (cddar x))))))))))))))) (put (quote function) (quote c!:code) (function c!:cfunction)) (put (quote function) (quote c!:valid) (function c!:valid_function)) (de c!:cgo (u env) (prog (w w1) (setq w1 proglabs) (prog nil lab1363 (cond (( null (and (null w) w1)) (return nil))) (progn (setq w (assoc!*!* (cadr u) ( car w1))) (setq w1 (cdr w1))) (go lab1363)) (cond ((null w) (error 0 (list u "label not set")))) (c!:endblock (quote goto) (list (cadr w))) (return nil))) (put (quote go) (quote c!:code) (function c!:cgo)) (put (quote go) (quote c!:valid) (function c!:valid_quote)) (de c!:cif (u env) (prog (v join l1 l2 w) (setq v (c!:newreg)) (setq join ( c!:my_gensym)) (setq l1 (c!:my_gensym)) (setq l2 (c!:my_gensym)) (c!:cjumpif (car (setq u (cdr u))) env l1 l2) (c!:startblock l1) (c!:outop (quote movr) v nil (c!:cval (car (setq u (cdr u))) env)) (c!:endblock (quote goto) (list join)) (c!:startblock l2) (setq u (cdr u)) (cond (u (setq u (car u)))) ( c!:outop (quote movr) v nil (c!:cval u env)) (c!:endblock (quote goto) (list join)) (c!:startblock join) (return v))) (put (quote if) (quote c!:code) (function c!:cif)) (de c!:clabels (u env) (error 0 "labels")) (put (quote labels) (quote c!:code) (function c!:clabels)) (de c!:expand!-let (vl b) (cond ((null vl) (cons (quote progn) b)) (t (cond ( (null (cdr vl)) (c!:expand!-let!* vl b)) (t (prog (vars vals) (prog (var1365) (setq var1365 vl) lab1364 (cond ((null var1365) (return nil))) (prog (v) ( setq v (car var1365)) (cond ((atom v) (progn (setq vars (cons v vars)) (setq vals (cons nil vals)))) (t (cond ((atom (cdr v)) (progn (setq vars (cons (car v) vars)) (setq vals (cons nil vals)))) (t (progn (setq vars (cons (car v) vars)) (setq vals (cons (cadr v) vals)))))))) (setq var1365 (cdr var1365)) ( go lab1364)) (return (cons (cons (quote lambda) (cons vars b)) vals)))))))) (de c!:clet (x env) (c!:cval (c!:expand!-let (cadr x) (cddr x)) env)) (de c!:valid_let (x) (cond ((null x) t) (t (cond ((not (c!:valid_cond (car x) )) nil) (t (c!:valid_list (cdr x))))))) (put (quote !~let) (quote c!:code) (function c!:clet)) (put (quote !~let) (quote c!:valid) (function c!:valid_let)) (de c!:expand!-let!* (vl b) (cond ((null vl) (cons (quote progn) b)) (t (prog (var val) (setq var (car vl)) (cond ((not (atom var)) (progn (setq val (cdr var)) (setq var (car var)) (cond ((not (atom val)) (setq val (car val))))))) (setq b (list (list (quote return) (c!:expand!-let!* (cdr vl) b)))) (cond ( val (setq b (cons (list (quote setq) var val) b)))) (return (cons (quote prog ) (cons (list var) b))))))) (de c!:clet!* (x env) (c!:cval (c!:expand!-let!* (cadr x) (cddr x)) env)) (put (quote let!*) (quote c!:code) (function c!:clet!*)) (put (quote let!*) (quote c!:valid) (function c!:valid_let)) (de c!:clist (u env) (cond ((null (cdr u)) (c!:cval nil env)) (t (cond ((null (cddr u)) (c!:cval (cons (quote ncons) (cdr u)) env)) (t (cond ((eqcar (cadr u) (quote cons)) (c!:cval (list (quote acons) (cadr (cadr u)) (caddr (cadr u )) (cons (quote list) (cddr u))) env)) (t (cond ((null (cdddr u)) (c!:cval ( cons (quote list2) (cdr u)) env)) (t (cond ((null (cddddr u)) (c!:cval (cons (quote list3) (cdr u)) env)) (t (cond ((null (cdr (cddddr u))) (c!:cval (cons (quote list4) (cdr u)) env)) (t (c!:cval (list (quote list3!*) (cadr u) ( caddr u) (cadddr u) (cons (quote list) (cddddr u))) env)))))))))))))) (put (quote list) (quote c!:code) (function c!:clist)) (de c!:clist!* (u env) (prog (v) (setq u (reverse (cdr u))) (setq v (car u)) (prog (var1367) (setq var1367 (cdr u)) lab1366 (cond ((null var1367) (return nil))) (prog (a) (setq a (car var1367)) (setq v (list (quote cons) a v))) ( setq var1367 (cdr var1367)) (go lab1366)) (return (c!:cval v env)))) (put (quote list!*) (quote c!:code) (function c!:clist!*)) (de c!:ccons (u env) (prog (a1 a2) (setq a1 (s!:improve (cadr u))) (setq a2 ( s!:improve (caddr u))) (cond ((or (equal a2 nil) (equal a2 (quote (quote nil) )) (equal a2 (quote (list)))) (return (c!:cval (list (quote ncons) a1) env))) ) (cond ((eqcar a1 (quote cons)) (return (c!:cval (list (quote acons) (cadr a1) (caddr a1) a2) env)))) (cond ((eqcar a2 (quote cons)) (return (c!:cval ( list (quote list2!*) a1 (cadr a2) (caddr a2)) env)))) (cond ((eqcar a2 (quote list)) (return (c!:cval (list (quote cons) a1 (list (quote cons) (cadr a2) ( cons (quote list) (cddr a2)))) env)))) (return (c!:ccall (car u) (cdr u) env) ))) (put (quote cons) (quote c!:code) (function c!:ccons)) (de c!:cget (u env) (prog (a1 a2 w r r1) (setq a1 (s!:improve (cadr u))) ( setq a2 (s!:improve (caddr u))) (cond ((and (eqcar a2 (quote quote)) (idp ( setq w (cadr a2))) (setq w (symbol!-make!-fastget w nil))) (progn (setq r ( c!:newreg)) (c!:outop (quote fastget) r (c!:cval a1 env) (cons w (cadr a2))) (return r))) (t (return (c!:ccall (car u) (cdr u) env)))))) (put (quote get) (quote c!:code) (function c!:cget)) (de c!:cflag (u env) (prog (a1 a2 w r r1) (setq a1 (s!:improve (cadr u))) ( setq a2 (s!:improve (caddr u))) (cond ((and (eqcar a2 (quote quote)) (idp ( setq w (cadr a2))) (setq w (symbol!-make!-fastget w nil))) (progn (setq r ( c!:newreg)) (c!:outop (quote fastflag) r (c!:cval a1 env) (cons w (cadr a2))) (return r))) (t (return (c!:ccall (car u) (cdr u) env)))))) (put (quote flagp) (quote c!:code) (function c!:cflag)) (de c!:cgetv (u env) (cond ((not !*fastvector) (c!:ccall (car u) (cdr u) env) ) (t (c!:cval (cons (quote qgetv) (cdr u)) env)))) (put (quote getv) (quote c!:code) (function c!:cgetv)) (de c!:cputv (u env) (cond ((not !*fastvector) (c!:ccall (car u) (cdr u) env) ) (t (c!:cval (cons (quote qputv) (cdr u)) env)))) (put (quote putv) (quote c!:code) (function c!:cputv)) (de c!:cqputv (x env) (prog (rr) (setq rr (c!:pareval (cdr x) env)) (c!:outop (quote qputv) (caddr rr) (car rr) (cadr rr)) (return (caddr rr)))) (put (quote qputv) (quote c!:code) (function c!:cqputv)) (de c!:cmacrolet (u env) (error 0 "macrolet")) (put (quote macrolet) (quote c!:code) (function c!:cmacrolet)) (de c!:cmultiple_value_call (u env) (error 0 "multiple_value_call")) (put (quote multiple!-value!-call) (quote c!:code) (function c!:cmultiple_value_call)) (de c!:cmultiple_value_prog1 (u env) (error 0 "multiple_value_prog1")) (put (quote multiple!-value!-prog1) (quote c!:code) (function c!:cmultiple_value_prog1)) (de c!:cor (u env) (prog (next done v r) (setq v (c!:newreg)) (setq done ( c!:my_gensym)) (setq u (cdr u)) (prog nil lab1368 (cond ((null (cdr u)) ( return nil))) (progn (setq next (c!:my_gensym)) (c!:outop (quote movr) v nil (c!:cval (car u) env)) (setq u (cdr u)) (c!:endblock (list (quote ifnull) v) (list next done)) (c!:startblock next)) (go lab1368)) (c!:outop (quote movr) v nil (c!:cval (car u) env)) (c!:endblock (quote goto) (list done)) ( c!:startblock done) (return v))) (put (quote or) (quote c!:code) (function c!:cor)) (de c!:cprog (u env) (prog (w w1 bvl local_proglabs progret progexit fluids env1 body decs) (setq env1 (car env)) (setq bvl (cadr u)) (setq w ( s!:find_local_decs (cddr u) t)) (setq body (cdr w)) (setq localdecs (cons ( car w) localdecs)) (prog (var1370) (setq var1370 bvl) lab1369 (cond ((null var1370) (return nil))) (prog (v) (setq v (car var1370)) (progn (cond ((and ( not (globalp v)) (not (fluidp v)) (c!:local_fluidp v localdecs)) (progn ( make!-special v) (setq decs (cons v decs))))))) (setq var1370 (cdr var1370)) (go lab1369)) (prog (var1372) (setq var1372 bvl) lab1371 (cond ((null var1372 ) (return nil))) (prog (v) (setq v (car var1372)) (progn (cond ((globalp v) ( prog (oo) (setq oo (wrs nil)) (princ "+++++ ") (prin v) (princ " converted from GLOBAL to FLUID") (terpri) (wrs oo) (unglobal (list v)) ( fluid (list v))))) (cond ((fluidp v) (progn (setq fluids (cons (cons v ( c!:newreg)) fluids)) (flag (list (cdar fluids)) (quote c!:live_across_call)) (setq env1 (cons (cons (quote c!:dummy!:name) (cdar fluids)) env1)) (c!:outop (quote ldrglob) (cdar fluids) v (c!:find_literal v)) (c!:outop (quote nilglob) nil v (c!:find_literal v)))) (t (progn (setq env1 (cons (cons v ( c!:newreg)) env1)) (c!:outop (quote movk1) (cdar env1) nil nil)))))) (setq var1372 (cdr var1372)) (go lab1371)) (cond (fluids (c!:outop (quote fluidbind ) nil nil fluids))) (setq env (cons env1 (append fluids (cdr env)))) (setq u body) (setq progret (c!:newreg)) (setq progexit (c!:my_gensym)) (setq blockstack (cons (cons nil (cons progret progexit)) blockstack)) (prog ( var1374) (setq var1374 u) lab1373 (cond ((null var1374) (return nil))) (prog (a) (setq a (car var1374)) (cond ((atom a) (cond ((atsoc a local_proglabs) ( progn (cond ((not (null a)) (progn (setq w (wrs nil)) (princ "+++++ multiply defined label: ") (prin a) (terpri) (wrs w)))))) (t (setq local_proglabs (cons (list a (c!:my_gensym)) local_proglabs))))))) (setq var1374 (cdr var1374)) (go lab1373)) (setq proglabs (cons local_proglabs proglabs)) (prog (var1376) (setq var1376 u) lab1375 (cond ((null var1376) ( return nil))) (prog (a) (setq a (car var1376)) (cond ((atom a) (progn (setq w (cdr (assoc!*!* a local_proglabs))) (cond ((null (cdr w)) (progn (rplacd w t ) (c!:endblock (quote goto) (list (car w))) (c!:startblock (car w))))))) (t ( c!:cval a env)))) (setq var1376 (cdr var1376)) (go lab1375)) (c!:outop (quote movk1) progret nil nil) (c!:endblock (quote goto) (list progexit)) ( c!:startblock progexit) (prog (var1378) (setq var1378 fluids) lab1377 (cond ( (null var1378) (return nil))) (prog (v) (setq v (car var1378)) (c!:outop ( quote strglob) (cdr v) (car v) (c!:find_literal (car v)))) (setq var1378 (cdr var1378)) (go lab1377)) (setq blockstack (cdr blockstack)) (setq proglabs ( cdr proglabs)) (unfluid decs) (setq localdecs (cdr localdecs)) (return progret))) (put (quote prog) (quote c!:code) (function c!:cprog)) (de c!:valid_prog (x) (c!:valid_list (cdr x))) (put (quote prog) (quote c!:valid) (function c!:valid_prog)) (de c!:cprog!* (u env) (error 0 "prog*")) (put (quote prog!*) (quote c!:code) (function c!:cprog!*)) (de c!:cprog1 (u env) (prog (g) (setq g (c!:my_gensym)) (setq g (list (quote prog) (list g) (list (quote setq) g (cadr u)) (cons (quote progn) (cddr u)) ( list (quote return) g))) (return (c!:cval g env)))) (put (quote prog1) (quote c!:code) (function c!:cprog1)) (de c!:cprog2 (u env) (prog (g) (setq u (cdr u)) (setq g (c!:my_gensym)) ( setq g (list (quote prog) (list g) (list (quote setq) g (cadr u)) (cons ( quote progn) (cddr u)) (list (quote return) g))) (setq g (list (quote progn) (car u) g)) (return (c!:cval g env)))) (put (quote prog2) (quote c!:code) (function c!:cprog2)) (de c!:cprogn (u env) (prog (r) (setq u (cdr u)) (cond ((equal u nil) (setq u (quote (nil))))) (prog (var1380) (setq var1380 u) lab1379 (cond ((null var1380) (return nil))) (prog (s) (setq s (car var1380)) (setq r (c!:cval s env))) (setq var1380 (cdr var1380)) (go lab1379)) (return r))) (put (quote progn) (quote c!:code) (function c!:cprogn)) (de c!:cprogv (u env) (error 0 "progv")) (put (quote progv) (quote c!:code) (function c!:cprogv)) (de c!:cquote (u env) (prog (v) (setq u (cadr u)) (setq v (c!:newreg)) (cond ((or (null u) (equal u (quote t)) (c!:small_number u)) (c!:outop (quote movk1 ) v nil u)) (t (c!:outop (quote movk) v u (c!:find_literal u)))) (return v))) (de c!:valid_quote (x) t) (put (quote quote) (quote c!:code) (function c!:cquote)) (put (quote quote) (quote c!:valid) (function c!:valid_quote)) (de c!:creturn (u env) (prog (w) (setq w (assoc!*!* nil blockstack)) (cond (( null w) (error 0 "RETURN out of context"))) (c!:outop (quote movr) (cadr w) nil (c!:cval (cadr u) env)) (c!:endblock (quote goto) (list (cddr w))) ( return nil))) (put (quote return) (quote c!:code) (function c!:creturn)) (put (quote return!-from) (quote c!:code) (function c!:creturn_from)) (de c!:csetq (u env) (prog (v w) (setq v (c!:cval (caddr u) env)) (setq u ( cadr u)) (cond ((not (idp u)) (error 0 (list u "bad variable in setq"))) (t ( cond ((setq w (c!:locally_bound u env)) (c!:outop (quote movr) (cdr w) nil v) ) (t (cond ((flagp u (quote c!:constant)) (error 0 (list u "attempt to use setq on a constant"))) (t (c!:outop (quote strglob) v u ( c!:find_literal u)))))))) (return v))) (put (quote setq) (quote c!:code) (function c!:csetq)) (put (quote noisy!-setq) (quote c!:code) (function c!:csetq)) (de c!:cprivate_tagbody (u env) (prog nil (setq u (cdr u)) (c!:endblock ( quote goto) (list (car u))) (c!:startblock (car u)) (setq c!:current_args ( prog (var1382 var1383) (setq var1382 c!:current_args) lab1381 (cond ((null var1382) (return (reversip var1383)))) (prog (v) (setq v (car var1382)) (setq var1383 (cons (prog (z) (setq z (assoc!*!* v (car env))) (return (cond (z ( cdr z)) (t v)))) var1383))) (setq var1382 (cdr var1382)) (go lab1381))) ( return (c!:cval (cadr u) env)))) (put (quote c!:private_tagbody) (quote c!:code) (function c!:cprivate_tagbody )) (de c!:cthe (u env) (c!:cval (caddr u) env)) (put (quote the) (quote c!:code) (function c!:cthe)) (de c!:cunless (u env) (prog (v join l1 l2) (setq v (c!:newreg)) (setq join ( c!:my_gensym)) (setq l1 (c!:my_gensym)) (setq l2 (c!:my_gensym)) (c!:cjumpif (cadr u) env l2 l1) (c!:startblock l1) (c!:outop (quote movr) v nil (c!:cval (cons (quote progn) (cddr u)) env)) (c!:endblock (quote goto) (list join)) ( c!:startblock l2) (c!:outop (quote movk1) v nil nil) (c!:endblock (quote goto ) (list join)) (c!:startblock join) (return v))) (put (quote unless) (quote c!:code) (function c!:cunless)) (de c!:cunwind_protect (u env) (error 0 "unwind_protect")) (put (quote unwind!-protect) (quote c!:code) (function c!:cunwind_protect)) (de c!:cwhen (u env) (prog (v join l1 l2) (setq v (c!:newreg)) (setq join ( c!:my_gensym)) (setq l1 (c!:my_gensym)) (setq l2 (c!:my_gensym)) (c!:cjumpif (cadr u) env l1 l2) (c!:startblock l1) (c!:outop (quote movr) v nil (c!:cval (cons (quote progn) (cddr u)) env)) (c!:endblock (quote goto) (list join)) ( c!:startblock l2) (c!:outop (quote movk1) v nil nil) (c!:endblock (quote goto ) (list join)) (c!:startblock join) (return v))) (put (quote when) (quote c!:code) (function c!:cwhen)) (de c!:expand_map (fnargs) (prog (carp fn fn1 args var avar moveon l1 r s closed) (setq fn (car fnargs)) (cond ((or (equal fn (quote mapc)) (equal fn ( quote mapcar)) (equal fn (quote mapcan))) (setq carp t))) (setq fnargs (cdr fnargs)) (cond ((atom fnargs) (error 0 "bad arguments to map function"))) ( setq fn1 (cadr fnargs)) (prog nil lab1384 (cond ((null (or (eqcar fn1 (quote function)) (and (eqcar fn1 (quote quote)) (eqcar (cadr fn1) (quote lambda)))) ) (return nil))) (progn (setq fn1 (cadr fn1)) (setq closed t)) (go lab1384)) (setq args (car fnargs)) (setq l1 (c!:my_gensym)) (setq r (c!:my_gensym)) ( setq s (c!:my_gensym)) (setq var (c!:my_gensym)) (setq avar var) (cond (carp (setq avar (list (quote car) avar)))) (cond (closed (setq fn1 (list fn1 avar) )) (t (setq fn1 (list (quote apply1) fn1 avar)))) (setq moveon (list (quote setq) var (list (quote cdr) var))) (cond ((or (equal fn (quote map)) (equal fn (quote mapc))) (setq fn (sublis (list (cons (quote l1) l1) (cons (quote var) var) (cons (quote fn) fn1) (cons (quote args) args) (cons (quote moveon) moveon)) (quote (prog (var) (setq var args) l1 (cond ((not var) (return nil) )) fn moveon (go l1)))))) (t (cond ((or (equal fn (quote maplist)) (equal fn (quote mapcar))) (setq fn (sublis (list (cons (quote l1) l1) (cons (quote var ) var) (cons (quote fn) fn1) (cons (quote args) args) (cons (quote moveon) moveon) (cons (quote r) r)) (quote (prog (var r) (setq var args) l1 (cond (( not var) (return (reversip r)))) (setq r (cons fn r)) moveon (go l1)))))) (t (setq fn (sublis (list (cons (quote l1) l1) (cons (quote l2) (c!:my_gensym)) (cons (quote var) var) (cons (quote fn) fn1) (cons (quote args) args) (cons ( quote moveon) moveon) (cons (quote r) (c!:my_gensym)) (cons (quote s) ( c!:my_gensym))) (quote (prog (var r s) (setq var args) (setq r (setq s (list nil))) l1 (cond ((not var) (return (cdr r)))) (rplacd s fn) l2 (cond ((not ( atom (cdr s))) (setq s (cdr s)) (go l2))) moveon (go l1))))))))) (return fn)) ) (put (quote map) (quote c!:compile_macro) (function c!:expand_map)) (put (quote maplist) (quote c!:compile_macro) (function c!:expand_map)) (put (quote mapc) (quote c!:compile_macro) (function c!:expand_map)) (put (quote mapcar) (quote c!:compile_macro) (function c!:expand_map)) (put (quote mapcon) (quote c!:compile_macro) (function c!:expand_map)) (put (quote mapcan) (quote c!:compile_macro) (function c!:expand_map)) (de c!:expand_carcdr (x) (prog (name) (setq name (cdr (reverse (cdr (explode2 (car x)))))) (setq x (cadr x)) (prog (var1386) (setq var1386 name) lab1385 ( cond ((null var1386) (return nil))) (prog (v) (setq v (car var1386)) (setq x (list (cond ((equal v (quote a)) (quote car)) (t (quote cdr))) x))) (setq var1386 (cdr var1386)) (go lab1385)) (return x))) (progn (put (quote caar) (quote c!:compile_macro) (function c!:expand_carcdr) ) (put (quote cadr) (quote c!:compile_macro) (function c!:expand_carcdr)) ( put (quote cdar) (quote c!:compile_macro) (function c!:expand_carcdr)) (put ( quote cddr) (quote c!:compile_macro) (function c!:expand_carcdr)) (put (quote caaar) (quote c!:compile_macro) (function c!:expand_carcdr)) (put (quote caadr) (quote c!:compile_macro) (function c!:expand_carcdr)) (put (quote cadar) (quote c!:compile_macro) (function c!:expand_carcdr)) (put (quote caddr) (quote c!:compile_macro) (function c!:expand_carcdr)) (put (quote cdaar) (quote c!:compile_macro) (function c!:expand_carcdr)) (put (quote cdadr) (quote c!:compile_macro) (function c!:expand_carcdr)) (put (quote cddar) (quote c!:compile_macro) (function c!:expand_carcdr)) (put (quote cdddr) (quote c!:compile_macro) (function c!:expand_carcdr)) (put (quote caaaar) (quote c!:compile_macro) (function c!:expand_carcdr)) (put (quote caaadr) (quote c!:compile_macro) (function c!:expand_carcdr)) (put (quote caadar) (quote c!:compile_macro) (function c!:expand_carcdr)) (put (quote caaddr) (quote c!:compile_macro) (function c!:expand_carcdr)) (put (quote cadaar) (quote c!:compile_macro) (function c!:expand_carcdr)) (put (quote cadadr) (quote c!:compile_macro) (function c!:expand_carcdr)) (put (quote caddar) (quote c!:compile_macro) (function c!:expand_carcdr)) (put (quote cadddr) (quote c!:compile_macro) (function c!:expand_carcdr)) (put (quote cdaaar) (quote c!:compile_macro) (function c!:expand_carcdr)) (put (quote cdaadr) (quote c!:compile_macro) (function c!:expand_carcdr)) (put (quote cdadar) (quote c!:compile_macro) (function c!:expand_carcdr)) (put (quote cdaddr) (quote c!:compile_macro) (function c!:expand_carcdr)) (put (quote cddaar) (quote c!:compile_macro) (function c!:expand_carcdr)) (put (quote cddadr) (quote c!:compile_macro) (function c!:expand_carcdr)) (put (quote cdddar) (quote c!:compile_macro) (function c!:expand_carcdr)) (put (quote cddddr) (quote c!:compile_macro) (function c!:expand_carcdr))) (de c!:builtin_one (x env) (prog (r1 r2) (setq r1 (c!:cval (cadr x) env)) ( c!:outop (car x) (setq r2 (c!:newreg)) (cdr env) r1) (return r2))) (de c!:builtin_two (x env) (prog (a1 a2 r rr) (setq a1 (cadr x)) (setq a2 ( caddr x)) (setq rr (c!:pareval (list a1 a2) env)) (c!:outop (car x) (setq r ( c!:newreg)) (car rr) (cadr rr)) (return r))) (de c!:narg (x env) (c!:cval (expand (cdr x) (get (car x) (quote c!:binary_version))) env)) (prog (var1388) (setq var1388 (quote ((plus plus2) (times times2) (iplus iplus2) (itimes itimes2)))) lab1387 (cond ((null var1388) (return nil))) ( prog (n) (setq n (car var1388)) (progn (put (car n) (quote c!:binary_version) (cadr n)) (put (car n) (quote c!:code) (function c!:narg)))) (setq var1388 ( cdr var1388)) (go lab1387)) (de c!:cplus2 (u env) (prog (a b) (setq a (s!:improve (cadr u))) (setq b ( s!:improve (caddr u))) (return (cond ((and (numberp a) (numberp b)) (c!:cval (plus a b) env)) (t (cond ((equal a 0) (c!:cval b env)) (t (cond ((equal a 1) (c!:cval (list (quote add1) b) env)) (t (cond ((equal b 0) (c!:cval a env)) (t (cond ((equal b 1) (c!:cval (list (quote add1) a) env)) (t (cond ((equal b (minus 1)) (c!:cval (list (quote sub1) a) env)) (t (c!:ccall (car u) (cdr u) env)))))))))))))))) (put (quote plus2) (quote c!:code) (function c!:cplus2)) (de c!:ciplus2 (u env) (prog (a b) (setq a (s!:improve (cadr u))) (setq b ( s!:improve (caddr u))) (return (cond ((and (numberp a) (numberp b)) (c!:cval (plus a b) env)) (t (cond ((equal a 0) (c!:cval b env)) (t (cond ((equal a 1) (c!:cval (list (quote iadd1) b) env)) (t (cond ((equal b 0) (c!:cval a env)) (t (cond ((equal b 1) (c!:cval (list (quote iadd1) a) env)) (t (cond ((equal b (minus 1)) (c!:cval (list (quote isub1) a) env)) (t (c!:builtin_two u env) ))))))))))))))) (put (quote iplus2) (quote c!:code) (function c!:ciplus2)) (de c!:cdifference (u env) (prog (a b) (setq a (s!:improve (cadr u))) (setq b (s!:improve (caddr u))) (return (cond ((and (numberp a) (numberp b)) ( c!:cval (difference a b) env)) (t (cond ((equal a 0) (c!:cval (list (quote minus) b) env)) (t (cond ((equal b 0) (c!:cval a env)) (t (cond ((equal b 1) (c!:cval (list (quote sub1) a) env)) (t (cond ((equal b (minus 1)) (c!:cval ( list (quote add1) a) env)) (t (c!:ccall (car u) (cdr u) env)))))))))))))) (put (quote difference) (quote c!:code) (function c!:cdifference)) (de c!:cidifference (u env) (prog (a b) (setq a (s!:improve (cadr u))) (setq b (s!:improve (caddr u))) (return (cond ((and (numberp a) (numberp b)) ( c!:cval (difference a b) env)) (t (cond ((equal a 0) (c!:cval (list (quote iminus) b) env)) (t (cond ((equal b 0) (c!:cval a env)) (t (cond ((equal b 1) (c!:cval (list (quote isub1) a) env)) (t (cond ((equal b (minus 1)) (c!:cval (list (quote iadd1) a) env)) (t (c!:builtin_two u env)))))))))))))) (put (quote idifference) (quote c!:code) (function c!:cidifference)) (de c!:ctimes2 (u env) (prog (a b) (setq a (s!:improve (cadr u))) (setq b ( s!:improve (caddr u))) (return (cond ((and (numberp a) (numberp b)) (c!:cval (times a b) env)) (t (cond ((or (equal a 0) (equal b 0)) (c!:cval 0 env)) (t (cond ((equal a 1) (c!:cval b env)) (t (cond ((equal b 1) (c!:cval a env)) (t (cond ((equal a (minus 1)) (c!:cval (list (quote minus) b) env)) (t (cond (( equal b (minus 1)) (c!:cval (list (quote minus) a) env)) (t (c!:ccall (car u) (cdr u) env)))))))))))))))) (put (quote times2) (quote c!:code) (function c!:ctimes2)) (de c!:citimes2 (u env) (prog (a b) (setq a (s!:improve (cadr u))) (setq b ( s!:improve (caddr u))) (return (cond ((and (numberp a) (numberp b)) (c!:cval (times a b) env)) (t (cond ((or (equal a 0) (equal b 0)) (c!:cval 0 env)) (t (cond ((equal a 1) (c!:cval b env)) (t (cond ((equal b 1) (c!:cval a env)) (t (cond ((equal a (minus 1)) (c!:cval (list (quote iminus) b) env)) (t (cond ( (equal b (minus 1)) (c!:cval (list (quote iminus) a) env)) (t (c!:builtin_two u env)))))))))))))))) (put (quote itimes2) (quote c!:code) (function c!:citimes2)) (de c!:cminus (u env) (prog (a b) (setq a (s!:improve (cadr u))) (return ( cond ((numberp a) (c!:cval (minus a) env)) (t (cond ((eqcar a (quote minus)) (c!:cval (cadr a) env)) (t (c!:ccall (car u) (cdr u) env)))))))) (put (quote minus) (quote c!:code) (function c!:cminus)) (de c!:ceq (x env) (prog (a1 a2 r rr) (setq a1 (s!:improve (cadr x))) (setq a2 (s!:improve (caddr x))) (cond ((equal a1 nil) (return (c!:cval (list ( quote null) a2) env))) (t (cond ((equal a2 nil) (return (c!:cval (list (quote null) a1) env)))))) (setq rr (c!:pareval (list a1 a2) env)) (c!:outop (quote eq) (setq r (c!:newreg)) (car rr) (cadr rr)) (return r))) (put (quote eq) (quote c!:code) (function c!:ceq)) (de c!:cequal (x env) (prog (a1 a2 r rr) (setq a1 (s!:improve (cadr x))) ( setq a2 (s!:improve (caddr x))) (cond ((equal a1 nil) (return (c!:cval (list (quote null) a2) env))) (t (cond ((equal a2 nil) (return (c!:cval (list ( quote null) a1) env)))))) (setq rr (c!:pareval (list a1 a2) env)) (c!:outop ( cond ((or (c!:eqvalid a1) (c!:eqvalid a2)) (quote eq)) (t (quote equal))) ( setq r (c!:newreg)) (car rr) (cadr rr)) (return r))) (put (quote equal) (quote c!:code) (function c!:cequal)) (de c!:is_fixnum (x) (and (fixp x) (geq x (minus 134217728)) (leq x 134217727 ))) (de c!:certainlyatom (x) (or (null x) (equal x t) (c!:is_fixnum x) (and ( eqcar x (quote quote)) (or (symbolp (cadr x)) (c!:is_fixnum (cadr x)))))) (de c!:atomlist1 (u) (or (atom u) (and (or (symbolp (car u)) (c!:is_fixnum ( car u))) (c!:atomlist1 (cdr u))))) (de c!:atomlist (x) (or (null x) (and (eqcar x (quote quote)) (c!:atomlist1 ( cadr x))) (and (eqcar x (quote list)) (or (null (cdr x)) (and ( c!:certainlyatom (cadr x)) (c!:atomlist (cons (quote list) (cddr x)))))) (and (eqcar x (quote cons)) (c!:certainlyatom (cadr x)) (c!:atomlist (caddr x)))) ) (de c!:atomcar (x) (and (or (eqcar x (quote cons)) (eqcar x (quote list))) ( not (null (cdr x))) (c!:certainlyatom (cadr x)))) (de c!:atomkeys1 (u) (or (atom u) (and (not (atom (car u))) (or (symbolp ( caar u)) (c!:is_fixnum (caar u))) (c!:atomlist1 (cdr u))))) (de c!:atomkeys (x) (or (null x) (and (eqcar x (quote quote)) (c!:atomkeys1 ( cadr x))) (and (eqcar x (quote list)) (or (null (cdr x)) (and (c!:atomcar ( cadr x)) (c!:atomkeys (cons (quote list) (cddr x)))))) (and (eqcar x (quote cons)) (c!:atomcar (cadr x)) (c!:atomkeys (caddr x))))) (de c!:comsublis (x) (cond ((c!:atomkeys (cadr x)) (cons (quote subla) (cdr x ))) (t nil))) (put (quote sublis) (quote c!:compile_macro) (function c!:comsublis)) (de c!:comassoc (x) (cond ((or (c!:certainlyatom (cadr x)) (c!:atomkeys ( caddr x))) (cons (quote atsoc) (cdr x))) (t nil))) (put (quote assoc) (quote c!:compile_macro) (function c!:comassoc)) (put (quote assoc!*!*) (quote c!:compile_macro) (function c!:comassoc)) (de c!:commember (x) (cond ((or (c!:certainlyatom (cadr x)) (c!:atomlist ( caddr x))) (cons (quote memq) (cdr x))) (t nil))) (put (quote member) (quote c!:compile_macro) (function c!:commember)) (de c!:comdelete (x) (cond ((or (c!:certainlyatom (cadr x)) (c!:atomlist ( caddr x))) (cons (quote deleq) (cdr x))) (t nil))) (put (quote delete) (quote c!:compile_macro) (function c!:comdelete)) (de c!:ctestif (x env d1 d2) (prog (l1 l2) (setq l1 (c!:my_gensym)) (setq l2 (c!:my_gensym)) (c!:jumpif (cadr x) l1 l2) (setq x (cddr x)) (c!:startblock l1) (c!:jumpif (car x) d1 d2) (c!:startblock l2) (c!:jumpif (cadr x) d1 d2))) (put (quote if) (quote c!:ctest) (function c!:ctestif)) (de c!:ctestnull (x env d1 d2) (c!:cjumpif (cadr x) env d2 d1)) (put (quote null) (quote c!:ctest) (function c!:ctestnull)) (put (quote not) (quote c!:ctest) (function c!:ctestnull)) (de c!:ctestatom (x env d1 d2) (prog nil (setq x (c!:cval (cadr x) env)) ( c!:endblock (list (quote ifatom) x) (list d1 d2)))) (put (quote atom) (quote c!:ctest) (function c!:ctestatom)) (de c!:ctestconsp (x env d1 d2) (prog nil (setq x (c!:cval (cadr x) env)) ( c!:endblock (list (quote ifatom) x) (list d2 d1)))) (put (quote consp) (quote c!:ctest) (function c!:ctestconsp)) (de c!:ctestsymbol (x env d1 d2) (prog nil (setq x (c!:cval (cadr x) env)) ( c!:endblock (list (quote ifsymbol) x) (list d1 d2)))) (put (quote idp) (quote c!:ctest) (function c!:ctestsymbol)) (de c!:ctestnumberp (x env d1 d2) (prog nil (setq x (c!:cval (cadr x) env)) ( c!:endblock (list (quote ifnumber) x) (list d1 d2)))) (put (quote numberp) (quote c!:ctest) (function c!:ctestnumberp)) (de c!:ctestizerop (x env d1 d2) (prog nil (setq x (c!:cval (cadr x) env)) ( c!:endblock (list (quote ifizerop) x) (list d1 d2)))) (put (quote izerop) (quote c!:ctest) (function c!:ctestizerop)) (de c!:ctesteq (x env d1 d2) (prog (a1 a2 r) (setq a1 (cadr x)) (setq a2 ( caddr x)) (cond ((equal a1 nil) (return (c!:cjumpif a2 env d2 d1))) (t (cond ((equal a2 nil) (return (c!:cjumpif a1 env d2 d1)))))) (setq r (c!:pareval ( list a1 a2) env)) (c!:endblock (cons (quote ifeq) r) (list d1 d2)))) (put (quote eq) (quote c!:ctest) (function c!:ctesteq)) (de c!:ctesteqcar (x env d1 d2) (prog (a1 a2 r d3) (setq a1 (cadr x)) (setq a2 (caddr x)) (setq d3 (c!:my_gensym)) (setq r (c!:pareval (list a1 a2) env)) (c!:endblock (list (quote ifatom) (car r)) (list d2 d3)) (c!:startblock d3) (c!:outop (quote qcar) (car r) nil (car r)) (c!:endblock (cons (quote ifeq) r ) (list d1 d2)))) (put (quote eqcar) (quote c!:ctest) (function c!:ctesteqcar)) (global (quote (least_fixnum greatest_fixnum))) (setq least_fixnum (minus (expt 2 27))) (setq greatest_fixnum (difference (expt 2 27) 1)) (de c!:small_number (x) (and (fixp x) (geq x least_fixnum) (leq x greatest_fixnum))) (de c!:eqvalid (x) (cond ((atom x) (c!:small_number x)) (t (cond ((flagp (car x) (quote c!:fixnum_fn)) t) (t (and (equal (car x) (quote quote)) (or (idp ( cadr x)) (c!:small_number (cadr x))))))))) (flag (quote (iplus iplus2 idifference iminus itimes itimes2)) (quote c!:fixnum_fn)) (de c!:ctestequal (x env d1 d2) (prog (a1 a2 r) (setq a1 (s!:improve (cadr x) )) (setq a2 (s!:improve (caddr x))) (cond ((equal a1 nil) (return (c!:cjumpif a2 env d2 d1))) (t (cond ((equal a2 nil) (return (c!:cjumpif a1 env d2 d1))) ))) (setq r (c!:pareval (list a1 a2) env)) (c!:endblock (cons (cond ((or ( c!:eqvalid a1) (c!:eqvalid a2)) (quote ifeq)) (t (quote ifequal))) r) (list d1 d2)))) (put (quote equal) (quote c!:ctest) (function c!:ctestequal)) (de c!:ctestneq (x env d1 d2) (prog (a1 a2 r) (setq a1 (s!:improve (cadr x))) (setq a2 (s!:improve (caddr x))) (cond ((equal a1 nil) (return (c!:cjumpif a2 env d1 d2))) (t (cond ((equal a2 nil) (return (c!:cjumpif a1 env d1 d2)))) )) (setq r (c!:pareval (list a1 a2) env)) (c!:endblock (cons (cond ((or ( c!:eqvalid a1) (c!:eqvalid a2)) (quote ifeq)) (t (quote ifequal))) r) (list d2 d1)))) (put (quote neq) (quote c!:ctest) (function c!:ctestneq)) (de c!:ctestilessp (x env d1 d2) (prog (r) (setq r (c!:pareval (list (cadr x) (caddr x)) env)) (c!:endblock (cons (quote ifilessp) r) (list d1 d2)))) (put (quote ilessp) (quote c!:ctest) (function c!:ctestilessp)) (de c!:ctestigreaterp (x env d1 d2) (prog (r) (setq r (c!:pareval (list (cadr x) (caddr x)) env)) (c!:endblock (cons (quote ifigreaterp) r) (list d1 d2))) ) (put (quote igreaterp) (quote c!:ctest) (function c!:ctestigreaterp)) (de c!:ctestand (x env d1 d2) (prog (next) (prog (var1390) (setq var1390 (cdr x)) lab1389 (cond ((null var1390) (return nil))) (prog (a) (setq a (car var1390)) (progn (setq next (c!:my_gensym)) (c!:cjumpif a env next d2) ( c!:startblock next))) (setq var1390 (cdr var1390)) (go lab1389)) (c!:endblock (quote goto) (list d1)))) (put (quote and) (quote c!:ctest) (function c!:ctestand)) (de c!:ctestor (x env d1 d2) (prog (next) (prog (var1392) (setq var1392 (cdr x)) lab1391 (cond ((null var1392) (return nil))) (prog (a) (setq a (car var1392)) (progn (setq next (c!:my_gensym)) (c!:cjumpif a env d1 next) ( c!:startblock next))) (setq var1392 (cdr var1392)) (go lab1391)) (c!:endblock (quote goto) (list d2)))) (put (quote or) (quote c!:ctest) (function c!:ctestor)) (fluid (quote (c!:c_entrypoint_list))) (null (setq c!:c_entrypoint_list (quote ((abs c!:c_entrypoint "Labsval") ( apply0 c!:c_entrypoint "Lapply0") (apply1 c!:c_entrypoint "Lapply1") (apply2 c!:c_entrypoint "Lapply2") (apply3 c!:c_entrypoint "Lapply3") (ash1 c!:c_entrypoint "Lash1") (atan c!:c_entrypoint "Latan") (atom c!:c_entrypoint "Latom") (atsoc c!:c_entrypoint "Latsoc") (batchp c!:c_entrypoint "Lbatchp") (boundp c!:c_entrypoint "Lboundp") (bps!-putv c!:c_entrypoint "Lbpsputv") ( caaaar c!:c_entrypoint "Lcaaaar") (caaadr c!:c_entrypoint "Lcaaadr") (caaar c!:c_entrypoint "Lcaaar") (caadar c!:c_entrypoint "Lcaadar") (caaddr c!:c_entrypoint "Lcaaddr") (caadr c!:c_entrypoint "Lcaadr") (caar c!:c_entrypoint "Lcaar") (cadaar c!:c_entrypoint "Lcadaar") (cadadr c!:c_entrypoint "Lcadadr") (cadar c!:c_entrypoint "Lcadar") (caddar c!:c_entrypoint "Lcaddar") (cadddr c!:c_entrypoint "Lcadddr") (caddr c!:c_entrypoint "Lcaddr") (cadr c!:c_entrypoint "Lcadr") (car c!:c_entrypoint "Lcar") (cdaaar c!:c_entrypoint "Lcdaaar") (cdaadr c!:c_entrypoint "Lcdaadr" ) (cdaar c!:c_entrypoint "Lcdaar") (cdadar c!:c_entrypoint "Lcdadar") (cdaddr c!:c_entrypoint "Lcdaddr") (cdadr c!:c_entrypoint "Lcdadr") (cdar c!:c_entrypoint "Lcdar") (cddaar c!:c_entrypoint "Lcddaar") (cddadr c!:c_entrypoint "Lcddadr") (cddar c!:c_entrypoint "Lcddar") (cdddar c!:c_entrypoint "Lcdddar") (cddddr c!:c_entrypoint "Lcddddr") (cdddr c!:c_entrypoint "Lcdddr") (cddr c!:c_entrypoint "Lcddr") (cdr c!:c_entrypoint "Lcdr") (char!-code c!:c_entrypoint "Lchar_code") (close c!:c_entrypoint "Lclose") (codep c!:c_entrypoint "Lcodep") (constantp c!:c_entrypoint "Lconstantp") (date c!:c_entrypoint "Ldate") (deleq c!:c_entrypoint "Ldeleq") (digit c!:c_entrypoint "Ldigitp") (eject c!:c_entrypoint "Leject") (endp c!:c_entrypoint "Lendp") (eq c!:c_entrypoint "Leq") (eqcar c!:c_entrypoint "Leqcar") (eql c!:c_entrypoint "Leql") (eqn c!:c_entrypoint "Leqn") (error1 c!:c_entrypoint "Lerror0") (evenp c!:c_entrypoint "Levenp") (evlis c!:c_entrypoint "Levlis") (explode c!:c_entrypoint "Lexplode") (explode2 c!:c_entrypoint "Lexplodec") (explodec c!:c_entrypoint "Lexplodec") (expt c!:c_entrypoint "Lexpt") (fix c!:c_entrypoint "Ltruncate") (fixp c!:c_entrypoint "Lfixp") (flag c!:c_entrypoint "Lflag") (flagp!*!* c!:c_entrypoint "Lflagp") (flagp c!:c_entrypoint "Lflagp") (flagpcar c!:c_entrypoint "Lflagpcar") (float c!:c_entrypoint "Lfloat") (floatp c!:c_entrypoint "Lfloatp") (fluidp c!:c_entrypoint "Lsymbol_specialp") (gcdn c!:c_entrypoint "Lgcd") (gctime c!:c_entrypoint "Lgctime") (gensym c!:c_entrypoint "Lgensym") (gensym1 c!:c_entrypoint "Lgensym1") (geq c!:c_entrypoint "Lgeq") (get!* c!:c_entrypoint "Lget") (getenv c!:c_entrypoint "Lgetenv") (getv c!:c_entrypoint "Lgetv") (svref c!:c_entrypoint "Lgetv") (globalp c!:c_entrypoint "Lsymbol_globalp") ( greaterp c!:c_entrypoint "Lgreaterp") (iadd1 c!:c_entrypoint "Liadd1") ( idifference c!:c_entrypoint "Lidifference") (idp c!:c_entrypoint "Lsymbolp") (igreaterp c!:c_entrypoint "Ligreaterp") (ilessp c!:c_entrypoint "Lilessp") ( iminus c!:c_entrypoint "Liminus") (iminusp c!:c_entrypoint "Liminusp") ( indirect c!:c_entrypoint "Lindirect") (integerp c!:c_entrypoint "Lintegerp") (iplus2 c!:c_entrypoint "Liplus2") (iquotient c!:c_entrypoint "Liquotient") ( iremainder c!:c_entrypoint "Liremainder") (irightshift c!:c_entrypoint "Lirightshift") (isub1 c!:c_entrypoint "Lisub1") (itimes2 c!:c_entrypoint "Litimes2") (length c!:c_entrypoint "Llength") (lengthc c!:c_entrypoint "Llengthc") (leq c!:c_entrypoint "Lleq") (lessp c!:c_entrypoint "Llessp") ( linelength c!:c_entrypoint "Llinelength") (load!-module c!:c_entrypoint "Lload_module") (lposn c!:c_entrypoint "Llposn") (macro!-function c!:c_entrypoint "Lmacro_function") (macroexpand!-1 c!:c_entrypoint "Lmacroexpand_1") (macroexpand c!:c_entrypoint "Lmacroexpand") (make!-bps c!:c_entrypoint "Lget_bps") (make!-global c!:c_entrypoint "Lmake_global") ( make!-simple!-string c!:c_entrypoint "Lsmkvect") (make!-special c!:c_entrypoint "Lmake_special") (mapstore c!:c_entrypoint "Lmapstore") (max2 c!:c_entrypoint "Lmax2") (memq c!:c_entrypoint "Lmemq") (min2 c!:c_entrypoint "Lmin2") (minus c!:c_entrypoint "Lminus") (minusp c!:c_entrypoint "Lminusp") (mkquote c!:c_entrypoint "Lmkquote") (mkvect c!:c_entrypoint "Lmkvect") (mod c!:c_entrypoint "Lmod") (modular!-difference c!:c_entrypoint "Lmodular_difference") (modular!-expt c!:c_entrypoint "Lmodular_expt") (modular!-minus c!:c_entrypoint "Lmodular_minus") ( modular!-number c!:c_entrypoint "Lmodular_number") (modular!-plus c!:c_entrypoint "Lmodular_plus") (modular!-quotient c!:c_entrypoint "Lmodular_quotient") (modular!-reciprocal c!:c_entrypoint "Lmodular_reciprocal") (modular!-times c!:c_entrypoint "Lmodular_times") ( nconc c!:c_entrypoint "Lnconc") (neq c!:c_entrypoint "Lneq") (not c!:c_entrypoint "Lnull") (null c!:c_entrypoint "Lnull") (numberp c!:c_entrypoint "Lnumberp") (oddp c!:c_entrypoint "Loddp") (onep c!:c_entrypoint "Lonep") (orderp c!:c_entrypoint "Lorderp") (pagelength c!:c_entrypoint "Lpagelength") (pairp c!:c_entrypoint "Lconsp") (plist c!:c_entrypoint "Lplist") (plusp c!:c_entrypoint "Lplusp") (posn c!:c_entrypoint "Lposn") (put c!:c_entrypoint "Lputprop") (putv!-char c!:c_entrypoint "Lsputv") (putv c!:c_entrypoint "Lputv") (qcaar c!:c_entrypoint "Lcaar") (qcadr c!:c_entrypoint "Lcadr") (qcar c!:c_entrypoint "Lcar") (qcdar c!:c_entrypoint "Lcdar") (qcddr c!:c_entrypoint "Lcddr") (qcdr c!:c_entrypoint "Lcdr") (qgetv c!:c_entrypoint "Lgetv") (rds c!:c_entrypoint "Lrds") (reclaim c!:c_entrypoint "Lgc") (remd c!:c_entrypoint "Lremd") (remflag c!:c_entrypoint "Lremflag") (remob c!:c_entrypoint "Lunintern") (remprop c!:c_entrypoint "Lremprop") (reverse c!:c_entrypoint "Lreverse") (reversip c!:c_entrypoint "Lnreverse") (rplaca c!:c_entrypoint "Lrplaca") (rplacd c!:c_entrypoint "Lrplacd") (schar c!:c_entrypoint "Lsgetv") (seprp c!:c_entrypoint "Lwhitespace_char_p") ( set!-small!-modulus c!:c_entrypoint "Lset_small_modulus") (set c!:c_entrypoint "Lset") (smemq c!:c_entrypoint "Lsmemq") (spaces c!:c_entrypoint "Lxtab") (special!-char c!:c_entrypoint "Lspecial_char") ( special!-form!-p c!:c_entrypoint "Lspecial_form_p") (spool c!:c_entrypoint "Lspool") (stop c!:c_entrypoint "Lstop") (stringp c!:c_entrypoint "Lstringp") (subla c!:c_entrypoint "Lsubla") (subst c!:c_entrypoint "Lsubst") ( symbol!-env c!:c_entrypoint "Lsymbol_env") (symbol!-function c!:c_entrypoint "Lsymbol_function") (symbol!-name c!:c_entrypoint "Lsymbol_name") ( symbol!-set!-definition c!:c_entrypoint "Lsymbol_set_definition") ( symbol!-set!-env c!:c_entrypoint "Lsymbol_set_env") (symbol!-value c!:c_entrypoint "Lsymbol_value") (system c!:c_entrypoint "Lsystem") (terpri c!:c_entrypoint "Lterpri") (threevectorp c!:c_entrypoint "Lthreevectorp") ( time c!:c_entrypoint "Ltime") (ttab c!:c_entrypoint "Lttab") (tyo c!:c_entrypoint "Ltyo") (unmake!-global c!:c_entrypoint "Lunmake_global") ( unmake!-special c!:c_entrypoint "Lunmake_special") (upbv c!:c_entrypoint "Lupbv") (verbos c!:c_entrypoint "Lverbos") (wrs c!:c_entrypoint "Lwrs") ( xcons c!:c_entrypoint "Lxcons") (xtab c!:c_entrypoint "Lxtab") (zerop c!:c_entrypoint "Lzerop") (cons c!:direct_entrypoint (2 . "cons")) (ncons c!:direct_entrypoint (1 . "ncons")) (list2 c!:direct_entrypoint (2 . "list2") ) (list2!* c!:direct_entrypoint (3 . "list2star")) (acons c!:direct_entrypoint (3 . "acons")) (list3 c!:direct_entrypoint (3 . "list3") ) (list3!* c!:direct_entrypoint (4 . "list3star")) (list4 c!:direct_entrypoint (4 . "list4")) (plus2 c!:direct_entrypoint (2 . "plus2") ) (difference c!:direct_entrypoint (2 . "difference2")) (add1 c!:direct_entrypoint (1 . "add1")) (sub1 c!:direct_entrypoint (1 . "sub1")) ( lognot c!:direct_entrypoint (1 . "lognot")) (ash c!:direct_entrypoint (2 . "ash")) (quotient c!:direct_entrypoint (2 . "quot2")) (remainder c!:direct_entrypoint (2 . "Cremainder")) (times2 c!:direct_entrypoint (2 . "times2")) (minus c!:direct_entrypoint (1 . "negate")) (lessp c!:direct_predicate (2 . "lessp2")) (leq c!:direct_predicate (2 . "lesseq2")) (greaterp c!:direct_predicate (2 . "greaterp2")) (geq c!:direct_predicate (2 . "geq2")) (zerop c!:direct_predicate (1 . "zerop")))))) (null (setq c!:c_entrypoint_list (append c!:c_entrypoint_list (quote ((append c!:c_entrypoint "Lappend") (assoc c!:c_entrypoint "Lassoc") (compress c!:c_entrypoint "Lcompress") (delete c!:c_entrypoint "Ldelete") (divide c!:c_entrypoint "Ldivide") (equal c!:c_entrypoint "Lequal") (intern c!:c_entrypoint "Lintern") (liter c!:c_entrypoint "Lalpha_char_p") (member c!:c_entrypoint "Lmember") (prin c!:c_entrypoint "Lprin") (prin1 c!:c_entrypoint "Lprin") (prin2 c!:c_entrypoint "Lprinc") (princ c!:c_entrypoint "Lprinc") (print c!:c_entrypoint "Lprint") (printc c!:c_entrypoint "Lprintc") (read c!:c_entrypoint "Lread") (readch c!:c_entrypoint "Lreadch") (sublis c!:c_entrypoint "Lsublis") (vectorp c!:c_entrypoint "Lsimple_vectorp") (get c!:direct_entrypoint (2 . "get")))))) ) (prog (var1394) (setq var1394 c!:c_entrypoint_list) lab1393 (cond ((null var1394) (return nil))) (prog (x) (setq x (car var1394)) (put (car x) (cadr x ) (caddr x))) (setq var1394 (cdr var1394)) (go lab1393)) (flag (quote (atom atsoc codep constantp deleq digit endp eq eqcar evenp eql fixp flagp flagpcar floatp get globalp iadd1 idifference idp igreaterp ilessp iminus iminusp indirect integerp iplus2 irightshift isub1 itimes2 liter memq minusp modular!-difference modular!-expt modular!-minus modular!-number modular!-plus modular!-times not null numberp onep pairp plusp qcaar qcadr qcar qcdar qcddr qcdr remflag remprop reversip seprp special!-form!-p stringp symbol!-env symbol!-name symbol!-value threevectorp vectorp zerop)) (quote c!:no_errors)) % end of file
[ { "context": "; DEALINGS IN THE SOFTWARE.\n;\n; Original author: Sol Swords <[email protected]>\n\n(in-package \"ACL2\")\n\n(def", "end": 1387, "score": 0.9998593926429749, "start": 1377, "tag": "NAME", "value": "Sol Swords" }, { "context": "IN THE SOFTWARE.\n;\n; Original author: Sol Swords <[email protected]>\n\n(in-package \"ACL2\")\n\n(defevaluator eval-for-mv-", "end": 1409, "score": 0.9999321103096008, "start": 1389, "tag": "EMAIL", "value": "[email protected]" } ]
books/tools/mv-nth.lisp
MattKaufmann/acl2
1
; MV-NTH Meta Rule ; 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: Sol Swords <[email protected]> (in-package "ACL2") (defevaluator eval-for-mv-nth eval-for-mv-nth-list ((mv-nth n x) (cons a b))) (defn mv-nth-eval-rec (n x orig) (declare (xargs :guard (natp n))) (if (zp n) (case-match x (('cons a . &) a) (('quote (const . &) . &) (list 'quote const)) (& orig)) (case-match x (('cons & d . &) (mv-nth-eval-rec (1- n) d orig)) (('quote const . &) (list 'quote (ec-call (nth n const)))) (& orig)))) (defn mv-nth-eval-fn (x) (declare (xargs :guard t)) (case-match x (('mv-nth ('quote n . &) rst . &) (if (natp n) (mv-nth-eval-rec n rst x) x)) (& x))) (defthm eval-for-mv-nth-rec-thm (implies (equal (eval-for-mv-nth x a) (mv-nth n (eval-for-mv-nth term a))) (equal (eval-for-mv-nth (mv-nth-eval-rec n term x) a) (mv-nth n (eval-for-mv-nth term a)))) :hints (("Goal" :induct (mv-nth-eval-rec n term x)))) (defthm mv-nth-cons-meta (equal (eval-for-mv-nth x a) (eval-for-mv-nth (mv-nth-eval-fn x) a)) :rule-classes ((:meta :trigger-fns (mv-nth)))) (in-theory (disable mv-nth))
92945
; MV-NTH Meta Rule ; 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 "ACL2") (defevaluator eval-for-mv-nth eval-for-mv-nth-list ((mv-nth n x) (cons a b))) (defn mv-nth-eval-rec (n x orig) (declare (xargs :guard (natp n))) (if (zp n) (case-match x (('cons a . &) a) (('quote (const . &) . &) (list 'quote const)) (& orig)) (case-match x (('cons & d . &) (mv-nth-eval-rec (1- n) d orig)) (('quote const . &) (list 'quote (ec-call (nth n const)))) (& orig)))) (defn mv-nth-eval-fn (x) (declare (xargs :guard t)) (case-match x (('mv-nth ('quote n . &) rst . &) (if (natp n) (mv-nth-eval-rec n rst x) x)) (& x))) (defthm eval-for-mv-nth-rec-thm (implies (equal (eval-for-mv-nth x a) (mv-nth n (eval-for-mv-nth term a))) (equal (eval-for-mv-nth (mv-nth-eval-rec n term x) a) (mv-nth n (eval-for-mv-nth term a)))) :hints (("Goal" :induct (mv-nth-eval-rec n term x)))) (defthm mv-nth-cons-meta (equal (eval-for-mv-nth x a) (eval-for-mv-nth (mv-nth-eval-fn x) a)) :rule-classes ((:meta :trigger-fns (mv-nth)))) (in-theory (disable mv-nth))
true
; MV-NTH Meta Rule ; 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 "ACL2") (defevaluator eval-for-mv-nth eval-for-mv-nth-list ((mv-nth n x) (cons a b))) (defn mv-nth-eval-rec (n x orig) (declare (xargs :guard (natp n))) (if (zp n) (case-match x (('cons a . &) a) (('quote (const . &) . &) (list 'quote const)) (& orig)) (case-match x (('cons & d . &) (mv-nth-eval-rec (1- n) d orig)) (('quote const . &) (list 'quote (ec-call (nth n const)))) (& orig)))) (defn mv-nth-eval-fn (x) (declare (xargs :guard t)) (case-match x (('mv-nth ('quote n . &) rst . &) (if (natp n) (mv-nth-eval-rec n rst x) x)) (& x))) (defthm eval-for-mv-nth-rec-thm (implies (equal (eval-for-mv-nth x a) (mv-nth n (eval-for-mv-nth term a))) (equal (eval-for-mv-nth (mv-nth-eval-rec n term x) a) (mv-nth n (eval-for-mv-nth term a)))) :hints (("Goal" :induct (mv-nth-eval-rec n term x)))) (defthm mv-nth-cons-meta (equal (eval-for-mv-nth x a) (eval-for-mv-nth (mv-nth-eval-fn x) a)) :rule-classes ((:meta :trigger-fns (mv-nth)))) (in-theory (disable mv-nth))