id
int64 0
45.1k
| file_name
stringlengths 4
68
| file_path
stringlengths 14
193
| content
stringlengths 32
9.62M
| size
int64 32
9.62M
| language
stringclasses 1
value | extension
stringclasses 6
values | total_lines
int64 1
136k
| avg_line_length
float64 3
903k
| max_line_length
int64 3
4.51M
| alphanum_fraction
float64 0
1
| repo_name
stringclasses 779
values | repo_stars
int64 0
882
| repo_forks
int64 0
108
| repo_open_issues
int64 0
90
| repo_license
stringclasses 8
values | repo_extraction_date
stringclasses 146
values | sha
stringlengths 64
64
| __index_level_0__
int64 0
45.1k
| exdup_ids_cmlisp_stkv2
sequencelengths 1
47
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
25,694 | simut.lisp | foss-santanu_simut/simut.lisp | ;;;; simut.lisp
(in-package #:simut)
;;; "simut" goes here. Hacks and glory await!
| 88 | Common Lisp | .lisp | 3 | 26.666667 | 45 | 0.675 | foss-santanu/simut | 1 | 0 | 0 | GPL-2.0 | 9/19/2024, 11:28:28 AM (Europe/Amsterdam) | bb6c668b32d701456ff980ff18f73fbda6f042d88a95bb6f1de55f8da4bfd7ae | 25,694 | [
-1
] |
25,695 | test-unit-test-structs.lisp | foss-santanu_simut/test/test-unit-test-structs.lisp | (in-package #:test-simut)
;; Test for create-fixture
(create-fixture initialize-a
(setf a (make-hash-table))
(setf (gethash 'name a) "santanu"))
;; Call setup function initialize-a to set variable a
(initialize-a)
(assert (string= (gethash 'name a) "santanu"))
;; Test for create-unit-test
;; 1. no suite, no set up, no tear down
(create-unit-test my-test () (setf t-sum (+ 1 2 3 4 5 6 7 8 9 10)))
;; Execute my-test and verify
(my-test)
(assert (= t-sum (+ 1 2 3 4 5 6 7 8 9 10)))
;; 2. no suite, set up and tear down
(create-fixture f1 (setf aa 20))
(create-fixture f2 (setf aa 30))
(create-unit-test my-test2 (:set-up f1 :tear-down f2) (setf t-aa aa))
;; Execute my-test2 and verify
(my-test2)
(assert (= t-aa 20))
(assert (= aa 30))
;; 3. suite, set up and tear down
(setf *global-test-suite* (make-hash-table))
(assert (null (gethash 'my-suite *global-test-suite*)))
(create-unit-test my-test3 (:in-suite my-suite :set-up f1 :tear-down f2) (setf z-aa aa))
;; Execute my-test3 and verify
(my-test3)
(assert (= z-aa 20))
(assert (= aa 30))
(assert (gethash 'my-suite *global-test-suite*))
;; Check that my-test3 is contained by my-suite
(let ((suite (gethash 'my-suite *global-test-suite*)))
(setf test-fn1 (gethash 'my-test3 suite))
(assert (eq test-fn1 (symbol-function 'my-test3))))
;; Test for run-test
;; 1. unknown suite name
(let ((mssg))
(handler-case (run-test 'any-test :in-suite 'any-suite)
(error (c) (setf mssg (princ-to-string c))))
(assert (string= "Test suite ANY-SUITE not found" mssg)))
;; 2. unknown test name
(let ((mssg))
(handler-case (run-test 'any-test :in-suite 'my-suite)
(error (c) (setf mssg (princ-to-string c))))
(assert (string= "Unit test ANY-TEST not found in test suite MY-SUITE" mssg)))
;; 3. unit test invoking error
(clrhash *global-test-suite*)
(create-unit-test unit-test-1 () (error "throwing error forcefully"))
(let ((run-output (make-array '(0) :element-type 'base-char
:fill-pointer 0 :adjustable t))
(exp-output) (test-count-str))
;; capture test output to a string
(with-output-to-string (*standard-output* run-output) (run-test 'unit-test-1))
(setf exp-output (format nil "Test UNIT-TEST-1: failed~%throwing error forcefully"))
(setf test-count-str (format nil "Test success: 0 and failure: 1"))
;; search if expected output is contained by run-output
(assert (search exp-output run-output))
(assert (search test-count-str run-output)))
;; 4. successful unit test with run-time set up and tear down
(clrhash *global-test-suite*)
(create-fixture f1 (setf a 20))
(create-fixture f2 (setf a 30))
(create-unit-test unit-test-2 () (assert (= 20 a)))
(let ((run-output (make-array '(0) :element-type 'base-char
:fill-pointer 0 :adjustable t))
(exp-output) (test-count-str))
;; capture test output to a string
(with-output-to-string (*standard-output* run-output)
(run-test 'unit-test-2 :set-up 'f1 :tear-down 'f2))
(setf exp-output (format nil "Test UNIT-TEST-2: passed"))
(setf test-count-str (format nil "Test success: 1 and failure: 0"))
;; search if expected output is contained by run-output
(assert (search exp-output run-output))
(assert (search test-count-str run-output))
(assert (= 30 a)))
;; Test for run-suite
;; 1. unknown suite name
(let ((mssg))
(handler-case (run-suite 'any-suite)
(error (c) (setf mssg (princ-to-string c))))
(assert (string= "Test suite ANY-SUITE not found" mssg)))
;; 2. test suite containing two unit tests
(create-fixture tf1 (setf x 6))
(create-fixture tf2 (setf x 0))
(create-unit-test unit-test-3 (:in-suite test-suite-1) (assert (= 16 y)))
(create-unit-test unit-test-4 (:in-suite test-suite-1
:set-up tf1 :tear-down tf2)
(setf x (+ y x)) (assert (= 16 x)))
(create-fixture tf3 (setf y 10))
(let ((run-output (make-array '(0) :element-type 'base-char
:fill-pointer 0 :adjustable t))
(exp-output) (test-count-str))
;; capture test output to a string
(with-output-to-string (*standard-output* run-output)
(run-suite 'test-suite-1 :set-up 'tf3))
;; search if expected output is contained by run-output
(setf exp-output (format nil "Test UNIT-TEST-4: passed"))
(assert (search exp-output run-output))
(setf exp-output (format nil "Test UNIT-TEST-3: failed"))
(assert (search exp-output run-output))
(setf test-count-str (format nil "Test success: 1 and failure: 1"))
(assert (search test-count-str run-output))
(assert (= 0 x))
(assert (= 10 y)))
;; Test for run-all
(create-fixture tf4 (let ((x 1)) (defun seq-gen (increment) (incf x increment))))
(create-unit-test unit-test-5 (:in-suite test-suite-2 :set-up tf4)
(assert (= 11 (seq-gen y))))
(let ((run-output (make-array '(0) :element-type 'base-char
:fill-pointer 0 :adjustable t))
(exp-output) (test-count-str))
;; capture test output to a string
(with-output-to-string (*standard-output* run-output)
(run-all :set-up 'tf3))
;; search if expected output is contained by run-output
(setf exp-output (format nil "Result for test item: TEST-SUITE-1"))
(assert (search exp-output run-output))
(setf exp-output (format nil "Test UNIT-TEST-4: passed"))
(assert (search exp-output run-output))
(setf exp-output (format nil "Test UNIT-TEST-3: failed"))
(assert (search exp-output run-output))
(setf test-count-str (format nil "Test success: 1 and failure: 1"))
(assert (search test-count-str run-output))
(setf exp-output (format nil "Result for test item: TEST-SUITE-2"))
(assert (search exp-output run-output))
(setf exp-output (format nil "Test UNIT-TEST-5: passed"))
(assert (search exp-output run-output))
(setf test-count-str (format nil "Test success: 1 and failure: 0"))
(assert (search test-count-str run-output))
(setf test-count-str (format nil "Total test success: 2"))
(assert (search test-count-str run-output))
(setf test-count-str (format nil "Total test failure: 1"))
(assert (search test-count-str run-output))
(assert (= 0 x))
(assert (= 10 y))) | 6,196 | Common Lisp | .lisp | 136 | 41.610294 | 88 | 0.667603 | foss-santanu/simut | 1 | 0 | 0 | GPL-2.0 | 9/19/2024, 11:28:28 AM (Europe/Amsterdam) | 653e52a99f2d68cd46b1a58f76b427a2b58265243a75070cc45eba40c565e7eb | 25,695 | [
-1
] |
25,696 | unit-test-structs.lisp | foss-santanu_simut/src/unit-test-structs.lisp | (in-package #:simut)
;; Repository of all test cases and test suites
(setf *global-test-suite* (make-hash-table))
(defmacro create-fixture (fixture-name &rest forms)
"create-fixture: builds a fixture function and assigns to a symbol
Arguments: fixture-name - name of fixture function
forms - Lisp forms to execute before or after a test"
`(defun ,fixture-name ()
(format t "Executing fixture: ~S ...~%" ',fixture-name)
,@forms))
(defmacro create-unit-test (test-name (&key in-suite set-up tear-down) &rest forms)
"create-unit-test: builds a unit test function and assigns a name test-name
Arguments: test-name - name of unit test function
in-suite - test suite containing the unit test
set-up - fixture to do initialization tasks
tear-down - fixture to clear up after executing test
forms - Lisp forms to execute as part of unit test"
`(progn
;; Create test-name unit test function
;; Executes set-up if present then all forms and lastly tear-down if present
(defun ,test-name ()
(when ',set-up (,set-up))
(format t "Executing test: ~S ...~%" ',test-name)
;; tear-down is executed even if test code fails
(unwind-protect
(progn
,@forms
)
(when ',tear-down (,tear-down))))
;; If test suite mentioned put the test case in test suite
(when ',in-suite
;; Check if the suite is already present
(let ((suite (gethash ',in-suite *global-test-suite*)))
(when (not suite) ;; New test suite - create
(setf (gethash ',in-suite *global-test-suite*) (make-hash-table))
(setf suite (gethash ',in-suite *global-test-suite*)))
;; Add test case to test suite
(setf (gethash ',test-name suite) (symbol-function ',test-name))))))
(defmacro exec-test (unit-test)
"exec-test: sets up test execution to enable reporting success/failure
Arguments: unit-test - symbol representing a unit test"
`(let ((success-p
(restart-case
(progn
(funcall ,unit-test)
t)
(continue-next-test () nil))))
(when success-p (signal 'test-success-condition))))
;; test-success-condition: condition to signal successful test execution
(define-condition test-success-condition (simple-condition) ())
;; test-exec-report: test execution statistics and messages
;; Instance members: report-item - name of a test suite or test case
;; success-count - number of test successes
;; failure-count - number of test failures
;; messages - list of test messages
(defclass test-exec-report ()
((report-item :initarg :report-item
:initform (error "Must provide report item name")
:reader report-item)
(success-count :initform 0
:reader success-count)
(failure-count :initform 0
:reader failure-count)
(messages :initform (make-array 128 :adjustable t :fill-pointer 0)
:reader messages)))
;; Interfaces of test-exec-report
(defgeneric increment-success (test-report &optional count)
(:documentation "Increments success count"))
(defgeneric increment-failure (test-report &optional count)
(:documentation "Increments failure count"))
(defgeneric add-message (test-report message)
(:documentation "Adds a message to the list of messages"))
(defmethod increment-success ((test-report test-exec-report) &optional (count 1))
(with-slots (success-count) test-report
(incf success-count count)))
(defmethod increment-failure ((test-report test-exec-report) &optional (count 1))
(with-slots (failure-count) test-report
(incf failure-count count)))
(defmethod add-message ((test-report test-exec-report) message)
(with-slots (messages) test-report
(vector-push-extend message messages)))
;; Global repository of all test results
(setf *global-test-results* (make-hash-table))
(defun report-test (test-name &optional (suite-name nil) (failure-report-p nil) (message nil))
"report-test: reports test result for a unit test
Arguments: test-name - name of the unit test
suite-name - test suite where unit test belongs
failure-report-p - success or failure report?
message - if failure report additional failure message"
(let ((report-item-name) (test-report) (test-message))
(if suite-name (setf report-item-name suite-name)
(setf report-item-name test-name))
(setf test-report (gethash report-item-name *global-test-results*))
(when (not test-report)
(setf (gethash report-item-name *global-test-results*) (make-instance 'test-exec-report :report-item report-item-name))
(setf test-report (gethash report-item-name *global-test-results*)))
(if failure-report-p (progn
(increment-failure test-report)
(setf test-message (format nil "Test ~S: failed~%~A" test-name message)))
(progn
(increment-success test-report)
(setf test-message (format nil "Test ~S: passed~%" test-name))))
(add-message test-report test-message)))
;; print-result: prints a single test result entry
(flet ((print-result (report-item total-success total-failure)
(let ((test-result (gethash report-item *global-test-results*)))
(with-slots (success-count failure-count messages) test-result
(incf total-success success-count)
(incf total-failure failure-count)
(format t "Test success: ~D and failure: ~D~%~%" success-count failure-count)
(loop for message across messages do (format t "~A~%" message)))
(values total-success total-failure))))
(defun print-result-for-test (test-name &key suite-name (summary-p t))
" print-result-for-test: prints results after running the test
Arguments: test-name - name of the unit test
suite-name - name of the test suite (optional)
summary-p - should display test summary? default true
Note: reset *global-test-results* once printing is complete"
(let ((total-success 0) (total-failure 0) (report-item))
(if suite-name (setf report-item suite-name)
(setf report-item test-name))
(format t "Result for unit test: ~A~%" test-name)
(multiple-value-setq (total-success total-failure)
(print-result report-item total-success total-failure))
(when summary-p
(format t "========== Summary Result ==========~%")
(format t "Total test success: ~D~%" total-success)
(format t "Total test failure: ~D~%" total-failure)))
;; reset test result repository
(clrhash *global-test-results*))
(defun print-result-for-suite (suite-name &key (summary-p t))
"print-result-for-suite: prints results after running the test suite
Arguments: suite-name - name of the test suite
summary-p - should display test summary? default true
Note: reset *global-test-results* once printing is complete"
(let ((total-success 0) (total-failure 0) (report-item))
(setf report-item suite-name)
(format t "Result for test case: ~A~%" suite-name)
(multiple-value-setq (total-success total-failure)
(print-result report-item total-success total-failure))
(when summary-p
(format t "========== Summary Result ==========~%")
(format t "Total test success: ~D~%" total-success)
(format t "Total test failure: ~D~%" total-failure)))
;; reset test result repository
(clrhash *global-test-results*))
(defun print-result-for-all (&key (summary-p t))
"print-result-for-all: prints results after running all the tests
Arguments: summary-p - should display test summary? default true
Note: reset *global-test-results* once printing is complete"
(let ((total-success 0) (total-failure 0) (report-item))
(format t "===== Test Result Breakups =====~%")
(maphash #'(lambda (k v) (setf report-item k)
(format t "Result for test item: ~A~%" k)
(multiple-value-setq (total-success total-failure)
(print-result report-item total-success total-failure)))
*global-test-results*)
(when summary-p
(format t "========== Summary Result ==========~%")
(format t "Total test success: ~D~%" total-success)
(format t "Total test failure: ~D~%" total-failure)))
;; reset test result repository
(clrhash *global-test-results*))
)
(defun continue-next-test (c current-test &optional current-suite)
"Restart for continue-next-test"
(report-test current-test current-suite t (princ-to-string c))
(let ((restart (find-restart 'continue-next-test)))
(when restart (invoke-restart restart))))
(defmacro with-success-failure-handlers ((test-name &key suite-name) &rest forms)
"with-success-failure-handlers: short-cut for handler definitions
Arguments: test-name - unit test
suite-name - test suite
forms - Lisp forms that actually executes the unit test"
`(handler-bind ((error #'(lambda (c) (continue-next-test c ,test-name ,suite-name)))
(test-success-condition #'(lambda (c) (report-test ,test-name ,suite-name))))
,@forms))
(defun run-test (test-name &key in-suite set-up tear-down (print-result-p t))
"run-test: runs a unit test
Arguments: test-name - name of the unit test
in-suite - name of the test suite
set-up - set up task needed before running the test
tear-down - clean up needed after running the test
print-result-p - need to print test result? default true"
;; if in-suite supplied, check test-name belongs to in-suite
(when in-suite
(let ((suite (gethash in-suite *global-test-suite*)))
(cond
((not suite) (error (format nil "Test suite ~A not found" in-suite)))
((not (gethash test-name suite))
(error (format nil "Unit test ~A not found in test suite ~A" test-name in-suite))))))
(when set-up (funcall set-up))
;; set up success/failure handlers and execute test
(with-success-failure-handlers (test-name :suite-name in-suite) (exec-test test-name))
(when tear-down (funcall tear-down))
(when print-result-p (print-result-for-test test-name :suite-name in-suite)))
(defun run-suite (suite-name &key set-up tear-down (print-result-p t))
"run-suite: runs all unit tests in a test suite
Arguments: suite-name - name of test suite
set-up - set up task needed before running all tests
tear-down - clean up task after all tests are complete
print-result-p - need to print test result? default true"
;; check if test suite is defined
(let ((suite (gethash suite-name *global-test-suite*)) (test-name))
(when (not suite) (error (format nil "Test suite ~A not found" suite-name)))
(when set-up (funcall set-up))
;; set up success/failure handlers and execute tests
(with-success-failure-handlers (test-name :suite-name suite-name)
(maphash #'(lambda (test-nm test-fn) (setf test-name test-nm) (exec-test test-fn))
suite))
(when tear-down (funcall tear-down))
(when print-result-p (print-result-for-suite suite-name))))
(defun run-all (&key set-up tear-down (print-result-p t))
"run-all: runs all unit tests in all test suites
Arguments: set-up - set up task needed before running all tests
tear-down - clean up task after all tests are complete
print-result-p - need to print test result? default true"
(let ((suite-name) (test-name))
(when set-up (funcall set-up))
;; set up success/failure handlers and execute tests
(with-success-failure-handlers (test-name :suite-name suite-name)
(maphash #'(lambda (suite-nm suite)
(setf suite-name suite-nm)
(maphash #'(lambda (test-nm test-fn)
(setf test-name test-nm)
(exec-test test-fn))
suite))
*global-test-suite*))
(when tear-down (funcall tear-down))
(when print-result-p (print-result-for-all)))) | 12,378 | Common Lisp | .lisp | 230 | 45.813043 | 125 | 0.651155 | foss-santanu/simut | 1 | 0 | 0 | GPL-2.0 | 9/19/2024, 11:28:28 AM (Europe/Amsterdam) | 4d45ae930b679e233152153c614ab9543174d8a6c7ec22e74d2bca988c6e31d0 | 25,696 | [
-1
] |
25,697 | simut.asd | foss-santanu_simut/simut.asd | ;;;; simut.asd
(asdf:defsystem #:simut
:serial t
:description "My (sim)ple (u)nit (t)esting framework"
:author "Santanu Chakrabarti <[email protected]>"
:version "0.1"
:license "GPL"
:components ((:file "package")
(:file "simut")
(:module "src"
:components ((:file "unit-test-structs")))
(:module "test"
:components ((:file "test-unit-test-structs")))
)
)
| 494 | Common Lisp | .asd | 15 | 23.533333 | 71 | 0.530526 | foss-santanu/simut | 1 | 0 | 0 | GPL-2.0 | 9/19/2024, 11:28:28 AM (Europe/Amsterdam) | 35c537ab0c33837f6041ae89996c0335c318767a3953bee17ffb8041bf891d9b | 25,697 | [
-1
] |
25,701 | user_manual.md | foss-santanu_simut/user_manual.md |
## Rudimentary Documentation for UNIT-TEST-STRUCTS.LISP
*Containing Directory /host/santanu/programming/Lisp/simut/src/*
### API Documentation
#### CREATE-FIXTURE (fixture-name &rest forms) [MACRO]
>
> create-fixture: builds a fixture function and assigns to a symbol
> Arguments: fixture-name - name of fixture function
> forms - Lisp forms to execute before or after a test
---
#### CREATE-UNIT-TEST (test-name (&key in-suite set-up tear-down) &rest forms) [MACRO]
>
> create-unit-test: builds a unit test function and assigns a name
> test-name
> Arguments: test-name - name of unit test function
> in-suite - test suite containing the unit test
> set-up - fixture to do initialization tasks
> tear-down - fixture to clear up after executing test
> forms - Lisp forms to execute as part of unit test
---
#### EXEC-TEST (unit-test) [MACRO]
>
> exec-test: sets up test execution to enable reporting success/failure
> Arguments: unit-test - symbol representing a unit test
---
#### TEST-SUCCESS-CONDITION () [CONDITION]
---
#### TEST-EXEC-REPORT [CLASS]
>
> Superclasses
> None.
> Initialization Arguments
> The :report-item argument is a
> Readers
> report-item Generic Function
> test-exec-report
> Returns
> success-count Generic Function
> test-exec-report
> Returns
> failure-count Generic Function
> test-exec-report
> Returns
> messages Generic Function
> test-exec-report
> Returns
> Writers
---
#### INCREMENT-SUCCESS (test-report &optional count) [GENERIC FUNCTION]
>
> Increments success count
---
#### INCREMENT-FAILURE (test-report &optional count) [GENERIC FUNCTION]
>
> Increments failure count
---
#### ADD-MESSAGE (test-report message) [GENERIC FUNCTION]
>
> Adds a message to the list of messages
---
#### INCREMENT-SUCCESS ((test-report test-exec-report) &optional (count 1)) [METHOD]
---
#### INCREMENT-FAILURE ((test-report test-exec-report) &optional (count 1)) [METHOD]
---
#### ADD-MESSAGE ((test-report test-exec-report) message) [METHOD]
---
#### REPORT-TEST (test-name &optional (suite-name nil) (failure-report-p nil) (message nil)) [FUNCTION]
>
> report-test: reports test result for a unit test
> Arguments: test-name - name of the unit test
> suite-name - test suite where unit test belongs
> failure-report-p - success or failure report?
> message - if failure report additional failure message
---
#### PRINT-RESULT-FOR-TEST (test-name &key suite-name (summary-p t)) [FUNCTION]
>
> print-result-for-test: prints results after running the test
> Arguments: test-name - name of the unit test
> suite-name - name of the test suite (optional)
> summary-p - should display test summary? default
> true Note: reset *global-test-results* once printing is complete
---
#### PRINT-RESULT-FOR-SUITE (suite-name &key (summary-p t)) [FUNCTION]
>
> print-result-for-suite: prints results after running the test suite
> Arguments: suite-name - name of the test suite
> summary-p - should display test summary? default true
> Note: reset *global-test-results* once printing is complete
---
#### PRINT-RESULT-FOR-ALL (&key (summary-p t)) [FUNCTION]
>
> print-result-for-all: prints results after running all the tests
> Arguments: summary-p - should display test summary? default true
> Note: reset *global-test-results* once printing is complete
---
#### CONTINUE-NEXT-TEST (c current-test &optional current-suite) [FUNCTION]
>
> Restart for continue-next-test
---
#### WITH-SUCCESS-FAILURE-HANDLERS ((test-name &key suite-name) &rest forms) [MACRO]
>
> with-success-failure-handlers: short-cut for handler definitions
> Arguments: test-name - unit test
> suite-name - test suite
> forms - Lisp forms that actually executes the unit test
---
#### RUN-TEST (test-name &key in-suite set-up tear-down (print-result-p t)) [FUNCTION]
>
> run-test: runs a unit test
> Arguments: test-name - name of the unit test
> in-suite - name of the test suite
> set-up - set up task needed before running the test
> tear-down - clean up needed after running the test
> print-result-p - need to print test result? default
> true
---
#### RUN-SUITE (suite-name &key set-up tear-down (print-result-p t)) [FUNCTION]
>
> run-suite: runs all unit tests in a test suite
> Arguments: suite-name - name of test suite
> set-up - set up task needed before running all tests
> tear-down - clean up task after all tests are complete
> print-result-p - need to print test result? default
> true
---
#### RUN-ALL (&key set-up tear-down (print-result-p t)) [FUNCTION]
>
> run-all: runs all unit tests in all test suites
> Arguments: set-up - set up task needed before running all tests
> tear-down - clean up task after all tests are complete
> print-result-p - need to print test result? default
> true
---
## Dependency Documentations
### File Dependencies
"/host/santanu/programming/Lisp/simut/src/unit-test-structs.lisp" --> ("/host/santanu/programming/Lisp/simut/src/unit-test-structs.lisp")
### Call Dependencies
#### Function/Macro Calls
SIMUT::PRINT-RESULT-FOR-ALL is referenced by SIMUT:RUN-ALL.
SIMUT::PRINT-RESULT-FOR-SUITE is referenced by SIMUT:RUN-SUITE.
SIMUT::TEST-FN is referenced by SIMUT:RUN-ALL SIMUT:RUN-SUITE.
SIMUT::PRINT-RESULT-FOR-TEST is referenced by SIMUT:RUN-TEST.
SIMUT::TEAR-DOWN is referenced by SIMUT:RUN-ALL SIMUT:RUN-SUITE SIMUT:RUN-TEST.
SIMUT::TEST-NAME is referenced by SIMUT:RUN-TEST.
SIMUT::EXEC-TEST is referenced by SIMUT:RUN-ALL SIMUT:RUN-SUITE SIMUT:RUN-TEST.
SIMUT::CONTINUE-NEXT-TEST is referenced by SIMUT:RUN-ALL SIMUT:RUN-SUITE SIMUT:RUN-TEST.
SIMUT::WITH-SUCCESS-FAILURE-HANDLERS is referenced by SIMUT:RUN-ALL SIMUT:RUN-SUITE SIMUT:RUN-TEST.
SIMUT::SET-UP is referenced by SIMUT:RUN-ALL SIMUT:RUN-SUITE SIMUT:RUN-TEST.
SIMUT::REPORT-TEST is referenced by SIMUT:RUN-ALL SIMUT:RUN-SUITE SIMUT:RUN-TEST SIMUT::CONTINUE-NEXT-TEST.
:UNNAMED-LAMBDA is referenced by SIMUT:RUN-ALL SIMUT:RUN-SUITE SIMUT:RUN-TEST SIMUT::PRINT-RESULT-FOR-ALL.
SIMUT::PRINT-RESULT is referenced by SIMUT::PRINT-RESULT-FOR-ALL SIMUT::PRINT-RESULT-FOR-SUITE SIMUT::PRINT-RESULT-FOR-TEST.
SIMUT::ADD-MESSAGE is referenced by SIMUT::REPORT-TEST.
SIMUT::INCREMENT-SUCCESS is referenced by SIMUT::REPORT-TEST.
SIMUT::INCREMENT-FAILURE is referenced by SIMUT::REPORT-TEST.
SIMUT::TEST-EXEC-REPORT is referenced by SIMUT::REPORT-TEST.
#### Variable Readers
SIMUT::CONTINUE-NEXT-TEST is referenced by SIMUT:RUN-ALL SIMUT:RUN-SUITE SIMUT:RUN-TEST.
SIMUT::TEST-SUCCESS-CONDITION is referenced by SIMUT:RUN-ALL SIMUT:RUN-SUITE SIMUT:RUN-TEST.
SIMUT:\*GLOBAL-TEST-SUITE\* is referenced by SIMUT:RUN-ALL SIMUT:RUN-SUITE SIMUT:RUN-TEST.
SIMUT::ACROSS is referenced by SIMUT::PRINT-RESULT.
SIMUT::FOR is referenced by SIMUT::PRINT-RESULT.
SIMUT:\*GLOBAL-TEST-RESULTS\* is referenced by SIMUT::PRINT-RESULT-FOR-ALL SIMUT::PRINT-RESULT-FOR-SUITE SIMUT::PRINT-RESULT-FOR-TEST SIMUT::PRINT-RESULT SIMUT::REPORT-TEST.
SIMUT::MESSAGES is referenced by SIMUT::PRINT-RESULT SIMUT::ADD-MESSAGE.
SIMUT::MESSAGE is referenced by SIMUT::PRINT-RESULT SIMUT::ADD-MESSAGE.
SIMUT::FAILURE-COUNT is referenced by SIMUT::PRINT-RESULT SIMUT::INCREMENT-FAILURE.
SIMUT::SUCCESS-COUNT is referenced by SIMUT::PRINT-RESULT SIMUT::INCREMENT-SUCCESS.
SIMUT::TEST-REPORT is referenced by SIMUT::ADD-MESSAGE SIMUT::INCREMENT-FAILURE SIMUT::INCREMENT-SUCCESS.
#### Variable Setters
SIMUT::SUITE-NM is referenced by SIMUT:RUN-ALL.
SIMUT::TEST-FN is referenced by SIMUT:RUN-ALL SIMUT:RUN-SUITE.
SIMUT::TEST-NM is referenced by SIMUT:RUN-ALL SIMUT:RUN-SUITE.
SIMUT::SUCCESS-P is referenced by SIMUT:RUN-ALL SIMUT:RUN-SUITE SIMUT:RUN-TEST.
SIMUT::SUITE is referenced by SIMUT:RUN-ALL SIMUT:RUN-SUITE SIMUT:RUN-TEST.
SIMUT::PRINT-RESULT-P is referenced by SIMUT:RUN-ALL SIMUT:RUN-SUITE SIMUT:RUN-TEST.
SIMUT::TEAR-DOWN is referenced by SIMUT:RUN-ALL SIMUT:RUN-SUITE SIMUT:RUN-TEST.
SIMUT::SET-UP is referenced by SIMUT:RUN-ALL SIMUT:RUN-SUITE SIMUT:RUN-TEST.
SIMUT::IN-SUITE is referenced by SIMUT:RUN-TEST.
SIMUT::CURRENT-SUITE is referenced by SIMUT::CONTINUE-NEXT-TEST.
SIMUT::CURRENT-TEST is referenced by SIMUT::CONTINUE-NEXT-TEST.
SIMUT::C is referenced by SIMUT:RUN-ALL SIMUT:RUN-SUITE SIMUT:RUN-TEST SIMUT::CONTINUE-NEXT-TEST.
SIMUT::V is referenced by SIMUT::PRINT-RESULT-FOR-ALL.
SIMUT::K is referenced by SIMUT::PRINT-RESULT-FOR-ALL.
SIMUT::SUMMARY-P is referenced by SIMUT::PRINT-RESULT-FOR-ALL SIMUT::PRINT-RESULT-FOR-SUITE SIMUT::PRINT-RESULT-FOR-TEST.
SIMUT::TEST-RESULT is referenced by SIMUT::PRINT-RESULT.
SIMUT::TOTAL-FAILURE is referenced by SIMUT::PRINT-RESULT-FOR-ALL SIMUT::PRINT-RESULT-FOR-SUITE SIMUT::PRINT-RESULT-FOR-TEST SIMUT::PRINT-RESULT.
SIMUT::TOTAL-SUCCESS is referenced by SIMUT::PRINT-RESULT-FOR-ALL SIMUT::PRINT-RESULT-FOR-SUITE SIMUT::PRINT-RESULT-FOR-TEST SIMUT::PRINT-RESULT.
SIMUT::REPORT-ITEM is referenced by SIMUT::PRINT-RESULT-FOR-ALL SIMUT::PRINT-RESULT-FOR-SUITE SIMUT::PRINT-RESULT-FOR-TEST SIMUT::PRINT-RESULT.
SIMUT::TEST-MESSAGE is referenced by SIMUT::REPORT-TEST.
SIMUT::REPORT-ITEM-NAME is referenced by SIMUT::REPORT-TEST.
SIMUT::FAILURE-REPORT-P is referenced by SIMUT::REPORT-TEST.
SIMUT::SUITE-NAME is referenced by SIMUT:RUN-ALL SIMUT:RUN-SUITE SIMUT::PRINT-RESULT-FOR-SUITE SIMUT::PRINT-RESULT-FOR-TEST SIMUT::REPORT-TEST.
SIMUT::MESSAGE is referenced by SIMUT::REPORT-TEST SIMUT::ADD-MESSAGE.
SIMUT::TEST-REPORT is referenced by SIMUT::REPORT-TEST SIMUT::ADD-MESSAGE SIMUT::INCREMENT-FAILURE SIMUT::INCREMENT-SUCCESS.
SIMUT::UNIT-TEST is referenced by SIMUT::EXEC-TEST.
SIMUT::TEST-NAME is referenced by SIMUT:RUN-ALL SIMUT:RUN-SUITE SIMUT:RUN-TEST SIMUT::PRINT-RESULT-FOR-TEST SIMUT::REPORT-TEST SIMUT:CREATE-UNIT-TEST.
SIMUT::FORMS is referenced by SIMUT:CREATE-FIXTURE.
SIMUT::FIXTURE-NAME is referenced by SIMUT:CREATE-FIXTURE.
| 10,819 | Common Lisp | .l | 196 | 53.086735 | 173 | 0.695052 | foss-santanu/simut | 1 | 0 | 0 | GPL-2.0 | 9/19/2024, 11:28:28 AM (Europe/Amsterdam) | 0f89d8a37ef24825d34d687c373408479d6c3554341ed51aa77165a8d8604074 | 25,701 | [
-1
] |
25,718 | day3.lisp | paul-jewell_advent-of-code-2020/2020/lisp/day3.lisp | (in-package #:day3)
(defparameter day3-input "~/Projects/advent-of-code-2020/input/day3-input.txt")
(defun parse-line (tree-line)
(coerce tree-line 'list))
(defparameter tree-lines (mapcar #'parse-line (uiop:read-file-lines day3-input)))
(defparameter trees (make-array (list (length tree-lines) (length (first tree-lines)))
:initial-contents tree-lines))
(defun tree-count (dr dc)
(loop :for r :below (first (array-dimensions trees)) :by dr
:for c :from 0 :by dc
:count (char= (aref trees r (mod c 31)) #\#)))
(defun solution1 ()
(tree-count 1 3))
(defun solution2 ()
(* (tree-count 1 1)
(tree-count 1 3)
(tree-count 1 5)
(tree-count 1 7)
(tree-count 2 1)))
| 742 | Common Lisp | .lisp | 19 | 33.684211 | 86 | 0.639665 | paul-jewell/advent-of-code-2020 | 1 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:28:28 AM (Europe/Amsterdam) | 8c89aa3513d837bb06995d51f1c5d827b524ca8f7ceae9cb68fb4ca3e6c2c684 | 25,718 | [
-1
] |
25,719 | day12.lisp | paul-jewell_advent-of-code-2020/2020/lisp/day12.lisp | (in-package :day12)
(defparameter day12-input "~/Projects/advent-of-code-2020/input/day12-input.txt")
(defparameter day12-test-input "~/Projects/advent-of-code-2020/input/day12-test-input.txt")
(defparameter +cardinals+ '((north 0) (east 90) (south 180) (west 270)))
(defparameter *part1-actions* '((N . n1)
(S . S1)
(E . E1)
(W . W1)
(L . L1)
(R . R1)
(F . F1)))
(defstruct ship
(course 'east)
(position (list 0 0))
(waypoint (list 10 1)))
(defun action-or-error1 (action-str)
(let ((action (assoc action-str *part1-actions* :test #'string-equal)))
(unless action
(error "unknown action ~A" action-str))
(cdr action)))
(defun parse-command (command)
(list (action-or-error1 (subseq command 0 1))
(parse-integer (subseq command 1))))
(defun move (boat val &optional (direction (ship-course boat)))
(ecase direction
(north (setf (cadr (ship-position boat)) (+ (cadr (ship-position boat)) val)))
(east (setf (car (ship-position boat)) (+ (car (ship-position boat)) val)))
(south (setf (cadr (ship-position boat)) (- (cadr (ship-position boat)) val)))
(west (setf (car (ship-position boat)) (- (car (ship-position boat)) val)))))
(defun F1 (boat val)
(move boat val))
(defun N1 (boat val)
(move boat val 'north))
(defun E1 (boat val)
(move boat val 'east))
(defun S1 (boat val)
(move boat val 'south))
(defun W1 (boat val)
(move boat val 'west))
(defun R1 (boat val)
(let* ((course (cadr (find (ship-course boat) +cardinals+ :key #'car)))
(new-course (mod (+ course val) 360)))
(setf (ship-course boat)
(car (find new-course +cardinals+ :key #'cadr)))))
(defun L1 (boat val)
(R1 boat (- val)))
(defun manhattan-distance (boat)
(+ (abs (car (ship-position boat)))
(abs (cadr (ship-position boat)))))
(defun part1 (file)
(let ((ferry (make-ship))
(commands (mapcar #'parse-command (uiop:read-file-lines file))))
(loop :for command in commands
do (funcall (car command) ferry (cadr command)))
(manhattan-distance ferry)))
(defun test1 ()
(part1 day12-test-input))
(defun solution1 ()
(part1 day12-input))
(defparameter *part2-actions* '((N . N2)
(S . S2)
(E . E2)
(W . W2)
(L . L2)
(R . R2)
(F . F2)))
(defun action-or-error2 (action-str)
(let ((action (assoc action-str *part2-actions* :test #'string-equal)))
(unless action
(error "unknown action ~A" action-str))
(cdr action)))
(defun parse-command2 (command)
(list (action-or-error2 (subseq command 0 1))
(parse-integer (subseq command 1))))
;; Waypoint moving functions
(defun N2 (boat val)
(setf (cadr (ship-waypoint boat)) (+ (cadr (ship-waypoint boat)) val)))
(defun S2 (boat val)
(N2 boat (- val)))
(defun E2 (boat val)
(setf (car (ship-waypoint boat)) (+ (car (ship-waypoint boat)) val)))
(defun W2 (boat val)
(E2 boat (- val)))
;; Rotation of vector:
;; x2 = sin(a).x1 - cos(a).y1
;; y2 = cos(a).y1 + sin(a).x1
(defun dsin (angle)
(sin (* (* 2 pi) (/ angle 360))))
(defun dcos (angle)
(cos (* (/ angle 360) (* 2.0 pi))))
(defparameter +mult+ '((-270 1 0)
(-180 0 -1)
(-90 -1 0)
(0 0 1)
(90 1 0)
(180 0 -1)
(270 -1 0)))
(defun L2 (boat angle)
(let ((sin-a (cadr (assoc angle +mult+)))
(cos-a (caddr (assoc angle +mult+)))
(x1 (car (ship-waypoint boat)))
(y1 (cadr (ship-waypoint boat))))
(setf (car (ship-waypoint boat)) (- (* cos-a x1) (* sin-a y1)))
(setf (cadr (ship-waypoint boat)) (+ (* sin-a x1) (* cos-a y1)))))
(defun R2 (boat angle)
(L2 boat (- angle)))
;; Move ship to waypoint n times
(defun F2 (boat val)
(setf (ship-position boat)
(mapcar #'+
(ship-position boat)
(mapcar (lambda (x)
(* val x))
(ship-waypoint boat)))))
(defun part2 (file)
(let ((ferry (make-ship))
(commands (mapcar #'parse-command2 (uiop:read-file-lines file))))
(loop :for command in commands
do (funcall (car command) ferry (cadr command)))
(manhattan-distance ferry)))
(defun test2 ()
(part2 day12-test-input))
(defun solution2 ()
(part2 day12-input))
| 4,681 | Common Lisp | .lisp | 124 | 29.604839 | 91 | 0.549215 | paul-jewell/advent-of-code-2020 | 1 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:28:28 AM (Europe/Amsterdam) | 2e8b5c9f14ec238732625dafbf3ec5a84ac9b8a7c50fe3f7e01f677aa59eb343 | 25,719 | [
-1
] |
25,720 | day16.lisp | paul-jewell_advent-of-code-2020/2020/lisp/day16.lisp | (in-package :day16)
(defparameter input "~/Projects/advent-of-code-2020/input/day16-input.txt")
(defparameter test-input "~/Projects/advent-of-code-2020/input/day16-test-input.txt")
(defparameter test-input-2 "~/Projects/advent-of-code-2020/input/day16-test-input-2.txt")
(defun parse-rule (rule-str)
(let* ((pos-colon (position #\: rule-str))
(ranges (subseq rule-str (+ 2 pos-colon)))
(range-strs (mapcar (lambda (s) (split "\-" s)) (split " or " ranges))))
(mapcar (lambda (r) (mapcar #'parse-integer r)) range-strs)))
(defun parse-input (file)
(let* ((data (split "\\n\\n" (uiop:read-file-string file)))
(rules (mapcar #'parse-rule (split "\\n" (first data))))
(my-ticket (mapcar 'parse-integer (split "," (second (split "\\n" (second data))))))
(near-tickets (mapcar (lambda (v)
(mapcar #'parse-integer (split #\, v)))
(cdr (split "\\n" (third data))))))
(list rules my-ticket near-tickets)))
;; Check if value is in the supplied ranges
(defun value-in-range-p (value &rest ranges)
(some (lambda (range) (<= (car range) value (cadr range))) ranges))
;; Remove all ticket values which are valid
(defun remove-valid-values (ranges ticket)
(remove-if (lambda (ticket-val)
(notevery 'null
(mapcar (lambda (range)
(apply #'value-in-range-p ticket-val range))
ranges)))
ticket))
;; Find all the invalid values in the tickets
(defun invalid-values (ranges tickets)
(apply #'nconc (mapcar (lambda (ticket) (remove-valid-values ranges ticket)) tickets)))
(defun part1 (file)
(let* ((data (parse-input file))
(ranges (first data))
(tickets (third data)))
(apply #'+ (invalid-values ranges tickets))))
(defun test1 ()
(part1 test-input))
(defun solution1 ()
(part1 input))
(defun check-ticket-p (ranges ticket)
(notevery #'null (mapcar (lambda (ticket-val)
(every 'null
(mapcar (lambda (r) (apply #'value-in-range-p ticket-val r))
ranges)))
ticket)))
(defun r-intersection (current others)
(if (null others)
current
(r-intersection (intersection current (car others)) (cdr others))))
(defun check-tickets (ranges tickets)
(remove-if (lambda (ticket) (check-ticket-p ranges ticket)) tickets))
(defun check-range (range tickets)
(loop :for ticket :in tickets
:collect (loop :for i :upto (1- (length ticket))
:if (apply 'value-in-range-p (nth i ticket) range)
:collect i)))
(defun check-ranges (ranges tickets)
(loop :for r :in ranges
:for res := (check-range r tickets)
:collect (r-intersection (car res) (cdr res))))
(defun match-range (iterations result)
(if (= 0 iterations)
result
(match-range (1- iterations)
(loop :for i upto (1- (length result))
:for r := (nth i result)
:if (and (listp r) (= 1 (length r)))
:nconc (nconc (mapcar (lambda (s)
(if (listp s)
(remove (car r) s)
s))
(subseq result 0 i))
r
(mapcar (lambda (s)
(if (listp s)
(remove (car r) s)
s))
(subseq result (1+ i))))))))
(defun part2 (file)
(let* ((data (parse-input file))
(rules (first data))
(my-ticket (second data))
(tickets (third data))
(ranges (check-ranges rules (check-tickets rules tickets))))
(apply '* (subseq (loop :for n :in (match-range (length ranges) ranges)
:collect (nth n my-ticket))
0 6))))
(defun solution2 ()
(part2 input))
| 4,344 | Common Lisp | .lisp | 90 | 33.6 | 96 | 0.504721 | paul-jewell/advent-of-code-2020 | 1 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:28:28 AM (Europe/Amsterdam) | a4e9f5de72417d745e308ef793fac88f14e5219b278bf6118add19a033b2b40e | 25,720 | [
-1
] |
25,721 | package.lisp | paul-jewell_advent-of-code-2020/2020/lisp/package.lisp | ;;;; package.lisp
(defpackage #:day1
(:use #:cl
#:cl-ppcre)
(:export solution1
solution2))
(defpackage #:day2
(:use #:cl
#:cl-ppcre)
(:export solution1
solution2))
(defpackage #:day3
(:use #:cl
#:cl-ppcre)
(:export solution1
solution2))
(defpackage #:day4
(:use #:cl
#:cl-ppcre)
(:export test1
solution1
test2
solution2))
(defpackage #:day5
(:use #:cl
#:cl-ppcre)
(:export test1
solution1
solution2))
(defpackage #:day6
(:use #:cl
#:cl-ppcre)
(:export test1
solution1
test2
solution2))
(defpackage #:day7
(:use #:cl
#:cl-ppcre)
(:export test1
solution1
test2
solution2))
(defpackage #:day8
(:use #:cl
#:cl-ppcre)
(:export test1
solution1
test2
solution2))
(defpackage #:day9
(:use #:cl
#:cl-ppcre)
(:export test1
solution1
test2
solution2))
(defpackage #:day10
(:use #:cl
#:cl-ppcre
#:org.tfeb.hax.memoize)
(:export test1
test2
solution1
test3
test4
solution2))
(defpackage #:day11
(:use #:cl
#:cl-ppcre)
(:export test1
solution1
test2
solution2))
(defpackage #:day12
(:use #:cl
#:cl-ppcre)
(:export test1
solution1
test2
solution2))
(defpackage #:day13
(:use #:cl
#:cl-ppcre)
(:export test1
solution1
test2
solution2))
(defpackage #:day14
(:use #:cl
#:cl-ppcre)
(:export test1
solution1
test2
solution2))
(defpackage #:day15
(:use #:cl
#:cl-ppcre)
(:export test1
solution1
test2
solution2))
(defpackage #:day16
(:use #:cl
#:cl-ppcre)
(:export test1
solution1
solution2))
(defpackage #:day17
(:use #:cl)
(:export test1
solution1
test2
solution2))
(defpackage #:day18
(:use #:cl
#:cl-ppcre)
(:export test1
test2
test3
test4
solution1
solution2))
(defpackage #:day19
(:use #:cl
#:cl-ppcre)
(:export test1
solution1
test2
solution2))
(defpackage #:day20
(:use #:cl
#:cl-ppcre)
(:export test1
solution1))
| 2,555 | Common Lisp | .lisp | 135 | 11.6 | 31 | 0.499167 | paul-jewell/advent-of-code-2020 | 1 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:28:28 AM (Europe/Amsterdam) | 2878a2809ea1039e51b0607784e7e5432b295eece6842c04c0f0f6c89f038d72 | 25,721 | [
-1
] |
25,722 | day13.lisp | paul-jewell_advent-of-code-2020/2020/lisp/day13.lisp | (in-package :day13)
(defparameter day13-test-input "~/Projects/advent-of-code-2020/input/day13-test-input.txt")
(defparameter day13-input "~/Projects/advent-of-code-2020/input/day13-input.txt")
(defun parse-input (file)
(let* ((input (uiop:read-file-lines file))
(start-time (parse-integer (car input)))
(buses (mapcar #'parse-integer
(remove-if (lambda (s) (string= s "x"))
(split #\, (cadr input))))))
(list start-time buses)))
;; This routine was written because I didn't know the function position existed!
;; An alternative approach is to find the minimum bus in the list:
;; (let ((next-bus-time (mapcar (lambda (x) (- x (rem (car input) x))) (second (input)))))
;; and then find the position (ie which bus has this minimum wait):
;; (position (apply 'min next-bus-time) next-bus-time)
(defun earliest-bus (buses &optional (min nil) (result nil))
(if (null buses)
result
(if (or (null min) (< (reduce '* (car buses)) min))
(earliest-bus (cdr buses) (reduce '* (car buses)) (car buses))
(earliest-bus (cdr buses) min result))))
(defun part1 (file)
(let* ((input (parse-input file))
(bus-times (mapcar (lambda (x) (list x (ceiling (/ (car input) x))))
(cadr input)))
(my-bus (earliest-bus bus-times)))
(* (car my-bus) (- (reduce '* my-bus) ;; bus arrival time
(car input))))) ;; my arrival time
(defun test1 ()
(part1 day13-test-input))
(defun solution1 ()
(part1 day13-input))
(defun parse-input2 (file)
(mapcar (lambda (s) (parse-integer s :junk-allowed t)) (split #\, (cadr (uiop:read-file-lines file)))))
(defun get-timestamp (timestamp increment buses)
(cond ((null buses) timestamp) ;; No buses left to process
((null (car buses)) (get-timestamp (+ timestamp 1) increment (cdr buses))) ;; no bus here
((= 0 (rem timestamp (car buses))) ;; Current bus works for this timestamp
(get-timestamp (+ timestamp 1) (lcm increment (car buses)) (cdr buses))) ;; check remaining buses
(t (get-timestamp (+ timestamp increment) increment buses)))) ;; Check next timestamp
(defun part2 (file)
(let ((input (parse-input2 file)))
(- (get-timestamp (car input) 1 input) (length input))))
(defun test2 ()
(part2 day13-test-input))
(defun solution2 ()
(part2 day13-input))
| 2,425 | Common Lisp | .lisp | 47 | 45.212766 | 106 | 0.628596 | paul-jewell/advent-of-code-2020 | 1 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:28:28 AM (Europe/Amsterdam) | e85cf2660b7347d343fd60fb682bce0d869cc9329328dd2ffdd287620a4fb372 | 25,722 | [
-1
] |
25,723 | day5.lisp | paul-jewell_advent-of-code-2020/2020/lisp/day5.lisp | (in-package :day5)
(defparameter day5-input "~/Projects/advent-of-code-2020/input/day5-input.txt")
(defparameter boarding-passes (uiop:read-file-lines day5-input))
(defparameter day5-test-input-1 "~/Projects/advent-of-code-2020/input/day5-test-input-1.txt")
(defparameter test-boarding-passes (uiop:read-file-lines day5-test-input-1))
;; The boarding pass is essentially a binary representation, so using this information, we can
;; simplify the process of finding the seat-id
;; - This was seen in the video from Mike Zemanski: https://www.youtube.com/watch?v=I8dbKJ_315Q
;; although he is coding in clojure. Thanks Mike, and those commenters who pointed this out to him!
(defun seat-id (boarding-pass)
(let ((vals '((#\B 1) (#\F 0) (#\R 1) (#\L 0))))
(loop :for i :from 0
:for c in (mapcar #'(lambda (c) (cadr (assoc c vals))) (reverse (coerce boarding-pass 'list)))
:sum (* (expt 2 i) c))))
(defun test1 ()
(apply #'max (mapcar #'seat-id test-boarding-passes)))
(defun solution1 ()
(apply #'max (mapcar #'seat-id boarding-passes)))
(defun solution2 ()
(let* ((passes (sort (mapcar #'seat-id boarding-passes) #'<))
(min-seat-id (apply #'min passes))
(max-seat-id (apply #'max passes)))
(loop :for i :upfrom min-seat-id :to max-seat-id
:when (not (find i passes))
return i)))
| 1,359 | Common Lisp | .lisp | 25 | 50.16 | 104 | 0.675452 | paul-jewell/advent-of-code-2020 | 1 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:28:28 AM (Europe/Amsterdam) | 15f4a20546e5d5b36ea99a51f469b59283f7b4f1c8f997f3ef4de375fe0bc09e | 25,723 | [
-1
] |
25,724 | day6.lisp | paul-jewell_advent-of-code-2020/2020/lisp/day6.lisp | (in-package :day6)
(defparameter day6-test-input "~/Projects/advent-of-code-2020/input/day6-test-input.txt")
(defparameter day6-input "~/Projects/advent-of-code-2020/input/day6-input.txt")
(defun count-yes (response)
(length (remove-duplicates
(remove-if #'(lambda (c)
(char= c #\newline))
(coerce response 'list)))))
(defun sol1 (input-file)
(apply #'+ (mapcar #'count-yes
(mapcar #'(lambda (s)
(coerce s 'list))
(split "\\n\\n" (uiop:read-file-string input-file))))))
(defun test1 ()
(sol1 day6-test-input))
(defun solution1 ()
(sol1 day6-input))
(defun common-response-count (response-list)
(length (if (= (length response-list) 1)
(car response-list)
(reduce #'intersection response-list))))
(defun sol2 (input-file)
(apply #'+
(mapcar 'common-response-count
(mapcar #'(lambda (group)
(mapcar #'(lambda (element)
(coerce element 'list))
group))
(mapcar #'(lambda (s)
(split "\\n" s))
(split "\\n\\n" (uiop:read-file-string input-file)))))))
(defun test2 ()
(sol2 day6-test-input))
(defun solution2 ()
(sol2 day6-input))
| 1,450 | Common Lisp | .lisp | 35 | 28.257143 | 89 | 0.501425 | paul-jewell/advent-of-code-2020 | 1 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:28:28 AM (Europe/Amsterdam) | 5b1a14ddfeb498bd6007c007170d628bdc89607726dad2215770b64b9cfb8c01 | 25,724 | [
-1
] |
25,725 | day19.lisp | paul-jewell_advent-of-code-2020/2020/lisp/day19.lisp | (in-package :day19)
(defparameter day19-test-input "~/Projects/advent-of-code-2020/input/day19-test-input.txt")
(defparameter day19-test-input2 "~/Projects/advent-of-code-2020/input/day19-test-input2.txt")
(defparameter day19-input "~/Projects/advent-of-code-2020/input/day19-input.txt")
;; These three functions need to be refactored / clarified
(defun parse-rule-body (str)
(if (char= #\" (aref str 0))
(aref str 1)
(prb-helper (split " " str) nil nil)))
(defun prb-helper (rules lst sublst)
(cond ((null rules) (reverse (cons (reverse sublst) lst)))
((char= #\| (aref (car rules) 0)) (prb-helper (cdr rules) (cons (reverse sublst) lst) nil))
(t (prb-helper (cdr rules) lst (cons (parse-integer (car rules)) sublst)))))
(defun read-rules (stream)
(multiple-value-bind (is-valid matches)
(scan-to-strings "^(\\d+): (.+)$" (read-line stream))
(when is-valid
(let
((rule-num (parse-integer (aref matches 0)))
(rule-body (parse-rule-body (aref matches 1))))
(cons (cons rule-num rule-body)
(read-rules stream))))))
(defun check-rule-seq (message rules-arr rule-seq)
"Check MESSAGE is valid against RULE-SEQ.
Input to this function should be a list of rules to be checked in
sequence. eg - '(1 2 3)"
(cond
((equal message 'invalid) (list message))
((null rule-seq) (list message)) ;If no rule sequence to check, return the message.
((null message) (list 'invalid))
(t (let ((result-lst (check-rule (list message) rules-arr (car rule-seq))))
(loop :for msg in result-lst
:append (check-rule-seq msg rules-arr (cdr rule-seq)))))))
(defun check-rule (message-lst rules-arr rule)
"Check each message in MESSAGE-LST against RULE, defined in RULE-ARR.
Return the list of results."
(let ((rules (aref rules-arr rule))) ;; Decompose the rule into constituent parts
(loop :for message in message-lst
:with result-lst
:do (cond
((equal 'invalid message) (push 'invalid result-lst))
((null message) (push 'invalid result-lst)) ; No more message, but rules still exist to satisfy
((characterp rules) ; This rule is a letter
(push (if (equal rules (car message))
(cdr message)
'invalid)
result-lst))
(t (loop :for rule-seq in rules
:do (setq result-lst (append (check-rule-seq message rules-arr rule-seq) result-lst)))))
:finally (return result-lst))))
(defun check (rules message)
(some #'null (check-rule (list message) rules 0)))
(defun parse-input (file)
(let* ((stream (open file))
(rules-lst (read-rules stream))
(rules
(loop :with array := (make-array (1+ (reduce #'max rules-lst :key #'car)))
:for r in rules-lst
:do (setf (aref array (car r)) (cdr r))
:finally (return array)))
(messages
(loop :for str := (read-line stream nil)
:while str
:collect (coerce str 'list))))
(list rules messages)))
(defun part1 (file)
(let* ((input (parse-input file))
(rules (first input))
(messages (second input)))
(count 't (mapcar (lambda (m) (check rules m)) messages))))
(defun test1 ()
(part1 day19-test-input))
(defun solution1 ()
(part1 day19-input))
;;======================================================================
;; Part 2
;;----------------------------------------------------------------------
(defun part2 (file)
(let* ((input (parse-input file))
(rules (first input))
(messages (second input)))
;; Modify rules 8 and 11 as described:
(setf (aref rules 8) '((42) (42 8)))
(setf (aref rules 11) '((42 31) (42 11 31)))
(count 't (mapcar (lambda (m) (check rules m)) messages))))
(defun test2 ()
(part2 day19-test-input2))
(defun solution2 ()
(part2 day19-input))
| 4,096 | Common Lisp | .lisp | 89 | 37.876404 | 116 | 0.577482 | paul-jewell/advent-of-code-2020 | 1 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:28:28 AM (Europe/Amsterdam) | 4976dacb802adc2d387d6ae8c3f1f14e25bd0a894beab4e76c4a1d39456fa969 | 25,725 | [
-1
] |
25,726 | day17.lisp | paul-jewell_advent-of-code-2020/2020/lisp/day17.lisp | (in-package #:day17)
(defparameter input "~/Projects/advent-of-code-2020/input/day17-input.txt")
(defparameter test-input "~/Projects/advent-of-code-2020/input/day17-test-input.txt")
;; Design choices
;; --------------
;; Initial array is 2 dimensional, and represents the layer in the middle of the
;; cube. Each iteration will grow the array in all 6 directions by 1. I could start
;; with an array sized to accommodate the full cube after the defined number of cycles
;; but optimise the calculations in each cycle to match the affected region in the cube.
;; For part 1, I don't expect this to be a signficant issue, but we will see what part
;; 2 brings.
;; TODO: Revisit logic for this - may be better to build the new array for each iteration
;; during processing
(defun expand-layer (size initial-state)
"Build and return a layer of inactive cells around the initial state."
(let* ((initial-size (length initial-state))
(side-padding (make-list size :initial-element #\.))
(row-padding (make-list (+ (* 2 size) initial-size) :initial-element #\.)))
(loop :for i :below (+ initial-size (* size 2))
:if (or (< i size)
(>= i (+ size initial-size)))
:append (list row-padding)
:else
:append (list (append side-padding
(nth (- i size) initial-state)
side-padding)))))
(defun build-3d-cube (size initial-state)
(let* ((new-size (+ (* size 2) (length initial-state)))
(layer-padding (loop :for i :below new-size
:append (list (make-list new-size :initial-element #\.)))))
;; looping through z axis. Initial state is two dimensional, so need to added
;; SIZE layers above and below the layer with the initial content.
(loop :for i :below (+ (* size 2) (length (car initial-state)))
:if (= i (ceiling (+ size (/ (length (car initial-state))))))
:append (list (expand-layer size initial-state))
:else
:append (list layer-padding))))
(defun new-state (cube x y z)
(let* ((state (aref cube x y z))
(max-size (1- (car (array-dimensions cube))))
(x-min (max (- x 1) 0))
(x-max (min (+ x 1) max-size))
(y-min (max (- y 1) 0))
(y-max (min (+ y 1) max-size))
(z-min (max (- z 1) 0))
(z-max (min (+ z 1) max-size))
(count-active (- (loop :for x :from x-min :to x-max
:sum (loop :for y :from y-min :to y-max
:sum (loop :for z from z-min :to z-max
:count (char= (aref cube x y z) #\#))))
(if (char= state #\#) ; Subtract candidate from sum if active
1 0))))
(if (char= state #\#)
(if (<= 2 count-active 3) #\# #\.) ; Already active - stay active if 2 or 3 around
(if (= 3 count-active) #\# #\.)))) ; Become active if exactly 3
(defun process-3d-step (cube moves)
(if (= 0 moves)
cube
(let* ((cube-size (car (array-dimensions cube)))
(new-cube (make-array (array-dimensions cube)
:initial-element #\.)))
(loop :for x :below cube-size
:do (loop :for y :below cube-size
:do (loop :for z :below cube-size
:do (setf (aref new-cube x y z) (new-state cube x y z)))))
(process-3d-step new-cube (1- moves)))))
(defun count-active (cube)
(count #\# (make-array (array-total-size cube) :displaced-to cube)))
(defun part1 (file moves)
(let* ((initial-state (mapcar (lambda (s) (coerce s 'list)) (uiop:read-file-lines file)))
(expanded-data (build-3d-cube moves initial-state))
(size (length (car expanded-data)))
(cube (make-array (list size size size) :initial-contents expanded-data)))
(let ((cube (process-3d-step cube moves)))
(count-active cube))
))
(defun test1 ()
(part1 test-input 6))
(defun solution1 ()
(part1 input 6))
(defun build-4d-cube (size initial-state)
(let* ((new-size (+ (* size 2) (length initial-state)))
(layer-padding (make-list new-size
:initial-element
(make-list new-size :initial-element #\.))))
(loop
:for z :below new-size
:append (list (loop
:for w below new-size
:if (and (= w size) (= z size))
:append (list (expand-layer size initial-state))
:else
:append (list layer-padding))))))
(defun new-4d-state (cube x y z w)
(let* ((state (aref cube x y z w))
(max-size (1- (car (array-dimensions cube))))
(x-min (max (- x 1) 0))
(x-max (min (+ x 1) max-size))
(y-min (max (- y 1) 0))
(y-max (min (+ y 1) max-size))
(z-min (max (- z 1) 0))
(z-max (min (+ z 1) max-size))
(w-min (max (- w 1) 0))
(w-max (min (+ w 1) max-size))
(count-active (- (loop
:for x :from x-min :to x-max
:sum (loop
:for y :from y-min :to y-max
:sum (loop
:for z :from z-min :to z-max
:sum (loop :for w :from w-min :to w-max
:count (char= (aref cube x y z w) #\#)))))
(if (char= state #\#) ; Subtract candidate from sum if active
1 0))))
(if (char= state #\#)
(if (<= 2 count-active 3) #\# #\.) ; Already active - stay active if 2 or 3 around
(if (= 3 count-active) #\# #\.)))) ; Become active if exactly 3
(defun process-4d-step (cube moves)
(if (= 0 moves)
cube
(let* ((cube-size (car (array-dimensions cube)))
(new-cube (make-array (array-dimensions cube)
:initial-element #\.)))
(loop
:for x :below cube-size
:do (loop
:for y :below cube-size
:do (loop
:for z :below cube-size
:do (loop
:for w :below cube-size
:do (setf (aref new-cube x y z w) (new-4d-state cube x y z w))))))
(process-4d-step new-cube (1- moves)))))
(defun part2 (file moves)
(let* ((initial-state (mapcar (lambda (s) (coerce s 'list)) (uiop:read-file-lines file)))
(expanded-data (build-4d-cube moves initial-state))
(size (length (car expanded-data)))
(cube (make-array (list size size size size) :initial-contents expanded-data)))
(count-active (process-4d-step cube moves))))
(defun test2 ()
(part2 test-input 6))
(defun solution2 ()
(part2 input 6))
| 7,108 | Common Lisp | .lisp | 143 | 37.006993 | 96 | 0.514541 | paul-jewell/advent-of-code-2020 | 1 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:28:28 AM (Europe/Amsterdam) | 4f05bd8cfb722a50a9e834222623cd6f3d94db0c1444831a36b4ba476ad77f43 | 25,726 | [
-1
] |
25,727 | day4.lisp | paul-jewell_advent-of-code-2020/2020/lisp/day4.lisp | (in-package :day4)
(defparameter day4-test-input-1 "~/Projects/advent-of-code-2020/input/day4-test-input.txt")
;; Test input 2 containts 4 valid and 4 invalid passports according to part 2 criteria
(defparameter day4-test-input-2 "~/Projects/advent-of-code-2020/input/day4-test-input-2.txt")
(defparameter day4-input "~/Projects/advent-of-code-2020/input/day4-input.txt")
(defun read-passports (passport-file)
(split "\\n\\n" (uiop:read-file-string passport-file)))
(defun passport-valid-1-p (passport)
(let ((fields-in-passport (loop :for field :in (split "\\s" passport)
:collect (first (split ":" field)))))
(every (lambda (f)
(find f fields-in-passport :test #'string=))
'("byr" "iyr" "eyr" "hgt" "hcl" "ecl" "pid"))))
;;; Additional validation functions for solution 2
(defun validate-date-p (date-str min max)
(<= min (parse-integer date-str) max))
(defun validate-height-p (hgt)
(let* ((unit-pos (- (length hgt) 2))
(unit (subseq hgt unit-pos))
(height (parse-integer (subseq hgt 0 unit-pos))))
(cond
((equal unit "in") (<= 59 height 76))
((equal unit "cm") (<= 150 height 193))
(T nil))))
(defun validate-eye-colour-p (ecl)
(find ecl '("amb" "blu" "brn" "gry" "grn" "hzl" "oth") :test #'string=))
(defun validate-hair-colour-p (hcl)
(scan "^#[a-f0-9]{6}$" hcl))
(defun validate-passport-id-p (pid)
(scan "^\\d{9}$" pid))
(defun passport-valid-2-p (passport-str)
(let ((passport (make-hash-table :test 'equal)))
(loop :for (key . value) :in (mapcar (lambda (f)
(split ":" f))
(split "\\s" passport-str))
:do (setf (gethash key passport) (first value)))
(and (passport-valid-1-p passport-str)
(validate-date-p (gethash "byr" passport) 1920 2002)
(validate-date-p (gethash "iyr" passport) 2010 2020)
(validate-date-p (gethash "eyr" passport) 2020 2030)
(validate-height-p (gethash "hgt" passport))
(validate-hair-colour-p (gethash "hcl" passport))
(validate-eye-colour-p (gethash "ecl" passport))
(validate-passport-id-p (gethash "pid" passport)))))
(defun test1 ()
(count-if #'passport-valid-1-p (read-passports day4-test-input-1)))
(defun solution1 ()
(count-if #'passport-valid-1-p (read-passports day4-input)))
(defun test2 ()
(count-if #'passport-valid-2-p (read-passports day4-test-input-2)))
(defun solution2 ()
(count-if #'passport-valid-2-p (read-passports day4-input)))
| 2,587 | Common Lisp | .lisp | 52 | 42.942308 | 93 | 0.625 | paul-jewell/advent-of-code-2020 | 1 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:28:28 AM (Europe/Amsterdam) | 6ccd83d54eeea068626f4aa671adb22e0e998d2ec641084201a36fd8877dc893 | 25,727 | [
-1
] |
25,728 | day15.lisp | paul-jewell_advent-of-code-2020/2020/lisp/day15.lisp | (in-package :day15)
(defparameter input '(12 1 16 3 11 0))
(defparameter test-input '(0 3 6))
(defvar memory)
(defun load-initial-data (data)
(loop :for turn :from 1
:for value :in data
:do (setf (gethash value memory) turn)))
(defun compute-next-number (num turn end)
(cond ((= turn end) num)
((null (gethash num memory)) (setf (gethash num memory) turn)(compute-next-number 0 (1+ turn) end))
(t (let ((next (- turn (gethash num memory))))
(setf (gethash num memory) turn) (compute-next-number next (1+ turn) end)))))
(defun solution (input end)
(setq memory (make-hash-table))
(load-initial-data input)
(compute-next-number 0 (1+ (hash-table-count memory)) end))
(defun test1 ()
(solution test-input 2020))
(defun solution1 ()
(solution input 2020))
(defun test2 ()
(solution test-input 30000000))
(defun solution2 ()
(solution input 30000000))
| 920 | Common Lisp | .lisp | 25 | 32.88 | 107 | 0.670056 | paul-jewell/advent-of-code-2020 | 1 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:28:28 AM (Europe/Amsterdam) | 0d58fd1e9f3b9186391c0cf06ddc0e8fc4c644225987dff7018f333644edd2db | 25,728 | [
-1
] |
25,729 | day14.lisp | paul-jewell_advent-of-code-2020/2020/lisp/day14.lisp | (in-package :day14)
(defparameter day14-input "~/Projects/advent-of-code-2020/input/day14-input.txt")
(defparameter day14-test-input "~/Projects/advent-of-code-2020/input/day14-test-input.txt")
(defparameter day14-test-input-2 "~/Projects/advent-of-code-2020/input/day14-test-input-2.txt")
(defstruct d-comp
code
(mask nil)
(PC 0)
(memory (make-hash-table)))
(defun new-value (value mask)
(parse-integer (coerce (loop :for m in (coerce mask 'list)
:for v in (coerce (format nil "~36,'0B" value) 'list)
:collect (if (char= m #\X) v m))
'string)
:radix 2))
(defun parse-input (file)
(let ((input (uiop:read-file-lines file)))
(loop :for line :in input
:collect (split " = " line))))
(defun run-program (computer)
(loop :for (opcode . operand) :in (d-comp-code computer)
:do (cond ((string= opcode "mask") (setf (d-comp-mask computer) (car operand)))
(T (let ((mem-location (parse-integer (subseq opcode 4) :junk-allowed T))
(masked-value (new-value (parse-integer (car operand)) (d-comp-mask computer))))
(setf (gethash mem-location (d-comp-memory computer)) masked-value)))))
computer)
(defun part1 (file)
(let ((computer (make-d-comp :code (parse-input file))))
(run-program computer)
(loop :for v :being :the :hash-values :of (d-comp-memory computer)
:sum v)))
(defun test1 ()
(part1 day14-test-input))
(defun solution1 ()
(part1 day14-input))
;; Mask and address are already lists...
(defun store-val (computer mask address value &optional (index 0))
(if (= (length mask) index)
(setf (gethash (parse-integer (coerce address 'string)) (d-comp-memory computer)) value)
(cond
((char= #\0 (nth index mask)) ;; address value remains
(store-val computer mask address value (1+ index)))
((char= #\1 (nth index mask)) ;; address value set to 1
(store-val computer
mask
(nconc (subseq address 0 index) (list #\1) (nthcdr (+ index 1) address))
value
(1+ index)))
((char= #\X (nth index mask))
(progn (store-val computer
mask
(nconc (subseq address 0 index) (list #\0) (nthcdr (+ index 1) address))
value
(1+ index))
(store-val computer
mask
(nconc (subseq address 0 index) (list #\1) (nthcdr (+ index 1) address))
value
(1+ index)))))))
(defun run-program-2 (computer)
(loop :for (opcode . operand) :in (d-comp-code computer)
:do (cond ((string= opcode "mask") (setf (d-comp-mask computer) (coerce (car operand) 'list)))
(T (store-val computer
(d-comp-mask computer)
(coerce (format nil "~36,'0B" (parse-integer (subseq opcode 4) :junk-allowed T)) 'list)
(parse-integer (car operand))))))
computer)
(defun part2 (file)
(let ((computer (make-d-comp :code (parse-input file))))
(run-program-2 computer)
(loop :for v :being :the :hash-values :of (d-comp-memory computer)
:sum v)))
(defun test2 ()
(part2 day14-test-input-2))
(defun solution2 ()
(part2 day14-input))
| 3,537 | Common Lisp | .lisp | 76 | 35.276316 | 119 | 0.554266 | paul-jewell/advent-of-code-2020 | 1 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:28:28 AM (Europe/Amsterdam) | 0936bb16a89ab0c58be54c32e8de32dc08dadd10bbcbf88e7a9b18c2634e2571 | 25,729 | [
-1
] |
25,730 | day9.lisp | paul-jewell_advent-of-code-2020/2020/lisp/day9.lisp | (in-package :day9)
(defparameter day9-test-input "~/Projects/advent-of-code-2020/input/day9-test-input.txt")
(defparameter day9-input "~/Projects/advent-of-code-2020/input/day9-input.txt")
(defun sums-in-preamble (list)
(loop :for values on list
:for x := (first values)
:nconc (loop :for y :in (rest values)
:when (/= x y)
:collect (+ x y))))
(defun part1 (filename preamble)
(let ((data (mapcar #'parse-integer (uiop:read-file-lines filename))))
(loop :for i :from preamble
:to (1- (length data))
:when (null (find (nth i data) (sums-in-preamble (subseq data (- i preamble) i))))
:collect (nth i data))))
(defun test1 ()
(car (part1 day9-test-input 5)))
(defun solution1 ()
(car (part1 day9-input 25)))
(defun find-value (value live-list remaining-list)
(let ((sum (apply #'+ live-list)))
(cond ((null live-list) (find-value value (list (car remaining-list)) (cdr remaining-list)))
((> sum value) (find-value value (butlast live-list) remaining-list)) ; drop 1st value
((= sum value) (+ (apply #'min live-list) (apply #'max live-list))) ; successful completion
(t (find-value value (cons (car remaining-list) live-list) (cdr remaining-list))))))
(defun test2 ()
(find-value (test1) nil (mapcar #'parse-integer (uiop:read-file-lines day9-test-input))))
(defun solution2 ()
(find-value (solution1) nil (mapcar #'parse-integer (uiop:read-file-lines day9-input))))
| 1,514 | Common Lisp | .lisp | 29 | 46.103448 | 103 | 0.63981 | paul-jewell/advent-of-code-2020 | 1 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:28:28 AM (Europe/Amsterdam) | 48a9c882c7086175c31884fda1f0926778ef4ea22b6e92d784f48766bb1f9edf | 25,730 | [
-1
] |
25,731 | day18.lisp | paul-jewell_advent-of-code-2020/2020/lisp/day18.lisp | (in-package :day18)
(defparameter +test1-input+ "2 * 3 + (4 * 5)")
(defparameter +test2-input+ "5 + (8 * 3 + 9 + 3 * 4 * 3)")
(defparameter +test3-input+ "5 * 9 * (7 * 3 * 3 + 9 * 3 + (8 + 6 * 4))")
(defparameter +test4-input+ "((2 + 4 * 9) * (6 + 9 * 8 + 6) + 6) + 2 + 4 * 2")
(defparameter day18-input "~/Projects/advent-of-code-2020/input/day18-input.txt")
(defun prepare-string (str)
(read-from-string (concatenate 'string "(" str ")")))
(defun parse-input (input)
(mapcar #'prepare-string input))
;;Kudos to David Barringer - I spent several hours working through this problem, but couldn't find a way
;; through. David created this excellent concise routine. Thanks for sharing!
(defun eval1 (expr)
(cond ((= 1 (length expr)) (car expr))
((listp (car expr)) (eval1 (cons (eval1 (car expr)) (cdr expr))))
((listp (caddr expr)) (eval1 (nconc (list (car expr) (cadr expr) (eval1 (caddr expr))) (cdddr expr))))
(t (eval1 (cons (funcall (cadr expr) (car expr) (caddr expr)) (cdddr expr))))))
(defun test1 ()
(eval1 (prepare-string +test1-input+)))
(defun test2 ()
(eval1 (prepare-string +test2-input+)))
(defun test3 ()
(eval1 (prepare-string +test3-input+)))
(defun test4 ()
(eval1 (prepare-string +test4-input+)))
(defun solution1 ()
(apply #'+ (mapcar #'eval1 (parse-input (uiop:read-file-lines day18-input)))))
(defun eval2 (expr)
(cond ((= 1 (length expr)) (car expr))
((listp (car expr)) (eval2 (cons (eval2 (car expr)) (cdr expr))))
((listp (caddr expr)) (eval2 (nconc (list (car expr) (cadr expr) (eval2 (caddr expr))) (cdddr expr))))
((eql '* (cadr expr)) (funcall (cadr expr) (eval2 (list (car expr))) (eval2 (cddr expr))))
(t (eval2 (cons (funcall (cadr expr) (car expr) (caddr expr)) (cdddr expr))))))
(defun solution2 ()
(apply #'+ (mapcar #'eval2 (parse-input (uiop:read-file-lines day18-input)))))
| 1,928 | Common Lisp | .lisp | 35 | 51.571429 | 110 | 0.619883 | paul-jewell/advent-of-code-2020 | 1 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:28:28 AM (Europe/Amsterdam) | fcf0c54e5afb99073da4220c15676018363ef9d483d5c1e6f678a6db3705e496 | 25,731 | [
-1
] |
25,732 | day11.lisp | paul-jewell_advent-of-code-2020/2020/lisp/day11.lisp | (in-package :day11)
(defparameter day11-input "~/Projects/advent-of-code-2020/input/day11-input.txt")
(defparameter day11-test-input "~/Projects/advent-of-code-2020/input/day11-test-input.txt")
(defun parse-layout (filename)
(let ((file-lines (uiop:read-file-lines filename)))
(make-array (list (length file-lines) (length (first file-lines)))
:initial-contents file-lines)))
(defun occupy-seat (layout x y)
(setf (aref layout x y) #\#))
(defun empty-seat (layout x y)
(setf (aref layout x y) #\L))
(defun occupied-p (layout x y)
(char= (aref layout x y) #\#))
(defun empty-p (layout x y)
(and (not (occupied-p layout x y))
(not (floor-p layout x y))))
(defun floor-p (layout x y)
(char= (aref layout x y) #\.))
(defun count-occupied-seats (layout x-seat y-seat)
(count-if-not #'null (let ((x-min (max (1- x-seat) 0))
(x-max (min (1+ x-seat) (1- (first (array-dimensions layout)))))
(y-min (max (1- y-seat) 0))
(y-max (min (1+ y-seat) (1- (second (array-dimensions layout))))))
(loop :for x :from x-min :to x-max
append (loop :for y :from y-min :to y-max
:if (not (and (= x-seat x)
(= y-seat y)))
collect (occupied-p layout x y))))))
(defun seat-change1 (start-seats)
(let ((new-layout (make-array (array-dimensions start-seats))) ;; May have to make new array to avoid corrupting original
(changed-p nil))
(loop :for x :below (first (array-dimensions start-seats))
:do (loop :for y :below (second (array-dimensions start-seats))
:do (cond
((and (empty-p start-seats x y)
(= (count-occupied-seats start-seats x y) 0))
(progn
(occupy-seat new-layout x y)
(setf changed-p T)))
; Seat: occupied -> empty
((and (occupied-p start-seats x y)
(>= (count-occupied-seats start-seats x y) 4))
(progn
(empty-seat new-layout x y)
(setf changed-p T)))
; No change -
(T (setf (aref new-layout x y) (aref start-seats x y))))))
(values new-layout changed-p)))
(defun seat-valid-p (seats coords)
(and (<= 0 (first coords) (1- (first (array-dimensions seats))))
(<= 0 (second coords) (1- (second (array-dimensions seats))))))
(defun sightline-check (seats seat direction)
(let ((new-loc (mapcar #'+ seat direction)))
(if (seat-valid-p seats new-loc)
(cond ((occupied-p seats (first new-loc) (second new-loc)) #\O)
((empty-p seats (first new-loc) (second new-loc)) #\F)
(T (sightline-check seats new-loc direction)))
nil)))
(defun count-visible-seats (seats seat-x seat-y)
(let ((seat-status (loop :for direction in '((0 1) (1 0) (-1 0) (0 -1) (-1 -1) (-1 1) (1 -1) (1 1))
collect (sightline-check seats (list seat-x seat-y) direction))))
(count-if (lambda (c) (equal c #\O)) seat-status)))
(defun seat-change2 (start-seats)
(let ((new-layout (make-array (array-dimensions start-seats)))
(changed-p nil))
(loop :for x below (first (array-dimensions start-seats))
:do (loop :for y :below (second (array-dimensions start-seats))
:do (cond
((and (empty-p start-seats x y)
(= (count-visible-seats start-seats x y) 0))
(progn
(occupy-seat new-layout x y)
(setf changed-p T)))
((and (occupied-p start-seats x y)
(>= (count-visible-seats start-seats x y) 5))
(progn
(empty-seat new-layout x y)
(setf changed-p T)))
(T (setf (aref new-layout x y) (aref start-seats x y))))))
(values new-layout changed-p)))
(defun count-all-seats (seats)
(count-if-not #'null (loop :for x :below (first (array-dimensions seats))
append (loop :for y :below (second (array-dimensions seats))
collect (occupied-p seats x y)))))
(defun part1 (seat-layout)
(multiple-value-bind (seats changed-p)
(seat-change1 seat-layout)
(if changed-p
(part1 seats)
(count-all-seats seats))))
(defun test1 ()
(part1 (parse-layout day11-test-input)))
(defun solution1 ()
(part1 (parse-layout day11-input)))
(defun part2 (seat-layout)
(multiple-value-bind (seats changed-p)
(seat-change2 seat-layout)
(if changed-p
(part2 seats)
(count-all-seats seats))))
(defun test2 ()
(part2 (parse-layout day11-test-input)))
(defun solution2 ()
(part2 (parse-layout day11-input)))
| 5,213 | Common Lisp | .lisp | 104 | 36.538462 | 124 | 0.522714 | paul-jewell/advent-of-code-2020 | 1 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:28:28 AM (Europe/Amsterdam) | a16974a64fd1cf69c8e1dff116d44b33912803759b14cbcc730482f7aeb7825c | 25,732 | [
-1
] |
25,733 | day10.lisp | paul-jewell_advent-of-code-2020/2020/lisp/day10.lisp | (in-package :day10)
(defparameter day10-test-input1 "~/Projects/advent-of-code-2020/input/day10-test-input-1.txt")
(defparameter day10-test-input2 "~/Projects/advent-of-code-2020/input/day10-test-input-2.txt")
(defparameter day10-input "~/Projects/advent-of-code-2020/input/day10-input.txt")
(defun part1 (filename)
(let* ((adaptors (sort (mapcar #'parse-integer
(uiop:read-file-lines filename))
#'<))
(max-jolt (apply #'max adaptors))
(data (append '(0) adaptors (list (+ max-jolt 3))))
(one-jolt 0)
(three-jolt 0))
(loop :for x from 0 upto (- (length data) 2)
:for y from 1 upto (1- (length data))
:do (if (= (- (nth y data)
(nth x data)) 1)
(setf one-jolt (1+ one-jolt))
(setf three-jolt (1+ three-jolt))))
(* one-jolt three-jolt)))
(defun test1 ()
(part1 day10-test-input1))
(defun test2 ()
(part1 day10-test-input2)) ;; process day10-test-input-2
(defun solution1 ()
(part1 day10-input))
(defun find-combinations (remaining-adaptors)
(when (= 1 (length remaining-adaptors))
(return-from find-combinations 1))
(loop :with start := (first remaining-adaptors)
:for (val . rest) :on (rest remaining-adaptors)
:while (<= (- val start) 3)
:sum (find-combinations (cons val rest))))
(unmemoize-functions)
(memoize-function 'find-combinations :test #'equal)
(defun read-data (filename)
(cons 0 (sort (mapcar #'parse-integer (uiop:read-file-lines filename)) #'<)))
(defun test3 ()
(find-combinations (read-data day10-test-input1)))
(defun test4 ()
(find-combinations (read-data day10-test-input2)))
(defun solution2 ()
(find-combinations (read-data day10-input)))
| 1,812 | Common Lisp | .lisp | 42 | 36.190476 | 94 | 0.62707 | paul-jewell/advent-of-code-2020 | 1 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:28:28 AM (Europe/Amsterdam) | 7d041d954b46d0af79af2af0aff994a5a6a2f32b14ed08a6c22b9ad8cf8523c8 | 25,733 | [
-1
] |
25,734 | day7.lisp | paul-jewell_advent-of-code-2020/2020/lisp/day7.lisp | (in-package :day7)
(defparameter day7-test-input "~/Projects/advent-of-code-2020/input/day7-test-input.txt")
(defparameter day7-input "~/Projects/advent-of-code-2020/input/day7-input.txt")
(defparameter test-input (uiop:read-file-lines day7-test-input))
;; Disclosure - I worked on this all day, but failed to find a way through by myself.
;; This code is basically from larsen's submission. Boy, do I have a lot to learn...!
(defun read-bag-rules (rule-file)
(let ((graph (make-hash-table :test 'equal)))
(loop :for rule :in (uiop:read-file-lines rule-file)
:do (register-groups-bind (colour rest-of-rule)
("^(\\w+ \\w+) bags contain \(.*\)" rule)
(setf (gethash colour graph)
(loop for rule-part in (split "," rest-of-rule)
collect (register-groups-bind ((#'parse-integer n) c-colour)
("\(\\d+\) \(\\w+ \\w+\) bag" rule-part)
(cons c-colour n))))))
graph))
(defun path (graph start end)
(labels ((path-using (graph start end node-list)
(if (equal start end)
(return-from path (car (reverse node-list)))
(dolist (child (mapcar #'car (gethash start graph)))
(path-using graph child end (cons child node-list))))))
(path-using graph start end (list start))))
;; TODO: The above path function uses a sub routine to break out of the dolist
;; with the result. I need to see if I can do it here without using the subroutine
(defun path2 (graph start end &optional (node-list (list start)))
(princ node-list)
(if (equal start end)
(return-from path2 (car (reverse node-list)))
(dolist (child (mapcar #'car (gethash start graph)))
(path2 graph child end (cons child node-list)))))
(defun sol1 (file)
(let ((graph (read-bag-rules file))
(solutions 0))
(loop :for colour being the hash-keys of graph
:when (and (not (string= colour "shiny gold"))
(path graph colour "shiny gold"))
:do (incf solutions)
:finally (return solutions))))
(defun test1 ()
(sol1 day7-test-input))
(defun solution1 ()
(sol1 day7-input))
(defun total-bags (start bag-rules)
(+ 1 (loop for (color . quantity) in (gethash start bag-rules)
when (numberp quantity)
sum (* quantity (total-bags color bag-rules)))))
(defun sol2 (rule-file)
(- (total-bags "shiny gold" (read-bag-rules rule-file)) 1))
(defun test2 ()
(sol2 day7-test-input))
(defun solution2 ()
(sol2 day7-input))
| 2,657 | Common Lisp | .lisp | 54 | 40.462963 | 89 | 0.607419 | paul-jewell/advent-of-code-2020 | 1 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:28:28 AM (Europe/Amsterdam) | 1c2482432da4071f16e5b12e0177190ba15c6192f7653f97907ff27fd67063e4 | 25,734 | [
-1
] |
25,735 | day1.lisp | paul-jewell_advent-of-code-2020/2020/lisp/day1.lisp | (in-package #:day1)
;; Read input into list
(defparameter day1-input "~/Projects/advent-of-code-2020/input/day1-input.txt")
(defparameter expenses (mapcar #'parse-integer (uiop:read-file-lines day1-input)))
;; Refactor - second version - credit and thanks to bpanthi on lisp discord
;; My observations/learning from this:
;; - Keywording the loop elements makes clearer
;; - Loop keyword :on
;; - So much clearer than my first version!
(defun solution1 ()
(loop :for (a . tail) on expenses
:for b = (- 2020 a)
:when (find b tail)
return (* a b)))
(defun solution2 ()
(loop :for (a . tail) on expenses
:do (loop :for (b . b-tail) :on tail
:for c := (- 2020 (+ a b))
:when (find c b-tail)
:do (return-from solution2
(* a b c)))))
| 860 | Common Lisp | .lisp | 21 | 33.809524 | 82 | 0.596871 | paul-jewell/advent-of-code-2020 | 1 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:28:28 AM (Europe/Amsterdam) | d416e79abc8d022e5ea6f40e14f10143e1763302a0a02cc74effd0c63a8fa7b6 | 25,735 | [
-1
] |
25,736 | day20.lisp | paul-jewell_advent-of-code-2020/2020/lisp/day20.lisp | (in-package :day20)
(defparameter day20-test-input "~/Projects/advent-of-code-2020/input/day20-test-input.txt")
(defparameter day20-input "~/Projects/advent-of-code-2020/input/day20-input.txt")
;; Parse tiles from input string
;; - First line: Tile nnnn:
(defun parse-input (file)
(let* ((tile-strs (split "\\n\\n" (uiop:read-file-string file))))
(mapcar #'tile-boundaries (mapcar (lambda (tile-str)
(let* ((tile-data (split "\\n" tile-str))
(tile-number (parse-integer (car tile-data) :start 5 :junk-allowed t))
(tile-image (cdr tile-data)))
(list tile-number tile-image)))
tile-strs))))
(defun numerate-string (str)
(parse-integer
(concatenate 'string
(loop :for char :across str
:collect
(if (char= char #\#)
#\1
#\0))) :radix 2))
(defun tile-boundaries (tile)
(let ((north (numerate-string (caadr tile)))
(east (numerate-string
(apply #'concatenate 'string
(loop :for line :in (cadr tile)
:collect
(subseq line 9)))))
(south (apply #'numerate-string (list (car (last (cadr tile))))))
(west (numerate-string
(apply #'concatenate 'string
(loop :for line :in (cadr tile)
:collect
(subseq line 0 1))))))
(list (car tile) (list north east south west))))
(defun north (tile)
(first (cadr tile)))
(defun east (tile)
(second (cadr tile)))
(defun south (tile)
(third (cadr tile)))
(defun west (tile)
(fourth (cadr tile)))
(defun tile-side (cardinal picture position)
(funcall cardinal (aref picture (array-pos-col position picture) (array-pos-row position picture))))
(defun tile-fit-pred (picture next-pos tile)
;;(format T "picture: ~A, next-pos: ~A, tile: ~A~%" picture next-pos tile)
(let ((position (array-pos next-pos picture)))
(if (= (car position) 0) ;; First column
(if (= (cadr position) 0) ;; First cell - top left - automatically fit!
T
(if (= (north tile)
(tile-side #'south picture (1- next-pos)))
T ;; Tile fits
nil))
(if (= (cadr position) 0) ;; Check only east/west match
(if (= (west tile)
(tile-side #'east picture
(let ((pos (- next-pos (car (array-dimensions picture)))))
(if (>= pos 0)
pos
0))))
T
nil)
(if (and (= (west tile)
(tile-side #'east picture
(let ((pos (- next-pos (car (array-dimensions picture)))))
(if (>= pos 0)
pos
0))))
(= (north tile)
(tile-side #'south picture (1- next-pos))))
T
nil)))))
(defun add-to-picture (picture next-pos tile)
;;(format T "Before adding tile: picture: ~A, next-pos: ~A, tile: ~A~%" picture next-pos tile)
(setf (aref picture (array-pos-col next-pos picture) (array-pos-row next-pos picture)) tile)
;;(format T "After: picture: ~A, next-pos: ~A, tile: ~A~%" picture next-pos tile)
picture)
(defun calculate-result (picture)
(let* ((array-dims (array-dimensions picture))
(max-row (1- (cadr array-dims)))
(max-col (1- (car array-dims))))
(* (car (aref picture 0 0))
(car (aref picture max-col 0))
(car (aref picture 0 max-row))
(car (aref picture max-col max-row)))))
;; Return the tile id
(defun tile-id (tile)
(car tile))
(defparameter tiles (parse-input day20-test-input))
;; (0,0) - top left hand corner
;; (x,y) - indexing down array then across... (significant for tile matching)
(defun array-pos-row (next-pos picture)
(floor (/ next-pos (car (array-dimensions picture)))))
(defun array-pos-col (next-pos picture)
(mod next-pos (car (array-dimensions picture))))
(defun array-pos (next-pos picture)
(list
(array-pos-col next-pos picture)
(array-pos-row next-pos picture)))
;; input parameters:
;; - picture - array of tiles positioned
;; - tiles - list of remaining tiles to be added to the picture (unrotated)
;; - next-pos - (x y) - position to test for next tile
(defun build-picture (picture tiles next-pos)
(if (= (length tiles) 0) ;; Picture is fully constructed - return result
(calculate-result picture)
(loop :for tile :in tiles ;; Need to locate the next tile
:do (loop :for rot-tile in (tile-rotations tile) ;; step through the tile rotations
:do (if (tile-fit-pred picture next-pos rot-tile) ;; Check if the tile fits
(let ((result (build-picture (add-to-picture picture next-pos rot-tile)
(cdr tiles)
(1+ next-pos))))
(if (not (equal result 0))
result
0)))))))
(defun part1 (input-file)
(let* ((input-tiles (parse-input input-file))
(pic-size (round (sqrt (length tiles))))
(picture (make-array (list pic-size pic-size)))
(next-pos 0)
(tile-list (rotate-list input-tiles)))
(loop for tiles in tile-list
collect (build-picture picture tiles next-pos))))
(defun test1 ()
(part1 day20-test-input))
;;-------------------------------------------------------------------------------------------
;; These functions are working:
(defun edge-rotate (edge)
(parse-integer (reverse
(format nil "~10,'0,,b" edge)) ;; leading zero pad to full width
:radix 2))
(defun tile-rotate (tile)
;; North to East - no change
;; East to South - rotation required
;; South to West - no change
;; West to North - rotation required
(let ((edges (cadr tile)))
(list (car tile) (list (edge-rotate (cadddr edges)) ;; W to N
(car edges) ;; N to E
(edge-rotate (cadr edges)) ;; E to S
(caddr edges))))) ;; S to W
(defun tile-rotations (tile)
"Perform tile rotation and return list of rotations"
(let* ((1st-rotation (tile-rotate tile))
(2nd-rotation (tile-rotate 1st-rotation))
(3rd-rotation (tile-rotate 2nd-rotation))
(flipped-tile (tile-flip tile))
(flipped-tile-1st-rotation (tile-rotate flipped-tile))
(flipped-tile-2nd-rotation (tile-rotate flipped-tile-1st-rotation))
(flipped-tile-3rd-rotation (tile-rotate flipped-tile-2nd-rotation))
)
(list tile 1st-rotation 2nd-rotation 3rd-rotation
flipped-tile flipped-tile-1st-rotation flipped-tile-2nd-rotation flipped-tile-3rd-rotation)))
(defun tile-flip (tile)
(let ((edges (cadr tile)))
(list (car tile) (list (car edges)
(cadddr edges)
(caddr edges)
(cadr edges)))))
(defun rotate-list (list)
"Rotate a list returning a list of all the rotations possible"
(let ((list-length (length list)))
(loop for l below list-length
collect (let ((element (nth l list)))
(reverse (append (remove element list :test #'equal) (cons element ())))))))
| 7,906 | Common Lisp | .lisp | 167 | 34.796407 | 117 | 0.52609 | paul-jewell/advent-of-code-2020 | 1 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:28:28 AM (Europe/Amsterdam) | 2adb8feb58945e29d89ba0d936d0dd7ad4f14b0f5a16bea82d95b759a3b3064e | 25,736 | [
-1
] |
25,737 | day2.lisp | paul-jewell_advent-of-code-2020/2020/lisp/day2.lisp | (in-package #:day2)
(defparameter day2-input "~/Projects/advent-of-code-2020/input/day2-input.txt")
(defun parse-password (pass-str)
;; Password line format:
;; x - y c: password
;; character c must be present between x and y times
(let* ((pos-- (position #\- pass-str))
(pos-space (position #\SPACE pass-str)) ;; the first space!
(pos-colon (position #\: pass-str))
(min (parse-integer (subseq pass-str 0 pos--)))
(max (parse-integer (subseq pass-str (1+ pos--) pos-space)))
(pass-letter (coerce (string-trim " " (subseq pass-str pos-space pos-colon))
'character))
(password (coerce (string-trim " " (subseq pass-str (1+ pos-colon)))
'list)))
(list min max pass-letter password)))
(defparameter passwords (mapcar #'parse-password (uiop:read-file-lines day2-input)))
(defun a-valid-password-p (password)
(let* ((min (first password))
(max (second password))
(letter (third password))
(password (nth 3 password))
(count (count letter password :test #'eq)))
(if (and (>= count min)
(<= count max))
T
nil)))
(defun solution1 ()
(count-if #'a-valid-password-p passwords))
(defun xor (x y)
(and (or x y)
(not (and x y))))
(defun b-valid-password-p (passlist)
(let* ((first-pos (first passlist))
(second-pos (second passlist))
(letter (third passlist))
(password (nth 3 passlist))
(first-letter (nth (1- first-pos) password))
(second-letter (nth (1- second-pos) password)))
(if (xor (eq first-letter letter)
(eq second-letter letter))
T
nil)))
(defun solution2 ()
(count-if #'b-valid-password-p passwords))
| 1,801 | Common Lisp | .lisp | 45 | 32.377778 | 85 | 0.590961 | paul-jewell/advent-of-code-2020 | 1 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:28:28 AM (Europe/Amsterdam) | 3a91db4ad0c683f5201f85dd708f65a437a3689e26589ca70c8e9a6b0ac8fcd8 | 25,737 | [
-1
] |
25,738 | day8.lisp | paul-jewell_advent-of-code-2020/2020/lisp/day8.lisp | (in-package :day8)
(defparameter day8-test-input "~/Projects/advent-of-code-2020/input/day8-test-input.txt")
(defparameter day8-input "~/Projects/advent-of-code-2020/input/day8-input.txt")
(defstruct console
code
(acc 0)
(pc 0))
(defmacro create-console (name code)
`(setq ,name (make-console :code ,code)))
;; This is my refactored from my version
;; - following advice from zulu.inuoe (discord: Lisp channel)
(defparameter *opcodes* '(jmp nop acc))
(defun opcode-fn-or-error (opcode)
(let ((op (find opcode *opcodes* :test #'string-equal)))
(unless op (error "unknown opcode ~A" opcode))
op))
(defun parse-program (program-file)
(let ((code (uiop:read-file-lines program-file)))
(loop :for line :in code
collect (destructuring-bind (opcode operand)
(split "\\s" line)
(list (opcode-fn-or-error opcode) (parse-integer operand))))))
(defun run-console1 (name visitlist)
(cond ((null (find (console-pc name) visitlist))
(setf visitlist (cons (console-pc name) visitlist))
(funcall (car (nth (console-pc name) (console-code name)))
name (cdr (nth (console-pc name) (console-code name))))
(run-console1 name visitlist))
(t (console-acc name))))
(defun nop (name in)
(declare (ignore in))
(setf (console-pc name) (+ 1 (console-pc name))))
(defun acc (name in)
(setf (console-acc name) (+ (car in) (console-acc name)))
(setf (console-pc name) (+ 1 (console-pc name))))
(defun jmp (name in)
(setf (console-pc name) (+ (car in) (console-pc name))))
(defun test1 ()
(let ((name 'prog))
(run-console1 (create-console name (parse-program day8-test-input)) nil)))
(defun solution1 ()
(let ((name 'prog))
(run-console1 (create-console name (parse-program day8-input)) nil)))
;; Part b specific code below
(defun replace-code (code old-opcode new-opcode)
(loop for i from 0 to (- (length code) 1)
if (equal old-opcode (car (nth i code)))
collect (nconc (subseq code 0 i) (list (cons new-opcode (cdr (nth i code)))) (nthcdr (+ i 1) code))))
(defun run-console2 (name visitlist)
(cond ((null (nth (console-pc name) (console-code name))) (console-acc name))
((null (find (console-pc name) visitlist))
(setf visitlist (cons (console-pc name) visitlist))
(funcall (car (nth (console-pc name) (console-code name))) name (cdr (nth (console-pc name) (console-code name))))
(run-console2 name visitlist))
(t nil)))
(defun part2 (program-file)
(let ((input (parse-program program-file))
(name 'prog))
(car (remove nil (loop :for program :in (nconc (replace-code input 'jmp 'nop)
(replace-code input 'nop 'jmp))
:collect (run-console2 (create-console name program) nil))))))
(defun test2 ()
(part2 day8-test-input))
(defun solution2 ()
(part2 day8-input))
| 2,977 | Common Lisp | .lisp | 65 | 39.492308 | 123 | 0.636678 | paul-jewell/advent-of-code-2020 | 1 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:28:28 AM (Europe/Amsterdam) | fd8de7263f788f64efeb2cdee0c0953066a80daacd5458dd6e48b2d2ec0a183f | 25,738 | [
-1
] |
25,739 | main.lisp | paul-jewell_advent-of-code-2020/2020/lisp/tests/main.lisp | ;;;; tests/main.lisp
;; note: answers in this test suite relate to the data provided to me
;; by the advent of code website. Different data sets are provided
;; to different users - your data set and answers therefore will be
;; different.
(defpackage #:advent2020/test
(:use #:cl
#:fiveam)
(:export #:run!
#:all-tests))
(in-package #:advent2020/test)
(def-suite advent2020
:description "test suite - ensure refactoring doesn't break anything!")
(in-suite advent2020)
(test day1
(is (= (day1:solution1) 440979))
(is (= (day1:solution2) 82498112)))
(test day2
(is (= (day2:solution1) 460))
(is (= (day2:solution2) 251)))
(test day3
(is (= (day3:solution1) 294))
(is (= (day3:solution2) 5774564250)))
;; From day4, I set up the tests for the sample data as well. Once the solution
;; is successfully submitted, I create tests for the puzzle solution, to make
;; sure I don't break anything during the refactoring stage.
(test day4-test
(is (= (day4:test1) 2))
(is (= (day4:test2) 4)))
(test day4-solutions
(is (= (day4:solution1) 237))
(is (= (day4:solution2) 172)))
(test day5-test
(is (= (day5:test1) 820)))
(test day5-solutions
(is (= (day5:solution1) 806))
(is (= (day5:solution2) 562)))
(test day6-test
(is (= (day6:test1) 11)))
(test day6-solutions
(is (= (day6:solution1) 6625))
(is (= (day6:solution2) 3360)))
(test day7-part-a
(is (= (day7:test1) 4))
(is (= (day7:solution1) 248)))
(test day7-part-b
(is (= (day7:test2) 32))
(is (= (day7:solution2) 57281)))
(test day8-test-part-a
(is (= (day8:test1) 5)))
(test day8-solution-part-a
(is (= (day8:solution1) 1814)))
(test day8-test-part-b
(is (= (day8:test2) 8)))
(test day8-solution-part-b
(is (= (day8:solution2) 1056)))
(test day9-test
(is (= (day9:test1) 127))
(is (= (day9:test2) 62)))
(test day9-solutions
(is (= (day9:solution1) 1038347917)))
(test day10-test1
(is (= (day10:test1) 35))
(is (= (day10:test2) 220)))
(test day10-test2
(is (= (day10:test3) 8))
(is (= (day10:test4) 19208)))
(test day10-solution1
(is (= (day10:solution1) 1984))
(is (= (day10:solution2) 3543369523456)))
(test day11-test1
(is (= (day11:test1) 37)))
(test day11-solution1
(is (= (day11:solution1) 2247)))
(test day11-test2
(is (= (day11:test2) 26)))
(test day11-solution2
(is (= (day11:solution2) 2011)))
(test day12-test1
(is (= (day12:test1) 25)))
(test day12-solution1
(is (= (day12:solution1) 759)))
(test day12-test2
(is (= (day12:test2) 286)))
(test day12-solution2
(is (= (day12:solution2) 45763)))
(test day13-test1
(is (= (day13:test1) 295)))
(test day13-solution1
(is (= (day13:solution1) 3464)))
(test day13-test2
(is (= (day13:test2) 1068781)))
(test day13-solution2
(is (= (day13:solution2) 760171380521445)))
(test day14-test1
(is (= (day14:test1) 165)))
(test day14-solution1
(is (= (day14:solution1) 5875750429995)))
(test day14-test2
(is (= (day14:test2) 208)))
(test day14-solution2
(is (= (day14:solution2) 5272149590143)))
(test day15-test1
(is (= (day15:test1) 436)))
(test day15-solution1
(is (= (day15:solution1) 1696)))
(test day15-test2
(is (= (day15:test2) 175594)))
(test day15-solution2
(is (= (day15:solution2) 37385)))
(test day16-test1
(is (= (day16:test1) 71)))
(test day16-solution1
(is (= (day16:solution1) 22073)))
(test day16-solution2
(is (= (day16:solution2) 1346570764607)))
(test day17-test1
(is (= (day17:test1) 112)))
(test day17-solution1
(is (= (day17:solution1) 401)))
(test day17-test2
(is (= (day17:test2) 848)))
(test day17-solution2
(is (= (day17:solution2) 2224)))
(test day18-test1
(is (= (day18:test1) 26))
(is (= (day18:test2) 437))
(is (= (day18:test3) 12240))
(is (= (day18:test4) 13632)))
(test day18-solution1
(is (= (day18:solution1) 3647606140187)))
(test day18-solution2
(is (= (day18:solution2) 323802071857594)))
(test day19-test1
(is (= (day19:test1) 2)))
(test day19-solution1
(is (= (day19:solution1) 151)))
(test day19-test2
(is (= (day19:test2) 12)))
(test day19-solution2
(is (= (day19:solution2) 386)))
(test day20-test1
(is (= (day20:test1) 20899048083289)))
| 4,217 | Common Lisp | .lisp | 143 | 26.895105 | 79 | 0.663344 | paul-jewell/advent-of-code-2020 | 1 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:28:28 AM (Europe/Amsterdam) | 1bd5bc407291e0769a9e8e9812f8e40ba80c3e6eb1942567a971e2fdadba621f | 25,739 | [
-1
] |
25,740 | advent2020.asd | paul-jewell_advent-of-code-2020/2020/lisp/advent2020.asd | ;;;; advent2020.asd
(defsystem #:advent2020
:description "Advent of Code 2020"
:author "Paul Jewell <[email protected]>"
:license "GNU3" ;; Check proper license attribution
:version "0.0.1"
:serial t
:depends-on (#:cl-ppcre
#:fiveam
#:memoize)
:components ((:file "package")
(:file "day1")
(:file "day2")
(:file "day3")
(:file "day4")
(:file "day5")
(:file "day6")
(:file "day7")
(:file "day8")
(:file "day9")
(:file "day10")
(:file "day11")
(:file "day12")
(:file "day13")
(:file "day14")
(:file "day15")
(:file "day16")
(:file "day17")
(:file "day18")
(:file "day19")
(:file "day20"))
:in-order-to ((test-op (test-op #:advent2020/test))))
(defsystem #:advent2020/test
:serial t
:depends-on (#:advent2020
#:fiveam)
:components ((:module "tests"
:components ((:file "main"))))
:perform (test-op (op _) (symbol-call :fiveam :run-all-tests)))
| 1,226 | Common Lisp | .asd | 39 | 20.512821 | 65 | 0.452321 | paul-jewell/advent-of-code-2020 | 1 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:28:28 AM (Europe/Amsterdam) | c5894e619c151aa19ca39df986c4018c621066e9b611f43c0007fa36ccf31cf0 | 25,740 | [
-1
] |
25,778 | index.lisp | gcentauri_iktomi/index.lisp | (in-package :spinneret)
(defun home ()
(with-html
(:doctype)
(:html
(:head
(:title "Home page"))
(:body
(:header
(:h1 "Home page"))
(:form
:action "my-form" :method "post"
(:div
(:label :for "name")
(:input :type "text" :id "name" :name "name"))
(:div
(:label :for "salary")
(:input :type "number" :id "salary" :name "salary"))
(:div
(:label :for "age")
(:input :type "number" :id "age" :name "age"))
(:button "submit"))))))
(with-open-file (f "dist/index.html" :direction :output
:if-exists :supersede
:if-does-not-exist :create)
(write-sequence (with-html-string (home)) f))
| 776 | Common Lisp | .lisp | 26 | 21.192308 | 60 | 0.487282 | gcentauri/iktomi | 1 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:28:28 AM (Europe/Amsterdam) | 4ae43987f2fd5dd810a8bada56a15464e3708f37ecac27693d83654b7ef57ec5 | 25,778 | [
-1
] |
25,781 | netlify.toml | gcentauri_iktomi/dist/netlify.toml | [[redirects]]
from = "/my-form"
to = "https://postman-echo.com/post"
status = 200
headers = {X-From = "Netlify"}
signed = "API_SIGNATURE_TOKEN" | 153 | Common Lisp | .l | 6 | 23 | 38 | 0.641892 | gcentauri/iktomi | 1 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:28:28 AM (Europe/Amsterdam) | 43a75fed314d04cfebaa61090c900c134635b423eeb1625a15849c7100bd6836 | 25,781 | [
-1
] |
25,782 | index.html | gcentauri_iktomi/dist/index.html | <!DOCTYPE html>
<html lang=en>
<head>
<meta charset=UTF-8>
<title>Home page</title>
</head>
<body>
<header>
<h1>Home page</h1>
</header>
<form action=my-form method=post>
<div>
<label for=name></label>
<input type=text id=name name=name>
</div>
<div>
<label for=salary></label>
<input type=number id=salary name=salary>
</div>
<div>
<label for=age></label>
<input type=number id=age name=age>
</div>
<button>submit</button>
</form>
</body>
</html> | 511 | Common Lisp | .l | 27 | 15.592593 | 45 | 0.624742 | gcentauri/iktomi | 1 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:28:28 AM (Europe/Amsterdam) | f831a26432e606c36412fef83acd9004c424fc251d9cb14a081a3e9a491cf997 | 25,782 | [
-1
] |
25,797 | package.lisp | Junker_extracond/package.lisp | (defpackage extracond
(:use #:cl)
(:export #:let1
#:if-let1
#:when-let1
#:if-let*
#:cond-list))
| 144 | Common Lisp | .lisp | 7 | 12.714286 | 24 | 0.445255 | Junker/extracond | 1 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:28:28 AM (Europe/Amsterdam) | 3221f628153ba4603f1de0903e366a88c9c333aeabdaa2e7f283c16ec2b68f38 | 25,797 | [
-1
] |
25,798 | extracond.lisp | Junker_extracond/extracond.lisp | (in-package #:extracond)
(defmacro let1 (var val &body body)
"Bind VAR to VAL and evaluate BODY.
Same as (let ((VAR VAL)) BODY)"
`(let ((,var ,val))
,@body))
(defmacro if-let1 (var val &body body)
"Bind VAR to VAL in THEN/ELSE form."
`(uiop:if-let ((,var ,val))
,@body))
(defmacro when-let1 (var val &body body)
"Bind VAR to VAL and executes BODY if VAL is non-nil."
`(uiop:if-let ((,var ,val))
(progn
,@body)))
(defmacro if-let* (bindings then-form else-form)
"Creates new variable bindings, and conditionally executes either
THEN-FORM or ELSE-FORM. ELSE-FORM defaults to NIL.
IF-LET* is similar to IF-LET, but the bindings of variables are performed sequentially rather than in parallel."
(let ((outer (gensym))
(inner (gensym)))
`(block ,outer
(block ,inner
(let* ,(loop :for (symbol value) :in bindings
:collect `(,symbol (or ,value
(return-from ,inner nil))))
(return-from ,outer ,then-form)))
,else-form)))
;; borrowed from https://github.com/mhayashi1120/Emacs-gauche-macros/blob/main/gauche-macros.el
(defmacro cond-list (&rest clauses)
"Construct a list by conditionally adding entries. Each clause has a test and expressions.
When its test yields true, the result of associated expression is used to construct the resulting list.
When the test yields false, nothing is inserted.
Clause must be either one of the following form:
(test expr …)
Test is evaluated, and when it is true, expr … are evaluated, and the return value
becomes a part of the result.
If no expr is given, the result of test is used if it is not false.
(test => proc)
Test is evaluated, and when it is true, proc is called with the value,
and the return value is used to construct the result.
(test @ expr …)
Like (test expr …), except that the result of the last expr must be a list,
and it is spliced into the resulting list, like unquote-splicing.
(test => @ proc)
Like (test => proc), except that the result of proc must be a list,
and it is spliced into the resulting list, like unquote-splicing.
(let ((alist '((x 3) (y -1) (z 6))))
(cond-list ((assoc 'x alist) 'have-x)
((assoc 'w alist) 'have-w)
((assoc 'z alist) => cadr)))
⇒ (have-x 6)
(let ((x 2) (y #f) (z 5))
(cond-list (x @ `(:x ,x))
(y @ `(:y ,y))
(z @ `(:z ,z))))
⇒ (:x 2 :z 5)
"
(reduce
(lambda (clause accum)
(when (null clause)
(error "No matching clause ~S" clause))
(let ((test-result (make-symbol "result"))
(test (car clause))
(body (cdr clause)))
`(let ((,test-result ,test))
(append
(if ,test-result
,(cond
;; (TEST => @ PROC)
((and (eq (car body) '=>)
(eq (cadr body) '@))
(unless (= (length (cddr body)) 1)
(error "Invalid clause ~S" body))
(let ((proc (caddr body)))
(unless (functionp proc)
(error "Form must be a function but ~S" proc))
`(funcall ,proc ,test-result)))
;; (TEST => PROC)
((eq (car body) '=>)
(unless (= (length (cdr body)) 1)
(error "Invalid clause ~s" body))
(let ((proc (cadr body)))
(unless (functionp proc)
(error "Form must be a function but ~S" proc))
`(list (funcall ,proc ,test-result))))
;; (TEST @ EXPR ...)
((eq (car body) '@)
`(progn ,@(cdr body)))
;; (TEST EXPR ...)
(t
`(list (progn ,@body))))
nil)
,accum))))
clauses
:from-end t
:initial-value nil))
| 3,980 | Common Lisp | .lisp | 97 | 31.381443 | 112 | 0.548989 | Junker/extracond | 1 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:28:28 AM (Europe/Amsterdam) | 779f1e7bd13cfb7cc8e8152c829a3148996da093482a351bd8966cb26fcc0f0e | 25,798 | [
-1
] |
25,799 | extracond.asd | Junker_extracond/extracond.asd | (defsystem extracond
:version "0.1.0"
:author "Dmitrii Kosenkov"
:license "GPL3"
:depends-on ()
:description "Extra set of conditional macros"
:homepage "https://github.com/Junker/extracond"
:source-control (:git "https://github.com/Junker/extracond.git")
:components ((:file "package")
(:file "extracond")))
| 340 | Common Lisp | .asd | 10 | 29.9 | 66 | 0.684848 | Junker/extracond | 1 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:28:28 AM (Europe/Amsterdam) | 291a2e1c94d4422cbb68612f1af5802cbfa1e104766a03f25ddd6b5dd77ce038 | 25,799 | [
-1
] |
25,817 | cl-utils.lisp | LeoMingo_cl-utils/cl-utils.lisp | (defpackage cl-utils
(:export :make-adjustable-array
:make-adjustable-string
:push-char
:split-at
:trim-arr-edge
:trim-nth
:conc-str-arr
:concstr
:concarr
:char-arr->str
:seq ;A reverse of subseq
:insert-arr
:insert-str
:incremental-arr-check
:insert-str-all
:fst
:snd
:read-str
:read-line-arr
:write-str
:write-line-arr))
(defun make-adjustable-array (arr)
(make-array (length arr)
:fill-pointer (length arr)
;:fill-pointer t
:adjustable t
:initial-contents arr))
(defun make-adjustable-string (str)
(make-array (length str)
:fill-pointer (length str)
:adjustable t
:initial-contents str))
(defun push-char (c str)
(let ((ns (make-adjustable-string str)))
(vector-push-extend c ns)
ns))
;;Token character is ignored
(defun split-at (str token)
(let ( (slen (length str))
(str-arr (make-array '(0)
:fill-pointer t
:adjustable t
:element-type 'string))
(str-temp (make-array '(0)
:fill-pointer t
:adjustable t
:element-type 'character
:initial-contents ""))
(empty-str (make-array '(0)
:fill-pointer t
:adjustable t
:element-type 'character
:initial-contents "")) )
(dotimes (idx slen)
do (if (equal (aref str idx) token)
(progn
(vector-push-extend str-temp str-arr)
(setf str-temp empty-str))
(setf str-temp (push-char (aref str idx) str-temp))))
(vector-push-extend str-temp str-arr)
str-arr))
(defun concstr (&rest body)
(let ((new-str ""))
(dotimes (i (length body))
(setf new-str (concatenate 'string new-str (nth i body))))
(make-adjustable-string new-str)))
(defun concarr (&rest body)
(let ((new-arr (make-array '(0) :adjustable t :fill-pointer t)))
(dotimes (i (length body))
(setf new-arr (concatenate 'array new-arr (nth i body))))
(make-adjustable-array new-arr)))
(defun trim-arr-edge (arr edge)
(let ((na (make-array (list (- (length arr) 1))
:adjustable t
:fill-pointer t
:element-type (array-element-type arr)))
(len-1 (- (length arr) 1)))
(dotimes (i len-1)
(cond ((equal edge "s") ;trim off the head of array
(setf (aref na i) (aref arr (+ i 1))))
((equal edge "e")
(setf (aref na i) (aref arr i)))
(t (setf na arr)))
)
na))
(defun trim-nth (seq n)
(let ((g (gensym)))
(setf (elt seq n) g)
(delete g seq)))
(defun conc-str-arr (str-arr)
(let ((len (length str-arr))
(str ""))
(dotimes (i len)
(setf str (concstr str (aref str-arr i))))
str))
(defun char-arr->str (char-arr)
(let ((len (length char-arr))
(str (make-adjustable-string "")))
(dotimes (i len)
(setf str (push-char (aref char-arr i) str)))
str))
;;a reverse version of subseq
(defun seq (arr n)
(dotimes (i (- (length arr) n))
(setf arr (trim-arr-edge arr "e")))
arr)
(defun insert-arr (arr ele i)
(let ((leftside (seq arr i))
(rightside (subseq arr i)))
(vector-push-extend ele leftside)
(concarr leftside rightside)))
(defun insert-str (str-base str-inserted idx)
(let ((csi (concatenate 'array str-inserted))
(new-str (concatenate 'array str-base)))
(dotimes (i (length csi))
(setf new-str (insert-arr new-str (aref csi i)(+ i idx))))
(char-arr->str new-str)))
#||
Add incremental-arr-reverse-check
Add insert-str-rever-idx-all
||#
(defun incremental-arr-check (base-arr checked-arr idx)
(let ((bool-rst t)
(ba-len (length base-arr))
(checked-len (length checked-arr)))
(if (> (+ checked-len idx) ba-len) ;exclude the case of index of base-arr out range
(setf bool-rst nil)
(dotimes (i checked-len)
(if (not (equal (aref checked-arr i) (aref base-arr (+ i idx))))
(setf bool-rst nil))))
bool-rst))
(defun insert-str-all (str-base str-tok str-ins)
(let ((rst-str (make-adjustable-string ""))
(strlen-1 (- (length str-tok) 1))
(sblen (length str-base)))
(dotimes (i (- sblen strlen-1))
(if (incremental-arr-check str-base str-tok i)
(progn (setf rst-str (concstr rst-str str-ins))
(setf rst-str (push-char (aref str-base i) rst-str)))
(setf rst-str (push-char (aref str-base i) rst-str))))
(dotimes (i strlen-1)
(setf rst-str (push-char (aref str-base (+ (- sblen strlen-1) i)) rst-str)))
rst-str))
(defun fst (arr)
(aref arr 0))
(defun snd (arr)
(aref arr 1))
(defun read-line-arr (filename)
(defparameter file-str-arr (make-array '(0)
:initial-element ""
:element-type 'string
:adjustable t
:fill-pointer t))
(let ((in (open filename :if-does-not-exist nil)))
(when in
(loop for line = (read-line in nil)
while line do
(vector-push-extend line file-str-arr))
(close in)))
file-str-arr)
(defun flatten-array (arr)
"Flatten a 2-dimensional array into a 1-dimentional array"
(let ((new-arr (make-adjustable-array #())))
(dotimes (i (length arr))
(setf new-arr (concarr new-arr (aref arr i))))
new-arr))
(defun read-str (filename &key (newline nil))
(let ((file-arr (read-line-arr filename))
(temp-str "")
(str ""))
(if newline
(progn
(dotimes (i (1- (length file-arr)))
(setf temp-str (push-char #\newline (aref file-arr i)))
(setf str (concstr str temp-str)))
;;Lastly we set the last line without #\newline
(setf str (concstr str (aref file-arr (1- (length file-arr))))))
(setf str (flatten-array file-arr)))
(char-arr->str str)))
(defun write-str (filename line)
(with-open-file (stm filename
:direction :output
:if-exists :append
:if-does-not-exist :create)
(princ #\newline stm)
(princ line stm)))
(defun write-line-arr (filename line-arr)
(with-open-file (stm filename
:direction :output
:if-exists :append
:if-does-not-exist :create)
(dotimes (i (length line-arr))
(princ #\newline stm)
(princ (aref line-arr i) stm))))
| 7,198 | Common Lisp | .lisp | 195 | 26.292308 | 88 | 0.527919 | LeoMingo/cl-utils | 1 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:28:28 AM (Europe/Amsterdam) | d4822300c7e2db5954fedbef2c25973df86ef681983f0b98910e578ede10a402 | 25,817 | [
-1
] |
25,834 | package.lisp | atgreen_cl-vault/package.lisp | ;;; -*- Mode: LISP; Syntax: COMMON-LISP; Package: CL-VAULT; Base: 10 -*-
;;;
;;; Copyright (C) 2019 Anthony Green <[email protected]>
;;;
;;; This program is free software: you can redistribute it and/or
;;; modify it under the terms of the GNU Affero General Public License
;;; as published by the Free Software Foundation, either version 3 of
;;; the License, or (at your option) any later version.
;;;
;;; This program is distributed in the hope that it will be useful,
;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
;;; Affero General Public License for more details.
;;;
;;; You should have received a copy of the GNU Affero General Public
;;; License along with this program. If not, see
;;; <http://www.gnu.org/licenses/>.
(defpackage #:cl-vault
(:use #:cl)
(:export fetch-vault-secrets))
| 922 | Common Lisp | .lisp | 20 | 43.55 | 72 | 0.707778 | atgreen/cl-vault | 1 | 0 | 0 | AGPL-3.0 | 9/19/2024, 11:28:28 AM (Europe/Amsterdam) | 99a8589d6ca2a946e8670aa435ef9cbd94b036ec807e7ae9493187d7eddbafae | 25,834 | [
-1
] |
25,835 | vault.lisp | atgreen_cl-vault/vault.lisp | ;;; -*- Mode: LISP; Syntax: COMMON-LISP; Package: CL-VAULT; Base: 10 -*-
;;;
;;; Copyright (C) 2019 Anthony Green <[email protected]>
;;;
;;; This program is free software: you can redistribute it and/or
;;; modify it under the terms of the GNU Affero General Public License
;;; as published by the Free Software Foundation, either version 3 of
;;; the License, or (at your option) any later version.
;;;
;;; This program is distributed in the hope that it will be useful,
;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
;;; Affero General Public License for more details.
;;;
;;; You should have received a copy of the GNU Affero General Public
;;; License along with this program. If not, see
;;; <http://www.gnu.org/licenses/>.
;; Top level for cl-vault
(in-package :cl-vault)
(defun fetch-vault-secrets (url token)
"Return an alist of secrets from hashicorp vault at URL using TOKEN"
(check-type url (and string (not null)))
(check-type token (and string (not null)))
(cdr
(assoc :data
(json:decode-json-from-string
(handler-case
(multiple-value-bind (body response-code)
(drakma:http-request url :additional-headers (list (cons "X-Vault-Token" token)))
(case response-code
(200 (flexi-streams:octets-to-string body))
(t (error "http response code ~A" response-code))))
(error (condition)
(error "error fetching secrets from '~A': ~A" url condition)))))))
| 1,540 | Common Lisp | .lisp | 34 | 41.764706 | 86 | 0.699268 | atgreen/cl-vault | 1 | 0 | 0 | AGPL-3.0 | 9/19/2024, 11:28:28 AM (Europe/Amsterdam) | 8717618e83d85ccdfeff092414a3e01fe6fa3e0fcfce8511cc17c2e4e7a02fbc | 25,835 | [
-1
] |
25,836 | cl-vault.asd | atgreen_cl-vault/cl-vault.asd | ;;; -*- Mode: LISP; Syntax: COMMON-LISP; Package: CL; Base: 10 -*-
;;;
;;; Copyright (C) 2019 Anthony Green <[email protected]>
;;;
;;; This program is free software: you can redistribute it and/or
;;; modify it under the terms of the GNU Affero General Public License
;;; as published by the Free Software Foundation, either version 3 of
;;; the License, or (at your option) any later version.
;;;
;;; This program is distributed in the hope that it will be useful,
;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
;;; Affero General Public License for more details.
;;;
;;; You should have received a copy of the GNU Affero General Public
;;; License along with this program. If not, see
;;; <http://www.gnu.org/licenses/>.
(asdf:defsystem #:cl-vault
:description "Convenience routines for accessing hashicorp vault"
:author "Anthony Green <[email protected]>"
:license "AGPL"
:depends-on (#:drakma #:cl-json #:flexi-streams)
:serial t
:components ((:file "package")
(:file "vault")))
| 1,137 | Common Lisp | .asd | 25 | 42.32 | 70 | 0.702703 | atgreen/cl-vault | 1 | 0 | 0 | AGPL-3.0 | 9/19/2024, 11:28:28 AM (Europe/Amsterdam) | c4d78a343e1b9a97185f499b1e18205bc6e26ab687e200ce3f584f5754e329f3 | 25,836 | [
-1
] |
25,855 | cl-lib-version.lisp | Bradford-Miller_CL-LIB/cl-lib-version.lisp | (in-package cl-lib)
;; load this AFTER :cl-lib-essentials
;; when updating the functions put this line before the CL-LIB one (so the time stamp is updated).
(cl-lib-essentials:version-reporter "CL-LIB-FNS" 5 20
";; Time-stamp: <2022-01-31 12:53:51 gorbag>"
";; remove-keyword-args")
;; when updating the library (new package) put this line before the CL-LIB-FNS one (so the time stamp is updated).
(cl-lib-essentials:version-reporter "CL-LIB" 5 17
";; Time-stamp: <2019-10-26 20:29:39 Bradford Miller(on Aragorn.local)>"
";; 5am")
(pushnew :cl-lib *features*)
(pushnew :cl-lib-5 *features*)
| 744 | Common Lisp | .lisp | 12 | 48.25 | 114 | 0.583448 | Bradford-Miller/CL-LIB | 1 | 0 | 1 | LGPL-3.0 | 9/19/2024, 11:28:28 AM (Europe/Amsterdam) | 5db87af8acec9e47529dc77d750b283c32a78f4773fcea340fa09756f48a2954 | 25,855 | [
-1
] |
25,856 | init-extras.lisp | Bradford-Miller_CL-LIB/init-extras.lisp | ;;; -*- Mode: LISP; Syntax: ansi-common-lisp; Package: CL-LIB; Base: 10 -*-
;; Time-stamp: <2008-05-03 13:12:47 gorbag>
;; CVS: $Id: init-extras.lisp,v 1.2 2008/05/03 17:41:47 gorbag Exp $
(in-package cl-lib)
;;;
;; This portion of CL-LIB Copyright (C) 2000-2008 Bradford W. Miller
;;
;; This library is free software; you can redistribute it and/or modify it under the terms of the GNU
;; Lesser General Public License as published by the Free Software Foundation; either version 3.0 of
;; the License, or (at your option) any later version.
;; This library 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.
;; You should have received a copy of the GNU Lesser General Public License along with this library;
;; if not, see <http://www.gnu.org/licenses/>.
;;;
;;; The following is contributed by [email protected]
(add-initialization "Cleanup *general-warning-list*"
'(setq *general-warning-list* nil)
() '*warn-or-error-cleanup-initializations*)
(add-initialization "Run Warn-or-error cleanups"
'(initializations '*warn-or-error-cleanup-initializations*)
'(:before-cold))
(add-initialization "announce cl-lib" '(format *terminal-io* "~& CL-LIB Version: ~A~%" *cl-lib-version*)
'(:warm))
| 1,441 | Common Lisp | .lisp | 1 | 1,440 | 1,441 | 0.700208 | Bradford-Miller/CL-LIB | 1 | 0 | 1 | LGPL-3.0 | 9/19/2024, 11:28:28 AM (Europe/Amsterdam) | 678e10512f211e6e8cff4bb98c838cdf3af00b2ff20afa91e05b2a1891dc134e | 25,856 | [
-1
] |
25,857 | cl-lib-tests.lisp | Bradford-Miller_CL-LIB/cl-lib-tests.lisp | (cl-lib:version-reporter "CL-LIB-Tests" 5 18 ";; Time-stamp: <2020-01-04 17:12:45 Bradford Miller(on Aragorn.local)>"
"5am testing initializations")
(defpackage :CL-LIB-TESTS
(:shadowing-import-from :clos-facets
#:defclass #:slot-makunbound #:slot-unbound #:slot-value #:slot-boundp #:unbound-slot
#:slot-makunbound-using-class #:slot-value-using-class #:slot-boundp-using-class)
(:use :Common-lisp :it.bese.FiveAM :cl-lib :clos-facets)
(:export #:etest))
(in-package :cl-lib-tests)
;; 5.18 1/ 3/20 Fix some symbol/pacakge issues
;; 5.17 10/26/19 Typo in comments
;; 5.16 3/ 1/19 New!
;;; Copyright (C) 2019, 2020 by Bradford W. Miller ([email protected])
;; This library is free software; you can redistribute it and/or modify it under the terms of the GNU
;; Lesser General Public License as published by the Free Software Foundation; either version 3.0 of
;; the License, or (at your option) any later version.
;; This library 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.
;; You should have received a copy of the GNU Lesser General Public License along with this library;
;; if not, see <http://www.gnu.org/licenses/>.
;; miller - Brad Miller ([email protected])
;; note that this function would only be loaded if cl-lib-tests.asd
;; is. It requires FiveAM, which is distributed separately. See:
;; https://common-lisp.net/project/fiveam/
(defun test-cl-lib-all ()
;; basic functions
(run! 'function-tests)
;; package defined in cl-lib-essentials.asd
(run! 'initialization-tests)
;; package-defined-in cl-lib-clos-facets.asd
(run! 'facet-tests)
;(clos-facets::facet-tester t)
;; package defined in cl-lib-locatives.asd
;; (cl-lib::test-setters) ; old version (pre-5am)
(run! 'cl-lib::locatives)
;; package defined in cl-lib-resources.asd
(run! 'cl-lib::resources-tests)
(lispdoc::generate-docfiles)) ; not really a test, but generates the documentation needed for a release
| 2,217 | Common Lisp | .lisp | 39 | 52.307692 | 118 | 0.713822 | Bradford-Miller/CL-LIB | 1 | 0 | 1 | LGPL-3.0 | 9/19/2024, 11:28:28 AM (Europe/Amsterdam) | 8bfbdb4c12ffec83ba3f167895811f98fca7bba36ef57451eb7f55e99aa3ec0b | 25,857 | [
-1
] |
25,858 | cl-lib-lispdoc.asd | Bradford-Miller_CL-LIB/cl-lib-lispdoc.asd | ;; Time-stamp: <2019-01-27 17:57:26 Bradford Miller(on Aragorn.local)>
;; This portion of CL-LIB Copyright (C) 2019 Bradford W. Miller
;;
;; This library is free software; you can redistribute it and/or modify it under the terms of the GNU
;; Lesser General Public License as published by the Free Software Foundation; either version 3.0 of
;; the License, or (at your option) any later version.
;; This library 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.
;; You should have received a copy of the GNU Lesser General Public License along with this library;
;; if not, see <http://www.gnu.org/licenses/>.
;; miller - Brad Miller ([email protected])
;; new fractured cl-lib, with multiple defsystems for each package. So the "right ones" can be added as needed.
(in-package :asdf)
(defsystem :cl-lib-lispdoc
:depends-on (:cl-lib-essentials)
:components
((:module "packages" :serial t
:components
((:file "lispdoc")))))
| 1,143 | Common Lisp | .lisp | 20 | 54.55 | 111 | 0.747312 | Bradford-Miller/CL-LIB | 1 | 0 | 1 | LGPL-3.0 | 9/19/2024, 11:28:28 AM (Europe/Amsterdam) | 0211e4a32e6d92c65db6230a16ccfaa3da63ec4cf1f5718e913db608fcd651ff | 25,858 | [
-1
] |
25,859 | clim-extensions.lisp | Bradford-Miller_CL-LIB/compatibility/clim-extensions.lisp | ;;; -*- Mode: LISP; Syntax: ansi-common-lisp; Package: CL-LIB; Base: 10 -*-
;; Time-stamp: <2012-01-05 17:49:12 millerb>
;; CVS: $Id: clim-extensions.lisp,v 1.2 2012/01/05 22:51:27 millerb Exp $
;;;
;;; Copyright (C) 2002 by Bradford W. Miller [email protected]
;;;
;;; Right of use & redistribution is granted as per the terms of the
;;; GNU LIBRARY GENERAL PUBLIC LICENCE version 2 which is incorporated here by
;;; reference.
;;; This program is free software; you can redistribute it and/or modify
;;; it under the terms of the GNU Library General Public License as published
;;; by the Free Software Foundation; version 2.
;;; 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 Library General Public License for more details.
;;; You should have received a copy of the GNU Library General Public License
;;; along with this program; if not, write to the Free Software
;;; Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
;;;
(in-package cl-lib)
#-lispworks
(defgeneric frame-pane (frame)
(:documentation "Returns the pane tht is the top-level pane of the
current layout of the frame"))
#-lispworks
(defmethod frame-pane (frame)
(let ((panes (clim:frame-current-panes frame)))
(while (cdr panes)
(if (member (clim:frame-parent (car panes))
(cdr panes)) ; not the top-level pane
(pop panes)
(return-from frame-pane (car panes))))
(car panes)))
| 1,583 | Common Lisp | .lisp | 34 | 43.735294 | 78 | 0.715953 | Bradford-Miller/CL-LIB | 1 | 0 | 1 | LGPL-3.0 | 9/19/2024, 11:28:28 AM (Europe/Amsterdam) | e1f862c158be3f6a7bc882c1d98ae675b851a30f711509fa37854f23e5c7f360 | 25,859 | [
-1
] |
25,860 | process.lisp | Bradford-Miller_CL-LIB/compatibility/process.lisp | ;;; -*- Mode: LISP; Syntax: Ansi-common-lisp; Package: process; Base: 10; Vsp: 1 -*-
;; Time-stamp: <2007-05-18 11:32:47 miller>
;; CVS: $Id: process.lisp,v 1.1.1.1 2007/11/19 17:38:18 gorbag Exp $
;;;; Copyright (C) 1994, 1993, 1992 by the Trustees of the University of Rochester. All rights reserved.
;;; Right of use & redistribution is granted as per the terms of the
;;; GNU LIBRARY GENERAL PUBLIC LICENCE version 2 which is incorporated here by
;;; reference.
;;; This program is free software; you can redistribute it and/or modify
;;; it under the terms of the Gnu Library General Public License as published by
;;; the Free Software Foundation; version 2.
;;; 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 Library General Public License for more details.
;;; You should have received a copy of the Gnu Library General Public License
;;; along with this program; if not, write to the Free Software
;;; Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
;; allow code that runs on the symbolics to also run under allegro (possibly not optimally).
;; Modified from code written by Steve Luk for the TRAINS project.
(in-package process)
(defvar *default-process-priority* 0)
(when (fboundp 'mp:process-kill) ; make sure mp is loaded
(psetf (macro-function 'with-lock) (macro-function 'mp:with-process-lock)
(symbol-function 'lock) (symbol-function 'mp:process-lock)
(symbol-function 'unlock) (symbol-function 'mp:process-unlock)
(symbol-function 'process-name) (symbol-function 'mp:process-name)
(symbol-function 'interrupt) (symbol-function 'mp:process-interrupt)
(symbol-function 'process-wait) (symbol-function 'mp:process-wait)
(symbol-function 'runnable-p) (symbol-function 'mp:process-runnable-p)
(macro-function 'without-preemption) (macro-function 'mp:without-scheduling)
(macro-function 'without-interrupts) (macro-function 'excl:without-interrupts)
))
(defvar *process-verify-alist* nil)
(defun block-process (whostate verify-function &rest args)
(apply #'mp:process-wait whostate verify-function args))
; (let ((who (intern whostate :keyword)))
; (cl-lib:update-alist mp:*current-process* (list* who verify-function args) *process-verify-alist*)
; (cl-lib:while (not (apply verify-function args))
; (mp:process-add-arrest-reason mp:*current-process* who))
; ;; done
; (cl-lib:update-alist mp:*current-process* nil *process-verify-alist*)))
(defmacro block-and-poll-wait-function
(whostate interval verify-function &rest args)
`(mp:process-wait ,whostate ,verify-function ,@args))
#+allegro-v4.1
(cl-lib:add-initialization "lep-init for block"
'(lep::eval-in-emacs "(put 'block-and-poll-wait-function 'fi:lisp-indent-hook 1)")
'(:lep))
(defmacro block-and-poll-with-timeout
(n-seconds whostate interval verify-function &rest args)
`(mp:process-wait-with-timeout ,whostate ,n-seconds ,verify-function ,@args))
#+allegro-v4.1
(cl-lib:add-initialization "lep-init for block"
'(lep::eval-in-emacs "(put 'block-and-poll-with-timeout 'fi:lisp-indent-hook 1)")
'(:lep))
; Warning: the key words in symbolics and allegro are all compatable
(setf (symbol-function 'process-run-function)
(symbol-function 'mp:process-run-function))
; Not quite the idea, but works for the cases in this system
(defun process-abort (process &key message all query time-out stream)
(declare (ignore message all query time-out stream))
(mp:process-kill process))
(defun make-lock (name &key (type :simple) recursive area flavor)
(declare (ignore type recursive area flavor))
(mp:make-process-lock :name name))
; Well, the function is not completely the same in both machines. I guess it
; is better to rewrite the code than to use macro substitution.
(defmacro make-process (name
&rest init-args
&key (priority process:*default-process-priority*)
(initial-function nil) initial-function-arguments
verify-function verify-function-arguments
(run-reasons '(:enable)) flavor
area simple-p interrupt-handler system-process flags
top-level-whostate &allow-other-keys)
`(let ((process (mp:make-process :name ,name
:priority ,priority)))
(mp:process-enable process)
(cond
(,initial-function
(apply #'mp:process-preset process ,initial-function
,initial-function-arguments)
(mp:process-allow-schedule process)))
process))
#+allegro-v4.1
(cl-lib:add-initialization "lep-init for make"
'(lep::eval-in-emacs "(put 'make-process 'fi:lisp-indent-hook 1)")
'(:lep))
(defun make-process-priority (class priority &rest extra-args)
(declare (ignore extra-args))
(if (eq class :foreground)
priority
(error "This class is not currently supported")))
(defun reset (process &key (if-current-process t)
(if-without-aborts :ask))
(declare (ignore if-current-process if-without-aborts))
(mp:process-reset process))
(defun kill (process &key if-current-process if-without-aborts)
(declare (ignore if-current-process if-without-aborts))
(mp:process-kill process))
(defun wakeup (process)
t)
;; (if (eval (cddr (assoc process *process-verify-alist*)))
;; (wakeup-without-test process)))
(defun wakeup-without-test (process)
t)
;; (mp:process-revoke-arrest-reason process (cadr (assoc process *process-verify-alist*))))
(defun lock-idle-p (lock)
(null (mp:process-lock-locker lock)))
(defun make-lock-argument (ignore)
(declare (ignore ignore))
mp:*current-process*)
| 5,876 | Common Lisp | .lisp | 1 | 5,874 | 5,876 | 0.687713 | Bradford-Miller/CL-LIB | 1 | 0 | 1 | LGPL-3.0 | 9/19/2024, 11:28:28 AM (Europe/Amsterdam) | 60051b3bc947fcf118d34ad1fdc5f4bbd8acc07314f52f99c76c08a005297327 | 25,860 | [
-1
] |
25,861 | cltl2.lisp | Bradford-Miller_CL-LIB/compatibility/cltl2.lisp | ;;; -*- Mode: LISP; Syntax: Ansi-common-lisp; Package: FUTURE-COMMON-LISP-INTERNALS; Base: 10 -*-
;; Time-stamp: <2007-05-18 11:09:25 miller>
;; CVS: $Id: cltl2.lisp,v 1.1.1.1 2007/11/19 17:38:04 gorbag Exp $
(EVAL-WHEN (COMPILE LOAD EVAL)
(PUSHNEW :LOGICAL-PATHNAMES *FEATURES*)
(PUSHNEW :ANSI *FEATURES*)
#+SYMBOLICS (IF (MEMBER :IMACH SCL:*FEATURES*)
(PUSHNEW :IMACH *FEATURES*))
(PUSHNEW :CLIM *FEATURES*)
(PUSHNEW :CONDITIONS *FEATURES*)
(PUSHNEW :CLTL2 *FEATURES*))
| 491 | Common Lisp | .lisp | 1 | 489 | 491 | 0.665988 | Bradford-Miller/CL-LIB | 1 | 0 | 1 | LGPL-3.0 | 9/19/2024, 11:28:28 AM (Europe/Amsterdam) | e765121f73cb025f9494f4e6e19ede3aee9f3adc078bc6ea8ed88296455e808a | 25,861 | [
-1
] |
25,862 | cl-array-fns.lisp | Bradford-Miller_CL-LIB/functions/cl-array-fns.lisp | (in-package cl-lib)
(version-reporter "CL-LIB-FNS-Array Fns" 5 0 ";; Time-stamp: <2012-01-05 17:44:49 millerb>"
"CVS: $Id: cl-array-fns.lisp,v 1.2 2012/01/05 22:47:53 millerb Exp $
restructured version")
;;;
;;; Copyright (C) 1996--1992 by Bradford W. Miller, [email protected]
;;; and the Trustees of the University of Rochester
;;;
;;; Portions Copyright (C) 2002 by Bradford W. Miller, [email protected]
;;; Right of use & redistribution is granted as per the terms of the
;;; GNU LIBRARY GENERAL PUBLIC LICENCE version 2 which is incorporated here by
;;; reference.
;;; This program is free software; you can redistribute it and/or
;;; modify it under the terms of the GNU Library General Public
;;; License as published by the Free Software Foundation; version 2.
;;; 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 Library General Public License for more details.
;;; You should have received a copy of the GNU Library General Public License
;;; along with this program; if not, write to the Free Software
;;; Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
;;;
;;;
;;; The following is contributed by [email protected]
;; additions for other versions of lisp are welcome!
;;; the following is contributed by [email protected]
(defun Prefix? (Prefix Seq)
"Prefix? - Checks to see if Prefix is really a prefix of Seq. Returns
T if it is, NIL otherwise. Just checks that Prefix is no longer than
Seq, then checks to see if the the initial subsequence of Seq that is
the same length as Prefix is equal to Prefix. Prefix is a real prefix
if and only if both conditions hold."
(and (<= (length Prefix) (length Seq))
(equalp (subseq Seq 0 (length Prefix)) Prefix)))
;; duplicate an array. 12/29/93 by miller
(defun copy-array (array &optional (element-copier #'identity))
"Returns an (exact) copy of the passed array, with same size, fill
pointer (if there is one), adjustable quality, element type, and
contents. Uses element-copier to copy elements (default #'identity)."
(declare (optimize (speed 3) (safety 0) (debug 0)))
(progfoo (make-array (array-dimensions array)
:element-type (array-element-type array)
:adjustable (adjustable-array-p array)
:fill-pointer (and (array-has-fill-pointer-p array)
(fill-pointer array)))
(dotimes (i (array-total-size array))
(setf (row-major-aref foo i)
(funcall element-copier (row-major-aref array i))))))
;;;; The following functions were contributed by Mark Kantrowitz:
;;;; circular-list, dofile, seq-butlast, seq-last, firstn, in-order-union
;;;; parse-with-delimiter, parse-with-delimiters, string-search-car,
;;; string-search-cdr, parallel-substitute, lisp::nth-value,
;;;; parse-with-string-delimiter, parse-with-string-delimiter*,
;;;; member-or-eq, number-to-string, null-string, time-string.
;;;; list-without-nulls, cartesian-product, cross-product, permutations
;;;; powerset, occurs, split-string, format-justified-string,
;;;; eqmemb, neq, car-eq, dremove, displace, tailpush, explode,
;;;; implode, crush, listify-string, and-list, or-list, lookup,
;;;; make-variable, variablep, make-plist, make-keyword
;;;;
;;; ********************************
;;; Sequences **********************
;;; ********************************
(defun seq-butlast (sequence &optional (n 1))
(let* ((length (length sequence))
(delta (- length n)))
(when (plusp delta)
(subseq sequence 0 delta))))
(defun seq-last (sequence &optional (n 1))
(let* ((length (length sequence))
(delta (- length n)))
(when (plusp delta)
(subseq sequence delta length))))
| 3,949 | Common Lisp | .lisp | 74 | 49.337838 | 92 | 0.680239 | Bradford-Miller/CL-LIB | 1 | 0 | 1 | LGPL-3.0 | 9/19/2024, 11:28:28 AM (Europe/Amsterdam) | 3690e67b7b3fbc0a643ce6fce8d86dc2214c6a9f3bd36d9f09db1b228472ab25 | 25,862 | [
-1
] |
25,863 | cl-list-fns.lisp | Bradford-Miller_CL-LIB/functions/cl-list-fns.lisp | (in-package cl-lib)
(version-reporter "CL-LIB-FNS-List Fns" 5 13 ";; Time-stamp: <2019-02-18 16:00:00 Bradford Miller(on Aragorn.local)>"
";; use lispworks' version of dotted-list-p")
;; 5.13 10/19/11 use lispworks' version of dotted-list-p
;; 5.12 7/11/08 New: de-alistify, dotted-list-p, dotted-list
;; 5.9 2/19/08 New: tail-equalp
;; 5.4 5/18/07 New: alistify
;; 5.3 Fixed: update-alist-alist
;;;
;;; Copyright (C) 1996--1992 by Bradford W. Miller, [email protected]
;;; and the Trustees of the University of Rochester
;;;
;;; Portions Copyright (C) 2002-2011 by Bradford W. Miller, [email protected]
;;; Right of use & redistribution is granted as per the terms of the
;;; GNU LIBRARY GENERAL PUBLIC LICENCE version 2 which is incorporated here by
;;; reference.
;;; This program is free software; you can redistribute it and/or
;;; modify it under the terms of the GNU Library General Public
;;; License as published by the Free Software Foundation; version 2.
;;; 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 Library General Public License for more details.
;;; You should have received a copy of the GNU Library General Public License
;;; along with this program; if not, write to the Free Software
;;; Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
;;;
;;;
;;; The following is contributed by [email protected]
;; additions for other versions of lisp are welcome!
;; some type discriminators (at least for documentation purposes)
(deftype alist () 'list)
(defun true-list-p (term)
"Returns t if the term is a non-dotted list. Note that nil is a true list."
(declare (optimize (speed 3) (safety 0)))
(and (listp term)
(endp (cdr (last term)))))
(deftype true-list () '(and list (satisfies true-list-p)))
#-lispworks
(defun dotted-list-p (term)
"Returns t if the term is a dotted list."
(declare (optimize (speed 3) (safety 0)))
(and (listp term)
(not (endp (cdr (last term))))))
(deftype dotted-list () '(and list (satisfies dotted-list-p)))
;;; The #'eql has to be quoted, since this is a macro. Also, when
;;; binding variables in a macro, use gensym to be safe.
(defmacro update-alist (item value alist &key (test '#'eql) (key '#'identity))
"If alist already has a value for Key, it is updated to be Value.
Otherwise the passed alist is updated with key-value added as a new pair."
(let ((entry (gensym))
(itemv (gensym))
(valuev (gensym))) ; to assure proper evaluation order
; and single expansion
`(let* ((,itemv ,item)
(,valuev ,value)
(,entry (assoc ,itemv ,alist :test ,test :key ,key)))
(if ,entry
(progn (setf (cdr ,entry) ,valuev)
,alist)
(setf ,alist (acons ,itemv ,valuev ,alist))))))
(macro-indent-rule update-alist 1)
(defmacro update-alist-alist (outer-item inner-item inner-item-value alist-alist
&key (outer-test '#'eql) (inner-test '#'eql) (outer-key '#'identity) (inner-key '#'identity))
"Alists of alists comes up so often in my code, I've decided to just macroize it.
They're great for cheap and dirty (early pass) KBs, where the outer item is the object id and the inner-item is an attribute,
retrieving the value of the attribution on the object."
(let ((outer-itemv (gensym))
(inner-list (gensym)))
`(let* ((,outer-itemv ,outer-item)
(,inner-list (cdr (assoc ,outer-itemv ,alist-alist :test ,outer-test :key ,outer-key))))
(update-alist ,outer-itemv
(update-alist ,inner-item ,inner-item-value
,inner-list
:test ,inner-test :key ,inner-key)
,alist-alist
:test ,outer-test
:key ,outer-key))))
(defun reverse-alist (alist &key (test #'eql))
"Takes an alist of uniqe keys and non-unique values, and returns an
alist of unique keys based on the values, whose values are lists of
the original keys."
(declare (type alist alist))
(let (result)
(dolist (x alist)
(let ((assoc-result (assoc (cdr x) result :test test)))
(if assoc-result
(setf (cdr assoc-result) (cons (car x) (cdr assoc-result)))
(setq result (acons (cdr x) (list (car x)) result)))))
result))
(defun alistify (list)
"Turns a list of the form '(:key :value :key :value) as one might get with a lambda list into an alist
\'((:key :value) (:key :value))"
(declare (type list list))
(cond
((endp list)
nil)
(t
(cons (cons (car list) (cadr list))
(alistify (cddr list))))))
(defun de-alistify (alist &optional true-list-p)
"Turns an alist of of the form '((key value) (key . value)) into a lambda-list type form '(:key (value) :key value)
If true-list-p is non-nil, then '((key value)) becomes '(:key value), but '((key . value)) will generate an error.
In either case '((key value1 value2 value3)) becomes '(:key (value1 value2 value3))"
(declare (type alist alist))
(list* (make-keyword (caar alist))
(if (and true-list-p
(endp (cddar alist)))
(cadar alist)
(cdar alist))
(if (cdr alist)
(de-alistify (cdr alist) true-list-p))))
(defun tail-equalp (list1 list2)
"Return non-nil if list1 is equalp to some tail of list2. Like tailp, but cons structure does not have to be shared."
(cond
((null list1)
t)
((or (not (listp list2)) ; check list2 is a true list
(endp list2))
nil)
((equalp list1 list2))
(t
(tail-equalp list1 (cdr list2)))))
(defun force-list (foo)
(if (listp foo)
foo
(list foo)))
(defun delete-n (list n)
"Delete the nth element (0-based) of the list. Destructive."
(declare (type list list)
(type fixnum n))
;; find the cell to change
(cond
((zerop n)
(cdr list))
(t
(let ((cell (nthcdr (1- n) list)))
(when cell ; didn't go beyond the end of the list
(setf (cdr cell) (cddr cell))))
list)))
(defun remove-n (list n)
"Remove the nth element (0-based) of the list. Non-destructive."
(declare (type list list)
(type fixnum n))
(cond
((zerop n)
(cdr list))
((< n (list-length list))
(append
(subseq list 0 n)
(nthcdr (1+ n) list)))
(t
list))) ; nothing to remove
;;; the following is contributed by [email protected]
(defun Flatten (L)
"Flattens list L, i.e., returns a single list containing the
same atoms as L but with any internal lists 'dissolved'. For example,
(flatten '(a (b c) d)) ==> (a b c d)
Recursively flattens components of L, according to the following rules-
- an atom is already flattened.
- a list whose CAR is also a list is flattened by appending the
flattened CAR to the flattened CDR (this is what dissolves internal
lists).
- a list whose CAR is an atom is flattened by just flattening the CDR
and CONSing the original CAR onto the result.
These rules were chosen with some attention to minimizing CONSing."
(cond
((null L ) '() )
((atom L) L)
((consp L)
(if (consp (car L))
(append (Flatten (car L)) (Flatten (cdr L)))
(cons (car L) (Flatten (cdr L)))))
(t L)))
;;;; The following functions were contributed by Mark Kantrowitz:
;;;; circular-list, dofile, seq-butlast, seq-last, firstn, in-order-union
;;;; parse-with-delimiter, parse-with-delimiters, string-search-car,
;;; string-search-cdr, parallel-substitute, lisp::nth-value,
;;;; parse-with-string-delimiter, parse-with-string-delimiter*,
;;;; member-or-eq, number-to-string, null-string, time-string.
;;;; list-without-nulls, cartesian-product, cross-product, permutations
;;;; powerset, occurs, split-string, format-justified-string,
;;;; eqmemb, neq, car-eq, dremove, displace, tailpush, explode,
;;;; implode, crush, listify-string, and-list, or-list, lookup,
;;;; make-variable, variablep, make-plist, make-keyword
;;;;
(defun eqmemb (item list &key (test #'equal))
"Checks whether ITEM is either equal to or a member of LIST."
(if (listp list)
(member item list :test test)
(funcall test item list)))
(defun car-eq (x y)
"Checks whether Y is eq to the car of X."
(and (listp x) ; consp?
(eq (car x) y)))
(defun dremove (item list)
"Destructive remove which replaces the original list with the list
that results when ITEM is deleted from LIST."
;; This is safe only because of the way delete works.
(displace list (delete item list :test #'eq)))
(defun displace (list val)
"Replaces LIST with VAL by destructively modifying the car and cdr of LIST.
Warning: VAL must not share list structure with LIST or you'll be sorry."
(when list
;; Can't alter NIL.
(rplaca list (car val))
(rplacd list (cdr val))))
(defun tailpush (item list)
"Pushes ITEM onto the tail of LIST. Does not work if the list is null."
(when list
(rplacd (last list) (list item))))
(defun explode (symbol)
(map 'list #'identity (symbol-name symbol)))
(defun implode (list &optional (package *package*))
(intern (map 'string #'identity list) package))
(defun crush (a b &optional (package *package*))
(implode (append (explode a) (explode b)) package))
(defun listify-string (string)
"Turns a string into a list of symbols."
(declare (type string string))
(let ((eof (gensym))
(result nil)
(start 0)
item)
(loop
(multiple-value-setq (item start)
(read-from-string string nil eof :start start))
(when (eq item eof)
(return result))
(setq result (nconc result (list item))))))
(defun and-list (list)
(declare (type list list))
(dolist (item list t)
(unless item
(return nil))))
(defun or-list (list)
(declare (type list list))
(dolist (item list nil)
(unless item
(return t))))
(defun make-plist (keys data &optional (plist '()))
"Constructs a property list from keys and data (addition to plist)."
(cond ((and (null data) (null keys))
plist)
((or (null data) (null keys))
(error "The lists of keys and data are of unequal length."))
(t
(list* (car keys)
(car data)
(make-plist (cdr keys) (cdr data) plist)))))
| 10,507 | Common Lisp | .lisp | 250 | 37.18 | 126 | 0.655977 | Bradford-Miller/CL-LIB | 1 | 0 | 1 | LGPL-3.0 | 9/19/2024, 11:28:28 AM (Europe/Amsterdam) | 1a66167d27ffa59166dc81561c7dd3122b4cedcbda4064b5db43e01bf1a61035 | 25,863 | [
-1
] |
25,864 | cl-lib-function-tests.lisp | Bradford-Miller_CL-LIB/functions/cl-lib-function-tests.lisp | (in-package cl-lib-tests)
(version-reporter "CL-LIB-Func Tests" 5 18
";; Time-stamp: <2020-01-05 16:55:11 Bradford Miller(on Aragorn.local)>"
";; new 5am testing")
;; 5.18 1/ 3/20 fix array-fn test
;; 5.17 10/26/19 move etest here so we don't have problems later; fix various typos
;; 5.16. 3/16/19 5am testing (new)
;;; Copyright (C) 2019,2020 by Bradford W. Miller, [email protected]
;;;
;; This library is free software; you can redistribute it and/or modify it under the terms of the GNU
;; Lesser General Public License as published by the Free Software Foundation; either version 3.0 of
;; the License, or (at your option) any later version.
;; This library 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.
;; You should have received a copy of the GNU Lesser General Public License along with this library;
;; if not, see <http://www.gnu.org/licenses/>.
;; miller - Brad Miller ([email protected])
;; tests for a number of the functions in this directory, to help with github releases.
;; note that packages have tests either as part of their package or in that directory.
;; used later
(defmacro etest (expected-error error-generator)
`(handler-case ,error-generator
(,expected-error (condition) (declare (ignore condition)) t) ; had the expected error so OK
(:no-error (condition) (declare (ignore condition)) nil))) ; fail
(def-suite function-tests :description "Test suite for cl-lib functions")
(in-suite function-tests)
;; cl-array-fns
(test array-fns
"test fns in the cl-array-fns file"
(let* ((foo (list '(a b) '(c d) '(e f)))
(a1 (make-array '(3 2) :initial-contents foo))
a2)
(is (Prefix? "foobar" "foobarbletch"))
(is (not (Prefix? "foo123" "foo321ccd")))
(is (not (Prefix? "foo123" "foo12")))
(is (equalp (setq a2 (copy-array a1)) a1))
(is (not (eq (car foo) (aref a1 0))))
(is (equalp (seq-butlast foo) '((a b) (c d))))
(is (equalp (seq-last foo) '(e f)))))
;; cl-boolean
(defstruct (boolean-test-term)
(flags 0 :type fixnum))
(defflags boolean-test-term
frotz
bletch)
(test boolean-fns
"test fns in the cl-boolean file"
(let ((aaa (make-boolean-test-term)))
(setf (boolean-test-term-frotz-p aaa) t)
(setf (boolean-test-term-bletch-p aaa) nil)
(is (boolean-test-term-frotz-p aaa))
(is (not (boolean-test-term-bletch-p aaa))))
(is (xor (= 2 3) (= 4 4) (= 7 9)))
(is (not (xor (= 2 3) (= 4 4) (= 7 9) (= 8 8))))
(is (eqv (+ 2 3) (+ 3 2) (+ 4 1) (+ 1 4)))
(is (nand (= 2 3) (plusp -7) (= 17 17)))
(is (nor (= 2 3) (plusp -7) (= 17 31))))
;; cl-extensions
(test extensions
"test fns in the cl-extensions file"
(let ((foo nil)
(count 0))
;; functions:
;; copy-hash-table
;; tbd
;; let-maybe
(is (let-maybe t ((foo t)) foo))
(is (let-maybe nil ((foo t)) (not foo)))
;; while
(while (< count 100)
(incf count))
(is (= count 100))
;; while-not
(while-not (zerop count)
(decf count))
(is (= count 0))
;; let*-non-null
(is (= (let*-non-null ((a t) (b 12) (c 42)) c) 42))
(is (null (let*-non-null ((a t) (b 12) (d nil) (c 42)) c)))
;; msetq (trivial)
;; mlet (trivial)
;; cond-binding-predicate-to
(is (= 49 (cond-binding-predicate-to foo
((+ 18 31)
foo)
(t
foo))))
;; elapsed-time-in-seconds
;; tbd
;; progfoo
(is (= (progfoo 49
(incf foo))
50))
;; with-rhyme (trivial)
;; mv-progfoo
;; get-compiled-function-name
;; comment (trivial)
;; command-line-arg
;; getenv
;; if*
(is (= (if* nil t 1 2 3) 3))
;; make-variable
(setq foo (make-variable "foo"))
;; variablep
(is (variablep foo))
;; noting-progress
;; TBD
))
;; cl-lib-essentials - note these should be obvious as when CL-LIB is loaded, the versions for each file should print.
;; macro-indent-rule (not testable, allegro only)
;; interactive-lisp-p
;; version-reporter
;; detailed-version-reporter
;; report-version
;; cl-list-fns
(test list-fns
"test functions in the file cl-list-fns"
;; types
;; type alist ;; alists are just lists so not a particularly interesting test
;; type true-list
(is (typep '(a b c) 'true-list))
(is (not (typep '(a b . c) 'true-list)))
;; type dotted-list
(is (not (typep '(a b c) 'dotted-list)))
(is (typep '(a b . c) 'dotted-list))
;; functions
;; true-list-p ;; tested with type true-list
;; dotted-list-p ;; tested with type dotted-list
;; update-alist
(let ((a '((a . b) (c . d) (e . f))))
(is (eql (cdr (assoc 'c a)) 'd))
(update-alist 'c 'q a)
(is (eql (cdr (assoc 'c a)) 'q))
;; update-alist-alist
;; reverse-alist
(is (eql (cadr (assoc 'f (reverse-alist a))) 'e)))
;; alistify
(is (equalp (alistify '(foo bar bletch quux)) '((foo . bar) (bletch . quux))))
;; de-alistify
(is (equalp (de-alistify '((foo bar) (bletch quux))) '(:foo (bar) :bletch (quux))))
;; tail-equalp
(is (tail-equalp '(f g) '(a b c d e f g)))
(is (not (tail-equalp '(f g) '(a b c d e f g h))))
;; force-list
(is (listp (force-list 'a)))
;; delete-n
(let ((b '(a b c d e)))
(delete-n b 2)
(is (equalp b '(a b d e)))
;; remove-n
(is (equalp (remove-n b 1) '(a d e))))
;; flatten
(is (equalp '(a b c d e) (flatten '(((a) b (c ((d)) e))))))
;; eqmemb
(is (eqmemb 'a 'a))
(is (eqmemb 'a '(b c a d e)))
;; car-eq
(is (car-eq '(a b c d e) 'a))
;; dremove
(let ((c '(a b c d e)))
(dremove 'c c)
(is (equalp c '(a b d e))))
;; displace
;; tailpush
(let ((d '(a b c d e)))
(tailpush 'f d)
(is (equalp d '(a b c d e f))))
;; explode
;; implode
;; crush
;; TBD
;; listify-string
;; and-list
;; or-list
;; make-plist
)
;; cl-map-fns
(test map-fns
"test functions and macros in file cl-map-fns"
;; functions and macros
;; mapatoms
;; tbd
(let ((test-list '(a b . c)))
;; mapc-dotted-list
;; mapca
(is (equalp test-list (mapcar-dotted-list #'identity test-list)))
;; mapcan-dotted-list
;; maplist-dotted-list
;; some-dotted-list
(is (some-dotted-list #'(lambda (x) (eql x 'c)) test-list))
;; every-dotted-list
(is (every-dotted-list #'symbolp test-list))
;; dosequence
))
;; cl-sets
(test set-fns
"test functions and macros in file cl-sets"
;; functions
(let ((test-list-a '(a b c nil d e nil (f g nil h)))
result-a)
;; list-without-nulls
(setq result-a (list-without-nulls test-list-a))
(is (not (every-dotted-list #'identity test-list-a)))
(is (every-dotted-list #'identity result-a)) ; no nulls in top level list
;; cartesian-product
(is (equalp (cartesian-product '(a b) '(c d)) '((b . d) (b . c) (a . d) (a . c))))
;; more general cross-product
(is (null (set-difference (cross-product '(c d) '(e f) '(a b))
(cross-product '(a b) '(c d) '(e f))
:test #'set-difference))) ; because we are comparing subsets
;; permutations
(is (= (length (permutations '(a b c))) 6))
;; powerset
(is (= (length (powerset '(a b c))) 8)) ; 8 because nil is a subset too
;; circular-list
(is (equalp (mapcar #'+ '(1 2 3 4 5) (circular-list 3)) '(4 5 6 7 8)))
;; occurs
(is (occurs 'a '(((b c) d) e (f (g (h a))))))
(is (not (occurs 'i '(((b c) d) e (f (g (h a)))))))
;; firstn
(is (equalp (firstn '(a b c d e) 3) '(a b c)))
;; in-order-union
(is (equalp (in-order-union '(a b c) '(a d e f)) '(a b c d e f)))
;; fast-union
(is (equalp (union '(a b c) '(a d e f)) (fast-union '(a b c) '(a d e f))))
;; fast-intersection
(is (equalp (intersection '(a b c) '(a d e f)) (fast-intersection '(a b c) '(a d e f))))
))
;; clos-extensions
;; functions and macros
;; defclass-x
;; make-load-form-with-all-slots
;; determine-slot-readers (tested via make-load-form-with-all-slots)
;; determine-slot-writers (ditto)
;; determine-slot-initializers
;; generate-legal-slot-initargs
;; slot-for-initarg
;; files
;; functions and macros
;; load-once
;; do-file
;; keywords
;; functions and macros
;; truncate-keywords
;; remove-keyword-arg
;; extract-keyword
;; make-keyword
;; key-value-list-p
;; number-handling
;; functions and macros
;; bit-length
;; sum-of-powers-of-two-representation
;; difference-of-powers-of-two-representation
;; ordinal-string
;; between
;; round-to
;; factorial
;; round-off
;; strings
;; functions and macros
;; string-search-car
;; string-search-cdr
;; parse-with-delimiter
;; parse-with-delimiters
;; parallel-substitute
;; parse-with-string-delimiter
;; parse-with-string-delimiter*
;; split-string
;; format-justified-string
;; number-to-string
;; null-string
;; time-string
;; read-delimited-string
;; force-string
| 9,196 | Common Lisp | .lisp | 275 | 29.087273 | 118 | 0.605305 | Bradford-Miller/CL-LIB | 1 | 0 | 1 | LGPL-3.0 | 9/19/2024, 11:28:28 AM (Europe/Amsterdam) | 433001657f531b705da136ab8a8679735d17857a552c3d219a69ba2edc7a9f80 | 25,864 | [
-1
] |
25,865 | cl-map-fns.lisp | Bradford-Miller_CL-LIB/functions/cl-map-fns.lisp | (in-package cl-lib)
(version-reporter "CL-LIB-FNS-Map Fns" 5 0 ";; Time-stamp: <2012-01-05 17:45:44 millerb>"
"CVS: $Id: cl-map-fns.lisp,v 1.2 2012/01/05 22:47:54 millerb Exp $
restructured version")
;;;
;;; Copyright (C) 1996--1992 by Bradford W. Miller, [email protected]
;;; and the Trustees of the University of Rochester
;;;
;;; Portions Copyright (C) 2002 by Bradford W. Miller, [email protected]
;;; Right of use & redistribution is granted as per the terms of the
;;; GNU LIBRARY GENERAL PUBLIC LICENCE version 2 which is incorporated here by
;;; reference.
;;; This program is free software; you can redistribute it and/or
;;; modify it under the terms of the GNU Library General Public
;;; License as published by the Free Software Foundation; version 2.
;;; 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 Library General Public License for more details.
;;; You should have received a copy of the GNU Library General Public License
;;; along with this program; if not, write to the Free Software
;;; Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
;;;
;;;
;;; The following is contributed by [email protected]
;; additions for other versions of lisp are welcome!
;;; yep, verrry similar to the one in zetalisp, so on the symbolics we
;;; use that one instead.
#+SYMBOLICS (EVAL-WHEN (COMPILE LOAD EVAL) (SETF (SYMBOL-FUNCTION 'MAPATOMS) #'ZL:MAPATOMS))
#-SYMBOLICS
(DEFUN MAPATOMS (FUNC &OPTIONAL (PACKAGE *PACKAGE*) (INHERITED-SYMBOLS-TOO T))
"Maps the passed function over all symbols in the package, and if inherited-symbols-too is non-nil, then
over those symbols as well. Note that the function may be called >once on a symbol."
(DO-SYMBOLS (SYM PACKAGE)
(IF (OR INHERITED-SYMBOLS-TOO
(EQ PACKAGE (SYMBOL-PACKAGE SYM)))
(FUNCALL FUNC SYM))))
;;; add dynamic-extent declaration 3/8/91 - bwm
;;; rewrite for greater efficiency 5/28/93 - bwm
(DEFMACRO MAPC-DOTTED-LIST (FN &REST LISTS)
"Like normal Mapc, but handles dotted lists, and will apply the fn
to the dotted argument, unless it is NIL"
(let ((arglist `(,@(mapcar #'(lambda (l)
(declare (ignore l))
(gensym)) ; entry for each list passed.
lists)))
(fnv (gensym)))
`(BLOCK mdl (let ((,fnv ,fn)) ; avoid multiple evaluation
(MAPLIST #'(lambda ,arglist
(funcall ,FNv ,@(mapcar #'(lambda (argname) `(car ,argname)) arglist))
;; is cdr an atom
(COND
((or ,@(mapcar #'(lambda (arg) `(and (atom (cdr ,arg)) (cdr ,arg))) arglist))
(funcall ,FNv ,@(mapcar #'(lambda (argname) `(cdr ,argname)) arglist))
(RETURN-FROM mdl (VALUES)))))
,@LISTS))
(VALUES))))
(macro-indent-rule mapc-dotted-list (like mapc))
;;; add dynamic-extent declaration & use gensyms for local vars 3/8/91 - bwm
;;; rewrite for greater efficiency 5/28/93 - bwm
(DEFMACRO MAPCAR-DOTTED-LIST (FN &REST LISTS)
"Like normal Mapcar, but handles dotted lists, and will apply the fn
to the dotted argument, unless it is NIL"
(LET ((RETURN-VAL (GENSYM))
(last-retval (gensym))
(last-retval1 (gensym))
(LASTCDR (GENSYM))
(arglist `(,@(mapcar #'(lambda (l)
(declare (ignore l))
(gensym)) ; entry for each list passed.
lists)))
(fnv (gensym)))
`(LET (,RETURN-VAL ,LASTCDR ,last-retval1 (,fnv ,fn)) ; avoid multiple evaluation
(BLOCK mdl (MAPLIST #'(LAMBDA ,arglist
(let ((,last-retval (list (funcall ,FNv ,@(mapcar #'(lambda (argname) `(car ,argname)) arglist)))))
(if ,return-val
(nconc ,last-retval1 ,last-retval)
(setq ,return-val ,last-retval))
(setq ,last-retval1 ,last-retval))
;; is cdr an atom
(COND
((or ,@(mapcar #'(lambda (arg) `(and (atom (cdr ,arg)) (cdr ,arg))) arglist))
(SETQ ,LASTCDR (funcall ,FNv ,@(mapcar #'(lambda (argname) `(cdr ,argname)) arglist)))
(RETURN-FROM mdl (values)))))
,@LISTS))
(NCONC ,RETURN-VAL ,LASTCDR))))
(macro-indent-rule mapcar-dotted-list (like mapcar))
;;; add dynamic-extent declaration & use gensyms for local vars 3/8/91 - bwm
;;; rewrite for greater efficiency 5/28/93 - bwm
(DEFMACRO MAPCAN-DOTTED-LIST (FN &REST LISTS)
"Like normal Mapcan, but handles dotted lists, and will apply the fn
to the dotted argument, unless it is NIL"
(LET ((RETURN-VAL (GENSYM))
(fnv (gensym))
(arglist `(,@(mapcar #'(lambda (l)
(declare (ignore l))
(gensym)) ; entry for each list passed.
lists))))
`(LET (,RETURN-VAL (,fnv ,fn))
(BLOCK mdl (MAPLIST #'(lambda ,arglist
(SETQ ,RETURN-VAL (NCONC ,RETURN-VAL (funcall ,FNv ,@(mapcar #'(lambda (argname) `(car ,argname)) arglist))))
;; is cdr an atom
(COND
((or ,@(mapcar #'(lambda (arg) `(and (atom (cdr ,arg)) (cdr ,arg))) arglist))
(SETQ ,RETURN-VAL (NCONC ,RETURN-VAL (funcall ,FNv ,@(mapcar #'(lambda (argname) `(cdr ,argname)) arglist))))
(RETURN-FROM mdl (VALUES)))))
,@LISTS))
,RETURN-VAL)))
(macro-indent-rule mapcan-dotted-list (like mapcan))
;;; rewrite for greater efficiency 5/28/93 - bwm
(DEFMACRO MAPLIST-DOTTED-LIST (FN &REST LISTS)
"Like normal Maplist, but handles dotted lists, and will apply the
fn to the dotted argument, unless it is NIL"
(LET ((RETURN-VAL (GENSYM))
(fnv (gensym))
(arglist `(,@(mapcar #'(lambda (l)
(declare (ignore l))
(gensym)) ; entry for each list passed.
lists))))
`(LET (,RETURN-VAL (,fnv ,fn))
(BLOCK mdl (MAPLIST #'(lambda ,arglist
(SETQ ,RETURN-VAL (nconc ,RETURN-VAL (list (funcall ,FNv ,@arglist))))
;; is cdr an atom
(COND
((or ,@(mapcar #'(lambda (arg) `(and (atom (cdr ,arg)) (cdr ,arg))) arglist))
(SETQ ,RETURN-VAL (nconc ,RETURN-VAL (list (funcall ,FNv ,@(mapcar #'(lambda (argname) `(cdr ,argname)) arglist)))))
(RETURN-FROM mdl (VALUES)))))
,@LISTS))
,RETURN-VAL)))
(macro-indent-rule maplist-dotted-list (like maplist))
;;; add dynamic-extent declaration 3/8/91 - bwm
;;; rewrite for greater efficiency 5/28/93 - bwm
(DEFMACRO SOME-DOTTED-LIST (FN &REST LISTS)
"Like normal Some, but handles a single dotted list, and will apply
the fn to the dotted argument, unless it is NIL"
(let ((fnv (gensym))
(arglist `(,@(mapcar #'(lambda (l)
(declare (ignore l))
(gensym)) ; entry for each list passed.
lists))))
`(let ((,fnv ,fn))
(BLOCK sdl (MAPLIST #'(lambda ,arglist
(IF (funcall ,FNv ,@(mapcar #'(lambda (argname) `(car ,argname)) arglist))
(RETURN-FROM sdl T)
;; is cdr an atom
(COND
((or ,@(mapcar #'(lambda (arg) `(and (atom (cdr ,arg)) (cdr ,arg))) arglist))
(IF (funcall ,FNv ,@(mapcar #'(lambda (argname) `(cdr ,argname)) arglist))
(RETURN-FROM sdl T)
(RETURN-FROM sdl NIL))))))
,@LISTS)
NIL)))) ;fell thru maplist w/o return
(macro-indent-rule some-dotted-list (like some))
;;; add dynamic-extent declaration 3/8/91 - bwm
;;; rewrite for greater efficiency 5/28/93 - bwm
(DEFMACRO EVERY-DOTTED-LIST (FN &REST LISTS)
"Like normal Every, but handles dotted lists, and will apply the fn
to the dotted arguments, unless they are (all) NIL."
(let ((fnv (gensym))
(arglist `(,@(mapcar #'(lambda (l)
(declare (ignore l))
(gensym)) ; entry for each list passed.
lists))))
`(let ((,fnv ,fn))
(BLOCK Edl (MAPLIST #'(lambda ,arglist
(IF (funcall ,FNv ,@(mapcar #'(lambda (argname) `(car ,argname)) arglist))
;; is cdr an atom
(COND
((or ,@(mapcar #'(lambda (arg) `(and (atom (cdr ,arg)) (cdr ,arg))) arglist))
(IF (funcall ,FNv ,@(mapcar #'(lambda (argname) `(cdr ,argname)) arglist))
(RETURN-FROM Edl T)
(RETURN-FROM Edl NIL))))
(RETURN-FROM Edl NIL)))
,@LISTS)
T)))) ;fell thru maplist w/o return
(macro-indent-rule every-dotted-list (like every))
(defmacro dosequence ((var sequence &optional result) &BODY body)
"(dosequence (var sequence &optional result) &body body) [macro]
This macro is like DOLIST \(q.v.), except that the iteration is over
any sequence, not necessarily a list."
#+lispm (declare (zwei:indentation 1 1))
(check-type var symbol)
(let ((iter-index (gensym))
(iter-limit (gensym)))
`(do* ((,var)
(,iter-limit (length ,sequence))
(,iter-index 0 (+ ,iter-index 1)))
((= ,iter-index ,iter-limit)
(setq ,var nil)
,result)
(setq ,var (elt ,sequence ,iter-index))
,@body)))
(macro-indent-rule dosequence (like dolist))
| 10,214 | Common Lisp | .lisp | 193 | 40.740933 | 130 | 0.551365 | Bradford-Miller/CL-LIB | 1 | 0 | 1 | LGPL-3.0 | 9/19/2024, 11:28:28 AM (Europe/Amsterdam) | 62fbf4f14f0a9fd8975c1f1df5120300076eda5adadd7e47dc3446ade0adf824 | 25,865 | [
-1
] |
25,866 | keywords.lisp | Bradford-Miller_CL-LIB/functions/keywords.lisp | (in-package cl-lib)
(version-reporter "CL-LIB-FNS-Keyword Fns" 5 20 ";; Time-stamp: <2022-01-31 12:57:03 gorbag>"
";; remove-keyword-args")
;; 5.20 1/31/22 add remove-keyword-args as a more efficient version of
;; remove-keyword-arg when there are multiple
;; keywords to be removed and we don't care about
;; their value.
;; 5.19 2/ 8/21 make remove-keyword-arg more robust to odd numbers of arguments in argument-list
;; 5.16 2/23/19 use sbcl's sb-int:*Keyword-package* instead of consing another
;; 5.8 1/30/08 key-value-list-p
;; 5.2 6/28/07 make arglist of make-keyword more illuminating
;;;
;;; Copyright (C) 1996--1992 by Bradford W. Miller, [email protected]
;;; and the Trustees of the University of Rochester
;;;
;;; Portions Copyright (C) 2002 by Bradford W. Miller, [email protected]
;;; Right of use & redistribution is granted as per the terms of the
;;; GNU LIBRARY GENERAL PUBLIC LICENCE version 2 which is incorporated here by
;;; reference.
;;; This program is free software; you can redistribute it and/or
;;; modify it under the terms of the GNU Library General Public
;;; License as published by the Free Software Foundation; version 2.
;;; 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 Library General Public License for more details.
;;; You should have received a copy of the GNU Library General Public License
;;; along with this program; if not, write to the Free Software
;;; Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
;;;
;;;
;;; The following is contributed by [email protected]
;; additions for other versions of lisp are welcome!
;;; Faster definition. In old definition, length may wind up cdring
;;; down the list (depends on the lisp).
(defun truncate-keywords (input-list)
"Many functions take multiple arguments, via &rest, that can cause
problems when keyword arguments are also supplied. This function
truncates a list at the first top-level keyword. Thus, '(A B C :FOO D)
is returned as (A B C). Note that the new list is freshly consed to
avoid any stack problems with destroying a &rest argument."
(declare (type list input-list)
(optimize (speed 3) (safety 0)))
(ldiff input-list (member-if #'keywordp input-list)))
;; 2/8/21 - no longer goes down input-list 2 entries at a time, which allows us to handle odd lambda-lists (where not
;; all arguments are keywords!) Now O(n) instead of O(n/2) but that's fine.
;; changed to return multiple values 7/23/02 BWM
(defun remove-keyword-arg (keyword input-list)
"from a set of keyword arguments, remove a particular pair marked by
the passed keyword, i.e. \(remove-keyword-arg :a '(:b 2 :a 3 :d 7))
-> (:b 2 :d 7). Return multiple values, the first being the new list,
the second being the argument to the (first) keyword removed, and the third
indicating if there were a removal (useful if the second value is
null)."
(declare (type keyword keyword)
(type list input-list)
(values new-list keyword-value removed-p))
;; remember a keyword could be an argument, so we can't just find
;; the first occurance, we have to treat the list in pairs.
(cond
((null input-list)
(values nil nil nil))
((eql (car input-list) keyword)
(values (cddr input-list) (cadr input-list) t))
((endp (cdr input-list))
(values input-list nil nil))
(t
(mlet (new-list keyword-value removed-p)
(remove-keyword-arg keyword (cdr input-list))
(if removed-p
(values (list* (car input-list) new-list)
keyword-value
removed-p)
(values input-list nil nil))))))
;; sometimes we have multiple keywords
(defun remove-keyword-args (keyword-list input-list)
"Similar to remove-keyword-arg, but removes all of multiple items at the same time. Note that the keyword-value is no longer returned."
(declare (type list keyword-list input-list)
(values new-list removed-p))
(cond
((null input-list)
(values nil nil))
((member (car input-list) keyword-list)
(values (remove-keyword-args keyword-list (cddr input-list)) t))
((endp (cdr input-list))
(values input-list nil))
(t
(mlet (new-list removed-p)
(remove-keyword-args keyword-list (cdr input-list))
(if removed-p
(values (list* (car input-list) new-list) removed-p)
(values input-list nil))))))
;;
;;
;;; any benefit of the position's :from-end is lost by the calls to length,
;;; so use member.
;; 2/1/07 - as a second value, return the full binding - allows destructive update
;; - clarify and fix semantics of default and no-value. Not sure no-value is useful anymore.
(defun extract-keyword (key arglist &optional (default nil)
&key (no-value nil))
"Searches the arglist for keyword key, and returns the following mark,
or the default if supplied. If no-value is non-nil, then if the key is present and nothing follows it,
the no-value parameter it is returned."
(declare (type list arglist)
(type t default)
(type keyword key)
(optimize (speed 3) (safety 0)))
(let ((binding (member key arglist)))
(values (cond ((null binding)
default) ; nothing there
((cdr binding)
(cadr binding)) ;found it
(t
no-value)) ;it was there, but doesn't have a value (was the last item in the list)
binding)))
;; sbcl port 2/23/19 BWM
#-(or EXCL sbcl) (defvar *keyword-package* (find-package 'keyword))
(defun make-keyword (symbol-or-string)
(intern (IF (SYMBOLP SYMBOL-or-string)
(symbol-name symbol-or-string)
SYMBOL-or-string)
#-(or excl sbcl) *keyword-package*
#+excl excl:*keyword-package*
#+sbcl sb-int:*keyword-package*))
(defun key-value-list-p (key-value-pairs)
"Assure that the passed argument is an alternating list of keywords and something"
(or (null key-value-pairs) ; nil is fine (and allows tail recursion!)
(and (consp key-value-pairs) ; otherwise, better be a real list
(keywordp (car key-value-pairs))
(listp (cdr key-value-pairs)) ; check for . case
(not (endp (cdr key-value-pairs)))
(key-value-list-p (cddr key-value-pairs)))))
| 6,568 | Common Lisp | .lisp | 132 | 44.69697 | 137 | 0.679101 | Bradford-Miller/CL-LIB | 1 | 0 | 1 | LGPL-3.0 | 9/19/2024, 11:28:28 AM (Europe/Amsterdam) | 19f3601f7a8c5f0a229a6ff1ca49d29dc4eb47c91630178b0bcce8ca4868343b | 25,866 | [
-1
] |
25,867 | cl-lib-defpackage.lisp | Bradford-Miller_CL-LIB/functions/cl-lib-defpackage.lisp | (in-package cl-user)
(defpackage :cl-lib-initializations (:use common-lisp) (:export #:add-initialization #:initializations #:delete-initialization #:reset-initializations #:*cold-initialization-list* #:*warm-initialization-list* #:*once-initialization-list* #:*gc-initialization-list* #:*before-cold-initialization-list* #:*after-gc-initialization-list* #:*initialization-keywords*) (:documentation "Symbolics compatible initializations package for common lisp"))
(defpackage :cl-lib-essentials (:use common-lisp :cl-lib-initializations) (:export #:macro-indent-rule #:version-reporter #:detailed-version-reporter #:report-version #:interactive-lisp-p #:*cl-lib-version-announce-p* #:*cl-lib-version-reporter-string* #:*cl-lib-detailed-version-reporter-string*) (:documentation "Essential functions for implementing the cl-lib"))
(defparameter *cl-lib-defpackage-version* '(cl-lib-essentials:version-reporter "CL-LIB-Defpackage" 5 20
";; Time-stamp: <2022-01-31 12:55:02 gorbag>"
"remove-keyword-args"))
;; the ugliness above (putting the defpackages first) is to support the auto-update of the timestamp on the file (default top 5 lines).
;; 5.20 1/31/22 remove-keyword-args
;; 5.18 1/ 3/20 firstn wasn't exported?! Also create :clos-facet-tests package
;; 5.17 11/ 8/19 occurs wasn't exported?!
;; 5.16 2/16/19 Start to add FiveAM testing capabilities
;; 5.14 12/16/11 detailed-version-reporter
;; 5.13 10/19/11 use lispworks' version of dotted-list-p
;; 5.12 7/11/08 export de-alistify, true-list-p, true-list
;; 5.10 4/23/08 lispworks - export *keyword-package*
;; 5.9 2/19/08 tail-equalp
;; 5.8 1/30/08 key-value-list-p
;; 5.7 11/26/07 documentation on packages
;; 5.5-5.6 skipped
;; 5.4 10/10/07 export getenv if necessary
;; 5.2 export slot-for-initarg
;; This portion of CL-LIB Copyright (C) 1984-2011 Bradford W. Miller and the
;; Trustees of the University of Rochester
;; Some portions are Copyright (C) 2019, 2020 by Bradford W. Miller
;;
;; This library is free software; you can redistribute it and/or modify it under the terms of the GNU
;; Lesser General Public License as published by the Free Software Foundation; either version 3.0 of
;; the License, or (at your option) any later version.
;; This library 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.
;; You should have received a copy of the GNU Lesser General Public License along with this library;
;; if not, see <http://www.gnu.org/licenses/>.
;; the first few lines are crammed together to get the version stamp
;; into the cl-lib-defpackage-version line while still defining an
;; essential package.
;; miller - Brad Miller ([email protected]) (now [email protected])
;; new fractured cl-lib, with multiple defsystems for each package. So the "right ones" can be added as needed.
(defpackage :cl-lib
(:use common-lisp :cl-lib-initializations :cl-lib-essentials)
#+lispworks (:shadowing-import-from hcl #:getenv)
#+lispworks (:shadowing-import-from lispworks #:dotted-list-p)
(:documentation "A useful collection of functions that keep coming
up in general CL programming. Note that some are loaded by their own
system file (e.g., cl-lib-scheme-streams), so one can use only the
base system (cl-lib-essentials) plus those parts that one really
needs for a particular application.")
(:export
;; re-export from :cl-lib-initializations
#:add-initialization #:initializations #:delete-initialization #:reset-initializations
#:*cold-initialization-list* #:*warm-initialization-list* #:*once-initialization-list*
#:*gc-initialization-list* #:*before-cold-initialization-list* #:*after-gc-initialization-list*
#:*initialization-keywords*
;; re-export from :cl-lib-essentials
#:macro-indent-rule
#:version-reporter #:report-version #:detailed-version-reporter
#:command-line-arg #:getenv
#:force-list #:flatten #:alistify #:de-alistify #:tail-equalp
#:remove-n #:delete-n
;; clim-extensions.lisp
#+(AND CLIM (NOT LISPWORKS))
#:frame-pane
;; cl-sets.lisp
#:list-without-nulls #:cartesian-product #:cross-product
#:permutations #:powerset #:circular-list #:occurs
#:firstn #:in-order-union #:fast-union #:fast-intersection
#:seq-butlast #:seq-last #:dosequence
#:prefix?
#:elapsed-time-in-seconds
#:factorial #:round-to #:round-off
#:extract-keyword #:truncate-keywords #:remove-keyword-arg #:remove-keyword-args #:key-value-list-p
#:update-alist #:update-alist-alist #:msetq #:mlet #:while #:while-not #:let*-non-null
#:cond-binding-predicate-to
#:mapc-dotted-list #:mapcar-dotted-list #:mapcan-dotted-list #:maplist-dotted-list
#:some-dotted-list #:every-dotted-list
#:copy-hash-table
#:defclass-x #:defflag #:defflags #:let-maybe
#:eqmemb #-MCL #:neq #:car-eq #:dremove #:displace #:tailpush
#:explode #:implode #:crush
#:listify-string #:listify
#:and-list #:or-list
#:make-variable #:variablep
#:dofile #:copy-array
#-excl #:if*
#-excl #:*keyword-package*
#+excl #:raw-read-char
#+excl #:raw-peek-char
#+excl #:raw-read-char-no-hang
#:make-plist
#:make-keyword
#:internal-real-time-in-seconds #:read-char-wait
#:flags
#:mapatoms
#:reverse-alist
#:true-list-p #:dotted-list-p #:progfoo #:foo #:mv-progfoo #:mv-foo #:with-rhyme
#:get-compiled-function-name #:fast-read-char #:fast-read-file-char
;; better-errors.lisp
#:warn-or-error #:*general-warning-list* #:*warn-or-error-cleanup-initializations*
#:check
#:parser-error
;; resources.lisp
#-LispWorks #:defresource
#-LispWorks #:allocate-resource
#-LispWorks #:deallocate-resource
#-LispWorks #:clear-resource
#-LispWorks #:map-resource
#-LispWorks #:with-resource
#+excl #:edit-system
#:alist #:true-list #:dotted-list #:comment
#:xor #:eqv #:nand #:nor
#:load-once #:clear-load-once
;; locatives.lisp
#:locf #:location-contents #:locative-p #:locative
;; nregex.lisp
#:regex #:regex-compile
;; prompt-and-read
#+clim #:popup-read-form #+clim #:popup-error #:prompt-and-read #:prompt-for
#+clim #:convert-to-presentation-type #+clim #:convert-satisfies-to-presentation-type
#+clim #:*default-presentation-type* #+clim #:clim-prompt-for #+clim #:clim-prompt-for-with-default
#:*suppress-clim*
;; clos-extensions
#:make-load-form-with-all-slots #:determine-slot-readers #:determine-slot-writers #:determine-slot-initializers
#:generate-legal-slot-initargs #:*load-form-quote-p-fn* #:slot-for-initarg
;; syntax
#:add-syntax #:with-syntax #:set-syntax
;; scheme-streams
#:scheme-delay #:scheme-delay-p #:scheme-force #:scheme-stream
#:ss-head #:ss-tail #:cons-scheme-stream #:make-scheme-stream
#:list-scheme-stream #:rlist-to-scheme-stream #:fake-scheme-delay
#:scheme-stream-p #:scheme-stream-head #:scheme-stream-tail
#:scheme-stream-tail-closure-p
;; queues
#:make-queue #:queue-elements #:empty-queue-p #:queue-front #:dequeue #:enqueue #:safe-dequeue
;; strings
#:string-search-car #:string-search-cdr #:parse-with-delimiter #:parse-with-delimiters #:parallel-substitute
#:parse-with-string-delimiter #:parse-with-string-delimiter* #:split-string #:format-justified-string
#:number-to-string #:null-string #:time-string
#:read-delimited-string #:force-string
))
;; This portion of CL-LIB Copyright (C) 2019 Bradford W. Miller
;;
;; This library is free software; you can redistribute it and/or modify it under the terms of the GNU
;; Lesser General Public License as published by the Free Software Foundation; either version 3.0 of
;; the License, or (at your option) any later version.
;; This library 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.
;; You should have received a copy of the GNU Lesser General Public License along with this library;
;; if not, see <http://www.gnu.org/licenses/>.
;; miller - Brad Miller ([email protected])
(defpackage :clos-facets
(:use #:common-lisp #:cl-lib)
(:shadow #:defclass #:slot-makunbound #:slot-unbound #:slot-value #:slot-boundp #:unbound-slot
#:slot-makunbound-using-class #:slot-value-using-class #:slot-boundp-using-class)
(:export #:defclass #:slot-makunbound #:slot-unbound #:slot-value #:slot-boundp
#:slot-makunbound-using-class #:slot-value-using-class #:slot-boundp-using-class
#:defslot #:deffacet #:slot-definition-facets #:slot-facet-value #:slot-facet-value-using-class
#:clos-facets-error #:clos-facets-incompatible #:clos-facets-program-error #:value-type-decl-incompatible
#:cardinality-bounds-incompatible #:clos-facets-cell-error #:cardinality-bounds-error #:cardinality-bounds-underrun
#:cardinality-bounds-overrun #:value-type-error #:no-multiple-slotvalues #:unbound-slot #:unbound-slot-place
#:clos-facets-warning #:facet-missing #:facet-missing-error #:facet-unbound
#:no-multiple-slotvalues-instance #:no-multiple-slotvalues-place
;; support fns
#:clear-slot-value-cache)
(:documentation "See the file 'Extending CLOS with Facets.doc' for extensive documentation."))
| 9,792 | Common Lisp | .lisp | 165 | 54.381818 | 444 | 0.711656 | Bradford-Miller/CL-LIB | 1 | 0 | 1 | LGPL-3.0 | 9/19/2024, 11:28:28 AM (Europe/Amsterdam) | d28adddb01dde2a03ebce4930c90ebe064e75d4f0c7b3fa222db254479f02732 | 25,867 | [
-1
] |
25,868 | strings.lisp | Bradford-Miller_CL-LIB/functions/strings.lisp | ;;; -*- Mode: LISP; Syntax: Ansi-common-lisp; Package: CL-LIB; Base: 10 -*-
(IN-PACKAGE CL-LIB)
(version-reporter "CL-LIB-FNS-Strings" 5 0 ";; Time-stamp: <2008-05-03 13:36:04 gorbag>"
"CVS: $Id: strings.lisp,v 1.2 2008/05/03 17:42:01 gorbag Exp $
restructured version")
;; This portion of CL-LIB Copyright (C) 1986-2008 Bradford W. Miller and the
;; Trustees of the University of Rochester
;;
;; This library is free software; you can redistribute it and/or modify it under the terms of the GNU
;; Lesser General Public License as published by the Free Software Foundation; either version 3.0 of
;; the License, or (at your option) any later version.
;; This library 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.
;; You should have received a copy of the GNU Lesser General Public License along with this library;
;; if not, see <http://www.gnu.org/licenses/>.
;;;; Note the local extensions remain in cl-extensions. <miller>
;
;;;; ****************************************************************
;;;; Extensions to Common Lisp **************************************
;;;; ****************************************************************
;;;;
;;;; This file is a collection of extensions to Common Lisp.
;;;;
;;;; It is a combination of the CL-LIB package copyleft by Brad Miller
;;;; <[email protected]> and a similar collection by
;;;; Mark Kantrowitz <[email protected]>.
;;;;
;;;; The following functions were originally from CL-LIB:
;;;; let-if, factorial, update-alist, truncate-keywords, while,
;;;; defclass-x, copy-hash-table, defflag, round-to, extract-keyword
;;;; let*-non-null, mapc-dotted-list,
;;;; mapcar-dotted-list, mapcan-dotted-list, some-dotted-list,
;;;; every-dotted-list, msetq, mlet, dosequence, force-string, prefix?,
;;;; elapsed-time-in-seconds, bit-length, flatten,
;;;; sum-of-powers-of-two-representation,
;;;; difference-of-powers-of-two-representation,
;;;; ordinal-string, between,
;;;; cond-binding-predicate-to <[email protected]>
;;;; remove-keywords <[email protected]>
;;;;
;;;; The following functions were contributed by Mark Kantrowitz:
;;;; circular-list, dofile, seq-butlast, seq-last, firstn, in-order-union
;;;; parse-with-delimiter, parse-with-delimiters, string-search-car,
;;; string-search-cdr, parallel-substitute, lisp::nth-value,
;;;; parse-with-string-delimiter, parse-with-string-delimiter*,
;;;; member-or-eq, number-to-string, null-string, time-string.
;;;; list-without-nulls, cartesian-product, cross-product, permutations
;;;; powerset, occurs, split-string, format-justified-string,
;;;; eqmemb, neq, car-eq, dremove, displace, tailpush, explode,
;;;; implode, crush, listify-string, and-list, or-list, lookup,
;;;; make-variable, variablep, make-plist, make-keyword
;;;;
;;;; The GNU Emacs distribution agreement is included by reference.
;;;; Share and Enjoy!
;;;;
;
;;; Uncomment this to make the extensions accessible from the Lisp package
;;; without the EXT prefix.
;(in-package "LISP")
;;; ********************************
;;; Strings ************************
;;; ********************************
(defun string-search-car (character-bag string)
"Returns the part of the string before the first of the delimiters in
CHARACTER-BAG and the delimiter."
(let* ((delimiter nil)
(delimiter-position (position-if #'(lambda (character)
(when (find character
character-bag)
(setq delimiter character)))
string)))
(values (subseq string 0 delimiter-position)
delimiter)))
(defun string-search-cdr (character-bag string)
"Returns the part of the string after the first of the delimiters in
CHARACTER-BAG, if any, and the delimiter. If none of the delimiters
are found, returns NIL and NIL."
(let* ((delimiter nil)
(delimiter-position (position-if #'(lambda (character)
(when (find character
character-bag)
(setq delimiter character)))
string)))
(if delimiter-position
(values (subseq string (1+ delimiter-position))
delimiter)
;; Maybe this should be "" instead of NIL?
(values nil delimiter))))
(defun parse-with-delimiter (line &optional (delim #\newline))
"Breaks LINE into a list of strings, using DELIM as a
breaking point."
;; what about #\return instead of #\newline?
(let ((pos (position delim line)))
(cond (pos
(cons (subseq line 0 pos)
(parse-with-delimiter (subseq line (1+ pos)) delim)))
(t
(list line)))))
(defun parse-with-delimiters (line &optional (delimiters '(#\newline)))
"Breaks LINE into a list of strings, using DELIMITERS as a
breaking point."
;; what about #\return instead of #\newline?
(let ((pos (position-if #'(lambda (character) (find character delimiters))
line)))
(cond (pos
(cons (subseq line 0 pos)
(parse-with-delimiters (subseq line (1+ pos)) delimiters)))
(t
(list line)))))
;;; subst:sublis::substitute:? -- cl needs a parallel-substitute for
;;; performing many substitutions in a sequence in parallel.
(defun parallel-substitute (alist string)
"Makes substitutions for characters in STRING according to the ALIST.
In effect, PARALLEL-SUBSTITUTE can perform several SUBSTITUTE
operations simultaneously."
(declare (simple-string string))
;; This function should be generalized to arbitrary sequences and
;; have an arglist (alist sequence &key from-end (test #'eql) test-not
;; (start 0) (count most-positive-fixnum) end key).
(if alist
(let* ((length (length string))
(result (make-string length)))
(declare (simple-string result))
(dotimes (i length)
(let ((old-char (schar string i)))
(setf (schar result i)
(or (second (assoc old-char alist :test #'char=))
old-char))))
result)
string))
(defun parse-with-string-delimiter (delim string &key (start 0) end)
"Returns up to three values: the string up to the delimiter DELIM
in STRING (or NIL if the field is empty), the position of the beginning
of the rest of the string after the delimiter, and a value which, if
non-NIL (:delim-not-found), specifies that the delimiter was not found."
(declare (simple-string string))
;; Conceivably, if DELIM is a string consisting of a single character,
;; we could do this more efficiently using POSITION instead of SEARCH.
;; However, any good implementation of SEARCH should optimize for that
;; case, so nothing to worry about.
(setq end (or end (length string)))
(let ((delim-pos (search delim string :start2 start :end2 end))
(dlength (length delim)))
(cond ((null delim-pos)
;; No delimiter was found. Return the rest of the string,
;; the end of the string, and :delim-not-found.
(values (subseq string start end) end :delim-not-found))
((= delim-pos start)
;; The field was empty, so return nil and skip over the delimiter.
(values nil (+ start dlength)))
;; The following clause is subsumed by the last cond clause,
;; and hence should probably be eliminated.
(t
;; The delimiter is in the middle of the string. Return the
;; field and skip over the delimiter.
(values (subseq string start delim-pos)
(+ delim-pos dlength))))))
(defun parse-with-string-delimiter* (delim string &key (start 0) end
include-last)
"Breaks STRING into a list of strings, each of which was separated
from the previous by DELIM. If INCLUDE-LAST is nil (the default),
will not include the last string if it wasn't followed by DELIM
(i.e., \"foo,bar,\" vs \"foo,bar\"). Otherwise includes it even if
not terminated by DELIM. Also returns the final position in the string."
(declare (simple-string string))
(setq end (or end (length string)))
(let (result)
(loop
(if (< start end)
(multiple-value-bind (component new-start delim-not-found)
(parse-with-string-delimiter delim string :start start :end end)
(when delim-not-found
(when include-last
(setq start new-start)
(push component result))
(return))
(setq start new-start)
(push component result))
(return)))
(values (nreverse result)
start)))
;; set in user-manual
(defun split-string (string &key (item #\space) (test #'char=))
;; Splits the string into substrings at spaces.
(let ((len (length string))
(index 0) result)
(dotimes (i len
(progn (unless (= index len)
(push (subseq string index) result))
(reverse result)))
(when (funcall test (char string i) item)
(unless (= index i);; two spaces in a row
(push (subseq string index i) result))
(setf index (1+ i))))))
(defun format-justified-string (prompt contents &optional (width 80)
(stream *standard-output*))
(let ((prompt-length (+ 2 (length prompt))))
(cond ((< (+ prompt-length (length contents)) width)
(format stream "~%~A- ~A" prompt contents))
(t
(format stream "~%~A-" prompt)
(do* ((cursor prompt-length)
(contents (split-string contents) (cdr contents))
(content (car contents) (car contents))
(content-length (1+ (length content)) (1+ (length content))))
((null contents))
(cond ((< (+ cursor content-length) width)
(incf cursor content-length)
(format stream " ~A" content))
(t
(setf cursor (+ prompt-length content-length))
(format stream "~%~A ~A" prompt content)))))))
(finish-output stream))
(defun number-to-string (number &optional (base 10))
(cond ((zerop number) "0")
((eql number 1) "1")
(t
(do* ((len (1+ (truncate (log number base))))
(res (make-string len))
(i (1- len) (1- i))
(q number) ; quotient
(r 0)) ; residue
((zerop q) ; nothing left
res)
(declare (simple-string res)
(fixnum len i r))
(multiple-value-setq (q r) (truncate q base))
(setf (schar res i)
(schar "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ" r))))))
(defun null-string (string &optional (start 0) end)
"Returns T if STRING is the null string \"\" between START and END."
(unless end (setf end (length string)))
(string-equal string "" :start1 start :end1 end))
;;;; ********************************
;;;; Time ***************************
;;;; ********************************
(defun time-string (&optional universal-time)
(unless universal-time (setf universal-time (get-universal-time)))
(multiple-value-bind (secs min hour date month year dow)
(decode-universal-time universal-time)
(format nil "~@:(~A ~A-~A-~A ~2,'0d:~2,'0d:~2,'0d~)"
(svref '#("Mon" "Tue" "Wed" "Thu" "Fri" "Sat" "Sun") dow)
date
(svref '#(0 "Jan" "Feb" "Mar" "Apr" "May"
"Jun" "Jul" "Aug" "Sep" "Oct"
"Nov" "Dec")
month)
(mod year 100)
hour min secs)))
;; miller
;; This function was inspired by a similar function on the Symbolics
;; lisp machine, which was used in the Rhet system. In fact, if we are
;; on a symbolics, use that one. It will return more values, but
;; that's ok. Plus we get the input editor "for free :-)" collect the
;; characters until we hit a delimiter or eof, then turn it into a
;; string and return!
#-SYMBOLICS
(DEFUN READ-DELIMITED-STRING (DELIMITERS &OPTIONAL (STREAM *STANDARD-INPUT*) (EOF-ERROR-P T) EOF-VALUE)
"Read a stream until one of the delimiters (a list of characters) is
found. Returns the characters so read until the delimiter as a string,
plus the additional values: EOF-VALUE, which is as passed if eof was
reached, and the delimiter that caused termination of the string. If
EOF-ERROR-P is non-nil (the default), then an EOF causes an error to
be signalled instead of returning EOF-VALUE."
(DECLARE (TYPE LIST DELIMITERS)
(TYPE STREAM STREAM))
(LET (CHAR-LIST)
(DECLARE (DYNAMIC-EXTENT CHAR-LIST))
(DO ((READ-CHAR (READ-CHAR STREAM EOF-ERROR-P :EOF) (READ-CHAR STREAM EOF-ERROR-P :EOF)))
((OR (MEMBER READ-CHAR DELIMITERS) (EQ READ-CHAR :EOF))
(VALUES (COERCE (NREVERSE CHAR-LIST) 'STRING)
(IF (EQ READ-CHAR :EOF) EOF-VALUE) READ-CHAR))
(PUSH READ-CHAR CHAR-LIST))))
;;; the following is contributed by [email protected]
(defun Force-String (Thing)
"Generates a string representation of Thing. This representation
is the print name for symbols, otherwise whatever 'coerce' can do (which may
be to generate an error sometimes)."
(cond
((symbolp Thing) (symbol-name Thing))
(t (coerce Thing 'string))))
| 12,757 | Common Lisp | .lisp | 1 | 12,756 | 12,757 | 0.647252 | Bradford-Miller/CL-LIB | 1 | 0 | 1 | LGPL-3.0 | 9/19/2024, 11:28:28 AM (Europe/Amsterdam) | 408d4421f17473854f6f6f3ebd88110b589ac9238c4e78afdeb2aa8c974aa3bc | 25,868 | [
-1
] |
25,869 | files.lisp | Bradford-Miller_CL-LIB/functions/files.lisp | ;;; -*- Mode: LISP; Syntax: Ansi-common-lisp; Package: CL-LIB; Base: 10 -*-
(IN-PACKAGE CL-LIB)
(version-reporter "CL-LIB-FNS-File Fns" 5 0 ";; Time-stamp: <2008-05-03 13:35:04 gorbag>"
"CVS: $Id: files.lisp,v 1.2 2008/05/03 17:42:01 gorbag Exp $
restructured version")
;; This portion of CL-LIB Copyright (C) 1984-2008 Bradford W. Miller and the
;; Trustees of the University of Rochester
;;
;; This library is free software; you can redistribute it and/or modify it under the terms of the GNU
;; Lesser General Public License as published by the Free Software Foundation; either version 3.0 of
;; the License, or (at your option) any later version.
;; This library 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.
;; You should have received a copy of the GNU Lesser General Public License along with this library;
;; if not, see <http://www.gnu.org/licenses/>.
;;;; Note the local extensions remain in cl-extensions. <miller>
;
;;;; ****************************************************************
;;;; Extensions to Common Lisp **************************************
;;;; ****************************************************************
;;;;
;;;; This file is a collection of extensions to Common Lisp.
;;;;
;;;; It is a combination of the CL-LIB package copyleft by Brad Miller
;;;; <[email protected]> and a similar collection by
;;;; Mark Kantrowitz <[email protected]>.
;;;;
;;;; The following functions were originally from CL-LIB:
;;;; let-if, factorial, update-alist, truncate-keywords, while,
;;;; defclass-x, copy-hash-table, defflag, round-to, extract-keyword
;;;; let*-non-null, mapc-dotted-list,
;;;; mapcar-dotted-list, mapcan-dotted-list, some-dotted-list,
;;;; every-dotted-list, msetq, mlet, dosequence, force-string, prefix?,
;;;; elapsed-time-in-seconds, bit-length, flatten,
;;;; sum-of-powers-of-two-representation,
;;;; difference-of-powers-of-two-representation,
;;;; ordinal-string, between,
;;;; cond-binding-predicate-to <[email protected]>
;;;; remove-keywords <[email protected]>
;;;;
;;;; The following functions were contributed by Mark Kantrowitz:
;;;; circular-list, dofile, seq-butlast, seq-last, firstn, in-order-union
;;;; parse-with-delimiter, parse-with-delimiters, string-search-car,
;;; string-search-cdr, parallel-substitute, lisp::nth-value,
;;;; parse-with-string-delimiter, parse-with-string-delimiter*,
;;;; member-or-eq, number-to-string, null-string, time-string.
;;;; list-without-nulls, cartesian-product, cross-product, permutations
;;;; powerset, occurs, split-string, format-justified-string,
;;;; eqmemb, neq, car-eq, dremove, displace, tailpush, explode,
;;;; implode, crush, listify-string, and-list, or-list, lookup,
;;;; make-variable, variablep, make-plist, make-keyword
;;;;
;;;; The GNU Emacs distribution agreement is included by reference.
;;;; Share and Enjoy!
;;;;
(let (loaded-pathnames)
(defun clear-load-once ()
(setq loaded-pathnames nil))
(defun load-once (pathname &rest load-opts)
(let ((preloaded (assoc pathname loaded-pathnames :test #'equalp)))
(cond
((and preloaded
(> (file-write-date pathname) (cdr preloaded)))
(apply #'load pathname load-opts)
(setf (cdr preloaded) (file-write-date pathname)))
((null preloaded)
(apply #'load pathname load-opts)
(push (cons pathname (file-write-date pathname)) loaded-pathnames))))))
(defmacro dofile ((var filename &optional return-form) &body body)
"Opens the specified file for input, reads successive lines
from the file, setting the specified variable <var> to
each line. When end of file is reached, the value of <return-form>
is returned."
(let ((eof (gensym "EOF"))
(stream (gensym "STREAM")))
`(with-open-file (,stream ,filename :direction :input)
(do ((,var (read-line ,stream nil ,eof)
(read-line ,stream nil ,eof)))
((eq ,var ,eof)
,return-form)
,@body))))
#+allegro-v4.1
(add-initialization "lep-init for dofile"
'(lep::eval-in-emacs "(put 'dofile 'fi:lisp-indent-hook '(like with-open-file))")
'(:lep))
| 4,432 | Common Lisp | .lisp | 86 | 48.139535 | 102 | 0.658053 | Bradford-Miller/CL-LIB | 1 | 0 | 1 | LGPL-3.0 | 9/19/2024, 11:28:28 AM (Europe/Amsterdam) | 5535e271404cde11ce00c1677349cdadf67994f695bb40300d86a98d9917fce5 | 25,869 | [
-1
] |
25,870 | number-handling.lisp | Bradford-Miller_CL-LIB/functions/number-handling.lisp | ;;; -*- Mode: LISP; Syntax: ansi-common-lisp; Package: CL-LIB; Base: 10 -*-
(in-package cl-lib)
(version-reporter "CL-LIB-FNS-Number Handling" 5 1 ";; Time-stamp: <2007-05-18 11:35:41 miller>"
"CVS: $Id: number-handling.lisp,v 1.1.1.1 2007/11/19 17:41:31 gorbag Exp $
add round-off")
;;;
;;; Copyright (C) 1994, 1993, 1992 by Bradford W. Miller, [email protected]
;;; and the Trustees of the University of Rochester
;;; Right of use & redistribution is granted as per the terms of the
;;; GNU LIBRARY GENERAL PUBLIC LICENCE version 2 which is incorporated here by
;;; reference.
;;; This program is free software; you can redistribute it and/or modify
;;; it under the terms of the GNU Library General Public License as published by
;;; the Free Software Foundation; version 2.
;;; 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 Library General Public License for more details.
;;; You should have received a copy of the GNU Library General Public License
;;; along with this program; if not, write to the Free Software
;;; Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
;;;
;;; The following is contributed by [email protected]
;;; the following is contributed by [email protected]
(defun Bit-Length (N)
" Computes the number of bits needed to represent integer N.
Assumes that 0 requires 1 bit to represent, positive numbers require
floor(log(N))+1 bits, and negative numbers require one bit more than
their positive counterparts (for the sign bit). This treatment of
negative integers is a little bit arbitrary, but seems as good as
anything else."
(cond
((= N 0) 1)
((< N 0) (+ (Bit-Length (- N)) 1))
((> N 0) (+ (floor (log N 2)) 1))))
(defun Sum-of-Powers-of-Two-Representation (N)
"Figures out how to represent N as a sum of powers of two. Returns a list of exponents,
the idea being the N is the sum over E in this list of two raised to the E-th power.
Requires N to be a positive integer, so that all exponents in the result list are integers."
(declare (integer N))
(assert (> N 0))
(do ( (I 0 (+ I 1))
(Exps '() (if (logbitp I N)
(cons I Exps)
Exps)) )
((>= I (integer-length N)) Exps)
(declare (integer I) (list Exps))))
(defun Difference-of-Powers-of-Two-Representation (N)
"Figures out how to represent N as the difference of a sequence of powers of 2
(e.g., 2^e1 - 2^e2 - ...). Returns a list of exponents, with e1 as the last and
the others in some arbitrary order. Requires N to be an integer greater than 0,
which simplifies the code but isn't absolutely necessary. Starts by figuring out
The smallest power of two greater than or equal to N - this exponent becomes e1.
Remaining exponents are just those of the greater power of two minus N."
(declare (integer N))
(assert (> N 0))
(let* ((E1 (ceiling (log N 2)))
(Next-Power (expt 2 E1)))
(declare (integer E1 Next-Power))
(if (= Next-Power N)
(list E1)
(append (Sum-of-Powers-of-Two-Representation (- Next-Power N)) (list E1)))))
(defun Ordinal-String (N)
" Generates a string representing N as an ordinal number (i.e., 1st, 2nd, etc.).
Works by printing N and the appropriate suffix to a string - N is printed in decimal,
the suffix is looked up based on the last digit of N (i.e., N mod 10)."
(declare (integer N))
(let ((Last-Digit (mod (abs N) 10))
(Last-2-Digits (mod (abs N) 100)))
(declare (integer Last-Digit))
(format nil "~d~a" N (cond
((or (= Last-2-Digits 11)
(= Last-2-Digits 12)
(= Last-2-Digits 13)) "th")
((= Last-Digit 1) "st")
((= Last-Digit 2) "nd")
((= Last-Digit 3) "rd")
(t "th")))))
(defun Between (Lo Hi)
"Generates a list of integers between Lo and Hi, inclusive.
Straightforward recursive definition, i.e., result is Lo consed onto
integers from Lo+1 to Hi, unless Lo is greater than Hi in which case
result is nil."
(declare (integer Lo Hi))
(cond
((> Lo Hi) '() )
(t (cons Lo (Between (+ Lo 1) Hi)))))
;; [email protected]
(DEFUN ROUND-TO (NUMBER &OPTIONAL (DIVISOR 1))
"Like Round, but returns the resulting number"
(* (ROUND NUMBER DIVISOR) DIVISOR))
(defun factorial (n)
"Compute the factorial of an integer"
(cond ((minusp n)
(cerror "Compute -(~D!) instead" "I can't do -~D!" n n)
(factorial (- n)))
(t
(do ((x n (1- x))
(result 1))
((zerop x) result)
(declare (fixnum x))
(setf result (* x result))))))
;; [email protected]
(defun round-off (n &optional (sig 0))
"rounds n off to sig significant figures (positive is right of decimal, negative is left), returning a float."
(/ (fround n (expt 10 (- sig)))
(expt 10 sig)))
| 5,003 | Common Lisp | .lisp | 1 | 5,002 | 5,003 | 0.64961 | Bradford-Miller/CL-LIB | 1 | 0 | 1 | LGPL-3.0 | 9/19/2024, 11:28:28 AM (Europe/Amsterdam) | e377e5ff81ef8b6319c3cd00145d5c82c60052c04768dabdd65c8e87ccf0a25e | 25,870 | [
-1
] |
25,871 | clos-extensions.lisp | Bradford-Miller_CL-LIB/functions/clos-extensions.lisp | (in-package cl-lib)
(version-reporter "CL-LIB-FNS-CLOS" 5 16 ";; Time-stamp: <2019-03-16 17:57:22 Bradford Miller(on Aragorn.local)>"
"update documentation descriptions")
;; 5.16 3/16/19 Expand some of the description fields before releasing to github
;; 5.0 5/ 3/08 make generate-inherited-slot-definer and generate-inherited-slot-writer more flexible
;; to handle cases of objects as arguments
;; Some portions Copyright (C) 2019 Bradford W. Miller
;; This portion of CL-LIB Copyright (C) 1984-2008 Bradford W. Miller and the
;; Trustees of the University of Rochester
;;
;; This library is free software; you can redistribute it and/or modify it under the terms of the GNU
;; Lesser General Public License as published by the Free Software Foundation; either version 3.0 of
;; the License, or (at your option) any later version.
;; This library 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.
;; You should have received a copy of the GNU Lesser General Public License along with this library;
;; if not, see <http://www.gnu.org/licenses/>.
(DEFMACRO DEFCLASS-X (TYPE SUPERTYPES SLOTS . STUFF)
"Extended defclass, also creates a TYPE-P function and MAKE-TYPE
function, like defstuct did."
`(eval-when (compile load eval)
(DEFCLASS ,TYPE ,SUPERTYPES ,SLOTS ,@STUFF)
(DEFUN ,(INTERN (CONCATENATE 'STRING (STRING TYPE) "-P")) (TERM)
(TYPEP TERM ',TYPE))
(DEFUN ,(INTERN (CONCATENATE 'STRING "MAKE-" (STRING TYPE))) (&REST ARGS)
(APPLY 'MAKE-INSTANCE ',TYPE ARGS))))
(macro-indent-rule defclass-x (like defclass))
;; Mostly, useful tools out of the Art of the MOP, or modifications.
(defvar *debug-clos-extensions* nil)
(defun make-load-form-with-all-slots (object &optional environment)
(declare (ignore environment))
(let ((new-instance (gentemp))
(*print-readably* t)) ; for coming up with objects to fill in the slots
`(let ((,new-instance (make-instance ',(type-of object)
,@(generate-inherited-slot-definer object))))
,@(generate-inherited-slot-writer new-instance object)
,new-instance)))
(defun sample-load-form-quote-p-fn (x)
"default function for creating load-forms"
(cond
((or (typep x 'standard-object) ; handle the case where we need to construct the slot value itself
(typep x 'structure-object))
'load-form)
((consp x)
'list)
((atom x)
'quote)
(t
'self)))
(defparameter *load-form-quote-p-fn* #'sample-load-form-quote-p-fn
"can be elaborated upon by the user, e.g., if it
returns a function, the function is called on the argument
\(this sets it up for splicing into the load-form as the value of the slot)
I did this instead of making process-argument a generic function to make it easier to overload the
\"sample\"-load-form-quote-p-fn
- you can supply your own load-form-quote-p-fn and bind it to the parameter. If process-argument were generic, then
overloading the predefined processing would generate errors.")
;; Yeah, it's uglier. I'm sure there's a better way, but I haven't thought of it (yet).
(defun process-argument (arg-value)
(let ((process-type (funcall *load-form-quote-p-fn* arg-value)))
(case process-type
(load-form
(make-load-form arg-value))
(quote
(list 'quote arg-value))
(list
`(list ,@(mapcar #'process-argument arg-value)))
(self
arg-value)
(otherwise
(funcall process-type arg-value)))))
(defun generate-inherited-slot-definer (object)
(let ((class (class-of object)))
(mapcan #'(lambda (slot)
(if (and (clos:slot-definition-initargs slot)
(slot-boundp object (clos:slot-definition-name slot)))
`(,(car (clos:slot-definition-initargs slot))
;; only quote the next argument if needed.
,(let* ((slot-reader (car (determine-slot-readers class (clos:slot-definition-name slot))))
(arg-value (if slot-reader
(funcall slot-reader object)
(clos::slot-value object (clos:slot-definition-name slot)))))
(process-argument arg-value)))))
(clos:class-slots class))))
(defun generate-inherited-slot-writer (instance object)
(let ((class (class-of object)))
(mapcan #'(lambda (slot)
(if (and (not (clos:slot-definition-initargs slot)) ; found it above in definer
(slot-boundp object (clos:slot-definition-name slot)))
;; if we can't write it, ignore it.
(or (let*-non-null ((writer (car (determine-slot-writers class (clos:slot-definition-name slot)))))
`((,(car writer) (,(cadr writer) ,instance)
,(process-argument (funcall (car (determine-slot-readers class (clos:slot-definition-name slot))) object)))))
(if *debug-clos-extensions*
(warn "Can't construct writer for slot ~W of ~W" slot object)))))
(clos:class-slots class))))
;; thanks to Steve Haflich ([email protected]) for the following tidbit.
(defmethod determine-slot-readers ((class standard-class) (slot-name symbol))
#+excl
(unless (clos:class-finalized-p class)
(clos:finalize-inheritance class))
(loop for c in (clos:class-precedence-list class)
as dsd = (find slot-name (clos:class-direct-slots c)
:key #'clos:slot-definition-name)
when dsd
append (clos:slot-definition-readers dsd #+ccl c)))
(defmethod determine-slot-writers ((class standard-class) (slot-name symbol))
#+excl
(unless (clos:class-finalized-p class)
(clos:finalize-inheritance class))
(loop for c in (clos:class-precedence-list class)
as dsd = (find slot-name (clos:class-direct-slots c)
:key #'clos:slot-definition-name)
when dsd
append (clos:slot-definition-writers dsd #+ccl c)))
(defmethod determine-slot-initializers ((class standard-class) (slot-name symbol))
#+excl
(unless (clos:class-finalized-p class)
(clos:finalize-inheritance class))
(loop for c in (clos:class-precedence-list class)
as dsd = (find slot-name (clos:class-direct-slots c)
:key #'clos:slot-definition-name)
when dsd
append (clos:slot-definition-initargs dsd)))
(defun generate-legal-slot-initargs (class)
#+excl
(unless (clos:class-finalized-p class)
(clos:finalize-inheritance class))
(mapcan #'(lambda (x) (copy-list (clos:slot-definition-initargs x))) (clos:class-slots class)))
(defun slot-for-initarg (class initarg)
(let ((slots (clos:class-slots class)))
(clos:slot-definition-name
(find-if #'(lambda (slot)
(member initarg (clos:slot-definition-initargs slot)))
slots))))
| 7,178 | Common Lisp | .lisp | 136 | 45.154412 | 152 | 0.655649 | Bradford-Miller/CL-LIB | 1 | 0 | 1 | LGPL-3.0 | 9/19/2024, 11:28:28 AM (Europe/Amsterdam) | 59b6ed038056883948ec1f7aa2544fef6bd1f83ec1644118b9b6e2fc10d89fc1 | 25,871 | [
-1
] |
25,872 | cl-lib-essentials.lisp | Bradford-Miller_CL-LIB/functions/cl-lib-essentials.lisp | ;;; -*- Mode: LISP; Syntax: ansi-common-lisp; Package: CL-LIB; Base: 10 -*-
(in-package cl-lib-essentials)
(defparameter *cl-lib-essentials-version* '(version-reporter "CL-LIB-Essentials" 5 16
";; Time-stamp: <2019-03-16 13:01:13 Bradford Miller(on Aragorn.local)>"
";; sbcl interactive-lisp-p"))
;; 5.16 2/22/19 sbcl port for interactive-lisp-p
;; 5.14 12/16/11 detailed-version-reporter
;; 10/22/07 5.6 longer version string
;;;
;;; Copyright (C) 2005, 2007, 2011, 2019 by Bradford W. Miller, [email protected]
;;;
;; This library is free software; you can redistribute it and/or modify it under the terms of the GNU
;; Lesser General Public License as published by the Free Software Foundation; either version 3.0 of
;; the License, or (at your option) any later version.
;; This library 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.
;; You should have received a copy of the GNU Lesser General Public License along with this library;
;; if not, see <http://www.gnu.org/licenses/>.
;; miller - Brad Miller ([email protected])
;;;
;; comments from the lep file fi-indent:
;;; Lisp form indentation specifications.
;;; Note that `t' specifies that the form is not special and `shadows'
;;; any indentation specified with the property stored under the
;;; indicator `fi:lisp-indent-hook'.
;;A note on indenting methods: (I think this is allegro specific)
;;
;; Triples are: depth, count and method. In the following example, the
;; indentation method is a list of two lists, (1 (2 t)((1 0 quote)(0 t nil)))
;; and (0 t 1). The first triple is for sexps at level 1 (ie, the arguments
;; to CASE). The second triple is for the CASE sexp itself (ie, the
;; indentation applies to the elements of the CASE expression, not the
;; indentation of the individual elements within the CASE). Note also that
;; triples for deeper sexps come first (ie, ordered depending on descending
;; depth). For depth 1, the count is (2 t), which means apply the method
;; to all but the elements 0 and 1 of the CASE (0 is CASE and 1 is the
;; first argument to the CASE). The method, ((1 0 quote) (0 t nil))
;; recursively defines what happens inside each of these elements in the
;; CASE (ie, refered to by a count of (2 t)): at depth 1 and count 0, the
;; elements are indented as quoted lists (aligned under the CAR); at depth
;; 0 for any element the standard indentation applies.
;;
;;(put 'case 'fi:lisp-indent-hook
;; '((1 (2 t) ((1 0 quote)
;; (0 t nil)))
;; (0 t 1)))
;; this came from the way to do things on allegro.
;; Lispworks uses (editor:setup-indent form-name no-of-args-to-treat-special &optional standard-indent-spaces special-indent-spaces)
(defmacro macro-indent-rule (symbol what)
"Inform the editor (emacs) of how to indent macros, used by CL-LIB"
#-lep (declare (ignore symbol what))
#+lep ;must be 4.1 or later, have lep
`(add-initialization ,(format nil "lep init for ~A" symbol)
'(lep::eval-in-emacs
,(concatenate 'string
"(put '"
(string-downcase (string symbol))
" 'fi:lisp-indent-hook "
(string-downcase (format nil "'~S)" what))))
'(:lep))
)
(defun interactive-lisp-p ()
"Return non-nil if the lisp is interactive (i.e., contains the development system)"
#+excl excl:*print-startup-message*
#+lispworks (not (boundp 'lw:*delivery-level*))
#+sbcl (not (eq sb-debug::*invoke-debugger-hook* 'sb-debug::debugger-disabled-hook)) ; true in sbcl-1.4.13
#-(or lispworks excl sbcl) t)
;; version reporting: allows various cl-lib modules (or your own programs!) to print out an announcement so you can keep track of
;; what's been loaded. Great for flushing into a log. This is a generalization of code I've implemented at least half a dozen
;; times for each new project I start. Not so useful once you deploy (you'll want real configuration management), this is more
;; a mechanism to make sure when you have multiple developers all running variations of code, you know which version of which
;; file each one used at the time a bug was reported. It also helps you make sure you are running the latest version. The basic
;; idea is to put a timestamp into each file that gets updated automatically by your editor (e.g., FSF emacs has time-stamp do
;; this, as at the top of this file). This can be captured into a lisp variable, and then printed into an appropriate log at the
;; right time. To modulate this, we create an initialization list (since the initialization package is already loaded), and a
;; macro for stuffing new initializations onto this list with the version info. Then there are functions to trigger the
;; initializations, which cause everything to get printed to a particular stream, *error-output*
;;
;; Note that version-reporter can supply a different symbol for the report string, and for the initialization list, these can
;; be your own for the system you are building. You can rebind your report-string symbol before calling report-version, in order
;; to change how the report is printed, and you can also rebind *error-output* to change the destination.
(defvar *cl-lib-version-reporter-initializations* nil)
(defparameter *cl-lib-version-reporter-string* "~&;; ~A~45t~A~72t~D.~D~%;;~2t(~A)~%" "Default control string to announce the version")
(defparameter *cl-lib-detailed-version-reporter-string* "~&;; ~A~45t~A~72t~D.~D.~D~%;;~2t(~A)~%" "Default detail control string to announce the version")
(defparameter *cl-lib-version-announce-p* t "change this to NIL to prevent version announcement at startup")
(defvar *report-depth*)
(defmacro version-reporter (part-name major-version minor-version date comments
&optional (report-string-symbol '*cl-lib-version-reporter-string*)
(initialization-list-symbol '*cl-lib-version-reporter-initializations*))
"set up a version announcement"
`(eval-when (load eval)
(cl-lib-initializations:add-initialization ,(format nil "~A report" part-name)
'(do-report-version ',report-string-symbol
,date ,(string part-name) ,major-version ,minor-version ,comments)
() ',initialization-list-symbol)))
(defmacro detailed-version-reporter (part-name major-version minor-version micro-version date comments
&key (report-string-symbol '*cl-lib-detailed-version-reporter-string*)
(initialization-list-symbol '*cl-lib-version-reporter-initializations*))
"set up a version announcement"
`(eval-when (load eval)
(cl-lib-initializations:add-initialization ,(format nil "~A report" part-name)
'(do-report-detailed-version ',report-string-symbol
,date ,(string part-name) ,major-version ,minor-version ,micro-version ,comments)
() ',initialization-list-symbol)))
(defun report-version (&optional depth (initialization-list '*cl-lib-version-reporter-initializations*))
"If depth is non-nil, then part names of the form foo-bar-bletch are suppressed at depth > 2. (using prefixes)."
(let ((*report-depth* depth))
(initializations initialization-list t)))
(defun report-at-depth-p (part-name)
(not (and *report-depth*
(> (count #\- part-name) *report-depth*))))
(defun do-report-version (report-string-symbol date part-name major-version minor-version comments)
(when (report-at-depth-p part-name)
(format *error-output* (symbol-value report-string-symbol) date part-name major-version minor-version comments)))
(defun do-report-detailed-version (report-string-symbol date part-name major-version minor-version micro-version comments)
(when (report-at-depth-p part-name)
(format *error-output* (symbol-value report-string-symbol) date part-name major-version minor-version micro-version comments)))
(eval-when (load eval)
;; deferred until we defined version-reporter here.
(eval cl-user::*cl-lib-defpackage-version*)
(eval cl-lib-initializations::*cl-lib-initializations-version*)
(eval cl-lib-essentials::*cl-lib-essentials-version*))
;; if you want cl-lib to announce itself in a saved image...
(eval-when (load eval)
(cl-lib-initializations:add-initialization "Announce cl-lib is on the job"
'(when (and *cl-lib-version-announce-p*
(interactive-lisp-p))
(report-version))
'(:warm)))
| 9,250 | Common Lisp | .lisp | 130 | 61.923077 | 153 | 0.66685 | Bradford-Miller/CL-LIB | 1 | 0 | 1 | LGPL-3.0 | 9/19/2024, 11:28:28 AM (Europe/Amsterdam) | c86e554fc59899bc92e398a83916fb6d07f5ad06617439fc44c07156f663933e | 25,872 | [
-1
] |
25,873 | cl-sets.lisp | Bradford-Miller_CL-LIB/functions/cl-sets.lisp | (IN-PACKAGE CL-LIB)
(version-reporter "CL-LIB-FNS-Set Fns" 5 16 ";; Time-stamp: <2019-03-23 21:17:01 Bradford Miller(on Aragorn.local)>"
"fix documentation strings")
;; 5.16 3/23/19 fix documentation strings
;; Some portions Copyright (C) 2019 Bradford W. Miller
;; This portion of CL-LIB Copyright (C) 1984-2008 Bradford W. Miller and the
;; Trustees of the University of Rochester
;;
;; This library is free software; you can redistribute it and/or modify it under the terms of the GNU
;; Lesser General Public License as published by the Free Software Foundation; either version 3.0 of
;; the License, or (at your option) any later version.
;; This library 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.
;; You should have received a copy of the GNU Lesser General Public License along with this library;
;; if not, see <http://www.gnu.org/licenses/>.
;;;; Note the local extensions remain in cl-extensions. <miller>
;
;;;; ****************************************************************
;;;; Extensions to Common Lisp **************************************
;;;; ****************************************************************
;;;;
;;;; This file is a collection of extensions to Common Lisp.
;;;;
;;;; It is a combination of the CL-LIB package copyleft by Brad Miller
;;;; <[email protected]> and a similar collection by
;;;; Mark Kantrowitz <[email protected]>.
;;;;
;;;; The following functions were originally from CL-LIB:
;;;; let-if, factorial, update-alist, truncate-keywords, while,
;;;; defclass-x, copy-hash-table, defflag, round-to, extract-keyword
;;;; let*-non-null, mapc-dotted-list,
;;;; mapcar-dotted-list, mapcan-dotted-list, some-dotted-list,
;;;; every-dotted-list, msetq, mlet, dosequence, force-string, prefix?,
;;;; elapsed-time-in-seconds, bit-length, flatten,
;;;; sum-of-powers-of-two-representation,
;;;; difference-of-powers-of-two-representation,
;;;; ordinal-string, between,
;;;; cond-binding-predicate-to <[email protected]>
;;;; remove-keywords <[email protected]>
;;;;
;;;; The following functions were contributed by Mark Kantrowitz:
;;;; circular-list, dofile, seq-butlast, seq-last, firstn, in-order-union
;;;; parse-with-delimiter, parse-with-delimiters, string-search-car,
;;; string-search-cdr, parallel-substitute, lisp::nth-value,
;;;; parse-with-string-delimiter, parse-with-string-delimiter*,
;;;; member-or-eq, number-to-string, null-string, time-string.
;;;; list-without-nulls, cartesian-product, cross-product, permutations
;;;; powerset, occurs, split-string, format-justified-string,
;;;; eqmemb, neq, car-eq, dremove, displace, tailpush, explode,
;;;; implode, crush, listify-string, and-list, or-list, lookup,
;;;; make-variable, variablep, make-plist, make-keyword
;;;;
;;;; The GNU Emacs distribution agreement is included by reference.
;;;; Share and Enjoy!
;;;;
;
;;; ********************************
;;; Sets ***************************
;;; ********************************
;;; list-without-nulls
;;; cross-product
;;; cartesian-product
;;; permutations
(defun list-without-nulls (list)
"Returns a copy of list with all null elements removed."
(let* ((head (list nil))
(tail head))
(loop
(if (null list)
(return-from list-without-nulls (cdr head))
(when (car list)
(rplacd tail (list (car list)))
(setf tail (cdr tail))))
(setf list (cdr list)))))
(defun cartesian-product (set1 set2)
"Returns the cartesian product of two sets."
(let ((result ()))
(dolist (elt1 set1)
(dolist (elt2 set2)
(push (cons elt1 elt2) result)))
result))
(defun cross-product (&rest lists)
"Returns the cross product of a set of lists."
(labels ((cross-product-internal (lists)
(if (null (cdr lists))
(mapcar #'list (car lists))
(let ((cross-product (cross-product-internal (cdr lists)))
(result '()))
(dolist (elt-1 (car lists))
(dolist (elt-2 cross-product)
(push (cons elt-1 elt-2) result)))
result))))
(cross-product-internal lists)))
(defun permutations (items)
"Given a list of items, returns all possible permutations of the list."
(let ((result nil))
(if (null items)
'(nil)
(dolist (item items result)
(dolist (permutation (permutations (remove item items)))
(push (cons item permutation) result))))))
(defun powerset (list)
"Given a set, returns the set of all subsets of the set."
(let ((result (list nil)))
(dolist (item list result)
(dolist (subset result)
(push (cons item subset) result)))))
#-lispm
(defun circular-list (&rest list)
"Creates a circular list of the arguments. Handy for use with
the list mapping functions. For example,
(mapcar #'+ '(1 2 3 4 5) (circular-list 3)) --> (4 5 6 7 8)
(mapcar #'+ '(1 2 3 4 5) (circular-list 0 1)) --> (1 3 3 5 5)"
(setf list (copy-list list))
(setf (cdr (last list)) list)
list)
(defun occurs (elt lst)
"Returns T if ELT occurs somewhere in LST's tree structure."
(cond ((null lst)
nil)
((consp lst)
;; This walks down the tree structure of LST.
(or (occurs elt (car lst))
(occurs elt (cdr lst))))
((atom lst)
;; If we are at a leaf, test if ELT is the same as the leaf.
(eq lst elt))))
(defun firstn (list &optional (n 1))
"Returns a new list the same as List with only the first N elements."
(cond ((> n (length list)) list)
((< n 0) nil)
(t (ldiff list (nthcdr n list)))))
(defun in-order-union (list1 list2)
"Append and remove duplicates. Like union, but the objects are
guarranteed to stay in order."
(remove-duplicates (append list1 list2) :from-end t))
;;;
;;; The following is contributed by [email protected]
;; Fast versions of the commonlisp union and intersection, that want
;; and return sorted lists. rewrite for more speed 6/1/93 by miller.
(defun fast-union (list1 list2 &optional (predicate #'eql) &key (test #'eql) (key #'identity))
"Like Union (but no support for test-not) should be faster because
list1 and list2 must be sorted. Fast-Union is a Merge that handles
duplicates. Predicate is the sort predicate."
(declare (type list list1 list2))
(let (result result1
(wlist1 list1)
(wlist2 list2))
(while (and wlist1 wlist2)
(cond
((funcall test (funcall key (car wlist1)) (funcall key (car wlist2)))
(setq result1 (nconc result1 (list (pop wlist1))))
(pop wlist2))
((funcall predicate (funcall key (car wlist1)) (funcall key (car wlist2)))
(setq result1 (nconc result1 (list (pop wlist1)))))
(t
(setq result1 (nconc result1 (list (pop wlist2))))))
(if (null result) (setq result result1)))
(cond
(wlist1
(nconc result wlist1))
(wlist2
(nconc result wlist2))
(t
result))))
(defun fast-intersection (list1 list2 predicate &key (test #'eql) (key #'identity))
"Like Intersection (but no support for test-not) should be faster
because list1 and list2 must be sorted. Fast-Intersection is a
variation on Merge that handles duplicates. Predicate is the sort
predicate."
(declare (type list list1 list2))
(let (result result1
(wlist1 list1)
(wlist2 list2))
(while (and wlist1 wlist2)
(cond
((funcall test (funcall key (car wlist1)) (funcall key (car wlist2)))
(setq result1 (nconc result1 (list (pop wlist1))))
(pop wlist2))
((funcall predicate (funcall key (car wlist1)) (funcall key (car wlist2)))
(pop wlist1))
(t
(pop wlist2)))
(if (null result) (setq result result1)))
result))
| 7,907 | Common Lisp | .lisp | 1 | 7,905 | 7,907 | 0.635513 | Bradford-Miller/CL-LIB | 1 | 0 | 1 | LGPL-3.0 | 9/19/2024, 11:28:28 AM (Europe/Amsterdam) | 3ef2783b41bf4f093b1dd500e9d838a98c9b9d97eec03596c52b637c92cf0c21 | 25,873 | [
-1
] |
25,874 | cl-extensions.lisp | Bradford-Miller_CL-LIB/functions/cl-extensions.lisp | (in-package cl-lib)
(cl-lib:version-reporter "CL-LIB-FNS-Extensions" 5 16
";; Time-stamp: <2019-03-03 11:47:39 Bradford Miller(on Aragorn.local)>"
"sbcl: get-compiled-function-name, getenv port")
;; 5.16 2/23/19 port get-compiled-function-name and getenv to sbcl
;;;
;;; Copyright (C) 1996--1992 by Bradford W. Miller, [email protected]
;;; and the Trustees of the University of Rochester
;;;
;;; Portions Copyright (C) 2002,2019 by Bradford W. Miller, [email protected]
;; This library is free software; you can redistribute it and/or modify it under the terms of the GNU
;; Lesser General Public License as published by the Free Software Foundation; either version 3.0 of
;; the License, or (at your option) any later version.
;; This library 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.
;; You should have received a copy of the GNU Lesser General Public License along with this library;
;; if not, see <http://www.gnu.org/licenses/>.
;; miller - Brad Miller ([email protected])
;;;
;;; The following is contributed by [email protected]
;; additions for other versions of lisp are welcome!
;;
#+ALLEGRO-V4.0
(EVAL-WHEN (COMPILE LOAD EVAL)
(setf (symbol-function 'COMMON-LISP:hash-table-size) (symbol-function 'excl::hash-table-buckets)
(symbol-function 'COMMON-LISP:hash-table-test) (symbol-function 'excl::hash-table-kind)))
;;
(DEFUN COPY-HASH-TABLE (OLD-HASH-TABLE)
#+SYMBOLICS (CLI::COPY-TABLE OLD-HASH-TABLE)
#-SYMBOLICS
(let ((new-hash (make-hash-table
:test (hash-table-test old-hash-table)
:size (hash-table-size old-hash-table)
:rehash-size (hash-table-rehash-size old-hash-table)
:rehash-threshold (hash-table-rehash-threshold old-hash-table))))
(maphash #'(lambda (key entry)
(setf (gethash key new-hash) entry))
old-hash-table)
NEW-HASH))
;;; fix to not use "declare" options in non-let clause - 3/14/91 bwm
;;; fix for optimized expansion when condition is already known
;;; (constant) nil or non-nil.
(DEFMACRO LET-MAYBE (CONDITION BINDINGS &BODY BODY)
"Binds let arguments only if condition is non-nil, and evaluates body in any case."
(cond
((null condition)
`(PROGN ,@(IF (EQ (CAAR BODY) 'DECLARE) (CDR BODY) BODY)))
((eq condition t)
`(let ,bindings ,@body))
(t ;defer to runtime
`(IF ,CONDITION
(LET ,BINDINGS
,@BODY)
(PROGN ,@(IF (EQ (CAAR BODY) 'DECLARE) (CDR BODY) BODY))))))
(macro-indent-rule let-maybe ((1 1 quote) (0 2 1)))
;;; Explicit tagbody, with end-test at the end, to be nice to poor
;;; compilers.
(defmacro while (test &body body)
"Keeps invoking the body while the test is true;
test is tested before each loop."
(let ((end-test (gensym))
(loop (gensym)))
`(block nil
(tagbody (go ,end-test)
,loop
,@body
,end-test
(unless (null ,test) (go ,loop))
(return)))))
(macro-indent-rule while 1)
(defmacro while-not (test &body body)
"Keeps invoking the body while the test is false;
test is tested before each loop."
(let ((end-test (gensym))
(loop (gensym)))
`(block nil
(tagbody (go ,end-test)
,loop
,@body
,end-test
(unless ,test (go ,loop))
(return)))))
(macro-indent-rule while-not 1)
(defmacro let*-non-null (bindings &body body)
"like let*, but if any binding is made to NIL, the let*-non-null
immediately returns NIL."
#+symbolics (declare lt:(arg-template ((repeat let)) declare . body))
`(block lnn (let* ,(mapcar #'process-let-entry bindings)
,@body)))
(macro-indent-rule let*-non-null (like let))
(defun process-let-entry (entry)
"if it isn't a list, it's getting a nil binding, so generate a
return. Otherwise, wrap with test."
(declare (optimize (speed 3) (safety 0)))
(if (atom entry)
`(,entry (return-from lnn nil))
`(,(car entry) (or ,@(cdr entry) (return-from lnn nil)))))
(defmacro msetq (vars value)
#+lispm (declare (compiler:do-not-record-macroexpansions)
(zwei:indentation 1 1))
`(multiple-value-setq ,vars ,value))
(macro-indent-rule msetq (like multiple-value-setq))
(defmacro mlet (vars value &body body)
#+lispm (declare (compiler:do-not-record-macroexpansions)
(zwei:indentation 1 3 2 1))
`(multiple-value-bind ,vars ,value ,@body))
(macro-indent-rule mlet (like multiple-value-bind))
;;; the following is contributed by [email protected] with
;;; slight modifications by [email protected]
(defmacro cond-binding-predicate-to (symbol &rest clauses)
"(cond-binding-predicate-to symbol . clauses) [macro]
a COND-like macro. The clauses are exactly as in COND. In the body
of a clause, the SYMBOL is lexically bound to the value returned by the
test. Example:
(cond-binding-predicate-to others
((member 'x '(a b c x y z))
(reverse others)))
evaluates to
(z y x)"
#+lispm (declare (zwei:indentation 0 3 1 1))
(check-type symbol symbol)
`(let (,symbol)
(cond ,@(mapcar #'(lambda (clause)
`((setf ,symbol ,(first clause))
,@(rest clause)))
clauses))))
(macro-indent-rule cond-binding-predicate-to (like case))
(defun Elapsed-Time-in-Seconds (Base Now)
"Returns the time in seconds that has elapsed between Base and Now.
Just subtracts Base from Now to get elapsed time in internal time units,
then divides by the number of internal units per second to get seconds."
(coerce (/ (- Now Base) internal-time-units-per-second) 'float))
;; OK, how many times have you written code of the form
;;
;; (let ((retval (mumble)))
;; (setf (slot retval) bletch)
;; (setf (slot retval) barf)
;; retval)
;; or things of the sort? More than you care to remember most
;; likely. Enter the utterly useful PROGFOO. Think of it as a PROG1
;; with the value being bound to FOO. inside it's extent Lexically, of
;; course.
(defmacro progfoo (special-term &body body)
`(let ((foo ,special-term))
,@body
foo))
(macro-indent-rule progfoo (like prog1))
(defmacro with-rhyme (body)
"Well, there must be rhyme OR reason, and we now admit there is no
reason, so... Used to flag silly constructs that may need to be
rewritten for best effect."
body)
(macro-indent-rule with-rhyme (like progn))
;; and for common lisp fans of multiple values... FOO is the first
;; value, you can access all the values as MV-FOO. returns the
;; multiple values, like multiple-values-prog1
(defmacro mv-progfoo (special-term &body body)
`(let* ((mv-foo (multiple-value-list ,special-term))
(foo (car mv-foo)))
,@body
(values-list mv-foo)))
(macro-indent-rule mv-progfoo (like multiple-value-prog1))
;; from the net
;; From: Kerry Koitzsch <[email protected]>
(defun GET-COMPILED-FUNCTION-NAME (fn)
"Returns the symbol name of a function. Covers the six major CL vendors."
#+lispm
(when (si:lexical-closure-p fn)
(return-from get-compiled-function-name nil))
(etypecase fn
(symbol fn)
(compiled-function #+cmu(kernel:%function-header-name fn)
#+:mcl(ccl::function-name fn)
#+lispm(si:compiled-function-name fn)
#+akcl(system::compiled-function-name fn)
#+lucid
(when (sys:procedurep fn)
(sys:procedure-ref fn SYS:PROCEDURE-SYMBOL))
#+excl (xref::object-to-function-name fn)
;; modified 6/4/02 by abm061 for Lispworks 4.2
;; note that it is only effective for debug level 1 or more.
#+lispworks
(mlet (a b name) (function-lambda-expression fn)
(declare (ignore a b))
name)
;; new 2/23/19 BWM
#+sbcl (sb-c::%fun-name fn)
)))
;; back to [email protected]
;; This may seem like a silly macro, but used inside of other macros
;; or code generation facilities it is very useful - you can see
;; comments in the (one-time) macro expansion!
(defmacro comment (&rest anything)
"Expands into nothing"
(declare (ignore anything)))
;; command line manipulation
(defun command-line-arg (command-line argname default &optional no-read)
(cond-binding-predicate-to foo
((member argname command-line :test #'equalp
:key #'(lambda (x) (if (symbolp x) (string x) x)))
(if no-read
(values (second foo) t)
(let ((read-value (if (stringp (second foo))
(read-from-string (second foo) nil :eof)
(second foo))))
(if (eq read-value :eof)
(values default nil)
(values read-value t)))))
(t
(values default nil))))
;; getenv - already exists in lispworks as of v5
#-lispworks
(defun getenv (env-variable)
#+excl (sys:getenv env-variable)
#+lispworks (lw:environment-variable env-variable)
;; 2/23/19 BWM
#+sbcl (posix-getenv env-variable)
#-(or excl lispworks sbcl)
(error "CL-LIB: getenv: Port me!"))
#-EXCL
(defmacro if* (condition true &rest false)
`(if ,condition ,true (progn ,@false)))
;;; ********************************
;;; misc ***************************
;;; ********************************
;;; we define a variable to be a symbol of the form ?NAME, i.e., a
;;; symbol whose first character is #\?. (Used in various logic languages like RHET, Shocker, etc.)
(defun make-variable (x)
(make-symbol (format nil "?~a" x)))
(defun variablep (item)
"Returns T if ITEM is a variable, namely a symbol of the form ?NAME,
whose first character is a question-mark."
(and (symbolp item)
(char= (char (symbol-name item) 0)
#\?)))
;;; ********************************
;;; Noting Progress ****************
;;; ********************************
(defmacro noting-progress ((&optional (width 70)) &body body)
"Every time NOTE-PROGRESS is called within the body of a NOTING-PROGRESS
macro, it prints out a dot. Every width number of dots it also outputs
a carriage return."
(let ((dot-counter (gensym "DOT")))
`(let ((,dot-counter 0))
(declare (special ,dot-counter))
(flet ((note-progress ()
(incf ,dot-counter)
(when (> ,dot-counter ,width)
(setf ,dot-counter 0)
(terpri))
(princ #\.)))
,@body))))
;;; *EOF*
| 10,753 | Common Lisp | .lisp | 1 | 10,752 | 10,753 | 0.623361 | Bradford-Miller/CL-LIB | 1 | 0 | 1 | LGPL-3.0 | 9/19/2024, 11:28:28 AM (Europe/Amsterdam) | addd94d474055fdbf86de6a9f6afe6bc1f3ffabdb41ab34977b4660ff7b6b126 | 25,874 | [
-1
] |
25,875 | cl-boolean.lisp | Bradford-Miller_CL-LIB/functions/cl-boolean.lisp | (IN-PACKAGE CL-LIB)
(version-reporter "CL-LIB-FNS-Boolean Fns" 5 16 ";; Time-stamp: <2019-03-16 16:32:58 Bradford Miller(on Aragorn.local)>"
"fix doc on nand")
;; 5.16. 3/16/19 fix doc on nand
;;;; ****************************************************************
;;;; Extensions to Common Lisp **************************************
;;;; ****************************************************************
;;;;
;;;; This file is a collection of extensions to Common Lisp.
;;;;
;;;; It is a combination of the CL-LIB package copyleft by Brad Miller
;;;; <[email protected]> and a similar collection by
;;;; Mark Kantrowitz <[email protected]>.
;;;;
;;;; The following functions were originally from CL-LIB:
;;;; let-if, factorial, update-alist, truncate-keywords, while,
;;;; defclass-x, copy-hash-table, defflag, round-to, extract-keyword
;;;; let*-non-null, mapc-dotted-list,
;;;; mapcar-dotted-list, mapcan-dotted-list, some-dotted-list,
;;;; every-dotted-list, msetq, mlet, dosequence, force-string, prefix?,
;;;; elapsed-time-in-seconds, bit-length, flatten,
;;;; sum-of-powers-of-two-representation,
;;;; difference-of-powers-of-two-representation,
;;;; ordinal-string, between,
;;;; cond-binding-predicate-to <[email protected]>
;;;; remove-keywords <[email protected]>
;;;;
;;;; The following functions were contributed by Mark Kantrowitz:
;;;; circular-list, dofile, seq-butlast, seq-last, firstn, in-order-union
;;;; parse-with-delimiter, parse-with-delimiters, string-search-car,
;;; string-search-cdr, parallel-substitute, lisp::nth-value,
;;;; parse-with-string-delimiter, parse-with-string-delimiter*,
;;;; member-or-eq, number-to-string, null-string, time-string.
;;;; list-without-nulls, cartesian-product, cross-product, permutations
;;;; powerset, occurs, split-string, format-justified-string,
;;;; eqmemb, neq, car-eq, dremove, displace, tailpush, explode,
;;;; implode, crush, listify-string, and-list, or-list, lookup,
;;;; make-variable, variablep, make-plist, make-keyword
;;;;
;; This portion of CL-LIB Copyright (C) 1994-2008 by Bradford W. Miller and the
;; Trustees of the University of Rochester
;;
;; This library is free software; you can redistribute it and/or modify it under the terms of the GNU
;; Lesser General Public License as published by the Free Software Foundation; either version 3.0 of
;; the License, or (at your option) any later version.
;; This library 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.
;; You should have received a copy of the GNU Lesser General Public License along with this library;
;; if not, see <http://www.gnu.org/licenses/>.
;;;;
;
;;; this is to support a field in a clos structrure called "flags",
;;; which is bit encoded. The testname can be used to see if the bit
;;; (defined by flagname - a constant) is set. It can also be setf to
;;; set or clear it. The type is the type of structure this test will
;;; handle, allowing multiple encodings of the flags field for
;;; different structures.
(DEFMACRO DEFFLAG (TESTNAME (TYPE FLAGNAME))
`(PROGN (DEFMETHOD ,TESTNAME ((TERM ,TYPE))
(LOGTEST ,FLAGNAME (FLAGS TERM)))
(DEFMETHOD (SETF ,TESTNAME) (NEW-FLAG (TERM ,TYPE))
(SETF (FLAGS TERM) (IF NEW-FLAG
(LOGIOR (FLAGS TERM) ,FLAGNAME)
(LOGAND (FLAGS TERM) (LOGNOT ,FLAGNAME)))))))
;; similar to above, but for defstruct type thingos; we assume the
;; accessor is "typename"-flags
;; fix to make sure we use typename in constant to avoid name
;; collisions 7/30/92 bwm
(DEFMACRO DEFFLAGS (TYPENAME &BODY FLAGNAMES)
(LET ((ACCESSOR (INTERN (FORMAT NIL "~A-FLAGS" TYPENAME)))
(VARNAME1 (GENSYM))
(VARNAME2 (GENSYM)))
(DO* ((FLAG FLAGNAMES (CDR FLAG))
(FUNNAME (INTERN (FORMAT NIL "~A-~A-P" TYPENAME (CAR FLAG))) (INTERN (FORMAT NIL "~A-~A-P" TYPENAME (CAR FLAG))))
(CONSTNAME (INTERN (FORMAT NIL "+~A-~A+" TYPENAME (CAR FLAG))) (INTERN (FORMAT NIL "+~A-~A+" TYPENAME (CAR FLAG))))
(COUNT 1 (* COUNT 2))
(CODE))
((NULL FLAG) `(PROGN ,@CODE))
(PUSH `(DEFSETF ,FUNNAME (,VARNAME1) (,VARNAME2)
`(SETF (,',ACCESSOR ,,VARNAME1) (IF ,,VARNAME2
(LOGIOR (,',ACCESSOR ,,VARNAME1) ,',constname)
(LOGAND (,',ACCESSOR ,,VARNAME1) (LOGNOT ,',constname)))))
CODE)
(PUSH `(DEFUN ,FUNNAME (,VARNAME1)
(LOGTEST ,constname (,ACCESSOR ,VARNAME1)))
CODE)
(PUSH `(DEFCONSTANT ,constname ,COUNT) CODE))))
(macro-indent-rule defflags 1)
;; define boolean control extensions to and, or, not... the bit
;; operators are there, but not the more general short-circuting ones.
;; Some of these will only make sense on two operands, and many can't
;; short circuit (exclusive ops, for instance).
(defmacro xor (&rest predicates)
"True only if exactly one predicate is true. Short circutes when it
finds a second one is true. Returns the true predicate"
(let ((result (gensym))
(temp (gensym))
(block-name (gensym)))
`(block ,block-name
(let ((,result ,(car predicates))
,temp)
,@(let (code-result)
(dolist (pred (cdr predicates))
(push `(cond
((and (setq ,temp ,pred)
,result)
(return-from ,block-name nil))
(,temp
(setq ,result ,temp)))
code-result))
(nreverse code-result))
,result))))
(macro-indent-rule xor (like and))
(defmacro eqv (&rest predicates)
"True iff all predicates produce the same result according to eql,
or passed :test (exclusive nor if binary)"
(let ((result (gensym))
(real-preds (truncate-keywords predicates))
(test-key (extract-keyword :test predicates #'eql))
(block-name (gensym)))
`(block ,block-name
(let ((,result ,(car real-preds)))
,@(let (code-result)
(dolist (pred (cdr real-preds))
(push `(if (not (funcall ,test-key ,pred ,result))
(return-from ,block-name nil))
code-result))
(nreverse code-result))
(or ,result t)))))
(macro-indent-rule eqv (like and))
(defmacro nand (&rest predicates)
"True only if at least one predicate is not true. Short circutes when it
finds one is false."
(let ((block-name (gensym)))
`(block ,block-name
,@(let (code-result)
(dolist (pred predicates)
(push `(if (not ,pred)
(return-from ,block-name t))
code-result))
(nreverse code-result))
nil)))
(macro-indent-rule nand (like and))
(defmacro nor (&rest predicates)
"True only if all predicates are false. Short circutes when it finds
a one is true."
(let ((block-name (gensym)))
`(block ,block-name
,@(let (code-result)
(dolist (pred predicates)
(push `(if ,pred
(return-from ,block-name nil))
code-result))
(nreverse code-result))
t)))
(macro-indent-rule nor (like and))
#-(or LISPM MCL)
(defun neq (x y)
"not eq"
(not (eq x y)))
| 7,492 | Common Lisp | .lisp | 161 | 40.496894 | 125 | 0.624674 | Bradford-Miller/CL-LIB | 1 | 0 | 1 | LGPL-3.0 | 9/19/2024, 11:28:28 AM (Europe/Amsterdam) | 39a7512640ecd98755ee9812bb6b67041830482af16769969acc4ed044e9a7cc | 25,875 | [
-1
] |
25,876 | re-to-dfa.lisp | Bradford-Miller_CL-LIB/packages/re-to-dfa.lisp | ;;; -*- Syntax: ANSI-Common-Lisp; Package: CL-LIB; Mode: LISP -*-
(in-package CL-LIB)
(cl-lib:version-reporter "CL-LIB-RE-to-DFA" 5 0 ";; Time-stamp: <2007-05-18 11:28:10 miller>"
"CVS: $Id: re-to-dfa.lisp,v 1.1.1.1 2007/11/19 17:47:19 gorbag Exp $
restructured version")
;;; Copyright (C) 1994, 1992, 1985 by Bradford W. Miller, [email protected]
;;; Right of use & redistribution is granted as per the terms of the
;;; GNU LIBRARY GENERAL PUBLIC LICENCE version 2 which is incorporated here by
;;; reference.
;;; This program is free software; you can redistribute it and/or modify
;;; it under the terms of the Gnu Library General Public License as published by
;;; the Free Software Foundation; version 2.
;;; 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 Library General Public License for more details.
;;; You should have received a copy of the Gnu Library General Public License
;;; along with this program; if not, write to the Free Software
;;; Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
;;;
;;;; RE/DFA package by Brad Miller (originally written as part of the RHET project)
;;; changes since 1985 other than bug fixes:
;;; 10/29/92 miller - change [] operator to () <grouping> so [] can be used for collection or range.
;;; change lispm characters to be appropriate for allegro, etc. (ascii)
;;;
;;;
;;; A string should be given as an arg to Convert-RE-To-DFA which will return a DFA.
;;; Calling CompatibleP on a string and the DFA will return T if the DFA accepts the string.
;;;
;;; Note that each character is treated individually. So, if you want to match FOO, you probably want to call
;;; (Convert-RE-To-DFA "F&O&O")
;;;
;;; The routine caches the dfas it generates. Call (clear-dfa-cache) to clear the cache.
;;;
;;;
(defconstant possible-literals
'(#\A #\B #\C #\D #\E #\F #\G #\H #\I #\J #\K #\L #\M
#\N #\O #\P #\Q #\R #\S #\T #\U #\V #\W #\X #\Y #\Z
#\a #\b #\c #\d #\e #\f #\g #\h #\i #\j #\k #\l #\m
#\n #\o #\p #\q #\r #\s #\t #\u #\v #\w #\x #\y #\z
#\0 #\1 #\2 #\3 #\4 #\5 #\6 #\7 #\8 #\9
#\< #\> #\- #\= #\! #\% #\/ #\SPACE)
"These are the possible values for literals in a RE.")
(defconstant +operators+ '(#\& #\( #\) #\[ #\] #\| #\/ #\, #\. #\$ #\^))
(defparameter *debug* nil) ;if t make things easier to analyze
(defvar *local-re*)
(defvar *cached-dfas* nil
"A hash table consisting of the dfa's we've encountered")
(defun clear-dfa-cache ()
(declare (optimize (speed 3) (safety 0)))
(cond
((hash-table-p *cached-dfas*)
(clrhash *cached-dfas*))
(t
(setq *cached-dfas* (make-hash-table :test #'equal)))))
(eval-when (load eval)
(clear-dfa-cache))
;;;
;;;
(defun compatiblep (string1 dfa)
"compatiblep returns t if the DFA could have generated the string.
Get the compiled DFA from convert-RE-to-DFA."
(declare (type string string1)
(type compiled-function dfa)
(optimize (speed 3) (safety 0)))
;; this is easy, given the dfa...
(funcall dfa string1))
(defun expand-re (re)
(let (result)
(while re
(cond
((member (car re) possible-literals)
(push (car re) result)
(if (member (cadr re) possible-literals)
(push #\& result)))
(t
(push (car re) result)))
(pop re))
(nreverse result)))
;;;
;;;
(defun convert-re-to-dfa (re)
"This function converts REs to DFAs (compiled)."
(declare (type string re)
(optimize (speed 3) (safety 0)))
;; We have to take the RE supplied and precidence parse it into a tree, then
;; convert that into an NFA with epsilon moves, then convert that to an NFA without
;; epsilon moves, and finally convert THAT into a DFA. The function returned should be
;; A compiled lisp function implementing the DFA and accepting one argument (a
;; string). It either returns T or NIL depending on whether the string matches
;; the DFA or not.
;;
;; For the moment, we will accept #\&, slash, epsilon, and * as operators, other symbols (A-Z and some
;; non alpha chars) as literals. We can add 'not' (or +) later as time permits.
;;
;; This is hard!
;;
;; Find Expression will return an NFA constructed from the RE. It does NOT return a lisp
;; function. Eliminate epsilon will remove epsilon rules from that NFA. It does NOT return a lisp
;; function. NFA to DFA will convert the NFA w/o epsilon rules to a DFA. It does NOT return a
;; lisp function. Optimize DFA will optimize the DFA. It does NOT return a lisp function. DFA to
;; function turns my representation of a DFA into a lisp function of one arg (the thing to match)
;; This is then compiled.
(cond
((gethash re *cached-dfas*))
(t
(let ((*local-re* (expand-re (coerce (format nil "~a" re) 'list))))
(declare (special *local-re*)) ;to use the HU algorithm, need these.
(cond
(*debug*
(gensym 0))) ;reset counter
(setf (gethash re *cached-dfas*)
(compile nil
(dfa-to-function
(optimize-dfa
(nfa-to-dfa
(eliminate-epsilon
(find-expression)))))))))))
;;;; non-exported functions...
;;;
;;; Structure of our internal rep of the rules
;;;
(defstruct rule
(from nil :type symbol)
(on nil :type character)
(to nil :type symbol))
(defstruct fa
(start nil :type symbol)
(end nil :type (or list symbol)) ;could be a list of symbols
(rules nil :type list)) ;list of rule structures.
;;;
;;;
(defun find-expression ()
"This function is from HU _Introduction to Automata Theory, Languages, and Computation_
NFAs look like (Start End (rules)) where rules are ((from char-to-match).to)"
(declare (optimize (speed 3) (safety 0)))
(let ((retval (find-product))) ;what we will return
(loop
(cond
((not (eql (car *local-re*) #\|))
(return))
(t
(pop *local-re*)
(let ((newval (find-product)) ;new nfa we will or in
(newstart (gensym "q"))
(newend (gensym "q")))
(setq retval
(make-fa :start newstart :end newend
:rules (list*
(make-rule :from newstart :on #\/ :to (fa-start retval))
(make-rule :from newstart :on #\/ :to (fa-start newval))
(make-rule :from (fa-end retval) :on #\/ :to newend)
(make-rule :from (fa-end newval) :on #\/ :to newend)
(nconc (fa-rules retval) (fa-rules newval)))))))))
retval))
;;;
;;;
(defun find-product ()
"this function is also from hu"
(declare (optimize (speed 3) (safety 0)))
(let ((retval (find-term))) ;what we will return
(loop
(cond
((not (eql (car *local-re*) #\&))
(return))
(t
(pop *local-re*)
(let ((newval (find-term))) ;new nfa we will and in
(setq retval (make-fa :start (fa-start retval) :end (fa-end newval)
:rules (list*
(make-rule :from (fa-end retval) :on #\/ :to (fa-start newval))
(nconc (fa-rules retval) (fa-rules newval)))))))))
retval))
;;;
;;;
(defun find-term ()
"this too is from HU
Represent an NFA a startnode, endnode(s) rules..."
(declare (optimize (speed 3) (safety 0)))
(let ((retval nil));what we will return
(cond
((member (car *local-re*) possible-literals)
(setq retval
(make-fa :start (gensym "q") :end (gensym "q"))) ;build nfa
(setf (fa-rules retval) (list
(make-rule :from (fa-start retval)
:on (car *local-re*)
:to (fa-end retval))))
(pop *local-re*))
((eql (car *local-re*) #\()
(pop *local-re*)
(setq retval (find-expression))
(cond
((eql (car *local-re*) #\))
(pop *local-re*))
(t
(error "re is not properly formed")))))
(loop
(cond
((eql (car *local-re*) #\*)
(pop *local-re*)
(let ((origstart (fa-start retval))
(origend (fa-end retval))
(newstart (gensym "q"))
(newend (gensym "q")))
(setq retval (make-fa :start newstart :end newend
:rules (list*
(make-rule :from origend :on #\/ :to origstart)
(make-rule :from newstart :on #\/ :to origstart)
(make-rule :from newstart :on #\/ :to newend)
(make-rule :from origend :on #\/ :to newend)
(fa-rules retval))))))
(t
(return))))
retval))
;;;
;;;
(defun eliminate-epsilon (nfa-with-epsilon)
"this function takes the internal rep of an nfa and eliminates the epsilon rules, using HU's algorithm.
Note, this function may return more than one end state in it's NFA rep."
(declare (type fa nfa-with-epsilon)
(optimize (speed 3) (safety 0)))
;; given the input NFA with epsilon rules, the basic thing is to be able to compute the epsilon
;; closure of each state. Note that if the epsilon closure of the original's start state includes
;; the end state, we must make sure that we allow the new NFA's start and finish state to both be
;; "finish" states.
(let* ((start-state (fa-start nfa-with-epsilon))
(old-finish (fa-end nfa-with-epsilon))
(rules (fa-rules nfa-with-epsilon))
(states-used (delete-duplicates (find-states rules)))
(e-closures (make-hash-table :test #'eq :size (list-length states-used) :rehash-threshold 0.99)))
;; first, calculate the e-closures for each state.
(calculate-e-closures rules e-closures states-used)
(make-fa
:start
start-state ;start state will be the same
:end
(cond ((member old-finish (gethash start-state e-closures))
(list start-state old-finish))
(t
(list old-finish)))
;; for each state/literal pair, compute the new transition(s)
:rules
(delete nil (mapcan
#'(lambda (x) (find-lit-transitions x (important-rules rules) e-closures))
states-used))))) ;for each state, look up all the transitions based on the literals used.
;;;
;;;
(defun find-lit-transitions (state rules e-hash-table)
"this function takes a particular state, and returns the state transition
rules from this state to any other state."
(declare (type atom state)
(type list rules)
(type hash-table e-hash-table)
(optimize (speed 3) (safety 0)))
;; for this state, and all states in it's epsilon closure, look up rules in RULES
;; that use a literal to move, and return those rules.
(delete nil
(mapcan
#'(lambda (x) (test-match-rule state x e-hash-table))
rules)))
;;;
;;;
(defun test-match-rule (STATE XRULE E-HASH-TABLE)
"this function is the guts of checking for rules."
(declare (type atom state)
(type hash-table e-hash-table)
(type rule xrule)
(optimize (speed 3) (safety 0)))
;; if any of the states are the source node in rule, then return a copy of the rule
;; substituting state for whatever state used to be present in from.
(cond
((and
(not (eql (rule-on xrule) #\/))
(member (rule-from xrule) (cons state (gethash state e-hash-table))))
(mapcar
#'(lambda (x) (make-rule :from state :on (rule-on xrule) :to x))
(cons (rule-to xrule) (gethash (rule-to xrule) e-hash-table))))
(t nil)))
;;;
;;;
(defun important-rules (rules)
"this function takes a list of rules and ruturns only those that contain a literal."
(declare (type list rules)
(optimize (speed 3) (safety 0)))
(let ((result nil))
(dolist
(x rules)
(cond
((not (eql #\/ (rule-on x)))
(push x result))))
result))
;;;
;;;
(defun calculate-e-closures (rules e-hash-table states)
"This function takes a list of rules and finds all e-closures for the rules.
It expects to add these to a passed hash table. (destructive!!)"
(declare (type list rules states)
(type hash-table e-hash-table)
(optimize (speed 3) (safety 0)))
;; for each rule in the rules passed, add the to node to the hash table for the from node, if epsilon
;; move. Then, recursively add nodes from the epsilon closures of each node in my closure, but don't
;; add a node twice. We can do this by deleting fully expanded nodes from the passed list of
;; states. note that we could not have (as a side effect of the NFA created) a node with an epsilon
;; move to another node with an epsilon move back to it. So we shouldn't have to do anything too
;; hard....
(mapc #'(lambda (x) (ec-internal x e-hash-table)) rules) ;process the table first
(let ((*states* (copy-list states))) ;I HAD TO DO IT!!
;;it has to be special!!! (reason is that subroutines may modify, and we want THIS ONE
;;to be the one modified). Passing both up and down would be worse, and inefficient, too.
(declare (special *states*))
;;we don't iterate over the *states* because each call to E-CLOSE may eliminate more than one
;;state in *states*
(loop
(cond
((null *states*)
(return))
(t
(e-close (car *states*) e-hash-table))))) ;call the recursive function to take care of it.
(values))
;;;
;;;
(defun ec-internal (xrule e-hash-table)
"This function processes the rules into the e-hash-table,
by checking to see if a rule is an epsilon move, and if so, adding the to node
to the hash of the from node."
(declare (type rule xrule)
(type hash-table e-hash-table)
(optimize (speed 3) (safety 0)))
(cond
((eql (rule-on xrule) #\/)
(setf
(gethash (rule-from xrule) e-hash-table)
(cons (rule-to xrule) (gethash (rule-from xrule) e-hash-table)))))
(values))
;;;
;;;
(defun e-close (state e-hash-table)
"this function processes the states passed, recursively, and adds their complete closure to the table.
It relies on the fact that there are no cycles of epsilon shifts."
(declare (type list *states*)
(special *states*)
(type hash-table e-hash-table)
(optimize (speed 3) (safety 0)))
(cond
((member state *states*);more to do....
(setq *states* (delete state *states*))
(setf (gethash state e-hash-table)
(append (gethash state e-hash-table)
(car (delete nil
(mapcar #'(lambda (x) (e-close x e-hash-table))
(gethash state e-hash-table))))))))
(gethash state e-hash-table))
;;;
;;;
(defun find-states (rules)
"this function scans a list of NFA or DFA rules, and returns a list of all the states present."
(declare (type list rules)
(optimize (speed 3) (safety 0)))
(cond
((null rules)
nil)
(t
(cons (rule-from (car rules)) ;start state of rule
(cons (rule-to (car rules)) ;end state of rule
(find-states (cdr rules))))))) ;rest of rules
;;;
;;;
(defun nfa-to-dfa (nfa-without-epsilon)
"this function takes the internal rep of an NFA without epsilon rules and turns it into a DFA
using HU's algorithm."
(declare (type fa nfa-without-epsilon)
(optimize (speed 3) (safety 0)))
;; starting with the nfa's start state, we create a rule in our DFA for each state or
;; combinations of states a move in our NFA w/o epsilons can get us to on a certain input. If we
;; are working on a "combination" state, our moves out are regulated by the union of the moves out
;; the of the individual component states in the NFA.
;; we return an DFA which is of essentially the same representation as the NFA we started with.
(let* ((*nfa-rules* (fa-rules nfa-without-epsilon))
(nfa-end (fa-end nfa-without-epsilon))
(nfa-start (fa-start nfa-without-epsilon))
(*nfa-literals* (remove-duplicates (find-literals *nfa-rules*)))
;; the number of states in the dfa could be 2**number of states in the nfa, but
;; typically is much smaller. estimate it at the number of nfa rules.
(*dfa-rules* (make-hash-table :test #'equal :size (list-length *nfa-rules*) :rehash-threshold 0.99))
(dfa-finish nil);end states for our dfa
(dfa-start (nfa-state-to-dfa-state nfa-start))
(*dfa-states*
(make-hash-table :test #'eq :size (list-length *nfa-rules*) :rehash-threshold 0.99))) ;the states in our dfa
(declare (special *dfa-rules* *nfa-rules* *dfa-states* *nfa-literals*)) ;sub funs will update...
;; get the closure of the start state, which will recursively get the closure of all states the
;; start state can reach (small optimization)
(lit*-closure nfa-start)
;; process the states of our nfa for potential end-states
(maphash #'(lambda (key val)
(cond ((intersection val nfa-end)
(setq dfa-finish (cons key dfa-finish)))))
*dfa-states*)
;; only dump the dfa states accessible from the start state (many were subs and won't be).
(make-fa
:start dfa-start
:end dfa-finish
:rules (follow-dfa-table dfa-start *dfa-rules*))))
;;;
;;;
(defun lit*-closure (nfa-symbol-to-close)
"THis function takes a symbol and a list of literals and finds it's closure in the nfa passed,
updating our DB of DFA rules and states."
(declare (type symbol nfa-symbol-to-close)
(type list *nfa-literals*)
(type hash-table *dfa-states*)
(special *dfa-states* *nfa-literals*) ;
(optimize (speed 3) (safety 0)))
(let ((dfa-symbol-to-close (nfa-state-to-dfa-state nfa-symbol-to-close)))
(cond
((gethash dfa-symbol-to-close *dfa-states*);already computed
nil)
(t
;; for each literal we know about, look up all the states we can get to from the passed
;; state
(mapc
#'(lambda (x)
(lit-closure nfa-symbol-to-close dfa-symbol-to-close x))
*nfa-literals*))))
(values))
;;;
;;;
(defun lit-closure (nfa-symbol-to-close dfa-symbol-to-close literal)
"this function is like lit*-closure, but for a single literal (called by lit*-closure)."
(declare (type symbol nfa-symbol-to-close)
(type atom dfa-symbol-to-close)
(type character literal)
(type list *nfa-rules*)
(special *nfa-rules*)
(optimize (speed 3) (safety 0)))
(let* ((state-set (nfa-accessible nfa-symbol-to-close literal *nfa-rules*))
(new-state (nfa-state-to-dfa-state state-set)))
(cond (state-set ;if there's something to expand on...
(dfa-from-nfa-internal new-state state-set dfa-symbol-to-close literal))))
(values))
;;;
;;;
(defun dfa-unify-states (union-state literal)
"this function takes a dfa state that is the union of many NFA states and a literal, and creates
a transition rule for the DFA union state of all the NFA states to a new set of states. (each
NFA state will already be interned as separate DFA transition rules, so we essentially look each
up, and then set the passed DFA state to be a transition on this literal to the union of all of
them."
(declare (type atom union-state)
(type character literal)
(type hash-table *dfa-states* *dfa-rules*)
(special *dfa-states* *dfa-rules*)
(optimize (speed 3) (safety 0)))
(let* ((new-union-state-set
(delete-duplicates
(remove nil
(mapcar ;the transition rules for all states in this closure
#'(lambda (x) (gethash x *dfa-rules*))
(mapcar ;keys of state/literal pairs
#'(lambda (x) (list (nfa-state-to-dfa-state x) literal))
(gethash union-state *dfa-states*))))))
(new-union-state (nfa-state-to-dfa-state new-union-state-set)))
(cond (new-union-state-set ;were there any for this literal?
(dfa-from-nfa-internal new-union-state new-union-state-set union-state literal))))
(values))
;;;
;;;
(defun dfa-from-nfa-internal (new-union-state new-union-state-set union-state literal)
"setup dfa rule
internal function that takes the new DFA state, the list of NFA states it represents, the
literal used for the transition, and the DFA state we are going from,
and updates the DFA rules appropriately."
(declare (type atom new-union-state union-state)
(type list *nfa-literals*)
(type character literal)
(type hash-table *dfa-states* *dfa-rules*)
(special *nfa-literals* *dfa-states* *dfa-rules*)
(optimize (speed 3) (safety 0)))
;; first, store the translation of statename to set of dfa states it represents, if we need to.
(cond
((null (gethash new-union-state *dfa-states*))
(setf (gethash new-union-state *dfa-states*) new-union-state-set)
(setf (gethash (list union-state literal) *dfa-rules*) new-union-state)
;; and get the closure of this new state
(mapc #'(lambda (x) (lit*-closure x)) new-union-state-set)
(mapc #'(lambda (x) (dfa-unify-states new-union-state x)) *nfa-literals*))
(t
;; since it was already there, just add the transition.
(setf (gethash (list union-state literal) *dfa-rules*) new-union-state)))
(values))
;;;
;;;
(defun nfa-accessible (state literal nfa-rules)
"this function takes an nfa state, and a literal, and returns all the states that can be gotten
to via the literal from that state."
(declare (type symbol state)
(type character literal)
(type list nfa-rules)
(optimize (speed 3) (safety 0)))
(let ((result nil))
(dolist (xrule nfa-rules)
(cond
((and (eq state (rule-from xrule)) (eql literal (rule-on xrule)))
(push (rule-to xrule) result))))
result))
;;;
;;;
(defun find-literals (rules)
"this function scans a list of nfa w/o epsilon move rules, and returns a list of all the literals present."
(declare (type list rules)
(optimize (speed 3) (safety 0)))
(cond
((null rules)
nil)
(t
(cons (rule-on (car rules)) (find-literals (cdr rules))))))
;;;
;;;
(defun follow-dfa-table (from-node dfa-table &optional (*history* nil))
"This function returns the real rules from a DFA rule hashtable
by tree walking it starting with the start node. (it isn't really a tree, so...)"
(declare (type symbol from-node) ;chart from this node
(type hash-table dfa-table) ;the rules
(type list *history*) ;which nodes should not be followed.
(special *history*)
(optimize (speed 3) (safety 0)))
(let ((retval nil)) ;list of rules
(cond
((member from-node *history*)
nil) ;don't follow, it's already output.
(t
(push from-node *history*)
(maphash #'(lambda (key val)
(cond
((eq (car key) from-node)
(push (make-rule :from (car key) :on (cadr key) :to val) retval)
(setq retval (nconc (follow-dfa-table val dfa-table *history*) retval)))
(t nil)))
dfa-table)))
retval))
;;;
;;;
(defun nfa-state-to-dfa-state (nstates)
"takes an nfa state or set of states and returns the dfa state that covers it.
\(intern if necessary)"
(declare (optimize (speed 3) (safety 0)))
(cond ((atom nstates)
(intern (concatenate 'simple-string "d" (subseq (string nstates) 1)) (find-package 'user)))
(t
(intern (apply #'concatenate
(list* 'simple-string "d"
(stable-sort
(mapcar #'(lambda (x) (subseq (string x) 1)) nstates)
#'string<))) (find-package 'user)))))
;;;
;;;
(defun optimize-dfa (dfa)
"this function takes the internal rep of a DFA and optimizes it (eliminates duplicate states)
It uses the algorithm described on pg. 70 of HU. to find the inequivalent states in the FA."
(declare (type fa dfa)
(optimize (speed 3) (safety 0)))
dfa) ;for the moment, just return it
; (let* ((q (remove-duplicates (find-states (fa-rules dfa)))) ;position of state in this list is critical!
; (mark-array (make-array (list (list-length q) (list-length q)) :initial-element nil))
; (f (fa-end dfa))
; (q-f (set-difference q f))
; (trans (fa-rules dfa))
; (alpha (find-literals trans))
; )
;
; (do ((q1 q (cdr q1)) ;assign to each atom in q a value.
; (n1 0 (+ n1 1)))
; ((null q1))
; (set (car q1) n1))
;
; ;;mark pairs of final and nonfinal states which can't possibly be equivalent.
; (dolist (p1 f)
; (dolist (q1 q-f)
; (mark p1 q1 mark-array)))
;
; ;; for each pair of distinct states (p,q) in fxf or (q-f)x(q-f) do
; (mapc
; #'(lambda (p1 q1)
; ;; if for some input symbol a, ((p, a), (q, a)) is marked
; (cond
; ((plusp
; (reduce #'+
; (mapcar
; #'(lambda (x)
; (apply #'aref
; `(mark-array
; ,(sort
; (eval (find-newstate p1 x trans))
; (eval (find-newstate q1 x trans))
; #'<))))
; alpha)))
; ;; mark (p, q), and recursively mark all unmarked pairs on the list for (p,q) and on
; ;; the lists of other pairs that are marked at this step
; (mark p1 q1 mark-array)
; (mark-list p1 q1 mark-array))
;
; (t
; (mapcar
; #'(lambda (x)
; (cond
; ((not (eq (find-newstate p1 x trans) (find-newstate q1 trans)))
; (push (list p1 q1)
; (apply #'aref
; `(mark-array
; ,(sort
; (eval (find-newstate p1 x trans))
; (eval (find-newstate q1 x trans))
; #'<)))))))
; alpha))))
;
; (append (cross f f) (cross q-f q-f)))
;
; (dotimes (q1 (listlength q)) ;assign to each atom in q it's equivalence class
; (do ((q2 (+ q1 1) (+ q2 1)))
; ((eql q2 (listlength q)))
; (cond
; ((not (eq 't (car (aref mark-array q1 q2))))
; (set (nth q1 q) (cons (nth q2 q) (eval (nth q1 q))))
; (set (nth q2 q) (cons (nth q1 q) (eval (nth q2 q))))))))
;
;
; ;; now that the table is set up, output the new dfa, combining the redundant states
; (make-fa
; :start (fa-start dfa)
; :end f
; :rules (minimal-rules trans mark-array))))
;
;;;;
;;;; for each pair stored in list for p,q passed, mark it.
;;;;
;(defun mark-list (p q mark-array)
; (declare (type atom p q)
; (type array mark-array)
; (optimize (speed 3) (safety 0)))
;
; (dolist (instance (apply #'aref `(mark-array ,(sort (eval p) (eval q) #'<))))
; (cond
; ((and (not (eq (car instance) 't)) (not (eq instance nil)))
; (apply #'mark (append instance mark-array))
; (apply #'mark-list (append instance mark-array)))))) ;recursively
;
;;;;
;;;; this function marks the appropriate point in the array (sorts the evaled args, etc.)
;;;;
;(defun mark (x y xarray)
; (declare (type atom x y)
; (type array mark-array)
; (optimize (speed 3) (safety 0)))
;
; (push 't (apply #'aref `(mark-array ,(sort (eval x) (eval y) #'<)))))
;
;;;
;;;
(defun find-newstate (state literal rules)
"this function takes a state and a literal, and finds the newstate in the list of rules (dfa simulator)."
(declare (type atom state)
(type character literal)
(optimize (speed 3) (safety 0)))
(dolist (xrule rules)
(cond
((and (eq state (rule-from xrule))
(eql literal (rule-on xrule)))
(return (rule-to xrule))))))
;;;;
;;;; this function takes two lists, and returns the cross product. it does not return duplicates.
;;;;
;(defun cross (x y)
; (declare (type list x y)
; (optimize (speed 3) (safety 0)))
;
; (let ((result nil))
; (dolist (x1 x)
; (dolist (y1 y)
; (cond ((not (eq x1 y1))
; (push (list x1 y1) result)))))
; (remove-duplicates result)))
;;;
;;;
(defun dfa-to-function (dfa)
"this function takes the internal rep of a dfa and converts it to a lisp function.
Right now, just return a tree walker. In the future, if I am sufficiently ambitious, I
could compile the DFA into real lisp code."
(declare (type fa dfa)
(optimize (speed 3) (safety 0)))
`(lambda (x)
(declare (type string x)
(optimize (speed 3) (safety 0)))
;; turn the passed dfa into a function that returns T if the string X matches, and NIL
;; if it doesn't (i.e. if it takes us to a final state or not)
(let ((current-state (quote ,(fa-start dfa)))
(finish-states (quote ,(fa-end dfa)))
(rules (quote ,(fa-rules dfa)))
(current-input x))
(loop
(cond ((string= "" current-input)
(cond
((member current-state finish-states)
(return 't)) ;done, success!
(t
(return nil)))) ;lossage!
(t
(cond
((setq current-state
(find-newstate current-state
(char current-input 0)
rules)) ;no, sim step on the first char
(setq current-input (subseq current-input 1)))
(t
(return nil))))))))) ;lossage!
(pushnew :cl-lib-re-to-dfa *features*)
| 28,071 | Common Lisp | .lisp | 1 | 28,070 | 28,071 | 0.630116 | Bradford-Miller/CL-LIB | 1 | 0 | 1 | LGPL-3.0 | 9/19/2024, 11:28:28 AM (Europe/Amsterdam) | a7702bd72d81bdfba7d6d694b529d4dcbbe60abac7518319c0039ec46baf9ff3 | 25,876 | [
-1
] |
25,877 | syntax.lisp | Bradford-Miller_CL-LIB/packages/syntax.lisp | (in-package CL-LIB)
(cl-lib:version-reporter "CL-LIB-Syntax" 5 0 ";; Time-stamp: <2008-05-03 13:20:20 gorbag>"
"CVS: $Id: syntax.lisp,v 1.2 2008/05/03 17:42:03 gorbag Exp $
restructured version")
;; This portion of CL-LIB Copyright (C) 1985-2008 by Bradford W. Miller and the Trustees of the University of Rochester
;;
;; This library is free software; you can redistribute it and/or modify it under the terms of the GNU
;; Lesser General Public License as published by the Free Software Foundation; either version 3.0 of
;; the License, or (at your option) any later version.
;; This library 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.
;; You should have received a copy of the GNU Lesser General Public License along with this library;
;; if not, see <http://www.gnu.org/licenses/>.
(defvar *syntax-alist* nil "Alist of declared syntaxes (readtables) as name . readtable-name")
;; we quote the readtable-symbol so the readtable can change independantly of this database.
(defun add-syntax (name readtable-symbol)
"Associate the name with the readtable-symbol, a quoted variable containing the readtable."
(update-alist name readtable-symbol *syntax-alist*))
(defun set-syntax (syntax-name)
(let ((readtable-name (cdr (assoc syntax-name *syntax-alist*))))
(setq *readtable* (if readtable-name
(symbol-value readtable-name)
(copy-readtable nil))))) ; use the common-lisp readtable
(defmacro with-syntax (syntax-name &body body)
`(let ((*readtable* *readtable*)) ; establish a binding
(set-syntax ,syntax-name)
,@body))
(pushnew :cl-lib-syntax *features*)
| 1,863 | Common Lisp | .lisp | 1 | 1,862 | 1,863 | 0.705851 | Bradford-Miller/CL-LIB | 1 | 0 | 1 | LGPL-3.0 | 9/19/2024, 11:28:28 AM (Europe/Amsterdam) | 3a209224b293b01a4fd158180dc6761e8570db8d2e42e1614693593b62be9fce | 25,877 | [
-1
] |
25,878 | transcripts.lisp | Bradford-Miller_CL-LIB/packages/transcripts.lisp | (in-package cl-user)
(cl-lib:version-reporter "CL-LIB-Transcripts" 5 13 ";; Time-stamp: <2011-11-16 17:31:23 millerb>"
"CVS: $Id: transcripts.lisp,v 1.5 2011/11/24 16:05:50 millerb Exp $
;; *suppress-logs*")
;; 5.13 11/16/11 add *suppress-logs* to disable opening logs (e.g. when testing from console)
;; 5.12 11/10/11 open-transcript-stream-p open-log-stream-p
;; 5.10 5/ 2/08
;; 5.7 11/22/07 function documentation
;; 5.5 10/15/07 efficiency of apply-format (also bug workaround)
;; 5.3 5/18/07 open-interactive-log-stream
;; Additional changes Copyright (C) 2011 Bradford W. Miller. Released under license as below.
;; THE TRANSCRIPTS PACKAGE: Bradford W. Miller
;; made part of CL-LIB 12/19/99 by [email protected] (BW Miller)
;; Based on code written for the TDS poject by Bradford W. Miller ([email protected]) 6/1994.
;; Reused for TRAINS 9/1995.
;;
;; This portion of CL-LIB Copyright (C) 1994-2008 Bradford W. Miller and the Trustees of the University of Rochester
;;
;; This library is free software; you can redistribute it and/or modify it under the terms of the GNU
;; Lesser General Public License as published by the Free Software Foundation; either version 3.0 of
;; the License, or (at your option) any later version.
;; This library 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.
;; You should have received a copy of the GNU Lesser General Public License along with this library;
;; if not, see <http://www.gnu.org/licenses/>.
(defpackage :transcripts
(:use common-lisp cl-lib)
(:export
#:do-log #:do-log-timestamp #:transcribe #:transcribe-and-log #:open-transcript-stream #:open-log-stream #:close-logs
#:open-log-stream-for-module ;; added 9/28 - use in trains
#:find-log-stream #:log-warning #:open-interactive-log-stream
#:debug-p #:debug-log #:when-debugging
#:stamp-view-log-indicator #:do-log-all
#:*transcript-stream* #:*log-file* #:*log-streams* #:*crash-log-stream*
#:open-transcript-stream-p #:open-log-stream-p
#:tassert
#:write-log-header
#:*suppress-transcripts* #:*suppress-logs*)
(:documentation "This package defines a mechanism for creating transcript, log, and debug type files in a somewhat structured
manner."))
(in-package :transcripts)
(defvar *suppress-transcripts* nil "When non-nil, supress all (non-crash) logging activities")
(defvar *suppress-logs* nil "When non-nil, supress opening logs")
;; patch
#+excl
(excl:without-package-locks
(defmethod open-stream-p ((x null))
nil))
(defun check-for-lep ()
"running under emacs?"
#+excl
(and (find-package 'lep)
(funcall (intern "LEP-IS-RUNNING" (find-package 'lep))))
#-excl
nil)
(defvar *log-file* nil "Path to a log file")
(defvar *transcript-stream* nil ; global
"Stream for the transcript")
(defvar *transcript-stream-stamp* '(1 2 3) "when we last printed to stream, so we know if we should drop a timestamp")
(defvar *log-streams* nil ; global
"Streams open for logs")
(defvar *crash-log-stream* nil "Special stream for dealing with crash messages")
(defgeneric write-log-header (stream who)
(:documentation "Puts a header at the top of each log file. For a particular who, may be overridden by the caller by
defining a method."))
(defmethod write-log-header (stream (who t))
(mlet (second minute hour date month year) (get-decoded-time)
(format stream "~&\
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;; ;;;;
;;;; Logfile for ~A~56T;;;;
;;;; ;;;;
;;;; Opened: ~D/~D/~4D ~2,'0D:~2,'0D:~2,'0D~56T;;;;
;;;; ;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;~%~%"
who month date year hour minute second)))
(defun drop-timestamp (stream last-timestamp &optional who)
(mlet (second minute hour) (get-decoded-time)
(let ((stamp (list second minute hour)))
(unless (and (not (null last-timestamp))
(equalp stamp (symbol-value last-timestamp)))
(if who
(format stream "~&<~2,'0D:~2,'0D:~2,'0D>(~A)~%" hour minute second who)
(format stream "~&<~2,'0D:~2,'0D:~2,'0D>~%" hour minute second))
(set last-timestamp stamp)))))
(defun apply-format (stream control arguments)
(declare (special cl-user::*debug*))
(if arguments
(apply #'format stream control arguments)
(write-string control stream)) ;; faster
(fresh-line stream)
(if cl-user::*debug*
(force-output stream)))
(defun open-log-stream-p (log-stream)
(and (not (null log-stream))
(streamp log-stream)
(open-stream-p log-stream)))
(defun open-transcript-stream-p ()
(open-log-stream-p *transcript-stream*))
(defun transcribe (who control &rest arguments)
"drop a timestamped message into the transcript from WHO."
(declare (ignore who))
(unless *suppress-transcripts*
(when (open-transcript-stream-p)
(drop-timestamp *transcript-stream* '*transcript-stream-stamp*)
(apply-format *transcript-stream* control arguments))))
(defun transcribe-and-log (who control &rest arguments)
"Like transcribe, but also drops into who's log."
(apply #'transcribe who control arguments)
(apply #'do-log who control arguments))
(defun find-log-stream (who)
"Given a who parameter, returns the associated log stream from *log-streams*"
(values-list (cdr (assoc (make-keyword who) *log-streams*))))
(defun update-stamp (who stamp)
(setf (second (cdr (assoc (make-keyword who) *log-streams*))) stamp))
(defun do-log (who control &rest arguments)
"writes to the who logfile based on format control/arguments."
(unless *suppress-transcripts*
(let ((*print-circle* t)
(*print-length* 400)
(*print-level* 20)
(*print-pretty* t)
(*print-readably* nil))
(apply #'do-log-direct who control arguments))))
(defvar *log-timestamp* nil)
(defun do-log-direct (who control &rest arguments)
(mlet (log-stream *log-timestamp*) (find-log-stream who)
(unless (open-log-stream-p log-stream)
(when *log-file*
(open-log-stream-for-module who)
(setq log-stream (find-log-stream who))))
(cond
((open-log-stream-p log-stream)
(drop-timestamp log-stream '*log-timestamp*)
(update-stamp who *log-timestamp*)
(apply-format log-stream control arguments)))))
(let ((run-time 0)
(real-time 0))
(defun reset-timestamp ()
(setq run-time (get-internal-run-time)
real-time (get-internal-real-time)))
(defun do-log-direct-timestamp (who control &rest arguments)
(mlet (log-stream stamp) (find-log-stream who)
(declare (ignore stamp))
(unless (open-log-stream-p log-stream)
(when *log-file*
(open-log-stream-for-module who)
(setq log-stream (find-log-stream who))))
(let ((current-run-time (- (get-internal-run-time) run-time))
(current-real-time (- (get-internal-real-time) real-time)))
(cond
((open-log-stream-p log-stream)
(format log-stream "~&< ~9D Run: ~9D Real>(~A) " current-run-time current-real-time who)
(apply-format log-stream control arguments)))))))
;; useful for metering
(defun do-log-timestamp (who control &rest arguments)
"Like do-log, but adds a timestamp"
(unless *suppress-transcripts*
(let ((*print-circle* t)
(*print-length* 400)
(*print-level* 20)
(*print-pretty* t)
(*print-readably* nil))
(apply #'do-log-direct-timestamp who control arguments))))
(defun debug-p (debug-level-needed)
"Return non-nil, if cl-user::*debug* is high enough to trigger debugging"
(declare (special cl-user::*debug* cl-user::*debug-levels*))
(when cl-user::*debug* ; skip if debugging is off
(or (eql cl-user::*debug* t)
(let ((posn-debug (position cl-user::*debug* cl-user::*debug-levels*))
(posn-needed (position debug-level-needed cl-user::*debug-levels*)))
(and (integerp posn-debug)
(integerp posn-needed)
(<= posn-needed posn-debug))))))
(defmacro when-debugging (debug-level-needed &body body)
"Macro that wraps the body in a (when (debug-p ,debug-level-needed) ,@body)"
`(when (debug-p ,debug-level-needed)
,@body))
(defun debug-log (who debug-level control &rest arguments)
"Main function for writing a messge to a debug log file. Users cl-user::*debug* and compares to debug-level to determine if the
diagnostic should be written. who defines which log file to use, control and arguments are as for format."
(declare (special cl-user::*debug*))
(cond
((or *suppress-transcripts*
(null cl-user::*debug*))) ; not debugging, so just return
((consp who)
;; multiple logs
(mapc #'(lambda (x) (apply #'debug-log x debug-level control arguments))
(delete-duplicates who :key #'find-log-stream))) ; only if they have different log streams
((or (debug-p debug-level)
(debug-p (make-keyword who)))
(apply #'do-log who control arguments))))
(defun log-warning (who control &rest arguments)
"Special warning formatting, and also sends to :warnings transcript"
(cond
((consp who)
;; multiple logs
(mapc #'(lambda (x) (apply #'do-log x control arguments))
(delete-duplicates who :key #'find-log-stream))
(apply #'do-log :warnings control arguments))
(t
(apply #'do-log who control arguments)
(apply #'do-log :warnings control arguments))))
(defun close-logs ()
"Close all open logs, after writing a timestamp to them."
(mlet (second minute hour) (get-decoded-time)
(when (open-transcript-stream-p)
(format *transcript-stream* "~&~%~%;; **** Log Closed: <~2,'0D:~2,'0D:~2,'0D> ****~%" hour minute second)
(close *transcript-stream*))
(dolist (ls *log-streams*)
(when (and (open-log-stream-p (cadr ls)) (not (equalp (cadr ls) *error-output*)))
(format (cadr ls) "~&~%~%;; **** Log Closed: <~2,'0D:~2,'0D:~2,'0D> ****~%" hour minute second)
(close (cadr ls))))
(setq *log-streams* nil)))
(defun open-transcript-stream (file)
"Opens a distinguished *transcript-stream* using file, after closing *transcript-stream* if it's an open stream."
(when (open-transcript-stream-p)
(close *transcript-stream*))
(when (and file (not *suppress-logs*))
(setq *transcript-stream* (open file
:direction :output
:if-exists :append
:if-does-not-exist :create))
(format *transcript-stream* ";; Transcript stream ~(~A~)~%~%" file)))
(defun open-log-stream-for-module (who &optional interactive-p)
"Opens a log stream for the passed module."
(unless *suppress-logs*
(assert (and (symbolp who) (not (null who))) (who) "Who should be a non-null symbol")
(setq who (make-keyword who))
(let ((log-stream (find-log-stream who)))
(unless (open-log-stream-p log-stream)
(let ((new-stream
(cond
(interactive-p
;; use *error-output* - useful for having some version of logging when running from a listener.
*error-output*)
(t
(open (merge-pathnames (pathname (string-downcase (string who) :start 1)) (pathname *log-file*))
:direction :output
:if-exists :append
:if-does-not-exist :create)))))
(write-log-header new-stream who)
(update-alist who (list new-stream '())
*log-streams*))))))
(defun open-log-stream (file default-module)
"Closes all the logs, then uses the passed file name as the default log stream for the module and sets it up as the *crash-log-stream*"
(if *log-streams* (close-logs))
(unless *suppress-logs*
(setq *log-file* file)
(when file
(open-log-stream-for-module (make-keyword default-module))
(setq *crash-log-stream* (find-log-stream (make-keyword default-module))))))
(defun open-interactive-log-stream (default-module)
"Closes all the logs, then uses standard out as the default log stream for the module and sets it up as the *crash-log-stream*"
(if *log-streams* (close-logs))
(open-log-stream-for-module (make-keyword default-module) t)
(setq *crash-log-stream* (find-log-stream (make-keyword default-module))))
(defun do-log-all (control &rest arguments)
"Write the log entry to all *log-streams*"
(apply #'transcribe nil control arguments)
(dolist (entry *log-streams*)
(apply #'do-log (car entry) control arguments)))
(defun stamp-view-log-indicator (number message &optional info-only)
"Print a message to all logs. If info-only is nil, scare formatting is used."
(if info-only
(do-log-all "~&;;; *** ~D ~W~%" number message)
(do-log-all "~&;;; ***~%;;; ***~%;;; ***VL*** ~D ~W~%;;; ***~%;;; ***" number message)))
(defmacro tassert (who debug-level test-form &optional places string &rest args)
"TASSERT who debug-level test-form [({place}*) [string {arg}*]]
If the test-form evals to NIL, then either signal an error or log an error, depending on the value of debug-level: if current tracing is such that we would
normally trace debug-level, assert instead. If tracing is such that we would ignore, log instead."
`(cond
((debug-p ,debug-level)
;; we do it this way instead of checking test-form to avoid reevaluation of test-form and make sure we use the host CL's version of assert.
(assert ,test-form ,places ,string ,@args))
(,test-form
nil)
(t
(do-log ,who ,string ,@args))))
(pushnew :cl-lib-transcripts *features*)
| 14,060 | Common Lisp | .lisp | 1 | 14,059 | 14,060 | 0.63357 | Bradford-Miller/CL-LIB | 1 | 0 | 1 | LGPL-3.0 | 9/19/2024, 11:28:28 AM (Europe/Amsterdam) | 4197b994b31709a273a4c43319d5730663dc656da4cb026509eabe690031c3dd | 25,878 | [
-1
] |
25,879 | triangular-matrices.lisp | Bradford-Miller_CL-LIB/packages/triangular-matrices.lisp | (in-package CL-LIB)
(cl-lib:version-reporter "CL-LIB-Triangular-Matrices" 5 16 ";; Time-stamp: <2019-11-11 17:03:48 Bradford Miller(on Aragorn.local)>"
"restructured version")
;; Version history
;; 5.16 5/19/19 Reformatting to fix nominal screen size (mostly just fixing comments and line breaks)
;; Updated licensing for consistency with other files
;;; ****************************************************************
;;; Triangular Matrices ********************************************
;;; ****************************************************************
;;;
;;; Copyright (C) 1994, 2019 by Bradford W. Miller ([email protected])
;; This library is free software; you can redistribute it and/or modify it under the terms of the GNU
;; Lesser General Public License as published by the Free Software Foundation; either version 3.0 of
;; the License, or (at your option) any later version.
;; This library 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.
;; You should have received a copy of the GNU Lesser General Public License along with this library;
;; if not, see <http://www.gnu.org/licenses/>.
;; miller - Brad Miller ([email protected])
;;; ********************************
;;; Motivation *********************
;;; ********************************
;;; Twofold. 1) using only the upper or lower portion of a multi-d
;;; matrix wastes 1/2 the space. That's a minor consideration. 2)
;;; increasing the size of a matrix by 1 (e.g. using adjust-array)
;;; potentially copies the entire array to a new location, which is
;;; O(n**axes) with n being the length of the axis (triangular arrays
;;; are "square") The following algorithm is O(n**(axes-1)).
;;; That is, for a two-d array it's O(n) instead of O(n**2). Time to
;;; access or write an element is still O(1) <for an existing array>,
;;; but the constant factor is larger than normal arrays, because an
;;; extra level of indirection is involved.
;;;
;;; ********************************
;;; Description ********************
;;; ********************************
;;; Instead of relying on adjust-array, we have increment-array to add
;;; a new row (column) to a upper/lower triangular matrix We also
;;; supply access (defsetf'd) functions to access triangular arrays.
;;; The basic idea is this.
;;; an axis of a triangular array is a vector, each element of which
;;; is another vector. For a "square" upper triangular matrix, the 0th
;;; entry will have length 1, the next entry length 2, etc. I.e. the
;;; size is the column j +1.
;;; to add a new column, then, we can just add a new slot to the axis
;;; vector (potentially copying it, an O(n) operation). and cons up a
;;; new column vector, which will be length n, another O(n)
;;; operation. Accessing is a two-step operation, and row-major-aref
;;; won't work with triangular arrays because they aren't linear in
;;; memory! We supply a copy function, however.
;;; The package supports 2d arrays, though the algorithm can be
;;; extended to any n-dimensions, just not this implementation. For
;;; upper dimensions, we need to store the extra dimension vectors in
;;; the tarray structure.
;;; Visualization each string xxx represents a vector (array) in the
;;; upper triangle, each string yyy is a vector (array) in the lower
;;; triangle. The lengths show connectivity is illustrated by length
;;; of the string. 0,0 is in the upper triangle. 2,0 and 2,1 are in
;;; the same vector of the lower triangle.
;;; 0 1 2 3 4 5 x-axis
;;;
;;; 0 x x x x x x
;;; x x x x x
;;; 1 y x x x x x
;;; x x x x
;;; 2 yyyyyy x x x x
;;; x x x
;;; 3 yyyyyyyyyyy x x x
;;; x x
;;; 4 yyyyyyyyyyyyyyyy x x
;;; x
;;; 5 yyyyyyyyyyyyyyyyyyyyy x
;;; y axis
;;; the algorithm (but not this code) works just as well in n-d. For
;;; 3-d, we would add planes (2d arrays) on each side of our starting
;;; cube each time we increment the axis maximum. We also need to add
;;; another index vector. Viewed from the "front", i.e. x/y axis, our
;;; planes would line up like the above diagram. From the top, we'd
;;; see:
;;; 0 1 2 3 4 5 z-axis
;;;
;;; 0 x z z z z z
;;; z z z z
;;; 1 xxxxxx z z z z
;;; z z z
;;; 2 xxxxxxxxxxx z z z
;;; z z
;;; 3 xxxxxxxxxxxxxxxx z z
;;; z
;;; 4 xxxxxxxxxxxxxxxxxxxxx z
;;;
;;; 5 xxxxxxxxxxxxxxxxxxxxxxxxxx
;;; x axis
;;; so the main extension to this implementation for higher order N
;;; would be to
;;; a) change the tarray defstruct to make the "upper" and "lower"
;;; vector slots a list of vectors, one for each dimension.
;;; b) change make-tarray to build each of the d arrays instead of just 2
;;; c) change the logic in taref to correctly figure out which (d-1)
;;; array a point is located in, and find it via the vectors in a).
;;; d) change the subroutines called in b) to correctly build multi-d
;;; arrays of the right size.
;;; so, the notion of "upper" and "lower" only works with 2d arrays,
;;; for n-d arrays, there are n senses of where a point is located.
;;; it obviously isn't practical to export all of them as separately
;;; creatable "slices" of an n-d array (though if an appropriate
;;; automatic naming scheme were arrived at, it might be
;;; possible). Also so generifying all the code below makes the 2d
;;; case slower, and that's the only case I care about right now :-).
;;; Using this code with >2 dimensions will work, but you'll only get
;;; the "pyramid"/ upper-d object corresponding to an upper triangle
;;; of an array, i.e. it won't fill in the rest of the matrix with the
;;; other slices. e.g. for a (3 3 3) triangular matix, you'll have
;;; slots (0,0,0) but not (0,0,1), and (1,1,1), but not (1,1,2)
;;; etc. Think of it as a pyramid. (It's not what you want, of course,
;;; but see above comments on extending this implementation for the
;;; full algorithm.
;;; ********************************
;;; HOW TO USE *********************
;;; ********************************
;;; As cltl/2 array like as possible, but displacement and
;;; fill-pointers are not supported. the type may be specialized or
;;; general (i.e. you get to supply an element type). All triangular
;;; matrices are "adjustable" but only via increment-array.
;;; Type is tarray; for the full (upper+lower) version, upper-tarray
;;; for i,j i>=j. lower-tarray for i,j i<j. Note that lower
;;; triangular+upper triangualr + full triangular, since only
;;; upper-triangular arrays allow i=j.
;;; make-tarray dimensions &key :element-type :initial-element :initial-contents
;;; the supported arguments have the same meaning as
;;; in CLtL/2's definition of make-array. Note that this will
;;; construct a pair of triangular arrays, upper and lower, but they
;;; will have the nice updating properties described above.
;;; Attempting to create a 1 dimensional triangular array will just
;;; create a vector. There is no advantage over using make-array or
;;; vector, and supplying :adjustable t.
;;; make-upper-tarray dimensions &key :element-type :initial-element :initial-contents
;;; see above, upper triangle only.
;;; make-lower-tarray dimensions &key :element-type :initial-element :initial-contents
;;; see above, lower triangle only.
;;; taref tarray &rest subscripts
;;; like aref, but works on triangular arrays. It **is an error** to
;;; attempt to access the lower-triangle of an upper triangular array,
;;; and vice-versa. A "full" triangular array (from make-tarray) has
;;; both, so it works.
;;; if you aren't sure if your subscripts are valid arguments to taref
;;; for a (upper/lower) triangular array, use tarry-in-bounds-p to
;;; check them.
;;; the following tarry-<fn> are just like array-<fn> in CLtL2.
;;; tarray-element-type
;;; tarray-rank
;;; tarray-dimension
;;; tarray-dimensions
;;; tarray-total-size (note, the total size of the triangle, i.e. about 1/2
;;; from the product of the dimensions for upper or lower tas.)
;;; tarray-in-bounds-p
;;;
;;; increment-tarray tarray :initial-element :initial-contents
;;; like adjust-array, but will only add 1 to (all of) the array dimensions. If triangular array
;;; is upper or lower only, then the right thing happens.
;;; The following to the obvious
;;; upper-tarray-p
;;; lower-tarray-p
;;; full-tarray-p
;;; tarray-p
;;; copy-tarray (takes an optional argument for the copier of the elements, defaults to #'identity)
;;; bits, general array adjustment, row-major-aref etc. are not currently supported.
;;; Note: I only needed this for 2d arrays, it should work for nd
;;; arrays, (and trivially tested) but it's possible that it's broken.
;;; representation issues
(defstruct (tarray (:constructor make-tarray-struct) (:copier nil) (:print-function print-tarray))
;; exported slots
(element-type 't)
(rank 0 :type fixnum)
(dimensions nil :type list)
;; internal only
(upper-vector nil :type (or null vector))
(lower-vector nil :type (or null vector))
)
(defun make-tarray (dimensions &key (element-type 't) (initial-element nil iep) (initial-contents nil icp))
"Create a full triangular array (both upper and lower). Supported
options like make-array."
(progfoo (make-upper-tarray-i dimensions element-type initial-element iep initial-contents icp nil)
(make-lower-tarray-i dimensions element-type initial-element iep initial-contents icp foo)))
(defun make-upper-tarray (dimensions &key (element-type 't) (initial-element nil iep) (initial-contents nil icp))
"Make only an upper triangular array. subscripts may be equal, for
any subscript ordering (1 .. i .. j .. n) the value of subscript i
must be >= j."
(make-upper-tarray-i dimensions element-type initial-element iep initial-contents icp nil))
(defun make-lower-tarray (dimensions &key (element-type 't) (initial-element nil iep) (initial-contents nil icp))
"Make only a lower triangular array. subscripts may NOT be equal,
for any subscript ordering (1 .. i .. j .. n) the value of subscript i
must be < j."
(make-lower-tarray-i dimensions element-type initial-element iep initial-contents icp nil))
(defun taref (tarray &rest subscripts)
"Like aref on tarrays."
(if (<= (first subscripts) (second subscripts))
(taref-upper-tarray tarray subscripts)
(taref-lower-tarray tarray subscripts)))
(defsetf taref (tarray &rest subscripts) (new-value)
`(if (<= ,(first subscripts) ,(second subscripts))
(setf (taref-upper-tarray ,tarray ,@subscripts) ,new-value)
(setf (taref-lower-tarray ,tarray ,@subscripts) ,new-value)))
(defun tarray-dimension (tarray axis-number)
"Return the dimension of a particular axis of the tarray. Note that
all axes must be equal, so one is as good as another."
(nth axis-number (tarray-dimensions tarray)))
(defun tarray-total-size (tarray)
"Return the total size of the passed tarray, including uninitialized cells."
(cond
((full-tarray-p tarray)
(reduce #'* (tarray-dimensions tarray)))
((upper-tarray-p tarray)
(reduce #'+ (mapcar #'array-total-size (tarray-upper-vector tarray))))
(t
(reduce #'+ (mapcar #'array-total-size (tarray-lower-vector tarray))))))
(defun tarray-in-bounds-p (tarray &rest subscripts)
(and (= (length subscripts) (tarray-rank tarray))
(every #'< subscripts (tarray-dimensions tarray))
(cond
((full-tarray-p tarray))
((upper-tarray-p tarray)
(let ((temp (car subscripts)))
(every #'(lambda (sub) (if (<= temp sub) (setq temp sub))) (cdr subscripts))))
(t ; lower tarray.
(let ((temp (car subscripts)))
(every #'(lambda (sub) (if (> temp sub) (setq temp sub))) (cdr subscripts)))))))
(defun upper-tarray-p (thingo)
"True iff thingo is an upper (not full) triangular array."
(and (tarray-p thingo)
(not (null (tarray-upper-vector thingo)))
(null (tarray-lower-vector thingo))))
(defun lower-tarray-p (thingo)
"True iff thingo is a lower (not full) triangular array."
(and (tarray-p thingo)
(not (null (tarray-lower-vector thingo)))
(null (tarray-upper-vector thingo))))
(defun full-tarray-p (thingo)
"True iff thingo is a full triangualr array."
(and (tarray-p thingo)
(not (null (tarray-upper-vector thingo)))
(not (null (tarray-lower-vector thingo)))))
(defun increment-tarray (tarray &key (initial-element nil iep) (initial-contents nil icp))
"Add 1 to the size of all axes of the passed tarray, and initialize as per adjust-array."
(when (tarray-lower-vector tarray)
(vector-push-extend (make-array (cdr (tarray-dimensions tarray))
:element-type (tarray-element-type tarray)
(if iep :initial-element :ignore) initial-element
(if icp :initial-contents :ignore) initial-contents
:allow-other-keys t)
(tarray-lower-vector tarray))
(assert (eql (fill-pointer (tarray-lower-vector tarray)) (1+ (car (tarray-dimensions tarray)))) ()
"Bad increment"))
(mapl #'(lambda (el) (setf (car el) (incf (car el))))
(tarray-dimensions tarray))
(when (tarray-upper-vector tarray)
(vector-push-extend (make-array (cdr (tarray-dimensions tarray))
:element-type (tarray-element-type tarray)
(if iep :initial-element :ignore) initial-element
(if icp :initial-contents :ignore) initial-contents
:allow-other-keys t)
(tarray-upper-vector tarray))
(assert (eql (fill-pointer (tarray-upper-vector tarray)) (car (tarray-dimensions tarray))) ()
"Bad increment")))
(defun copy-tarray (tarray &optional (element-copier #'identity))
(progfoo (make-tarray-struct :element-type (tarray-element-type tarray)
:rank (tarray-rank tarray)
:dimensions (copy-list (tarray-dimensions tarray)))
(when (tarray-upper-vector tarray)
(let ((vector (setf (tarray-upper-vector foo) (make-tarray-vector (tarray-dimensions tarray)))))
(dotimes (i (car (tarray-dimensions tarray)))
(setf (aref vector i) (copy-array (aref (tarray-upper-vector tarray) i) element-copier)))))
(when (tarray-lower-vector tarray)
(let ((vector (setf (tarray-lower-vector foo) (make-tarray-vector (tarray-dimensions tarray)))))
(dotimes (i (car (tarray-dimensions tarray)))
(setf (aref vector i) (copy-array (aref (tarray-lower-vector tarray) i) element-copier)))))))
;;; internal functions
(defun make-tarray-vector (dimensions)
(make-array (car dimensions)
:adjustable t
:fill-pointer t
:element-type (list* 'array (make-list (list-length (cdr dimensions)) :initial-element '*))))
(defun make-upper-tarray-i (dimensions element-type initial-element iep initial-contents icp reuse-tarray)
(unless reuse-tarray
(setq reuse-tarray (make-tarray-struct :element-type element-type
:rank (list-length dimensions)
:dimensions (copy-list dimensions))))
(let ((vector (setf (tarray-upper-vector reuse-tarray) (make-tarray-vector dimensions))))
(dotimes (i (car dimensions))
(setf (aref vector i)
(make-array (make-list (list-length (cdr dimensions)) :initial-element (1+ i))
:element-type element-type
(if iep :initial-element :ignore) initial-element
(if icp :initial-contents :ignore) initial-contents
:allow-other-keys t))))
reuse-tarray)
(defun make-lower-tarray-i (dimensions element-type initial-element iep initial-contents icp reuse-tarray)
(unless reuse-tarray
(setq reuse-tarray (make-tarray-struct :element-type element-type
:rank (list-length dimensions)
:dimensions (copy-list dimensions))))
(let ((vector (setf (tarray-lower-vector reuse-tarray) (make-tarray-vector dimensions))))
(dotimes (i (car dimensions))
(setf (aref vector i)
(make-array (make-list (list-length (cdr dimensions)) :initial-element i)
:element-type element-type
(if iep :initial-element :ignore) initial-element
(if icp :initial-contents :ignore) initial-contents
:allow-other-keys t))))
reuse-tarray)
(defun taref-upper-tarray (tarray subscripts)
(apply #'aref (aref (tarray-upper-vector tarray) (cadr subscripts)) (car subscripts) (cddr subscripts)))
(defun taref-lower-tarray (tarray subscripts)
(apply #'aref (aref (tarray-lower-vector tarray) (car subscripts)) (cdr subscripts)))
(defsetf taref-upper-tarray (tarray &rest subscripts) (new-value)
`(setf (aref (aref (tarray-upper-vector ,tarray) ,(cadr subscripts))
,(car subscripts)
,@(cddr subscripts))
,new-value))
(defsetf taref-lower-tarray (tarray &rest subscripts) (new-value)
`(setf (aref (aref (tarray-lower-vector ,tarray) ,(car subscripts)) ,@(cdr subscripts)) ,new-value))
(defun print-tarray (tarray stream depth)
(cond
((and *print-level* (> depth *print-level*))
(format stream "#"))
(t
(print-unreadable-object (tarray stream :identity t)
(format stream "~A of rank ~D" (cond ((upper-tarray-p tarray)
"Upper Tarray")
((full-tarray-p tarray)
"Full Tarray")
((lower-tarray-p tarray)
"Lower Tarray")
(t
"Illegal Tarray"))
(tarray-rank tarray))))))
(pushnew :cl-lib-tarray *features*)
| 18,684 | Common Lisp | .lisp | 1 | 18,683 | 18,684 | 0.621762 | Bradford-Miller/CL-LIB | 1 | 0 | 1 | LGPL-3.0 | 9/19/2024, 11:28:28 AM (Europe/Amsterdam) | 52c93e369975efd24a249973e23a472849b35365b83f78aa11ae055f03e88092 | 25,879 | [
-1
] |
25,880 | resources.lisp | Bradford-Miller_CL-LIB/packages/resources.lisp | (in-package CL-LIB)
(cl-lib:version-reporter "CL-LIB-Resources" 5 17 ";; Time-stamp: <2019-10-19 14:23:02 Bradford Miller(on Aragorn.local)>"
"fix toplevel")
;; 5.17 10/19/19 add lispworks specific allocation code (for gc purposes)
;; 5.16 3/ 1/19 add test code
;; 5.16 2/23/19 fixup toplevel
;;; ****************************************************************
;;; Resources ******************************************************
;;; ****************************************************************
;;; This is the resources package written February 1992 by
;;; Bradford W. Miller
;;; [email protected]
;;; University of Rochester, Department of Computer Science
;;; 610 CS Building, Comp Sci Dept., U. Rochester, Rochester NY 14627-0226
;;; 716-275-1118
;;; (Please note that I am no longer there or at that address)
;;; I will be glad to respond to bug reports or feature requests.
;;; Updated 6/4/93 by miller to improve efficiency for the typical case of not having a matcher
;;; or initialization function (since you do the work on deinitialization to allow gc).
;;; Added HOW TO USE section 1/3/94. (miller)
;;;
;;; This version was NOT obtained from the directory
;;; /afs/cs.cmu.edu/user/mkant/Public/Lisp-Utilities/initializations.lisp
;;; via anonymous ftp from a.gp.cs.cmu.edu. (you got it in cl-lib).
;;;
;;;
;;; Copyright (C) 2019, 1994, 1993, 1992 by Bradford W. Miller, [email protected]
;;; All rights reserved.
;; This library is free software; you can redistribute it and/or modify it under the terms of the GNU
;; Lesser General Public License as published by the Free Software Foundation; either version 3.0 of
;; the License, or (at your option) any later version.
;; This library 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.
;; You should have received a copy of the GNU Lesser General Public License along with this library;
;; if not, see <http://www.gnu.org/licenses/>.
;; miller - Brad Miller ([email protected])
;;;
;;; ********************************
;;; HOW TO USE THIS PACKAGE ********
;;; ********************************
;;; To create a new resource:
;;; (defresource (name (args) :initial-copies 0 :initializer nil :deinitializer nil
;;; :matcher nil &allow-other-keys)
;;; &body constructor) <macro>
;;; Name, an unevaluated symbol, will become the name of the new resource.
;;; Args, a lambda list, are used to initialize (create) instances of the
;;; resource, and come from allocate-resource (so it can be used to supply,
;;; e.g. default arguments)
;;;
;;; Note that these args will be used in the default matcher, and
;;; only resources created with the same args will be allowed to
;;; match. If you are creating resources that are homogeneous (that
;;; will be initialized or deinitialized to a common state, or where
;;; you don't care about the state), you should supply nil for args.
;;;
;;; Constructor is a function to call to make a new object when the resource
;;; is empty, and uses the parameters Args as arguments (think of it as a
;;; defun). Note this is required.
;;; Options are:
;;; :initial-copies (used to set up the pool to begin with). This is
;;; the number of times the constructor will be called initially
;;; to form a pool. This will only work if args is nil, or the
;;; constructor can be called with no args (since it has no idea
;;; what arguments to supply).
;;; :initializer (called on a newly allocated object, and the other
;;; parameters). Note the constructor isn't called on objects that
;;; are already in the pool. The initializer is called before handing
;;; an object in the pool to the user.
;;; :deinitializer (called on a newly freed object) Useful to
;;; allow gc of objects the resource refers to, or to
;;; preinitialize, if args aren't needed (if you e.g. do your
;;; deallocation at a user-insensitive time, but allocate at a
;;; user-sensitive time).
;;; :matcher Args are like initializer, but is expected to be a
;;; predicate that succeeds if the unallocated pool object is
;;; appropriate for the call. The default one assumes only pool
;;; objects created with the same parameters are appropriate.
;;; This is useful if, e.g. you are going to put different size
;;; objects in the pool, but don't want to have to create a new
;;; object when a (bigger) one already exists.
;;; allocate-resource (name &rest args) <function>
;;; Get a copy of the NAMEd resource, given the args (for the initializer,
;;; matcher and constructor).
;;; allocate-<resource-name> (&rest args) <function>
;;; specialized version of allocate-resource for resource-name (created by defresource).
;;; deallocate-resource (name object) <function>
;;; Return object to pool name. It's a bad idea to free an object to the wrong
;;; pool.
;;; deallocate-<resource-name> (object) <function>
;;; Specialized version of deallocate-resource for resource-name (created by defresource).
;;; clear-resource (name) <function>
;;; Zaps Name's pool, and starts from empty. Normally only used within
;;; DefResource when recompiled, or user should call if you change the
;;; constructor s.t. the old objects in the pool are obsolete.
;;; Not a good idea to call this if active objects are in use.
;;; clear-<resource-name> () <function>
;;; map-resource (function name) <macro>
;;; Incompatibly defined wrt Lispm, this one is more like mapcar - the
;;; function is called over all resources of type Name, which
;;; is not evaluated. The args are the object, and t if the object is in use,
;;; nil otherwise. I.e.
;;; (map-resource #'(lambda (object in-use) (if in-use (format t "using ~S~%" object))) 'foobar)
;;; will print out all of the foobar resources in use.
;;; map-<resource-name> (function) <macro>
;;; with-resource ((resource name &rest args) &body body) <macro>
;;; Resource is bound to a Named resource initialized with Args.
;;; Name is **not** eval'd but args are.
;;; The resource is freed when the form is exited.
;;; with-<resource-name> ((resource &rest args) &body body) <macro>
;;; ********************************
;;; Motivation *********************
;;; ********************************
;;;
;;; Resources are useful for avoid excessive consing and GCing by
;;; explicitly maintaining pools of objects for reuse, instead of
;;; creating them when needed and relying on the garbage collector to
;;; flush them when they are no longer needed. When an object is no
;;; longer needed, it is returned to the pool of objects of that type,
;;; and recycled when a new object of that type is needed. Using
;;; resources might wind up recycling objects faster than incremental
;;; GC, but it isn't clear whether there are any real time/space
;;; savings.
;;;
;;; Since I have been using the resource features of the explorer and
;;; symbolics, the following was inspired to allow a simple port to
;;; non-lispm lisps. It should be compatible with most uses of the
;;; lispm's versions, though it does not support (yet) the wide
;;; variety of options.
;;;
;;; note: efficiency can likely be improved; the basic idea is to take
;;; a name of a resource, and put some properties on it - the pool of
;;; all allocated resources and a freelist. So building a resource
;;; instance uses (at least) three cons cells - one on the pool, one
;;; on the freelist, and one on a description list for the default
;;; matcher. The default matcher isn't particularly efficient either
;;; since it uses position and nth; but most internal uses of
;;; resources have no args (all resources identical) so matcher isn't
;;; used anyway. Better would be to build a structure that keeps the
;;; description and other info in it, then we have to be able to find
;;; the structure on a free (symbolics passes an extra value to the
;;; user for just this purpose I beleive - I've not looked at their
;;; source code for this, of course :-)
;;;
;;; resources won't be that useful for tiny thingos, since the
;;; alloc/free cycle kicks out a cons cell per. For bigger things, the
;;; efficiency depends on use. Long lived objects are probably better
;;; off just using the usual gc. Particularly since on non-lispms we
;;; can't prevent scavenge attempts of resources anyway.
;;;
;;; another (internal) use of resources is to write code that may
;;; eventually depend on malloc - so the user has to get used to
;;; explicitly freeing things anyway. (Shocker back end is an example
;;; of this). Of course lisps that allow you to cons things in
;;; separate areas that aren't gc'd can improve efficiency by making
;;; sure resources are created there. and if CL had some sort of FREE
;;; function to explicitly free a list, (I mean it has to be cheaper,
;;; in some cases, for an application to know what's garbage than to
;;; have a gc discover it, no?) then resources could also be more
;;; (generically) efficient.
;;;
;;; Note: on a symbolics we use the built-in stuff (translating args
;;; as appropriate) since I assume that's gonna be more efficient than
;;; this code.
;;; ********************************
;;; New ***************************
;;; ********************************
;;; 12/29/93 Brad Miller
;;; Defresource now creates specialized allocate, deallocate, etc. fns called
;;; fn-<resource-name> rathern than <fn>-resource
;;; i.e. (allocate-resource 'frozboz 1 2 3) is the generic version of
;;; (allocate-frozboz 1 2 3)
;;; in particular for terms with no args, or other simplifications, the specialized
;;; versions can be much faster.
;; some simple work arounds for a different gc (just to nullify, feel
;; free to substitute something more appropriate, and SEND IT OVER!
#-excl (defpackage excl (:export #:*tenured-bytes-limit* tenuring))
#-excl
(defvar excl:*tenured-bytes-limit* 0)
#-excl (defmacro tenuring (&body body) `(progn ,@body))
(defstruct resource
(cons #'identity :type function)
(pool nil :type list)
(desc nil :type t)
(freel nil :type list)
(default #'identity :type function)
(free #'identity :type function)
(init #'identity :type function)
(matcher #'identity :type function)
)
(defun extract-parameters (args)
(let (result)
(dolist (arg args (nreverse result))
(if (consp arg)
(push (car arg) result)
;; (unless (char= #\& (char (string arg) 0))
;; (push arg result))
(unless (find arg lambda-list-keywords)
(push arg result))))))
(defmacro defresource ((name args &rest hack
&key (initial-copies 0)
initializer deinitializer
matcher &allow-other-keys)
&body constructor)
(declare (ignorable hack))
"Name, an unevaluated symbol, will become the name of the new resource
(like the lispm, it's a property of Name).
Args, a lambda list, are used to initialize (create) instances of the
resource, and come from allocate-resource (so it can be used to supply,
e.g. default arguments)
constructor is a function to call to make a new object when the resource
is empty, and uses the parameters Args as arguments (think of it as a
defun). Note this is required.
Options are:
:initial-copies (used to set up the pool to begin with).
:initializer (called on a newly allocated object, and the other
parameters). Note the constructor isn't called on objects that
are already in the pool.
:deinitializer (called on a newly freed object) Useful to allow gc
of objects the resource refers to.
:matcher Args are like initializer, but is expected to be a predicate
that succeeds if the unallocated pool object is appropriate for the
call. The default one assumes only pool objects created with the same
parameters are appropriate.
This is useful if you are going to put different size objects in the
pool, but don't want to have to create a new object when a (bigger)
one already exists.
The lispm supports other options too."
#+symbolics
`(scl:defresource ,name ,args :constructor ,@constructor ,@hack)
#-symbolics
(let ((parameters (extract-parameters args))
(i (gensym))
(oldlimit (gensym))
(resource (gensym))
(object (gentemp "OBJECT")) ; want symbol in current package. ; use gentemp 10/19/19 BWM
;; build specialized versions of allocate, deallocate, clear, map and with-resouce
(allocate-fn-name (intern (format nil "ALLOCATE-~A" name)))
(deallocate-fn-name (intern (format nil "DEALLOCATE-~A" name)))
(clear-fn-name (intern (format nil "CLEAR-~A" name)))
(map-fn-name (intern (format nil "MAP-~A" name)))
(with-fn-name (intern (format nil "WITH-~A" name))))
(declare (ignorable oldlimit))
`(let ((,resource (make-resource
:cons #'(lambda ,args ,@constructor)
:pool nil
:desc nil
:freel nil
:default #'(lambda ,args (list ,@parameters))
:free ,(if deinitializer
`#'(lambda (,object) (,deinitializer ,object)) ;; fix BWM 10/19/19
`#'(lambda (,object) ,object))
:init ,(if initializer
`#'(lambda (,object ,@args) (,initializer ,object ,@args)) ;; fix BWM 10/19/19
`#'(lambda (,object ,@args)
(declare (ignore ,@args))
,object))
:matcher #'(lambda (,object ,@args)
,object
,(or matcher
(null args)
`(let ((res (get ',name :resource)))
(declare (type resource res))
(every #'eql (list ,@parameters)
(nth (position ,object (resource-pool res))
(resource-desc res)))))))))
(declare (type resource ,resource))
(setf (get ',name :resource) ,resource)
,@(when (plusp initial-copies)
#+allegro
`((eval-when (load eval)
(excl:tenuring
(let ((,oldlimit excl:*tenured-bytes-limit*)
(,i ,initial-copies))
(setf excl:*tenured-bytes-limit* nil)
(while (plusp ,i)
(decf ,i) ; I'd use dotimes, but then i would be unref'd
(push (funcall (resource-cons ,resource))
(resource-pool ,resource))
,@(if (null args) nil
`((push (funcall (resource-default ,resource))
(resource-desc ,resource)))))
(setf excl:*tenured-bytes-limit* ,oldlimit)))
(clear-resource ',name)))
#+lispworks ;; 10/19/19 BWM
`((eval-when (load eval)
(let ((,i ,initial-copies))
(while (plusp ,i)
(decf ,i) ; I'd use dotimes, but then i would be unref'd
(push (sys:apply-with-allocation-in-gen-num :cons 3 #'resource-cons ,resource)
(resource-pool ,resource))
,@(if (null args) nil
`((push (sys:apply-with-allocation-in-gen-num :cons 3 #'resource-default ,resource)
(resource-desc ,resource))))))
(clear-resource ',name)))
#-(or allegro lispworks)
(error "no code for this lisp to build resource pool"))
(defun ,allocate-fn-name ,args
(do ((lasttry nil try)
(try (resource-freel ,resource) (cdr try)))
((null try) nil)
(declare (ignorable lasttry))
,@(cond
((and (null matcher) (null args) (null initializer))
`((return-from ,allocate-fn-name (pop (resource-freel ,resource)))))
((and (null matcher) (null args))
`((funcall (resource-init ,resource) (car try))
(return-from ,allocate-fn-name (pop (resource-freel ,resource)))))
((and (null args) (null initializer))
`((when (funcall (resource-matcher ,resource) (car try))
(if lasttry
(rplacd lasttry (cdr try))
(pop (resource-freel ,resource)))
(return-from ,allocate-fn-name (car try)))))
((null initializer)
`((when (apply (resource-matcher ,resource) (car try) ,@args)
(if lasttry
(rplacd lasttry (cdr try))
(pop (resource-freel ,resource)))
(return-from ,allocate-fn-name (car try)))))
((null args)
`((when (funcall (resource-matcher ,resource) (car try))
(funcall (resource-init ,resource) (car try))
(if lasttry
(rplacd lasttry (cdr try))
(pop (resource-freel ,resource)))
(return-from ,allocate-fn-name (car try)))))
(t
`((when (apply (resource-matcher ,resource) (car try) ,@args)
(apply (resource-init ,resource) (car try) ,@args)
(if lasttry
(rplacd lasttry (cdr try))
(pop (resource-freel ,resource)))
(return-from ,allocate-fn-name (car try)))))))
;; none found, init one
(let ((new ,(if args `(apply (resource-cons ,resource) ,@args)
`(progn ,@constructor))))
,@(cond
((and initializer args)
`((apply (resource-init ,resource) new ,@args)))
(initializer
`((funcall (resource-init ,resource) new))))
(push new (resource-pool ,resource))
,@(if args
`((push (list ,@args) (resource-desc ,resource))))
new))
(defun ,deallocate-fn-name (,object)
,@(if deinitializer
`((funcall (resource-free ,resource) ,object)))
(push ,object (resource-freel ,resource)))
(defun ,clear-fn-name ()
(setf (resource-freel ,resource) nil)
(dolist (res (resource-pool ,resource))
,@(if deinitializer
`((funcall (resource-free ,resource) res)))
(push res (resource-freel ,resource))))
(defmacro ,map-fn-name (function)
`(mapcar #'(lambda (ob)
(funcall ,function ob (not (member ob (resource-freel (get ',',name :resource))))))
(resource-pool (get ',',name :resource))))
(defmacro ,with-fn-name ((res ,@args) &body body)
`(let ((,res (,',allocate-fn-name ,,@args)))
(unwind-protect
(progn ,@body)
(,',deallocate-fn-name ,res)))))))
#+allegro-v4.1
(add-initialization "lep-init for defresource"
'(lep::eval-in-emacs "(put 'defresource 'fi:lisp-indent-hook '(like with-open-file))")
'(:lep))
(defun allocate-resource (name &rest args)
"Get a copy of the NAMEd resource, given the args (for the initializer,
matcher and constructor). Name is evaluated."
#+symbolics
(apply #'scl:allocate-resource name args)
#-symbolics
(let ((resource (get name :resource)))
(declare (type resource resource))
(do ((lasttry nil try)
(try (resource-freel resource) (cdr try)))
((null try) nil)
(when (if args
(apply (resource-matcher resource) (car try) args)
(funcall (resource-matcher resource) (car try)))
(if args
(apply (resource-init resource) (car try) args)
(funcall (resource-init resource) (car try)))
(if lasttry
(rplacd lasttry (cdr try))
(pop (resource-freel resource)))
(return-from allocate-resource (car try))))
;; none found; init one
(let ((new (if args (apply (resource-cons resource) args)
(funcall (resource-cons resource)))))
(if args
(apply (resource-init resource) new args)
(funcall (resource-init resource) new))
(push new (resource-pool resource))
(if args
(push (copy-list args) (resource-desc resource)))
new)))
(defun deallocate-resource (name object)
"Return object to pool name. It's a bad idea to free an object to the wrong
pool. Name is evaluated."
#+symbolics
(scl:deallocate-resource name object)
#-symbolics
(let ((resource (get name :resource)))
(declare (type resource resource))
(funcall (resource-free resource) object)
(push object (resource-freel resource))))
(defun clear-resource (name)
"Zaps Name's pool, and starts from empty. Normally only used within
DefResource when recompiled, or user should call if you change the
constructor s.t. the old objects in the pool are obsolete.
Not a good idea to call this if active objects are in use."
#+symbolics
(scl:clear-resource name)
#-symbolics
(let ((resource (get name :resource)))
(declare (type resource resource))
(setf (resource-freel resource) nil)
(dolist (res (resource-pool resource))
(when (resource-free resource) ;; 10/19/19 BWM
(funcall (resource-free resource) res))
(push res (resource-freel resource)))))
(defmacro map-resource (function name)
"Incompatibly defined wrt Lispm, this one is more like mapcar - the
function is called over all resources of type Name, which
is not evaluated. The args are the object, and t if the object is in use,
nil otherwise."
#+symbolics
`(scl:map-resource ,name ,function)
#-symbolics
(let ((resource (gensym)))
`(let ((,resource (get ',name :resource)))
(declare (type resource ,resource))
(mapcar #'(lambda (ob)
(funcall ,function ob (not (member ob (resource-freel ,resource)))))
(resource-pool ,resource)))))
#+allegro-v4.1
(add-initialization "lep-init for map"
'(lep::eval-in-emacs "(put 'map-resource 'fi:lisp-indent-hook 1)")
'(:lep))
(defmacro with-resource ((resource name &rest args) &body body)
"Resource is bound to a Named resource initialized with Args.
Name is **not** eval'd but args are.
The resource is freed when the form is exited."
#+symbolics
`(scl:using-resource (,resource ,name ,@args) ,@body)
#-symbolics
`(let ((,resource (allocate-resource ',name ,@args)))
(unwind-protect
(progn ,@body)
(deallocate-resource ',name ,resource))))
#+allegro-v4.1
(add-initialization "lep-init for with"
'(lep::eval-in-emacs "(put 'with-resource 'fi:lisp-indent-hook '(like with-open-file))")
'(:lep))
(pushnew :cl-lib-resources *features*)
;;; *EOF*
| 23,401 | Common Lisp | .lisp | 1 | 23,400 | 23,401 | 0.60335 | Bradford-Miller/CL-LIB | 1 | 0 | 1 | LGPL-3.0 | 9/19/2024, 11:28:28 AM (Europe/Amsterdam) | acf2f639eda522ac6dbd7fb5835cee9f7c073a4d855ebb36d72b8536e777ddae | 25,880 | [
-1
] |
25,881 | queues.lisp | Bradford-Miller_CL-LIB/packages/queues.lisp | ;;; -*- Mode: LISP; Syntax: Ansi-common-lisp; Package: CL-LIB; Base: 10 -*-
(in-package CL-LIB)
(cl-lib:version-reporter "CL-LIB-Queues" 5 0 ";; Time-stamp: <2012-01-05 17:47:01 millerb>"
"CVS: $Id: queues.lisp,v 1.2 2012/01/05 22:47:56 millerb Exp $
restructured version")
;;; This is a copy of the implementation for queues from Waters and
;;; Norvig's "Implementating Queues in Lisp" reprinted in TR 91-04
;;; Mitsubishi Electric Research Laboratories. "Some Useful Lisp
;;; Algorithms: Part 1"
;; Waters and Norvig present 3 final implementations, two based on
;; lists, and one on vectors. The trade-off is (in space time for the
;; following operations)
;; Figure 16 Figure 17 Figure 19
;; operation s t s t s t
;;
;; empty-queue-p 2 2 3 3 3 3
;;
;; queue-front 2 2 3 3 3 3
;;
;; dequeue 7 6 4 4 5 5
;;
;; enqueue 4 4 4 4 8 7
;;
;; Because we feel for most of our own code the enqueues and dequeues
;; are roughly balanced, but are more important than checking the
;; front or for an empty queue, the following code is from figure
;; 17. While not all compilers will support the inline declaration, we
;; have so declared it "just in case".
(declaim (inline make-queue queue-elements empty-queue-p
queue-front dequeue enqueue))
(defun make-queue ()
"Creates and returns a new empty queue"
(let ((q (list nil)))
(cons q q)))
(defun queue-elements (q)
"Returns a list of the elements in queue with the oldest element first.
The list returned may share structure with queue and therefore may be altered
by subsequent calls on enqueue and/or dequeue"
(cdar q))
(defun empty-queue-p (q)
"Returns t if queue does not contain any elements and nil otherwise"
(null (cdar q)))
(defun queue-front (q)
"Returns the oldest element in queue (i.e., the element that has
been in the queue the longest). When queue is empty, the results are
undefined"
(cadar q))
(defun dequeue (q)
"Queue is altered (by side effect) by removing the oldest element in
queue. THe removed element is returned. When queue is empty, the
results are undefined."
(car (setf (car q) (cdar q))))
;; this function contributed by [email protected]
(defun safe-dequeue (q)
"Dequeue that makes sure there is a non-empty queue, returning NIL
if queue is empty. (dequeue on empty queue will screw the data
structure!)"
(unless (empty-queue-p q)
(dequeue q)))
(defun enqueue (q item)
"Queue is altered (by side-effect) by adding the element item into
queue. The return value (if any) is undefined."
(setf (cdr q)
(setf (cddr q) (list item))))
#||
(setq q (make-queue)) -> (#1=(nil) . #1)
(progn (enqueue q 'a) (enqueue q 'b) (enqueue q 'c) q)
-> ((nil a b . #1=(c)) . #1#)
||#
(pushnew :cl-lib-queues *features*)
| 3,013 | Common Lisp | .lisp | 1 | 3,012 | 3,013 | 0.63392 | Bradford-Miller/CL-LIB | 1 | 0 | 1 | LGPL-3.0 | 9/19/2024, 11:28:28 AM (Europe/Amsterdam) | d0b0ca2bf805b0dffdf7f430306c5e05fad1883f2ff2d771bc6c65fa09671efb | 25,881 | [
-1
] |
25,882 | chart.lisp | Bradford-Miller_CL-LIB/packages/chart.lisp | ;; $Id: chart.lisp,v 1.2 2008/05/03 17:42:02 gorbag Exp $
;; Author Bradford W. Miller ([email protected])
(cl-lib:version-reporter "CL-LIB-Chart" 5 7 ";; Time-stamp: <2008-05-03 13:13:44 gorbag>"
"CVS: $Id: chart.lisp,v 1.2 2008/05/03 17:42:02 gorbag Exp $
;; documentation")
;;;
;;; Copyright (C) 1994, 1993, 1992 by Bradford W. Miller, [email protected]
;;; Unlimited use is granted to the end user, other rights to all users
;;; are as granted by the GNU LIBRARY GENERAL PUBLIC LICENCE
;;; version 2 which is incorporated here by reference.
;;; This program is free software; you can redistribute it and/or modify
;;; it under the terms of the GNU Library General Public License as published by
;;; the Free Software Foundation; version 2.
;;; 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 Library General Public License for more details.
;;; You should have received a copy of the GNU Library General Public License
;;; along with this program; if not, write to the Free Software
;;; Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
;;;
(defpackage chart
(:use common-lisp cl-lib)
(:export #:generic-chart #:generic-chart-p
#:generic-chart-entry #:generic-chart-entry-p
#:chart-entries-starting-at-index #:chart-entries-ending-at-index
#:chart-entry-indices #:chart-entry-label #:chart-entry-parents #:chart-last-index
#:chart-entries-next #:chart-entries-prior #:add-chart-entry
#:annotate-chart-entry #:chart-entry-annotation
#:chart-entry-content)
(:documentation "Chart abstraction, as used in chart parsers.
Charts can be viewed as lego blocks:
----------------------------------------
| S |
+--------------------------------------+
| NP | VP |
+------------------+-------------------+
| DET | N | V | ADVB |
+---------+--------+---------+---------+
| the | boy | ran | quickly | input
----------------------------------------
0 1 2 3 4 index
In the above example, we have used it as a chart parser might, showing that the labels for each chart consituent
constitutes a labelling of those sentence parts that are covered by the block.
Charts have the following functionality:
Every chart constituent (lego block) has a index for its start and end position.
we can ask for blocks that end at the point we start, or begin at the point we end.
Blocks can relable any other blocks they cover in the chart.
No block is inherently better than another, although typically we use charts to find covers of the input.
the input being a list of tokens (when used as a parser).
In this generalization of charts, we do not distinguish the input except that it will not be marked as a
relabelling of something. That is, it's possible to have your input cover more than one index if you want to.
Because we are creating an abstraction of charts here (although a simple implementation is also provided for testing),
we do not specify even the data structure(s) for charts, applications are free to optimize these for how they will use
charts. Note that the choice of data structure implementation, and supporting methods for the generic functions
defined below will determine the actual performace of your chart."))
(in-package chart)
;; Chart abstraction, as used in chart parsers.
;; This is used by pat-match-chart (the pattern match function), currently residing in the lymphocyte directory.
;; Charts can be viewed as lego blocks:
;; ----------------------------------------
;; | S |
;; +--------------------------------------+
;; | NP | VP |
;; +------------------+-------------------+
;; | DET | N | V | ADVB |
;; +---------+--------+---------+---------+
;; | the | boy | ran | quickly | input
;; ----------------------------------------
;;
;; 0 1 2 3 4 index
;; In the above example, we have used it as a chart parser might, showing that the labels for each chart consituent
;; constitutes a labelling of those sentence parts that are covered by the block.
;;
;; Charts have the following functionality:
;; Every chart constituent (lego block) has a index for its start and end position.
;; we can ask for blocks that end at the point we start, or begin at the point we end.
;;
;; Blocks can relable any other blocks they cover in the chart.
;;
;; No block is inherently better than another, although typically we use charts to find covers of the input.
;; the input being a list of tokens (when used as a parser).
;; In this generalization of charts, we do not distinguish the input except that it will not be marked as a
;; relabelling of something. That is, it's possible to have your input cover more than one index if you want to.
;; Because we are creating an abstraction of charts here (although a simple implementation is also provided for testing),
;; we do not specify even the data structure(s) for charts, applications are free to optimize these for how they will use
;; charts. Note that the choice of data structure implementation, and supporting methods for the generic functions
;; defined below will determine the actual performace of your chart.
;; A chart is a data object. Because we are not creating a particular chart here, our object will necessarily be
;; fairly sparse:
(defclass-x generic-chart ()
()
(:documentation "A chart is a way to collect data similar to an array, but entries can cover more than one
index. Typically, access is from (0,1) rather than (0), i.e. the indexes are vertices, and the data are segments between
vertices in the graph."))
(defclass-x generic-chart-entry ()
()
(:documentation "A chart entry is a constituent of a chart."))
(defgeneric chart-entries-starting-at-index (chart index)
(:documentation "Return the set of chart entries that start at the index in the chart"))
(defgeneric chart-entries-ending-at-index (chart index)
(:documentation "Return the set of chart entries that end at the index in the chart"))
(defgeneric chart-entry-indices (chart-entry)
(:documentation "Return a list of two values, (S E) indicating the start and end index covered by the chart-entry in the chart"))
(defgeneric chart-entry-label (chart-entry)
(:documentation "Return the label or name of the chart entry, e.g. \"NP\"."))
(defgeneric chart-entry-content (chart-entry)
(:documentation "Return the content of the chart entry (what it is we match against). This might just be the label."))
(defgeneric chart-entry-parents (chart-entry)
(:documentation "When a chart entry is derived from others, this function returns the entries that it was derived from, useful, e.g., in chart parsers to know which det and n a np entry covers, etc. Inputs will return NIL"))
(defgeneric chart-last-index (chart)
(:documentation "Return the highest index in the chart, i.e. the maximum index covered by some chart-entry"))
(defgeneric chart-entries-next (chart chart-entry)
(:documentation "Return the chart entries that start at the end index of the passed chart entry"))
(defgeneric chart-entries-prior (chart chart-entry)
(:documentation "Return the chart entries that end at the start index of the passed chart entry"))
(defgeneric add-chart-entry (chart label start end &optional content parents &key)
(:documentation "Creates a chart entry spanning the start and end index, with given label, and adds it to the chart. Note that other keywords are allowed, so you can put more information on your chart entry (and pass them to add-chart-entry). Returns the new chart-entry"))
(defgeneric annotate-chart-entry (chart chart-entry annotation-label annotation)
(:documentation "Effectively, annotation-label is a property-name, and annotation is the property."))
(defgeneric chart-entry-annotation (chart chart-entry annotation-label)
(:documentation "Effectively, annotation-label is a property-name, we return the property."))
(eval-when (load eval compile)
(defsetf chart-entry-annotation annotate-chart-entry))
;; here's some generic methods on the above. These won't be particularly efficient, but it allows one to define
;; fewer custom methods for their implementation, and get going. Later you can define all the methods for efficiency.
(defmethod chart-entries-next ((chart generic-chart) (chart-entry generic-chart-entry))
"Dumb but simple"
(chart-entries-starting-at-index chart (second (chart-entry-indices chart-entry))))
(defmethod chart-entries-prior ((chart generic-chart) (chart-entry generic-chart-entry))
"Dumb but simple"
(chart-entries-ending-at-index chart (first (chart-entry-indices chart-entry))))
(defmethod print-object ((o generic-chart-entry) stream)
(print-unreadable-object (o stream :type t :identity t)
(format stream "~A <~D,~D>" (chart-entry-label o) (first (chart-entry-indices o)) (second (chart-entry-indices o)))))
;; here's an implementation of a very simple chart that obeys the above protocols. It has some limitations:
(defclass-x simple-chart (generic-chart)
((chart-entries :type list :initform nil :accessor chart-entries)))
(defclass-x simple-chart-entry (generic-chart-entry)
((chart-entry-label :type symbol :initarg :chart-entry-label :accessor chart-entry-label) ; see defgeneric
(chart-entry-content :type t :initarg :chart-entry-content :accessor chart-entry-content) ; see defgeneric
(chart-entry-indices :type list :initarg :chart-entry-indices :accessor chart-entry-indices) ; see defgeneric
(chart-entry-parents :initform nil :initarg :chart-entry-parents :accessor chart-entry-parents) ; see defgeneric
(chart-entry-plist :initform nil :type alist :accessor chart-entry-plist :initarg :chart-entry-plist
:documentation "All chart entries must support a property list for portably adding annotations in code that deals with generic charts. Individual overrides with more efficient annotations are possible. See annotate-chart-entry.")))
(defmethod add-chart-entry ((chart simple-chart) label start end &optional (content label) parents &key)
(cl-lib:progfoo (make-simple-chart-entry
:chart-entry-label label
:chart-entry-indices (list start end)
:chart-entry-parents parents
:chart-entry-content content)
(push foo (chart-entries chart))))
(defmethod chart-entries-starting-at-index ((chart simple-chart) index)
"Dumb but simple"
(remove-if-not #'(lambda (entry) (eql index (first (chart-entry-indices entry)))) (chart-entries chart)))
(defmethod chart-entries-ending-at-index ((chart simple-chart) index)
"Dumb but simple"
(remove-if-not #'(lambda (entry) (eql index (second (chart-entry-indices entry)))) (chart-entries chart)))
(defmethod chart-last-index ((chart simple-chart))
(let ((result 0))
(dolist (entry (chart-entries chart))
(let ((end-point (second (chart-entry-indices entry))))
(when (> end-point result)
(setq result end-point))))
result))
(defmethod annotate-chart-entry (chart (chart-entry simple-chart-entry) annotation-label annotation)
(declare (ignore chart))
(update-alist annotation-label annotation (chart-entry-plist chart-entry))
annotation)
(defmethod chart-entry-annotation (chart (chart-entry simple-chart-entry) annotation-label)
(declare (ignore chart))
(cdr (assoc annotation-label (chart-entry-plist chart-entry))))
(pushnew :cl-lib-chart *features*)
| 11,824 | Common Lisp | .lisp | 1 | 11,823 | 11,824 | 0.690714 | Bradford-Miller/CL-LIB | 1 | 0 | 1 | LGPL-3.0 | 9/19/2024, 11:28:28 AM (Europe/Amsterdam) | 06a140ddbc2b69ff163fb0b6e44cdba82286c8efa4c6bc2bc59e64c29e2068ab | 25,882 | [
-1
] |
25,883 | nregex.lisp | Bradford-Miller_CL-LIB/packages/nregex.lisp | (in-package cl-lib) ; bwm
(cl-lib:version-reporter "CL-LIB-NRegex" 5 16 ";; Time-stamp: <2019-03-02 11:40:34 Bradford Miller(on Aragorn.local)>"
"fix toplevel") ; bwm
;; minor changes by BWM, no copyright on these changes asserted.
;; 5.16 3/ 2/19 make clear that thes top lines were added by me (not part of LEF's original code)
;; 5.16 2/23/19 fixup toplevel
;;; ORIGINAL CODE STARTS HERE:
;;;
;;; This code was written by:
;;;
;;; Lawrence E. Freil <[email protected]>
;;; National Science Center Foundation
;;; Augusta, Georgia 30909
;;;
;;; If you modify this code, please comment your modifications
;;; clearly and inform the author of any improvements so they
;;; can be incorporated in future releases.
;;;
;;; nregex.lisp - My 4/8/92 attempt at a Lisp based regular expression
;;; parser.
;;;
;;; This regular expression parser operates by taking a
;;; regular expression and breaking it down into a list
;;; consisting of lisp expressions and flags. The list
;;; of lisp expressions is then taken in turned into a
;;; lambda expression that can be later applied to a
;;; string argument for parsing.
;;;
;;; First we create a copy of macros to help debug the beast
;; update to ANSI standard 2/23/19 BWM
(eval-when (:compile-toplevel :load-toplevel :execute)
(defparameter *regex-debug* nil)) ; Set to nil for no debugging code
(defmacro info (message &rest args)
(if *regex-debug*
`(format *standard-output* ,message ,@args)))
;;;
;;; Declare the global variables for storing the paren index list.
;;;
(defvar *regex-groups* (make-array 10))
(defvar *regex-groupings* 0)
;;;
;;; Declare a simple interface for testing. You probably wouldn't want
;;; to use this interface unless you were just calling this once.
;;;
(defun regex (expression string)
"Usage: (regex <expression> <string)
This function will call regex-compile on the expression and then apply
the string to the returned lambda list."
(let ((findit (cond ((stringp expression)
(regex-compile expression))
((listp expression)
expression)))
(result nil))
;; patch by miller 6/18/93 to compile the lambda list
(setq findit (compile nil findit))
(if (not (funcall findit string))
(return-from regex nil))
(if (= *regex-groupings* 0)
(return-from regex t))
(dotimes (i *regex-groupings*)
(push (funcall 'subseq
string
(car (aref *regex-groups* i))
(cadr (aref *regex-groups* i)))
result))
(reverse result)))
;;;
;;; Declare some simple macros to make the code more readable.
;;;
(defvar *regex-special-chars* "?*+.()[]\\${}")
(defmacro add-exp (list)
"Add an item to the end of expression"
`(setf expression (append expression ,list)))
;;;
;;; Now for the main regex compiler routine.
;;;
(defun regex-compile (source &key (anchored nil))
"Usage: (regex-compile <expression> [ :anchored (t/nil) ])
This function take a regular expression (supplied as source) and
compiles this into a lambda list that a string argument can then
be applied to. It is also possible to compile this lambda list
for better performance or to save it as a named function for later
use"
(info "Now entering regex-compile with \"~A\"~%" source)
;;
;; This routine works in two parts.
;; The first pass take the regular expression and produces a list of
;; operators and lisp expressions for the entire regular expression.
;; The second pass takes this list and produces the lambda expression.
(let ((expression '()) ; holder for expressions
(group 1) ; Current group index
(group-stack nil) ; Stack of current group endings
(result nil) ; holder for built expression.
(fast-first nil)) ; holder for quick unanchored scan
;;
;; If the expression was an empty string then it alway
;; matches (so lets leave early)
;;
(if (= (length source) 0)
(return-from regex-compile
'(lambda (&rest args)
(declare (ignore args))
t)))
;;
;; If the first character is a caret then set the anchored
;; flags and remove if from the expression string.
;;
(cond ((eql (char source 0) #\^)
(setf source (subseq source 1))
(setf anchored t)))
;;
;; If the first sequence is .* then also set the anchored flags.
;; (This is purely for optimization, it will work without this).
;;
(if (>= (length source) 2)
(if (string= source ".*" :start1 0 :end1 2)
(setf anchored t)))
;;
;; Also, If this is not an anchored search and the first character is
;; a literal, then do a quick scan to see if it is even in the string.
;; If not then we can issue a quick nil,
;; otherwise we can start the search at the matching character to skip
;; the checks of the non-matching characters anyway.
;;
;; If I really wanted to speed up this section of code it would be
;; easy to recognize the case of a fairly long multi-character literal
;; and generate a Boyer-Moore search for the entire literal.
;;
;; I generate the code to do a loop because on CMU Lisp this is about
;; twice as fast a calling position.
;;
(if (and (not anchored)
(not (position (char source 0) *regex-special-chars*))
(not (and (> (length source) 1)
(position (char source 1) *regex-special-chars*))))
(setf fast-first `((if (not (dotimes (i length nil)
(if (eql (char string i)
,(char source 0))
(return (setf start i)))))
(return-from final-return nil)))))
;;
;; Generate the very first expression to save the starting index
;; so that group 0 will be the entire string matched always
;;
(add-exp '((setf (aref *regex-groups* 0)
(list index nil))))
;;
;; Loop over each character in the regular expression building the
;; expression list as we go.
;;
(do ((eindex 0 (1+ eindex)))
((= eindex (length source)))
(let ((current (char source eindex)))
(info "Now processing character ~A index = ~A~%" current eindex)
(case current
((#\.)
;;
;; Generate code for a single wild character
;;
(add-exp '((if (>= index length)
(return-from compare nil)
(incf index)))))
((#\$)
;;
;; If this is the last character of the expression then
;; anchor the end of the expression, otherwise let it slide
;; as a standard character (even though it should be quoted).
;;
(if (= eindex (1- (length source)))
(add-exp '((if (not (= index length))
(return-from compare nil))))
(add-exp '((if (not (and (< index length)
(eql (char string index) #\$)))
(return-from compare nil)
(incf index))))))
((#\*)
(add-exp '(ASTRISK)))
((#\+)
(add-exp '(PLUS)))
((#\?)
(add-exp '(QUESTION)))
((#\()
;;
;; Start a grouping.
;;
(incf group)
(push group group-stack)
(add-exp `((setf (aref *regex-groups* ,(1- group))
(list index nil))))
(add-exp `(,group)))
((#\))
;;
;; End a grouping
;;
(let ((group (pop group-stack)))
(add-exp `((setf (cadr (aref *regex-groups* ,(1- group)))
index)))
(add-exp `(,(- group)))))
((#\[)
;;
;; Start of a range operation.
;; Generate a bit-vector that has one bit per possible character
;; and then on each character or range, set the possible bits.
;;
;; If the first character is carat then invert the set.
(let* ((invert (eql (char source (1+ eindex)) #\^))
(bitstring (make-array 256 :element-type 'bit
:initial-element
(if invert 1 0)))
(set-char (if invert 0 1)))
(if invert (incf eindex))
(do ((x (1+ eindex) (1+ x)))
((eql (char source x) #\]) (setf eindex x))
(info "Building range with character ~A~%" (char source x))
(cond ((and (eql (char source (1+ x)) #\-)
(not (eql (char source (+ x 2)) #\])))
(if (>= (char-code (char source x))
(char-code (char source (+ 2 x))))
(error "Invalid range \"~A-~A\". Ranges must be in acending order"
(char source x) (char source (+ 2 x))))
(do ((j (char-code (char source x)) (1+ j)))
((> j (char-code (char source (+ 2 x))))
(incf x 2))
(info "Setting bit for char ~A code ~A~%" (code-char j) j)
(setf (sbit bitstring j) set-char)))
(t
(cond ((not (eql (char source x) #\]))
(let ((char (char source x)))
;;
;; If the character is quoted then find out what
;; it should have been
;;
(if (eql (char source x) #\\ )
(let ((length))
(multiple-value-setq (char length)
(regex-quoted (subseq source x) invert))
(incf x length)))
(info "Setting bit for char ~A code ~A~%" char (char-code char))
(if (not (vectorp char))
(setf (sbit bitstring (char-code (char source x))) set-char)
(bit-ior bitstring char t))))))))
(add-exp `((let ((range ,bitstring))
(if (>= index length)
(return-from compare nil))
(if (= 1 (sbit range (char-code (char string index))))
(incf index)
(return-from compare nil)))))))
((#\\ )
;;
;; Intreprete the next character as a special, range, octal, group or
;; just the character itself.
;;
(let ((length)
(value))
(multiple-value-setq (value length)
(regex-quoted (subseq source (1+ eindex)) nil))
(cond ((listp value)
(add-exp value))
((characterp value)
(add-exp `((if (not (and (< index length)
(eql (char string index)
,value)))
(return-from compare nil)
(incf index)))))
((vectorp value)
(add-exp `((let ((range ,value))
(if (>= index length)
(return-from compare nil))
(if (= 1 (sbit range (char-code (char string index))))
(incf index)
(return-from compare nil)))))))
(incf eindex length)))
(t
;;
;; We have a literal character.
;; Scan to see how many we have and if it is more than one
;; generate a string= verses as single eql.
;;
(let* ((lit "")
(term (dotimes (litindex (- (length source) eindex) nil)
(let ((litchar (char source (+ eindex litindex))))
(if (position litchar *regex-special-chars*)
(return litchar)
(progn
(info "Now adding ~A index ~A to lit~%" litchar
litindex)
(setf lit (concatenate 'string lit
(string litchar)))))))))
(if (= (length lit) 1)
(add-exp `((if (not (and (< index length)
(eql (char string index) ,current)))
(return-from compare nil)
(incf index))))
;;
;; If we have a multi-character literal then we must
;; check to see if the next character (if there is one)
;; is an astrisk or a plus. If so then we must not use this
;; character in the big literal.
(progn
(if (or (eql term #\*) (eql term #\+))
(setf lit (subseq lit 0 (1- (length lit)))))
(add-exp `((if (< length (+ index ,(length lit)))
(return-from compare nil))
(if (not (string= string ,lit :start1 index
:end1 (+ index ,(length lit))))
(return-from compare nil)
(incf index ,(length lit)))))))
(incf eindex (1- (length lit))))))))
;;
;; Plug end of list to return t. If we made it this far then
;; We have matched!
(add-exp '((setf (cadr (aref *regex-groups* 0))
index)))
(add-exp '((return-from final-return t)))
;;
;;; (print expression)
;;
;; Now take the expression list and turn it into a lambda expression
;; replacing the special flags with lisp code.
;; For example: A BEGIN needs to be replace by an expression that
;; saves the current index, then evaluates everything till it gets to
;; the END then save the new index if it didn't fail.
;; On an ASTRISK I need to take the previous expression and wrap
;; it in a do that will evaluate the expression till an error
;; occurs and then another do that encompases the remainder of the
;; regular expression and iterates decrementing the index by one
;; of the matched expression sizes and then returns nil. After
;; the last expression insert a form that does a return t so that
;; if the entire nested sub-expression succeeds then the loop
;; is broken manually.
;;
(setf result (copy-tree nil))
;;
;; Reversing the current expression makes building up the
;; lambda list easier due to the nexting of expressions when
;; and astrisk has been encountered.
(setf expression (reverse expression))
(do ((elt 0 (1+ elt)))
((>= elt (length expression)))
(let ((piece (nth elt expression)))
;;
;; Now check for PLUS, if so then ditto the expression and then let the
;; ASTRISK below handle the rest.
;;
(cond ((eql piece 'PLUS)
(cond ((listp (nth (1+ elt) expression))
(setf result (append (list (nth (1+ elt) expression))
result)))
;;
;; duplicate the entire group
;; NOTE: This hasn't been implemented yet!!
(t
(format *standard-output* "GROUP repeat hasn't been implemented yet~%")))))
(cond ((listp piece) ;Just append the list
(setf result (append (list piece) result)))
((eql piece 'QUESTION) ; Wrap it in a block that won't fail
(cond ((listp (nth (1+ elt) expression))
(setf result
(append `((progn (block compare
,(nth (1+ elt)
expression))
t))
result))
(incf elt))
;;
;; This is a QUESTION on an entire group which
;; hasn't been implemented yet!!!
;;
(t
(format *standard-output* "Optional groups not implemented yet~%"))))
((or (eql piece 'ASTRISK) ; Do the wild thing!
(eql piece 'PLUS))
(cond ((listp (nth (1+ elt) expression))
;;
;; This is a single character wild card so
;; do the simple form.
;;
(setf result
`((let ((oindex index))
(block compare
(do ()
(nil)
,(nth (1+ elt) expression)))
(do ((start index (1- start)))
((< start oindex) nil)
(let ((index start))
(block compare
,@result))))))
(incf elt))
(t
;;
;; This is a subgroup repeated so I must build
;; the loop using several values.
;;
))
)
(t t)))) ; Just ignore everything else.
;;
;; Now wrap the result in a lambda list that can then be
;; invoked or compiled, however the user wishes.
;;
(if anchored
(setf result
`(lambda (string &key (start 0) (end (length string)))
(setf *regex-groupings* ,group)
(block final-return
(block compare
(let ((index start)
(length end))
,@result)))))
(setf result
`(lambda (string &key (start 0) (end (length string)))
(setf *regex-groupings* ,group)
(block final-return
(let ((length end))
,@fast-first
(do ((marker start (1+ marker)))
((> marker end) nil)
(let ((index marker))
(if (block compare
,@result)
(return t)))))))))))
;;;
;;; Define a function that will take a quoted character and return
;;; what the real character should be plus how much of the source
;;; string was used. If the result is a set of characters, return an
;;; array of bits indicating which characters should be set. If the
;;; expression is one of the sub-group matches return a
;;; list-expression that will provide the match.
;;;
(defun regex-quoted (char-string &optional (invert nil))
"Usage: (regex-quoted <char-string> &optional invert)
Returns either the quoted character or a simple bit vector of bits set for
the matching values"
(let ((first (char char-string 0))
(result (char char-string 0))
(used-length 1))
(cond ((eql first #\n)
(setf result #\NewLine))
((eql first #\c)
(setf result #\Return))
((eql first #\t)
(setf result #\Tab))
((eql first #\d)
(setf result #*0000000000000000000000000000000000000000000000001111111111000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000))
((eql first #\D)
(setf result #*1111111111111111111111111111111111111111111111110000000000111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111))
((eql first #\w)
(setf result #*0000000000000000000000000000000000000000000000001111111111000000011111111111111111111111111000010111111111111111111111111110000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000))
((eql first #\W)
(setf result #*1111111111111111111111111111111111111111111111110000000000111111100000000000000000000000000111101000000000000000000000000001111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111))
((eql first #\b)
(setf result #*0000000001000000000000000000000011000000000010100000000000100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000))
((eql first #\B)
(setf result #*1111111110111111111111111111111100111111111101011111111111011111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111))
((eql first #\s)
(setf result #*0000000001100000000000000000000010000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000))
((eql first #\S)
(setf result #*1111111110011111111111111111111101111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111))
((and (>= (char-code first) (char-code #\0))
(<= (char-code first) (char-code #\9)))
(if (and (> (length char-string) 2)
(and (>= (char-code (char char-string 1)) (char-code #\0))
(<= (char-code (char char-string 1)) (char-code #\9))
(>= (char-code (char char-string 2)) (char-code #\0))
(<= (char-code (char char-string 2)) (char-code #\9))))
;;
;; It is a single character specified in octal
;;
(progn
(setf result (do ((x 0 (1+ x))
(return 0))
((= x 2) return)
(setf return (+ (* return 8)
(- (char-code (char char-string x))
(char-code #\0))))))
(setf used-length 3))
;;
;; We have a group number replacement.
;;
(let ((group (- (char-code first) (char-code #\0))))
(setf result `((let ((nstring (subseq string (car (aref *regex-groups* ,group))
(cadr (aref *regex-groups* ,group)))))
(if (< length (+ index (length nstring)))
(return-from compare nil))
(if (not (string= string nstring
:start1 index
:end1 (+ index (length nstring))))
(return-from compare nil)
(incf index (length nstring)))))))))
(t
(setf result first)))
(if (and (vectorp result) invert)
(bit-xor result #*1111111110011111111111111111111101111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111 t))
(values result used-length)))
| 20,251 | Common Lisp | .lisp | 1 | 20,249 | 20,251 | 0.631031 | Bradford-Miller/CL-LIB | 1 | 0 | 1 | LGPL-3.0 | 9/19/2024, 11:28:28 AM (Europe/Amsterdam) | d4765dbfc012796d43ba17358f54b3dbe55852a59fd83f70b8bbdc943a34dc5f | 25,883 | [
-1
] |
25,884 | initializations.lisp | Bradford-Miller_CL-LIB/packages/initializations.lisp | (in-package cl-lib-initializations)
(defparameter *cl-lib-initializations-version*
'(cl-lib:version-reporter "CL-LIB-Initializations" 5 16 ";; Time-stamp: <2019-02-18 13:14:31 Bradford Miller(on Aragorn.local)>"
"5am testing"))
;; 5.16. 2/16/19 5am testing (see file initializations-tests.lisp)
;; 5.15 1/27/19 Add *debug-initializations*
;; 5.11 5/16/11 Added support for 64-bit LispWorks
;; 5.1 5/18/07 default to silence when not interactive-lisp-p
;;; Copyright (C) 1991 by the Trustees of the University of Rochester.
;;; Portions Copyright (C) 2005, 2011, 2019 by Bradford W. Miller ([email protected])
;;; Right of use & redistribution is granted as per the terms of the
;;; GNU LIBRARY GENERAL PUBLIC LICENCE version 1 which is incorporated here by reference.
;;; 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 Library General Public License for more details.
;;; You should have received a copy of the Gnu Library General Public License
;;; along with this program; if not, write to the Free Software
;;; Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
;;; Written 3/91 by Bradford W. Miller [email protected]
;;; 4/8/94 ported to MCL 2.0.1 by miller
;;; 1/11/96 updated for Allegro 4.3beta by miller
;;; 11/29/01 added work-around for Lispworks braindamage with #|| ||# pairs spanning lines
;;; 6/ 3/02 fixed #+ stuff wrt LispWorks not liking two in a row.
;;; added gc links for LispWorks, still investigating links for :before-cold, etc.
;;; 6/ 7/02 Added links to LispWorks Actions Lists (which is pretty much their
;;; version of initializations).
;; 6/24/05 Updated for new CL-LIB organization (major release 5)
;;; Please send any bug reports or improvements to me at [email protected] or
;;; [email protected]
;;; I will be glad to respond to bug reports or feature requests.
;;;; Motivation:
;;; Since RHET and other projects have been using the initializations features of
;;; the explorer and symbolics, the following was inspired to allow a simple
;;; port to non-lispm lisps.
;;; Like the lisp machines, a number of lists are predefined, one to be run whenever
;;; the world is first booted (:WARM), one to force a single eval (:ONCE), one
;;; before any gc (:GC), after any gc (:AFTER-GC), before a non-checkpointed disk
;;; save (:BEFORE-COLD), and after a non-checkpointed world is first booted (:COLD).
;;; Lispms had a initialization-keywords variable for
;;; associating new lists with keywords, mine is called *initialization-keywords*.
;;; one can also define when an initializtion is run, either :normal, which only
;;; places the form on the list (the default, unless :once is specified), :now
;;; which is to eval now and add it to the list, :first, which causes immediate
;;; evaluation if it hasn't been evaluated before (default for :once), and :redo
;;; which will not eval the form now, but will cause the initialization to
;;; be run the next time the list is processed, even if it has already been
;;; run.
;;; initializations are ordered as first added, first run.
;;; first set up the default lists
(defvar *warm-initialization-list* nil
"Initializations run just after booting any world")
(defvar *cold-initialization-list* nil
"Initializations run just after booting a non-checkpointed world")
(defvar *before-cold-initialization-list* nil
"Initializations run just before saving a non-checkpointed world")
(defvar *once-initialization-list* nil
"Initializations to be run only once")
(defvar *gc-initialization-list* nil
"Initializations to be run before a gc")
(defvar *after-gc-initialization-list* nil
"Initializations to be run after a gc")
(defvar *quit-initialization-list* nil
"Initializations to be run just before image quits")
(defvar *debug-initializations* nil
"set non-nil to print some debug info")
#+allegro
(defvar *lep-initialization-list* nil
"Initializations to be run after lep has been established")
(defparameter *initialization-keywords*
(copy-list '((:warm *warm-initialization-list*)
(:cold *cold-initialization-list*)
(:before-cold *before-cold-initialization-list*)
(:once *once-initialization-list* :first)
#-sbcl ;; sbcl doesn't support before-gc hooks any more, so don't list it
(:gc *gc-initialization-list*)
#+allegro (:lep *lep-initialization-list*)
(:after-gc *after-gc-initialization-list*)
(:quit *quit-initialization-list*)))
"Alist of initialization-list keywords and the list itself. Third element,
if present, is the default run time, :normal if absent. This can be overridden
by the add-initialization function.")
(defstruct initialization
(name "" :type string)
(form nil :type list)
(flag nil)
(run nil :type list))
;;; TODO: make more robust by checking the input.
(defun reset-initializations (initialization-list-name)
"Sets the FLAG of each initialization on the passed list to NIL so it
will be (re)run the next time initializations is called on it."
(declare (type symbol initialization-list-name))
(dolist (init (symbol-value initialization-list-name))
(setf (initialization-flag init) nil)))
(defun delete-initialization (name &optional keywords initialization-list-name)
"Delete the initialization with name from either the list specified with the
keywords, or passed as initialization-list-name."
(declare (type string name)
(type list keywords)
(symbol initialization-list-name))
(unless initialization-list-name
(setq initialization-list-name (cadr (assoc (car keywords)
*initialization-keywords*))))
(set initialization-list-name (delete name (symbol-value initialization-list-name)
:test #'equal
:key #'(lambda (x) (initialization-name x)))))
(defun initializations (initialization-list-name &optional redo (flag t))
"Run the initializations on the passed list. If redo is non-nil, then the
current value of the flag on the initialization is ignored, and the
initialization is always run. Otherwise an initialization is only run if
the associated flag is NIL. Flag is the value stored into the initialization's
flag when it is run."
(declare (type symbol initialization-list-name))
(dolist (init (symbol-value initialization-list-name))
(when (or redo (not (initialization-flag init)))
(eval (initialization-form init))
(setf (initialization-flag init) flag))))
(defun add-initialization (name form &optional keywords initialization-list-name)
"The initialization form is given name name and added to the initialization list
specified either by the keywords or passed directly. The keywords can also be used
to change the default time to evaluate the initialization."
(declare (type string name)
(type list form keywords)
(type symbol initialization-list-name))
(let ((type '(:normal))
(list-name initialization-list-name)
list-key)
(cond
(list-name
(if keywords
(setq type keywords)))
(t
(setq list-name (cdr (some #'(lambda (x)
(setq list-key x) ; remember it
(assoc x *initialization-keywords*))
keywords)))
(if (cdr list-name)
(setq type (cdr list-name)))
(setq list-name (car list-name))
;; now check if keywords override.
(setq keywords (remove list-key keywords :test #'eq))
(if keywords
(setq type keywords))))
(assert list-name (keywords initialization-list-name) "No initialization list name given")
;; OK, now we can process the entry.... first, is it already there?
(let ((entry (if (boundp list-name)
(find name (symbol-value list-name)
:test #'equal
:key #'(lambda (x) (initialization-name x))))))
(cond
((null entry)
(set list-name
(nconc (if (boundp list-name)
(symbol-value list-name))
(list (setq entry (make-initialization
:name name
:form form
:run type))))))
(t
;; update the entry
(if *debug-initializations* (format *error-output* "~&Debug-Initializations: Updating ~S with ~S" entry form))
(setf (initialization-form entry) form)
(setf (initialization-run entry) type)))
(cond
((or (member :now type)
(and (member :first type)
(not (initialization-flag entry))))
(eval form)
(setf (initialization-flag entry) t)))
(cond
((member :redo type)
(setf (initialization-flag entry) nil))))))
;;; the rest of this stuff is just to make sure the various predefined lists are
;;; automatically processed at the appropriate time.
(defun reset-and-invoke-initializations (list-keyword)
(declare (type keyword list-keyword))
(let ((entry (assoc list-keyword *initialization-keywords*)))
(reset-initializations (cadr entry))
(initializations (cadr entry))))
;;; :once requires no processing. It's done only at add-initialization time.
;;;
;;; :gc / :after-gc surround invocations to gc
;; sbcl doesn't have an advice facility. Rather than invent our own (which won't work in the case of any inline codes),
;; we will leverage the defined hooks, listed here:
;;
;; for :warm & :cold
;; sb-ext:*init-hooks* - a list of function designators called in an
;; unspecified order after a saved core image starts up, after the
;; system itself has been initialized
;;
;; NB: since SBCL doesn't distinguish between warm and cold booting,
;; or allow us to do something different before initialization
;; finishes (we can only get control after it has initialized), we
;; just run :cold before we run :warm
;;
;; for :quit ...
;; sb-ext:*exit-hooks* - a list of function designators called in an
;; unspecified order when sbcl exits (however, it is omitted if
;; (sbcl-ext:exit :abort t) is used).
;;
;; for :before-cold...
;; sb-ext:*save-hooks* - ditto, called before creating a saved core image
;;
;; for :after-gc...
;; sb-ext:*after-gc-hooks* - called after gc, except if gc called
;; during thread exit. In a multithreaded image, may run in any
;; thread.
;;
;; NB: SBCL does not have any before-gc hooks (though CMUCL on which
;; SBCL is based did, so not sure what's up with that). At any rate,
;; until and unless we want to dive into the SBCL source to create a
;; robust advice facility (a poor man's version would just redefine
;; the fdefinitions of symbols and supress any warnings by generating
;; a wrapper around the original function, but that has issues with
;; inline directives, at least - I suspect the proper way to do this
;; would be to make sure even inline functions call a hook to look for
;; the existance of advice unless we've used a very high value for
;; optimize speed, which implies modifying the function compiler or at
;; least defun), we just won't support the :gc keyword on sbcl. Note
;; that sbcl does have extensions like weak pointers and finalization
;; meaning the most likely uses of such gc initializations would need
;; to be recoded to use those instead. (Browsing through some old sbcl
;; bug reports make me think they dropped before-gc because too many
;; users didn't grock that they shouldn't cons when gc had been
;; triggered! Talk about throwing out the baby with the bathwater...)
(defun execute-gc-inits ()
(reset-and-invoke-initializations :gc))
#+excl
(excl:advise excl:gc :before handle-gc-initializations nil
(execute-gc-inits))
#+ccl
(ccl:advise ccl:gc (execute-gc-inits) :when :before :name handle-gc-initializations)
#+(and LispWorks (not LispWorks-64bit))
(lispworks:defadvice (hcl:mark-and-sweep before-gc :before) (generation)
(progn generation (execute-gc-inits)))
#+LispWorks-64bit
(lispworks:defadvice (system:marking-gc before-gc :before) (generation &key &allow-other-keys)
(progn generation (execute-gc-inits)))
(defun execute-after-gc-inits ()
(reset-and-invoke-initializations :after-gc))
#+sbcl
(eval-when (:load-toplevel :execute)
(pushnew 'execute-after-gc-inits sb-ext:*after-gc-hooks*))
#+excl
(excl:advise excl:gc :after handle-after-gc-initializations nil
(execute-after-gc-inits))
#+ccl
(ccl:advise ccl:gc (execute-after-gc-inits) :when :after :name handle-after-gc-initializations)
#+(and LispWorks (not LispWorks-64bit))
(lispworks:defadvice (hcl:mark-and-sweep after-gc :after) (generation)
(progn generation
(execute-after-gc-inits)))
#+LispWorks-64bit
(lispworks:defadvice (system:marking-gc after-gc :after) (generation &key &allow-other-keys)
(progn generation (execute-after-gc-inits)))
#||
;; LispWorks has also implemented this callback in 64bit versions - but no before callback, so to be symmetric
;; we use the advice on marking-gc
(system:set-automatic-gc-callback nil #'(lambda (generation-number)
(declare (ignore generation-number))
(reset-and-invoke-initializations :after-gc)))
||#
;;; :before-cold happens when we disk save, unless we specify :checkpoint
;;; while :cold happens after the world comes back (unless we specify :checkpoint)
;;; and :warm happens in any case.
#+(and excl (not (version>= 4 3)))
(eval-when (:load-toplevel :execute)
(pushnew '(:eval initializations '*warm-initialization-list*) excl:*restart-actions* :test #'equalp))
(defun run-warm-inits () (initializations '*warm-initialization-list*))
#+(and excl (version>= 4 3))
(eval-when (:load-toplevel :execute)
(progn
(pushnew 'run-warm-inits excl:*restart-actions* :test #'equalp)))
#+ccl2
(eval-when (:load-toplevel :execute)
(pushnew '(lambda () (initializations '*warm-initialization-list*)) ccl:*lisp-startup-functions* :test #'equalp))
#+lispworks
(eval-when (:load-toplevel :execute)
(lw:define-action "When starting image"
"Run Warm Initializations"
'run-warm-inits
:after "System startup completed"))
#+(and excl (not (version>= 4 3)))
(eval-when (:load-toplevel :execute)
(pushnew '(:eval initializations '*cold-initialization-list*) excl:*restart-actions* :test #'equalp))
(defun run-cold-inits () (initializations '*cold-initialization-list*))
#+(and excl (version>= 4 3))
(eval-when (:load-toplevel :execute)
(progn
(pushnew 'run-cold-inits excl:*restart-actions* :test #'equalp)))
#+ccl2
(eval-when (:load-toplevel :execute)
(pushnew '(lambda () (initializations '*cold-initialization-list*)) ccl:*lisp-startup-functions* :test #'equalp))
#+Lispworks
(eval-when (:load-toplevel :execute)
(lw:define-action "When starting image"
"Run Cold Initializations"
'run-cold-inits
:before "System startup completed"))
#+excl
(excl:advise excl:dumplisp :before handle-initializations nil
(reset-initializations '*warm-initialization-list*)
(unless (extract-keyword :checkpoint excl:arglist)
(reset-and-invoke-initializations :before-cold)))
(defun run-cold-then-warm-inits ()
(run-cold-inits)
(run-warm-inits))
#+sbcl
(eval-when (:load-toplevel :execute)
(pushnew sb-ext:*init-hooks* 'run-cold-then-warm-inits))
(defun do-before-cold ()
(reset-initializations '*warm-initialization-list*)
(reset-and-invoke-initializations :before-cold))
#+ccl2
(eval-when (:load-toplevel :execute)
(pushnew '(do-before-cold) ccl:*save-exit-functions*))
#+lispworks
(eval-when (:load-toplevel :execute)
(lw:define-action "Delivery Actions"
"Before Cold Initializations"
'do-before-cold))
#+sbcl
(eval-when (:load-toplevel :execute)
(pushnew 'do-before-cold sb-ext:*save-hooks*))
(defun do-quit ()
(reset-and-invoke-initializations :quit))
#+excl
(format t "Don't know how to bind quit list for excl")
#+ccl2
(format t "Don't know how to bind quit list for ccl2")
#+lispworks
(eval-when (:load-toplevel :execute)
(lw:define-action "When quitting image"
"Quit Initializations"
'do-quit))
#+sbcl
(eval-when (:load-toplevel :execute)
(pushnew 'do-quit sb-ext:*exit-hooks*))
#+excl
(excl:advise excl:start-emacs-lisp-interface :after handle-initilizations nil
(mp:process-run-function "delayed LEP init"
#'(lambda () (sleep 8) (while-not (lep:lep-is-running) (sleep 8))
(reset-and-invoke-initializations :lep))))
(eval-when (:load-toplevel :execute)
(add-initialization "User Notification"
'(if (cl-lib-essentials:interactive-lisp-p)
(format *error-output* "~2&--> Running Before-Cold Initializations~2%"))
'(:before-cold))
(add-initialization "User Notification"
'(if (cl-lib-essentials:interactive-lisp-p)
(format *error-output* "~2&--> Running Cold Initializations~2%"))
'(:cold))
(add-initialization "User Notification"
'(if (cl-lib-essentials:interactive-lisp-p)
(format *error-output* "~2&--> Running Warm Initializations~2%"))
'(:warm))
#+excl
(add-initialization "User Notification"
'(if (cl-lib-essentials:interactive-lisp-p)
(format *error-output* "~2&--> Running after LEP Initializations~2%"))
'(:lep))
(add-initialization "User Notification"
'(if (cl-lib-essentials:interactive-lisp-p)
(format *error-output* "~2&--> Running Quit Initializations~2%"))
'(:quit))
(add-initialization "Reset Cold Initializations"
'(reset-initializations '*cold-initialization-list*)
'(:before-cold)))
;;;
;;; Here is a short example of the above (See also initializations-tests.lisp in this directory)
;;;
#+hell-freezes-over
(eval-when (:execute)
(add-initialization "test1" '(print "should print once") '(:once))
(add-initialization "test1" '(print "should print once") '(:once))
;; note the first immediately executed the print, and the second supressed it.
(defvar *new-init-list* nil)
(add-initialization "a hack" '(print "One hack") () '*new-init-list*)
;; didn't print yet
(initializations '*new-init-list*)
;; now it did
(initializations '*new-init-list*)
;; but not again until
(reset-initializations '*new-init-list*)
(initializations '*new-init-list*))
;;; Note in particular the :once list may be useful in init files, particularly
;;; where the result might be saved in a world and you don't want it redone
;;; e.g. in allegro checkpoint worlds.
;;;
;;; The other sorts of lists are particularly useful for housekeeping
(pushnew :cl-lib-initializations *features*)
| 19,455 | Common Lisp | .lisp | 391 | 43.639386 | 131 | 0.68358 | Bradford-Miller/CL-LIB | 1 | 0 | 1 | LGPL-3.0 | 9/19/2024, 11:28:28 AM (Europe/Amsterdam) | b50e7ed81f2651dcc4dd8738528ab9378145e8b5df92d3c958277b6d30901157 | 25,884 | [
-1
] |
25,885 | clos-facets.lisp | Bradford-Miller_CL-LIB/packages/clos-facets.lisp | (cl-lib:version-reporter "CL-LIB-CLOS-Facets" 5 17 ";; Time-stamp: <2019-10-27 16:39:13 Bradford Miller(on Aragorn.local)>"
"CVS: $Id: clos-facets.lisp,v 1.2 2008/05/03 17:42:02 gorbag Exp $
;; documentation")
;; 5.17 10/27/19 minor fixes to 5.16
;; 5.16 3/ 3/19 finish implementation of multiple values (to pass tests)
;; 0.3 5/18/07 parial implementation of multiple values
;; This portion of CL-LIB Copyright (C) 2003-2019 Bradford W. Miller
;;
;; This library is free software; you can redistribute it and/or modify it under the terms of the GNU
;; Lesser General Public License as published by the Free Software Foundation; either version 3.0 of
;; the License, or (at your option) any later version.
;; This library 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.
;; You should have received a copy of the GNU Lesser General Public License along with this library;
;; if not, see <http://www.gnu.org/licenses/>.
;; because a number of the following symbols likely collide with common-lisp definitions, you will probably want to copy
;; and paste the following into your defpackage
#||
(:shadowing-import-from #:clos-facets
#:defclass #:slot-makunbound #:slot-unbound #:slot-value #:slot-boundp #:unbound-slot
;; in some cases you may also need the following (e.g., you :use the clos class in LispWorks)
#:slot-makunbound-using-class #:slot-value-using-class #:slot-boundp-using-class
)
||#
;; alternatively you can explicitly reference this version using clos-facets:defclass for instance, for every relevant reference.
(in-package :clos-facets)
;; Our database to allow us to track what facets have been defined, etc.
;; For now, since we have relatively few facets, Alists should be sufficient (For something like a hash table to make sense
;; we need to expect on the order of 100 entries - I don't expect we'll have more than a couple dozen facets defined).
(defvar *facet-definition-alist* nil "Alist of (facet-name . definition entry) fields for all defined facets (see deffacet)")
(defstruct facet-definition
"Internal structure for defining a facet"
(super-facets nil :type list)
(option-value-pairs nil :type list) ; right now, only :all and :default are supported
;; list of the slots that this facet is valid for, if :all option is non-nil on option-value-pairs,
;; then all slots support this facet (useful for system-defined facets, like value-type)
(supported-slots nil :type list)
(comment "" :type string)
(facet-body nil :type list)) ; the guts of the frob
(define-condition clos-facets-error (error)
()
(:documentation "All clos-facets package related errors inherit from this condition"))
(define-condition clos-facets-incompatible (clos-facets-error)
()
(:documentation "Specialization of Clos-Facets-Error where there is
some incompatibility (constraint conflict) with some other
declaration. Generally this is due to some child class having a facet
declaration that is not a proper subtype of an ancester class."))
(define-condition clos-facets-program-error (clos-facets-error program-error)
()
(:documentation "Specialization of program-error for facets"))
(define-condition value-type-decl-incompatible (clos-facets-incompatible clos-facets-program-error)
()
(:documentation "the value-type declared on the slot is not
compatible with the value-type of the slot on a parent
class. Specifically, it must be the same or a proper subtype."))
(define-condition cardinality-bounds-incompatible (clos-facets-incompatible clos-facets-program-error)
()
(:documentation "The cardinality bounds are not a proper subinterval of some ancestor declaration."))
(define-condition clos-facets-cell-error (clos-facets-error cell-error)
((instance :initarg :instance :reader clos-facets-cell-error-instance)
(class :initarg :class :reader clos-facets-cell-error-class)
(facet :initarg :facet :reader clos-facets-cell-error-facet)
(operation :initarg :operation :reader clos-facets-cell-error-operation)
(new-value :initarg :new-value :reader clos-facets-cell-error-new-value))
(:documentation "Specialization of cell-error for faceted slots.
The type cell-error consists of error conditions that occur during a location access.
The name of the offending cell is initialized by the :name initialization argument to make-condition,
and is accessed by the function cell-error-name."))
(define-condition facet-missing-error (clos-facets-cell-error)
()
(:documentation "Signalled when a facet was expected"))
(define-condition cardinality-bounds-error (clos-facets-cell-error)
()
(:documentation "Either fewer or more values have been declared than the bounds allow"))
(define-condition cardinality-bounds-underrun (cardinality-bounds-error)
()
(:documentation "Too few values have been declared for the slot's cardinality"))
(define-condition cardinality-bounds-overrun (cardinality-bounds-error)
()
(:documentation "Too may values have been declared for the slot's cardinality"))
(define-condition value-type-error (clos-facets-cell-error)
()
(:documentation "an attempt to directly write a value to a cell that conflicts with the declared value-type."))
(define-condition no-multiple-slotvalues (clos-facets-cell-error)
((place :initarg :place :reader no-multiple-slotvalues-place :documentation "The place used on a slot that is single valued"))
(:documentation "An attempt was made to read or write a specific
slotvalue (using place on a supported function such as a slot
accessor), when the slot was declared or defaulted to be single
valued."))
(define-condition unbound-slot (clos-facets-cell-error common-lisp:unbound-slot)
((place :initarg :place :reader unbound-slot-place :documentation "The place (within a multiple-value slot) that is unbound"))
(:documentation "An attempt was made to read an unbound multiple value, generally using the place argument"))
(define-condition unbound-facet (clos-facets-cell-error)
()
(:documentation "An attempt was made to read a facet that is defined for the slot, but is not bound."))
(define-condition clos-facets-warning (warning)
()
(:documentation "All clos-facets package related warnings inherit from this warning"))
;; internal functions
(defun defined-facets ()
"Return a list of all the facets that have been defined"
(mapcar #'car *facet-definition-alist*))
(defun parse-slot-specifier (slot-specifier)
"Parse the slot specifier, sorting out the various options based on our interests in defclass, below."
(declare (values slot-name readers writers accessors facets rest))
(let ((unparsed-remainder (cdr slot-specifier))
(slot-name (car slot-specifier))
readers
writers
accessors
facets
rest)
(while unparsed-remainder
(case (car unparsed-remainder)
(:reader
(push (cadr unparsed-remainder) readers))
(:writer
(push (cadr unparsed-remainder) writers))
(:accessor
(push (cadr unparsed-remainder) accessors))
(t
(cond
((member (car unparsed-remainder) (defined-facets))
(setq facets (nconc (list (car unparsed-remainder) (cadr unparsed-remainder)) facets)))
(t
(setq rest (nconc (list (car unparsed-remainder) (cadr unparsed-remainder)) rest))))))
(setq unparsed-remainder (cddr unparsed-remainder)))
(values slot-name readers writers accessors facets rest)))
;; currently we aren't type specializing and we probably should (on the class formal)
(defun construct-facetized-slot-accessors (class-name slot-name
user-readers actual-reader
user-writers actual-writer
user-accessors actual-accessor
facets)
"Internal function that does the grunt work of putting together the code that will act as the
reader, writer, or accessor for slots on the class being defined."
;; the user-readers/writers etc. are the symbols the user has defined, the actual reader/writer etc. is the gentemp we handed to
;; the original defclass macro. So now we can hook that version (if we want to) or construct our own version afresh (e.g., for
;; multiple-values)
(declare (ignore class-name)) ;; for now
(let ((class-formal (gensym))
(writer-formal (gensym))
(place-formal (gensym))
(multiple-value-p (equal (extract-keyword :slot-values facets) :multiple))
deferred-code)
(flet ((make-accessor-internal (user-functions real-function writer-p accessor-p)
(when user-functions
(cond
((and real-function (not multiple-value-p))
;; just call the defclass version; later on we may add additional code.
(dolist (fn user-functions)
(when accessor-p
(push `(defmethod (setf ,fn) (,writer-formal ,class-formal)
(setf (,real-function ,class-formal) ,writer-formal))
deferred-code))
(push `(defmethod ,fn (,@(if writer-p `(,writer-formal)) ,class-formal)
(,real-function ,@(if writer-p `(,writer-formal)) ,class-formal)) ; for now
deferred-code)
(push `(defgeneric ,fn (,@(if writer-p `(,writer-formal)) ,class-formal))
deferred-code)))
(multiple-value-p
;; we can't actually use the defclass version because it doesn't handle the optional place
(dolist (fn user-functions)
(when accessor-p
(push `(defmethod (setf ,fn) (,writer-formal ,class-formal &optional ,place-formal)
(setf (clos-facets:slot-value ,class-formal ',slot-name ,place-formal) ,writer-formal))
deferred-code))
(push `(defmethod ,fn (,@(if writer-p `(,writer-formal)) ,class-formal &optional ,place-formal)
,(if writer-p
`(setf (clos-facets:slot-value ,class-formal ',slot-name ,place-formal) ,writer-formal)
`(clos-facets:slot-value ,class-formal ',slot-name ,place-formal)))
deferred-code)
(push `(defgeneric ,fn (,@(if writer-p `(,writer-formal)) ,class-formal &optional ,place-formal))
deferred-code)))
(t
;; no defclass version ?!
(warn "Incorrect expansion of clos-facets defclass form for user functions: ~S" user-functions))))))
(make-accessor-internal user-readers actual-reader nil nil)
(make-accessor-internal user-writers actual-writer t nil)
(make-accessor-internal user-accessors actual-accessor nil t))
`(progn ,@deferred-code)))
;; when we define new classes, they all inherit from this class
(common-lisp:defclass facet-support-class ()
((class-slot-facet-value-alist-alist :initform nil
:accessor class-slot-facet-value-alist-alist
:allocation :class ;; note that every new class should have their own
:documentation "An alist of slots whose values are themselves
alists of facets and their values at class definition time")
(slot-facet-value-alist-alist :initform nil :accessor slot-facet-value-alist-alist
:documentation "An alist of slots whose values are themselves alists of facets and their dynamic
values, initialized from class-slot-facet-value-alist-alist")))
;; Patches of CL/CLOS functions... (first part - more toward end of file)
;; (For defclass - to support facets at all! Yes, we could be using the MOP here, but while that would give us flexibility in
;; some ways it is at the cost of compatibility - most CLs don't yet support the MOP (fully or correctly). We will be as
;; MOPlike as possible, while avoiding anything that requires that slots be represented as objects (which is not supported in
;; MCL, at least, as of 5.0)
(defmacro defclass (class-name superclass-names slot-specifiers &rest class-options)
"A shadowing of the usual implementation of defclass, that intercepts the slot-specifiers in order to support facets.
Note that it is possible that slot accessors will not be compatible with the host implementation for classes not defined
using this macro."
;; the main things that have to be pulled apart are
;; slot specifiers - we want to yank out the facet related specifications and handle them separately... this also
;; lets us ultimately call the real defclass to do the work of defining the class - without having to have it get bogged
;; down in implemented facets using the MOP machinery (not that this is particularly bad, but this may be simpler
;; particularly for lisps without a full MOP).
;; The next thing we have to do is record what the user thinks are going to be the accessor functions for the slots. We'll
;; capture those with our own functions, reassign the ones defclass sees, so we can use them internally. Here, there may be
;; some implementation-specific code, depending on if an implementation implements accessors, readers, and writers as generic
;; functions or non CLOS functions (standard functions).
;; Next, we'll implement the various accessor functions, which will obey any needed facet protocols specified.
;; finally, we'll use the common-lisp version of defclass to implement the modified class.
;; lets get started!
(let ((user-slot-specifiers slot-specifiers)
processed-slot-specifiers
facet-specifiers
deferred-code)
;; first, we want to look at each slot specifier, and separate out the facets, the readers, the writers, and the accessors.
(dolist (slot-specifier user-slot-specifiers)
(let (actual-reader
actual-writer
actual-accessor)
(mlet (slot-name user-readers user-writers user-accessors facets rest)
(parse-slot-specifier slot-specifier)
;; create an internal name for any readers, writers and accessors to specify to the underlying cl:defclass
(when user-readers
(setq actual-reader (gentemp (format nil "~A-READER" slot-name))))
(when user-writers
(setq actual-writer (gentemp (format nil "~A-WRITER" slot-name))))
(when user-accessors
(setq actual-accessor (gentemp (format nil "~A-ACCESSOR" slot-name))))
;; save off the facet values
(update-alist slot-name
(alistify facets)
facet-specifiers)
;; create our version of the accessors, and push the result onto deferred code
(push (construct-facetized-slot-accessors class-name slot-name user-readers actual-reader user-writers actual-writer
user-accessors actual-accessor facets)
deferred-code)
;; build up the slot specifier that goes to cl:defclass
(push `(,slot-name
,@(if actual-reader
`(:reader ,actual-reader))
,@(if actual-writer
`(:writer ,actual-writer))
,@(if actual-accessor
`(:accessor ,actual-accessor))
,@rest)
processed-slot-specifiers))))
`(progn
(common-lisp:defclass ,class-name (,@superclass-names facet-support-class)
((class-slot-facet-value-alist-alist
:allocation :class
:documentation "Double alist, first of slotnames then facetnames to the value defined."
:initform ',facet-specifiers) ;; note that every new class should have their own
,@(nreverse processed-slot-specifiers))
,@class-options)
,@deferred-code)))
;;
;; Facets API
;;
;; Defclass itself appears above under patched functions
;;
(defun defslot (slot-name super-slots &key facet-initializations &allow-other-keys)
"Defslot allows one to define a hierarchy of slots, where slots are semantic relationships between class instances and
attributes (typically, other class instances). The current definition is pretty limited; the desired direction would, for
instance, allow us to define a general \"ancestor\" slot, and allow that to be a super-slot of, say, \"maternal-grandfather\",
specifying that the maternal grandfather is single-valued, but it's value is one of the multi-valued ancestor slot.
The current implementation only allows us to state that a slot supports set-oriented facets (for instance), and alas we
haven't (yet) implemented the :slot-type facet which would allow us to link such information to a \"kind\" of slot rather than
to a specific slot name. We will get to these more interesting applications of this concept later.
Note however, that defslot does make a global declaration about a particular slot name (within a package) as having a given
semantics. That is, unlike casual use of slotnames as relative to a class, defslot says that anytime a particular slotname
appears in any class, it has the same semantic meaning. The facet-initializations, if specified, is a list each element of
which is either the name of a facet to be supported by the slot-name, or a pair, the second element of which is the value of
the facet whenever it appears in a class. Setting a different value local to a class will signal an error; this allows one to
for instance, require that all decendants of a particular slot-name support multiple values."
(declare (ignore slot-name super-slots facet-initializations))
(warn "Defslot is not yet implemented"))
(defmacro deffacet (facet-name (super-facets &key (all nil) (default nil)) &optional unevaluated-comment &body body)
"The primary macro for creating a new facet. The body is invoked on any write to a slot (including initialization). The following
formals are bound on invocation, and may be used within the body (as lexical): facet-form, slotname, current-slotvalue,
new-slotvalue. The body should evaluate new-slotvalue in light of the current-slotvalue and the facet-form (the value of the
facet when the class was defined - this is what was in the defclass form as the argument to this facet), and either allow the
write by returning, or signal appropriately (q.v.)
:all implies all slots support the facet, with the :default value."
(unless (stringp unevaluated-comment)
(push unevaluated-comment body)
(setq unevaluated-comment ""))
`(update-alist ,(make-keyword facet-name)
(make-facet-definition :super-facets ',super-facets
:option-value-pairs '((:all ,all) (:default ,default))
:comment ',unevaluated-comment
:facet-body '(lambda (facet-form slotname current-slotvalue new-slotvalue)
,@body))
*facet-definition-alist*))
(defun get-facet-definition (facet-name)
(cdr (assoc (make-keyword facet-name) *facet-definition-alist*)))
(defgeneric slot-supports-facetp-using-class (class object slotname facetname)
)
(defmethod slot-supports-facetp-using-class ((class t) (object t) slotname facetname)
(facet-missing class object slotname facetname 'slot-supports-facetp))
(defmethod slot-supports-facetp-using-class ((class t) (object facet-support-class) slotname facetname)
(let ((facet-definition (get-facet-definition facetname)))
(unless facet-definition
(facet-missing class object slotname facetname 'slot-supports-facetp))
(or (member slotname (facet-definition-supported-slots facet-definition))
(cadr (assoc :all (facet-definition-option-value-pairs facet-definition))))))
(defun slot-supports-facetp (object slotname facetname)
"Defined in terms of slot-supports-facetp-using-class"
(slot-supports-facetp-using-class (class-of object) object slotname facetname))
(defgeneric slot-definition-facets (slot-definition)
(:documentation "return the facets defined for the slot-definition"))
(defgeneric slot-facet-value-using-class (object-class object slotname facetname)
(:documentation "Returns the value of the facet facetname on the
slot slotname for this class-object. The default primary method signals an error of type clos-facets-error if no such facet
is defined for this slot. If the facet is unbound for this slot, the default primary method signals an error of type
facet-unbound."))
(defmethod slot-facet-value-using-class ((object-class t) (object t) slotname facetname)
(facet-missing object-class object slotname facetname 'slot-facet-value))
(defmethod slot-facet-value-using-class ((object-class t) (object facet-support-class) slotname facetname)
(unless (slot-supports-facetp-using-class object-class object slotname facetname)
(facet-missing object-class object slotname facetname 'slot-facet-value))
(let* ((facet-alist (cdr (assoc slotname (slot-facet-value-alist-alist object))))
(facet-entry (assoc facetname facet-alist)))
(if facet-entry
(cdr facet-entry)
;; check to see if there is a default available
(let* ((facet-definition (get-facet-definition facetname))
(all-slots-p (cadr (assoc :all (facet-definition-option-value-pairs facet-definition))))
(default-value-entry (if all-slots-p
(assoc :default (facet-definition-option-value-pairs facet-definition)))))
(if default-value-entry
(cdr default-value-entry)
(facet-unbound object-class object slotname facetname))))))
(defun slot-facet-value (object slotname facetname)
"Returns the value of the facet facetname on the slot slotname for the object.
Implemented in terms of slot-facet-value-using-class"
(slot-facet-value-using-class (class-of object) object slotname facetname))
(defun clear-slot-value-cache ()
"used to clear our cache of slot value values"
;; not yet used
(values))
(defgeneric facet-missing (instance-class instance slot-name facet-name operation &optional new-value)
(:documentation "Patterned on slot-missing - invoked when an attempt is made to access a facet in an object
where the name of the facet is not a name of a facet supported on that slot on that class. The default method signals
an error (clos-facets-error). The generic function is not intended to be called by programmers. Programmers may write methods
for it."))
(defmethod facet-missing ((instance-class t) instance slot-name facet-name operation &optional new-value)
(error 'facet-missing-error
:instance instance
:class instance-class
:name slot-name
:facet facet-name
:operation operation
:new-value new-value))
(defgeneric facet-unbound (class instance slot-name facet-name)
(:documentation "Patterned on slot-unbound - invoked when an unbound facet is read. The default method signals an error of type
unbound-facet. The generic function facet-unbound is not intended to be called by programmers, but programmers may write methods
for it."))
(defmethod facet-unbound ((class t) instance slot-name facet-name)
(error 'unbound-facet :instance instance :class class :name slot-name :facet facet-name))
;;;; testing facet validity
;;
;; Facet validity testing is done on any write to a slot. This happens at two times
;; When creating an object, as a method on shared-initialize
;; (so it is also colled by the primary methods for initialize-instance, reinitialize-instance,
;; update-instance-for-different-class, and update-instance-for-redefined-class)
;; NB: this means that if a programmer does NOT use the system supplied primary function or otherwise calls shared-initialize in
;; these circumstances, then they must also hook their own functions to invoke facet validity tests, mutis mutandis.
;;
;; When changing the value of a slot on an object after it was created. Because reader and writer methods (provided by the
;; implementation) all use slot-value, it is slot-value
;; more patches to CLOS functions
;; the following patch existing functions in order to support :slot-values :multiple.
;; Note that for the most part, facets should not require such "deep" support, however, in this case the functions need
;; to take the additional "place" argument, preventing simply, e.g., adding methods for slot-value.
;;
;; Multiple values are represented using lists of values. The first in the list is the last one written
;; (that is, they appear in reverse order), and the 0th place is therefore the last element of the list.
;; (This implementation is subject to some debate, but at least in my own code, I found that the last place was the most frequently
;; accessed, thus the preference of putting it first in the list to make it the easiest to get to).
(defmethod shared-initialize :after ((instance facet-support-class) slot-names &rest initargs &key &allow-other-keys)
"After constructing a facet-support-class instance, initialize the slot-facet-value-alist-alist"
(setf (slot-facet-value-alist-alist instance) (class-slot-facet-value-alist-alist instance)))
(defun multiple-slot-values-p (class instance slot-name)
(equal (handler-case (slot-facet-value-using-class class instance slot-name :slot-values)
(unbound-facet ()))
:multiple))
(defgeneric slot-makunbound-using-class (class instance slot-name &optional place)
(:documentation "implements slot-makunbound - see the AMOP"))
(defmethod slot-makunbound-using-class ((class t) instance slot-name &optional place)
(let ((multiple-value-p (multiple-slot-values-p class instance slot-name)))
(cond
((and place (not multiple-value-p))
(error 'no-multiple-slotvalues :name slot-name :instance instance :place place))
((not multiple-value-p)
(clos:slot-makunbound-using-class class instance slot-name))
((not place)
;; just "unbind" the last value
(handler-case (pop (clos:slot-value-using-class class instance slot-name))
(unbound-slot ()))) ; we don't care if it's already unbound
(t
;; find the particular value and delete it
(handler-case (let ((values (clos:slot-value-using-class class instance slot-name)))
(setf (clos:slot-value-using-class class instance slot-name) (delete-n values place)))
(unbound-slot ())))))) ; if the slot is unbound, so is this place
(defun slot-makunbound (instance slot-name &optional place)
"Restores a slot in an instance to the unbound state. Calls slot-missing if no slot of the given name exists.
Implemented using slot-makunbound-using-class. If multi-valued, then place is used, and making a place unbound causes it to be removed if there are subsequent places, i.e., if places 1-6 exist, and place 4 is unbound, then the value of place 5 is now accessible only at place 4, etc."
(slot-makunbound-using-class (class-of instance) instance slot-name place))
(defgeneric slot-unbound (class instance slot-name &optional place)
(:documentation "Called when an unbound slot is read in an instance whose metaclass is standard-class.
The default method signals an error of condition type unbound-slot (with slots :name, naming the slot that was unbound, and :instance which is the instance that had the unbound slot). The function is called only by the function slot-value-using-class."))
(defmethod slot-unbound (class instance slot-name &optional place)
(error 'unbound-slot :place place :name slot-name :instance instance))
(defgeneric slot-value-using-class (class object slot-name &optional place)
(:documentation "Implementation for slot-value and setf of slot-value."))
(defmethod slot-value-using-class ((class t) object slot-name &optional place)
(cond
((and place (multiple-slot-values-p class object slot-name))
(if (slot-boundp-using-class class object slot-name place)
(nth place (common-lisp:slot-value object slot-name))
(slot-unbound class object slot-name place)))
((multiple-slot-values-p class object slot-name)
;; just return the first place
(if (slot-boundp-using-class class object slot-name 0)
(car (common-lisp:slot-value object slot-name))
(slot-unbound class object slot-name place)))
(t
(common-lisp:slot-value object slot-name))))
(defmethod (setf slot-value-using-class) (new-value (class t) object slot-name &optional place)
(flet ((do-set (new)
(if (common-lisp:slot-boundp object slot-name)
(setf (common-lisp:slot-value object slot-name)
(nconc (list new) (common-lisp:slot-value object slot-name))) ; add to beginning of list (see comments above) 10/26/19
(setf (common-lisp:slot-value object slot-name) (list new)))))
(cond
((and place (slot-boundp-using-class class object slot-name place))
;; replace existing value
(setf (nth place (common-lisp:slot-value object slot-name)) new-value))
;; check if there are *some* values there
((and place (common-lisp:slot-boundp object slot-name))
;; ok, we have to extend the list to be place-1 long, then we can append.
(let ((sv (common-lisp:slot-value object slot-name)))
(while (< (1+ (length sv)) place)
(setq sv (nconc sv (list :unset-value))))
(setf (common-lisp:slot-value object slot-name) sv)
(do-set new-value)))
(t
(do-set new-value)))))
(defun slot-value (object slot-name &optional place)
"Calls slot-missing if there is no slot of the given name. Implemented using slot-value-using-class. Setf'able"
(slot-value-using-class (class-of object) object slot-name place))
(defsetf slot-value (object slot-name &optional place) (new-value)
`(setf (slot-value-using-class (class-of ,object) ,object ,slot-name ,place) ,new-value))
(defgeneric slot-boundp-using-class (class instance slot-name &optional place)
(:documentation "implements slot-boundp - see the AMOP"))
(defmethod slot-boundp-using-class ((class t) instance slot-name &optional place)
(let ((multiple-value-p (multiple-slot-values-p class instance slot-name)))
(cond
((and place (not multiple-value-p))
(error 'no-multiple-slotvalues :name slot-name :instance instance :place place))
((or (not multiple-value-p) (not place))
(clos:slot-boundp-using-class class instance slot-name)) ; if place not spec, then any value means the last value is bound
(t
;; anything less than the length of the list of values is bound, but check the slot is bound first.
(and (clos:slot-boundp-using-class class instance slot-name)
(< place (list-length (clos:slot-value-using-class class instance slot-name))))))))
(defun slot-boundp (instance slot-name &optional place)
"Tests if a specific slot in an instance is bound, returning true or false. Can be used in :after methods on initialize instance. Implented using slot-boundp-using-class."
(slot-boundp-using-class (class-of instance) instance slot-name place))
(pushnew :cl-lib-clos-facets *features*)
| 31,768 | Common Lisp | .lisp | 474 | 59.518987 | 284 | 0.709027 | Bradford-Miller/CL-LIB | 1 | 0 | 1 | LGPL-3.0 | 9/19/2024, 11:28:28 AM (Europe/Amsterdam) | 93e0f5d05d8041ed3556e0edafbeabe9e09a52ed175b486cda50f003f9744c76 | 25,885 | [
-1
] |
25,886 | locatives.lisp | Bradford-Miller_CL-LIB/packages/locatives.lisp | (cl-lib:version-reporter "CL-LIB-Locatives" 5 17 ";; Time-stamp: <2020-01-05 17:09:03 Bradford Miller(on Aragorn.local)>"
"fix toplevel, add test-setters")
;; 5.17 10/27/19 add :key #'car to check-setter
;; 5.16 3/ 1/19 fixup toplevel, add test-setters. Note, not yet ported to SBCL!
;;; ****************************************************************
;;; Locatives ******************************************************
;;; ****************************************************************
;;;
;;; This is the locatives package written June 1993 by
;;; Bradford W. Miller
;;; [email protected]
;;; University of Rochester, Department of Computer Science
;;; 610 CS Building, Comp Sci Dept., U. Rochester, Rochester NY 14627-0226
;;; 716-275-1118
;;; I will be glad to respond to bug reports or feature requests.
;;; (please note I am no longer at that address)
;;;
;;; This version was NOT obtained from the directory
;;; /afs/cs.cmu.edu/user/mkant/Public/Lisp-Utilities/locatives.lisp
;;; via anonymous ftp from a.gp.cs.cmu.edu. (you got it in cl-lib).
;;;
;;;
;;;
;;; Copyright (C) 2001,2000,2019 by Bradford W. Miller
;;; Copyright (C) 1993 by Bradford W. Miller ([email protected])
;;; and the Trustees of the University of Rochester
;; This library is free software; you can redistribute it and/or modify it under the terms of the GNU
;; Lesser General Public License as published by the Free Software Foundation; either version 3.0 of
;; the License, or (at your option) any later version.
;; This library 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.
;; You should have received a copy of the GNU Lesser General Public License along with this library;
;; if not, see <http://www.gnu.org/licenses/>.
;; miller - Brad Miller ([email protected])
;;;
;;; Acknowledgements:
;;; This code has benefited from the comments of:
;;; Steven Haflich, ([email protected])
;;;
;;; Please note that while I beleive the above have contributed in
;;; a positive way to what you see before you, I remain soley
;;; responsible for the contents. In particular any errors, omissions,
;;; or major blunders are purely my own and do not reflect on anyone
;;; listed above!
;;;
;;; Updates:
;;; 1/27/00 for allegro 5.0.1, fix to appropriately handle (locf *global*)
;;; forms.
;;; 11/30/01 for Lispworks, by [email protected]
;;; 6/10/02 for Lispworks 4.2 by [email protected]
;;; ********************************
;;; Motivation *********************
;;; ********************************
;;;
;;; Locatives are useful for allowing destructive manipulation of objects
;;; based on reference, rather than keeping track of the objects themselves.
;;; This is similar to using pointers in C. Normally only a low-level hacker
;;; will need them.
;;; ********************************
;;; Limitations ********************
;;; ********************************
;;;
;;;
;;;Note that in most common lisps we don't have the full generality of
;;;really being able to refer to cells on the machine (though the lispms
;;;provided this). Therefore, this implementation is NOT compatible (in the
;;;sense that it doesn't use pointers) with
;;;what is available on the lisp machines, though it does try to emulate it
;;;in spirit. In particular, the storage consumed by this implementation is much
;;;larger than it would be on a lisp machine, since (except for lists), it must
;;;store two closures. It is possible to optimize cases other than simple lists
;;;to not require closures as well, at some minor compile-time and run-time cost.
;;;In addition the structure object itself requires 6 words, instead of the 2-3
;;;words a lispm needed for a locative.
;;;Large numbers of locatives are therefore possibly not a good idea.
;;;
;;;in particular, this simple implementation expects that the reference
;;;argument to locf contains a setf'able reference, and the code generated by
;;;setf is reversable (see reinvert-setter). To the extent the function isn't
;;;recognized by setf (get-setf-expansion) or the code generated by that isn't
;;;recognized by reinvert-setter, we will fail.
;;;
;;; All the common, likely cases under Allegro are handled, e.g. c*r, aref, elt, svref,
;;; nth, etc. The strategy is simple; we store away what it is the arguments to the
;;; reference function are (e.g. for car, the list), and remember what function it
;;; is that we are trying to use. So in some sense we just snapshot the arguments to
;;; our function and use that to evaluate the function application later (when we
;;; do location-contents or setf it).
;;; ********************************
;;; Description ********************
;;; ********************************
;;;
;;; (locative-p x) true if x is a locative
;;; (location-contents locative) returns the contents of what the
;;; locative points to, use setf to update
;;; (locf reference) convert reference to a locative. See above limitations.
;;;
;;; Examples of use:
;;; (setq bar '(a b c))
;;; (setq foo (locf (cadr bar)))
;;; bar -> (a b c)
;;; (location-contents foo) -> b
;;; (setf (location-contents foo) 'd)
;;; bar -> (a d c)
;;; (setf (location-contents (locf (symbol-value 'bar))) '(1 2 3))
;;; bar -> (1 2 3)
;;; (setf (location-contents foo) 'e)
;;; bar -> (1 2 3)
(in-package CL-LIB)
;; (export '(locf location-contents locative-p locative))
;;; in this implementation, a locative is a closure over a read and write function
(defstruct (locative (:print-function print-locative))
(read #'identity :type function)
(write #'identity :type function)
(flags 0 :type fixnum))
(defconstant +car-loc+ 1)
(defconstant +cdr-loc+ 2)
(defun print-locative (loc output-stream depth)
(if (and *print-level* (> depth *print-level*))
(format output-stream "#")
(print-unreadable-object (loc output-stream :type t :identity t))))
(defun location-contents (locative)
(case (locative-flags locative)
(0
(funcall (locative-read locative)))
(1 ; +car-loc+
(car (locative-read locative)))
(2 ; +cdr-loc+
(cdr (locative-read locative)))))
(defsetf location-contents (locative) (new-value)
`(case (locative-flags ,locative)
(0
(funcall (locative-write ,locative) ,new-value))
(,+car-loc+
(setf (car (locative-read ,locative)) ,new-value))
(,+cdr-loc+
(setf (cdr (locative-read ,locative)) ,new-value))))
;; we provide a translator for franz allegro. Others will need to
;; write their own lookup table. Some of these have been provided
;; thanks to "trial and error"; others thanks to "source code",
;; i.e. setf.cl
#-(or excl ccl lispworks)
(eval-when (:compile-toplevel :load-toplevel :execute)
(error "table to invert setf function not supplied. Locative code
will not work!"))
(defparameter *setter-inversion-table*
'((setq
identity)
(#+excl excl::.inv-car
#+ccl ccl::set-car
#+lispworks system::%rplaca
car)
(#+excl excl::.inv-cdr
#+ccl ccl::set-cdr
#+lispworks system::%rplacd
cdr)
#-excl
(#+ccl set-cadr
second)
#-excl
(#+ccl set-cdar
cdar)
#-excl
(#+ccl set-caar
caar)
#-excl
(#+ccl set-cddr
cddr)
(#+excl excl::.inv-elt
#+ccl ccl::set-elt
#+lispworks system::set-elt
elt)
(#+excl excl::.inv-s-aref
#+ccl ccl::aset
#+lispworks SETF::\"COMMON-LISP\"\ \"AREF\"
aref)
(#+excl excl::.inv-svref
#+ccl ccl::svset
#+lispworks system::set-svref
svref)
#+excl
(excl::.inv-structure-ref
structure-ref)
#+lispworks
(SETF::\"COMMON-LISP-USER\"\ \"STRUCTURE-REF\"
structure-ref)
#+excl
(excl::.inv-standard-instance-ref
standard-instance-ref)
#+lispworks
(SETF::\"COMMON-LISP-USER\"\ \"STANDARD-INSTANCE-REF\"
standard-instance-ref)
(#+excl excl::.inv-schar
#+ccl ccl::set-schar
#+lispworks system::set-schar
schar)
(#+excl excl::.inv-sbit
#+ccl ccl::%sbitset
#+lispworks SETF::\"COMMON-LISP\"\ \"SBIT\"
sbit)
(#+excl excl::.inv-symbol-function
#+ccl fset
#+lispworks system::set-symbol-function
symbol-function)
#-excl
(#+ccl set-fill-pointer
#+lispworks system::set-fill-pointer
fill-pointer)
#-excl
(#+ccl set-cdddr
cdddr)
#-excl
(#+ccl set-cddar
cddar)
#-excl
(#+ccl set-caddr
caddr)
#-excl
(#+ccl set-cadar
cadar)
#-excl
(#+ccl set-caadr
caadr)
#-excl
(#+ccl set-caaar
caaar)
#-excl
(#+ccl set-cdaar
cdaar)
#-excl
(#+ccl set-cdadr
cdadr)
(#+excl excl::.inv-symbol-plist
#+ccl ccl::set-symbol-plist
#+lispworks common-lisp::set-symbol-plist
symbol-plist)
(#+excl excl::.inv-nth
#+ccl ccl::%setnth
#+lispworks SETF::\"COMMON-LISP\"\ \"NTH\"
nth)
(#+excl excl::.inv-fill-pointer
#+ccl ccl::set-fill-pointer
fill-pointer)
#+:tr-strings
(#+excl excl::.inv-translated-string 'translated-string)
(#+excl excl::.inv-get
#+ccl ccl::set-get
#+lispworks common-lisp::setf-get
get)
(#+excl excl::.inv-macro-function
#+ccl ccl::set-macro-function
#+lispworks system::set-macro-function
macro-function)
(#+excl excl::.inv-compiler-macro-function
#+ccl ccl::set-compiler-macro-function
#+lispworks SETF::\"COMMON-LISP\"\ \"COMPILER-MACRO-FUNCTION\"
compiler-macro-function)
(#+excl excl::%puthash
#+ccl ccl::puthash
#+lispworks system::%puthash
gethash)
(set
symbol-value)
)
"Table of inversions and setters (arguments to setf")
(defun reinvert-setter (setf-function)
(let ((setf-case (assoc setf-function *setter-inversion-table*)))
(cond
(setf-case
(cadr setf-case))
(t
(error "Can't figure out inversion")))))
(defun check-setter (setter)
(let ((setf-function (rassoc setter *setter-inversion-table* :key #'car)))
(if setf-function
(car setf-function))))
(defun test-setters ()
(dolist (setter (mapcar #'cadr *setter-inversion-table*))
(mlet (temps formals setter-var setf-code access-code)
(#-ccl-2 get-setf-expansion
#+ccl-2 get-setf-method-multiple-value
setter nil) ; nil for the environment...
(declare (ignore temps formals setter-var access-code))
(assert (eql (check-setter setter) (car setf-code)) ()
"For Setter ~S, our table records a setf-code of ~S, but in this lisp it is actually ~S"
setter (check-setter setter) (car setf-code))))
:pass)
#+5am
;; try to make a 5am compatible version
;(it.bese.fiveam:test locatives "test the locatives package"
; (dolist (setter (mapcar #'cadr *setter-inversion-table*))
; (mlet (temps formals setter-var setf-code access-code)
; (#-ccl-2 get-setf-expansion
; #+ccl-2 get-setf-method-multiple-value
; setter nil) ; nil for the environment...
; (declare (ignore temps formals setter-var access-code))
; (is (eql (check-setter setter) (car setf-code))))))
;; better, since we'll get a better diagnostic output
(it.bese.fiveam:test locatives "test the locatives package"
(it.bese.fiveam:is (eql (test-setters) :pass)))
(defun fixup-args (setf-function) ; some of the args are reversed, etc.
(case setf-function
#+excl (excl::.inv-s-aref 'cdr) ; these take the "new" arg first
#+excl (excl::.inv-sbit 'cdr)
(t 'butlast) ; everything else takes new arg last
))
(defmacro locf (reference &environment env)
"Much like seeing a setf"
;; we have to capture what our reference refers to, then use it to
;; grab stuff at run-time.
;; find out which is the important "setter", everything else is "reference".
(mlet (temps formals setter-var setf-code access-code)
(#-ccl-2 get-setf-expansion
#+ccl-2 get-setf-method-multiple-value
reference env)
(declare (ignore setter-var access-code))
;; handle case of clos setter. Implementation independant way to do this?
(cond
((or (eq (car setf-code) 'cl-user::funcall)
#+lispworks
(and (null (ignore-errors (reinvert-setter (car setf-code))))
(or #|| (low:closurep (symbol-function (car setf-code))) ||# ; 6/10/02 ; 6/16/08
;; not sure if there is a modern substitute, for now comment out above.
(eql (symbol-package (car setf-code)) 'setf)))
#+excl
(and (eq (car setf-code) 'progn)
(eq (car (second (third setf-code))) 'excl::structure-ref)))
;; just treat as usual
`(make-locative :read #'(lambda () ,reference)
:write #'(lambda (new) (setf ,reference new))))
(t
(let ((ref-syms (mapcar #'(lambda (x) x (gensym))
(funcall (fixup-args (car setf-code))
(cdr setf-code))))
(ref-code (funcall (fixup-args (car setf-code)) (cdr setf-code))))
(do ((formal formals (cdr formal))
(temp temps (cdr temp)))
((null formal))
(labels ((walk-and-substitute (l)
(if (consp l)
(mapcar #'walk-and-substitute l)
(if (eq l (car temp)) (car formal) l))))
(setq ref-code (mapcar #'walk-and-substitute ref-code))))
(case (reinvert-setter (car setf-code))
(car
`(make-locative :read ,(car ref-code) :flags ,+car-loc+))
(cdr
`(make-locative :read ,(car ref-code) :flags ,+cdr-loc+))
(identity
`(make-locative :read #'(lambda () ,reference)
:write #'(lambda (new) (setf ,reference new))))
(t
`(let (,@(mapcar #'(lambda (ref setter)
(list ref setter))
ref-syms
ref-code))
(make-locative
:read
#'(lambda ()
(,(reinvert-setter (car setf-code)) ,@ref-syms))
;; do it this way because we discarded the needed args.
:write
#'(lambda (new)
(setf (,(reinvert-setter (car setf-code)) ,@ref-syms)
new)))))))))))
(cl-lib:macro-indent-rule locf (like setf))
(pushnew :cl-lib-locatives *features*)
| 14,764 | Common Lisp | .lisp | 1 | 14,763 | 14,764 | 0.599905 | Bradford-Miller/CL-LIB | 1 | 0 | 1 | LGPL-3.0 | 9/19/2024, 11:28:28 AM (Europe/Amsterdam) | 42f08b637fed6a68a38647e5fda13bf02b9e943cdf3cfcbe73b1cadc47944c35 | 25,886 | [
-1
] |
25,887 | reader.lisp | Bradford-Miller_CL-LIB/packages/reader.lisp | (in-package CL-LIB)
(cl-lib:version-reporter "CL-LIB-Reader" 5 16 ";; Time-stamp: <2019-05-19 17:18:52 Bradford Miller(on Aragorn.local)>"
"toplevel forms")
;; 5.16. 2/23/19 fix toplevel forms
;;;
;;;; (C) 1993 by Bradford W. Miller and the Trustees of the University of Rochester.
;;;; (C) 2019 by Bradford W. Miller
;; This library is free software; you can redistribute it and/or modify it under the terms of the GNU
;; Lesser General Public License as published by the Free Software Foundation; either version 3.0 of
;; the License, or (at your option) any later version.
;; This library 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.
;; You should have received a copy of the GNU Lesser General Public License along with this library;
;; if not, see <http://www.gnu.org/licenses/>.
;; miller - Brad Miller ([email protected])
;;; This is the incremental file expression reader package written by
;;; Bradford W. Miller
;;; University of Rochester, Department of Computer Science
;;; 610 CS Building, Comp Sci Dept., U. Rochester, Rochester NY 14627-0226
;;; 716-275-1118
;;; I will be glad to respond to bug reports or feature requests.
;;;
;;; This version was NOT obtained from the directory
;;; /afs/cs.cmu.edu/user/mkant/Public/Lisp-Utilities/reader.lisp
;;; via anonymous ftp from a.gp.cs.cmu.edu. (you got it in cl-lib).
;;;
;;; Note: The use of (raw-read-char) can translate to (read-char) on most
;;; architectures, under Allegro, it puts Gnu Emacs into raw mode, so a single
;;; character will be transmitted instead of waiting for an entire (buffered) line.
;;; (when using the fi interface, and loading more-allegro.lisp in the cl-lib
;;; distribution).
#-allegro
(defun raw-read-char ()
;; under emacs, we need to get the line anyway.
(let ((result (read-line)))
(if (eql (length result) 0)
#\return
(elt result 0))))
(defun do-non-clim-reader (pointer reader-expr obj)
(flet ((eval-expr (expr)
(restart-case
(PRINT (MULTIPLE-VALUE-LIST (eval eXPR)))
(nil ()
:report
(lambda (s) (format s "Continue READER as if form is ok"))))))
(loop
(format t "~%~%~a. ~s" pointer reader-expr)
(let ((input-char (raw-read-char)))
(case input-char
((#\space #\y #+lispm #\end #\return #-symbolics #\newline)
(eval-expr reader-expr)
(return-from do-non-clim-reader nil))
(#\q
(throw :abort 'end))
(#\s
(let ((skip (read)))
(while (plusp (decf skip))
(if (eq (read obj nil 'end) 'end)
(return-from do-non-clim-reader 'end))
(incf pointer))
(return-from do-non-clim-reader nil)))
(#\e
(format t "val: ")
(eval-expr (read))
(terpri))
(#\(
(unread-char input-char)
(format t "val: ")
(eval-expr (read))
(terpri))
((#\1 #\2 #\3 #\4 #\5 #\6 #\7 #\8 #\9)
(eval-expr reader-expr)
(unread-char input-char)
(dotimes (count (- (parse-integer (read))
1))
(progn count)
(if (eq (setq reader-expr (read obj nil 'end)) 'end)
(return-from do-non-clim-reader 'end))
(eval-expr reader-expr)
(incf pointer))
(return-from do-non-clim-reader nil))
(t (format t "~%~%
summary of commands
~~~~~~~~~~~~~~~~~~~
<space>, y, <end>: evaluates the next expression.
<number> : evaluates the next <number> of expressions.
s <number> : skips the next <number> of expressions.
e <lisp-expr> : evaluates the <lisp-expr>.
q : to exit the READER.
? : prints out this menu.
")
))))))
#+clim
(defun do-clim-reader (pointer reader-expr)
(flet ((eval-expr (expr)
(format t "~%~%~a. ~s" pointer expr)
(restart-case
(PRINT (MULTIPLE-VALUE-LIST (eval eXPR)))
(nil ()
:report
(lambda (s) (format s "Continue READER as if form is ok"))))))
(let ((stream *query-io*))
(restart-case
(progn
(CLIM:accepting-values (stream :own-window t
:exit-boxes '((:exit "<return> evaluate this term" )
(:abort "aborts")))
(format stream "~D: " pointer)
(clim:present reader-expr 'clim:form :stream stream)
(terpri stream)
(progfoo (CLIM:accept 'clim:form :stream stream :prompt "Evaluate an expression")
(when foo
(eval-expr foo))))
;; If we get here Ok was selected
(eval-expr reader-expr))
;; If we get here Abort was selected
(abort () (throw :abort :abort))))))
(defun reader (filename)
(catch :abort
(let ((reader-expr nil)
(pointer 0))
(with-open-file (obj filename)
(loop
(while (member (setq reader-expr (peek-char nil obj nil 'end))
'(#\space #\return #\newline #\;))
(if (eql reader-expr #\;)
(write-line (read-line obj nil #\space))
(write-char (read-char obj))))
(if (eq reader-expr 'end)
(return-from reader 'end))
(if (eq (setq reader-expr (read obj nil 'end)) 'end)
(return-from reader 'end))
(incf pointer)
#-clim (do-non-clim-reader pointer reader-expr obj)
#+clim (do-clim-reader pointer reader-expr)))
:reader-done)))
(eval-when (:load-toplevel :execute)
(export '(reader)))
(pushnew :cl-lib-reader *features*)
| 6,051 | Common Lisp | .lisp | 1 | 6,050 | 6,051 | 0.55528 | Bradford-Miller/CL-LIB | 1 | 0 | 1 | LGPL-3.0 | 9/19/2024, 11:28:28 AM (Europe/Amsterdam) | 39c611a807b6f7b3bd2ccbd987c611206379736ec512fafc5a1a42a7f209e08e | 25,887 | [
-1
] |
25,888 | prompt-and-read.lisp | Bradford-Miller_CL-LIB/packages/prompt-and-read.lisp | ;;; -*- Mode: LISP; Syntax: ansi-common-lisp; Package: CL-LIB; Base: 10 -*-
(in-package cl-lib)
(cl-lib:version-reporter "CL-LIB-Prompt" 5 0 ";; Time-stamp: <2007-05-18 11:27:37 miller>"
"CVS: $Id: prompt-and-read.lisp,v 1.1.1.1 2007/11/19 17:46:48 gorbag Exp $
restructured version")
;;;
;;; Copyright (C) 1994 by Bradford W. Miller, [email protected]
;;; and the Trustees of the University of Rochester
;;; Right of use & redistribution is granted as per the terms of the
;;; GNU LIBRARY GENERAL PUBLIC LICENCE version 2 which is incorporated here by
;;; reference.
;;; This program is free software; you can redistribute it and/or modify
;;; it under the terms of the GNU Library General Public License as published by
;;; the Free Software Foundation; version 2.
;;; 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 Library General Public License for more details.
;;; You should have received a copy of the GNU Library General Public License
;;; along with this program; if not, write to the Free Software
;;; Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
;;;
;;; The following is contributed by [email protected]
;;; various incantations for prompting for a non-binary choice (see also query.lisp in this directory).
;;; if CLIM is active, use that... thanks to George Ferguson for the initial take on the following three
;;; functions... ([email protected])
#+clim
(defun popup-read-form (type &optional (prompt nil pp) (default nil dp))
"Pops up a dialog box to read a symbol. Returns two values: the symbol
or NIL if Aborted and a flag that is T if Aborted."
(let (x
(stream *query-io*))
(restart-case
(progn
(CLIM:accepting-values (stream :own-window t)
(setq x
(cond ((and pp dp)
(CLIM:accept type :stream stream :prompt prompt :default default))
(pp
(CLIM:accept type :stream stream :prompt prompt))
(dp
(CLIM:accept type :stream stream :default default))
(t
(CLIM:accept type :stream stream)))))
;; If we get here Ok was selected
(values x nil))
;; If we get here Abort was selected
(abort () (values nil t)))))
(defvar *suppress-clim* nil "Turn off clim i/o")
(defun prompt-and-read (prompt &rest prompt-args)
"Prompt the user for an arbitrary response."
#+clim
(unless *suppress-clim*
(return-from prompt-and-read
(clim-prompt-for '(clim::form :auto-activate t) prompt prompt-args)))
(apply #'format *query-io* prompt prompt-args)
(read *query-io*))
(defun prompt-for (type &optional prompt &rest prompt-args)
"inspired by cltl/2, condition chapter."
(unless prompt
(setq prompt (format nil "Please enter a ~A" type)))
#+clim
(unless *suppress-clim*
(return-from prompt-for
(clim-prompt-for type prompt prompt-args)))
(let (result)
(while-not (typep (setq result (apply #'prompt-and-read prompt prompt-args)) type))
result))
#+clim
(defun clim-prompt-for (type prompt prompt-args)
(loop
(mlet (result aborted)
(popup-read-form (convert-to-presentation-type type) (if prompt (apply #'format nil prompt prompt-args)))
(cond
(aborted
(if (find-restart 'abort)
(abort)
(return-from clim-prompt-for (values nil t))))
(t
(return-from clim-prompt-for result))))))
#+clim
(defun clim-prompt-for-with-default (type default prompt prompt-args)
(loop
(mlet (result aborted)
(popup-read-form (convert-to-presentation-type type) (if prompt (apply #'format nil prompt prompt-args)) default)
(cond
(aborted
(if (find-restart 'abort)
(abort)
(return-from clim-prompt-for-with-default (values nil t))))
(t
(return-from clim-prompt-for-with-default result))))))
#+clim (defvar *default-presentation-type* '((clim:form) :auto-activate t))
#+clim
(defgeneric convert-to-presentation-type (type)
(:documentation "Convert a lisp type into a presentation type."))
#+clim
(defgeneric convert-satisfies-to-presentation-type (predicate args)
(:documentation "Convert a satisfies predicate into a presentation type."))
#+clim
(defmethod convert-to-presentation-type ((type t))
(if (clim:presentation-type-specifier-p type)
type
*default-presentation-type*))
#+clim
(defmethod convert-to-presentation-type ((type list))
;; handle satisfies, if user has defined it.
(if (equal (car type) 'satisfies)
(convert-satisfies-to-presentation-type (cadr type) (cddr type))
(call-next-method)))
(pushnew :cl-lib-prompt-and-read *features*)
| 4,910 | Common Lisp | .lisp | 1 | 4,909 | 4,910 | 0.658859 | Bradford-Miller/CL-LIB | 1 | 0 | 1 | LGPL-3.0 | 9/19/2024, 11:28:28 AM (Europe/Amsterdam) | d87fe40478ac7d7918e9ef56d0ba837bf32f22f76df3c923320bbfe2f57edab3 | 25,888 | [
-1
] |
25,889 | scheme-streams.lisp | Bradford-Miller_CL-LIB/packages/scheme-streams.lisp | ;;; -*- Mode: LISP; Syntax: ansi-common-lisp; Package: CL-LIB; Base: 10 -*-
(in-package CL-LIB)
(cl-lib:version-reporter "CL-LIB-Scheme-Streams" 5 0 ";; Time-stamp: <2012-01-05 17:47:16 millerb>"
"CVS: $Id: scheme-streams.lisp,v 1.2 2012/01/05 22:47:56 millerb Exp $
restructured version")
;;;
;;; Copyright (C) 1996--1992 by Bradford W. Miller, [email protected]
;;; and the Trustees of the University of Rochester
;;;
;;; Portions Copyright (C) 2002,2003 by Bradford W. Miller, [email protected]
;;; Right of use & redistribution is granted as per the terms of the
;;; GNU LIBRARY GENERAL PUBLIC LICENCE version 2 which is incorporated here by
;;; reference.
;;; This program is free software; you can redistribute it and/or
;;; modify it under the terms of the GNU Library General Public
;;; License as published by the Free Software Foundation; version 2.
;;; 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 Library General Public License for more details.
;;; You should have received a copy of the GNU Library General Public License
;;; along with this program; if not, write to the Free Software
;;; Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
;;;
;; scheme-stream (thanks to [email protected] for original code posted
;; in response to my question in comp.lang.lisp. "Improvements" are all mine,
;; and any errors are not to be blamed on him.)
;; Why use these instead of generators & series? Well, you can use
;; both. Note that generators discard their output, while
;; scheme-streams cache their output. What constitutes a tail-form
;; isn't specified. So it's valid to put, e.g. a Water's generator
;; there, or at least a fn that conses up a new scheme-stream whose
;; head is the result of the call on the generator, and whose tail is
;; another call on this fn.
(defstruct scheme-stream
head
tail
(tail-closure-p t))
(defmacro cons-scheme-stream (head tail-form)
`(make-scheme-stream :head ,head
:tail #'(lambda () ,tail-form)))
(defmacro list-scheme-stream (&rest args)
"Analogue to the cl list function, only the last arg is delayed."
(assert (> (list-length args) 1) (args)
"List-scheme-stream requires at least 2 args.")
(let* ((revargs (nreverse args))
(result `(cons-scheme-stream ,(second revargs) ,(pop revargs))))
(pop revargs)
(while revargs
(setq result `(make-scheme-stream :head ,(pop revargs)
:tail ,result :tail-closure-p nil)))
result))
(defun rlist-to-scheme-stream (rlist delay)
(let ((result (make-scheme-stream :head (pop rlist) :tail delay)))
(while rlist
(setq result (make-scheme-stream :head (pop rlist)
:tail result :tail-closure-p nil)))
result))
(defun ss-head (stream)
"Return the head of scheme stream Stream. If Stream is not a stream,
returns NIL (to allow the usual car of nil)."
(declare (optimize (speed 3) (safety 0)))
(if (scheme-stream-p stream)
(scheme-stream-head stream))) ;return nil for non-streams
(defun ss-tail (stream)
"Return the tail of the scheme stream Stream. Invokes lazy
evaluation if needed. If stream is not a scheme stream, return NIL
\(allows the usual cdr of nil)."
(declare (optimize (speed 3) (safety 0))
(values tail from-closure-p))
(cond
((not (scheme-stream-p stream))
(values nil nil))
((scheme-stream-tail-closure-p stream)
(values (setf (scheme-stream-tail-closure-p stream) nil
(scheme-stream-tail stream) (funcall
(scheme-stream-tail stream)))
t))
(t (values (scheme-stream-tail stream) nil))))
;; scheme force/delay model
(defstruct scheme-delay
(first-time-p t)
value)
(defmacro scheme-delay (form)
`(make-scheme-delay :value #'(lambda () ,form)))
(defmacro fake-scheme-delay (form)
`(make-scheme-delay :value ,form :first-time-p nil))
(defun scheme-force (delay)
(declare (type scheme-delay delay)
(values delay-value first-time-p))
(assert (scheme-delay-p delay) (delay)
"Attempt to force ~S, which is not a delay!" delay)
(let ((first-time-p (scheme-delay-first-time-p delay)))
(values
(cond (first-time-p
(setf (scheme-delay-first-time-p delay) nil
(scheme-delay-value delay) (funcall
(scheme-delay-value delay))))
(t (scheme-delay-value delay)))
first-time-p)))
(pushnew :cl-lib-scheme-streams *features*)
| 4,769 | Common Lisp | .lisp | 101 | 41.732673 | 100 | 0.671831 | Bradford-Miller/CL-LIB | 1 | 0 | 1 | LGPL-3.0 | 9/19/2024, 11:28:28 AM (Europe/Amsterdam) | c0f3fefdbcc5bc5fe83c6ffcce2e8e85b0d7f8f84633bfb2fb96a397cecde0cb | 25,889 | [
-1
] |
25,890 | clos-facets-tests.lisp | Bradford-Miller_CL-LIB/packages/clos-facets-tests.lisp | (in-package :clos-facets)
(cl-lib:version-reporter "CL-LIB-CLOS-Facets-Tests" 5 17
";; Time-stamp: <2020-01-04 17:14:12 Bradford Miller(on Aragorn.local)>"
"CVS: $Id: clos-facets-tests.lisp,v 1.3 2011/11/04 14:10:52 gorbag Exp $
;; development - note warnings on compile are OK")
;; This portion of CL-LIB Copyright (C) 2003-2008, 2019, 2020 Bradford W. Miller
;;
;; This library is free software; you can redistribute it and/or modify it under the terms of the GNU
;; Lesser General Public License as published by the Free Software Foundation; either version 3.0 of
;; the License, or (at your option) any later version.
;; This library 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.
;; You should have received a copy of the GNU Lesser General Public License along with this library;
;; if not, see <http://www.gnu.org/licenses/>.
;; 5.17 10/26/19 Move definitions to cl-lib-tests package instead of
;; clos-facets (note that the package should support that)
;; test facets library
;; some hack classes that illustrate facet uasage
;; mumble lets us test the basics: value-type and multiple slot-values.
;; convert to 5am 3/3/19 BWM
(in-package :cl-lib-tests)
(deftype hack-valid-symbol () '(member a b c d e))
(defclass mumble ()
((mumble-slota :initarg :a :accessor slota :value-type hack-valid-symbol) ; check value-type
(mumble-slotb :initarg :b :reader slotb-reader :writer slotb-writer ; check readers and writers
:slot-values :single :value-type hack-valid-symbol)
;; check many-values
(mumble-slotc :initarg :c :accessor slotc :slot-values :multiple :value-type hack-valid-symbol)))
;; someplace to put instances we will create
(defvar *frotz* ())
(defvar *foo* ())
(defvar *bar* ())
(defvar *bletch* ())
;; frotz adds cardinality checks
;; foo and bar check slot inverses
;; bletch makes use of denotational functions, testing everything together.
(eval-when (:compile-toplevel)
(format *error-output* "Expect two compiler warnings when compiling facet-tester:
;;;*** Warning in (SUBFUNCTION 3 CLOS-FACETS::FACET-TESTER): CLOS-FACETS::SLOTB-READER is called with the wrong number of arguments: Got 2 wanted 1
;;;*** Warning in (SUBFUNCTION 3 CLOS-FACETS::FACET-TESTER): (SETF CLOS-FACETS::SLOTA) is called with the wrong number of arguments: Got 3 wanted 2
--- this is due to the test intentionally attempting to perform a multi-value operation on a single value slot."))
(def-suite facet-tests :description "tests for the facet functions")
(in-suite facet-tests)
(defvar *mumble* )
(test basic-facet
(setq *mumble* (make-instance 'cl-lib-tests::mumble :a 'a :b 'b))
(is (equal (cl-lib-tests::slota *mumble*) 'a))
(is (equal (cl-lib-tests::slotb-reader *mumble*) 'b)))
(test facet-access
(setq *mumble* (make-instance 'cl-lib-tests::mumble :a 'a :b 'b))
(slotb-writer 'e *mumble*)
(setf (slota *mumble*) 'd)
(is (equal (slota *mumble*) 'd))
(is (equal (slotb-reader *mumble*) 'e)))
(test facet-multi-value
(setq *mumble* (make-instance 'cl-lib-tests::mumble :a 'a :b 'b))
;;fill up the multi-value slot
(setf (slotc *mumble*) 'a)
(setf (slotc *mumble*) 'b)
(setf (slotc *mumble*) 'c)
(is (slot-boundp *mumble* 'mumble-slotc 2))
(is (slot-boundp *mumble* 'mumble-slotc 0))
(is (equal (slotc *mumble* 0) 'c))
(is (equal (slotc *mumble* 1) 'b))
(is (equal (slotc *mumble* 2) 'a))
(is (equal (slot-value *mumble* 'mumble-slotc 2) 'a))
(setf (slotc *mumble* 1) 'd)
(is (equal (slotc *mumble* 0) 'c))
(is (equal (slotc *mumble* 1) 'd))
(is (equal (slotc *mumble* 2) 'a))
(slot-makunbound *mumble* 'mumble-slotc 0)
(is (equal (slotc *mumble* 0) 'd))
(is (equal (slotc *mumble* 1) 'a))
(is (etest unbound-slot (slotc *mumble* 2))))
(test facet-value-type-errors
(setq *mumble* (make-instance 'cl-lib-tests::mumble :a 'a :b 'b))
(is (etest clos-facets:value-type-error (slotb-writer 'g *mumble*)))
(is (etest clos-facets:value-type-error (setf (slota *mumble*) 7)))
(is (etest clos-facets:value-type-error (setf (slotc *mumble*) 9)))
(is (etest clos-facets:unbound-slot (slotc *mumble* 8)))
(is (etest clos-facets:no-multiple-slotvalues (slotb-reader *mumble* 2))) ;; should give an error on compile!
(is (etest clos-facets:no-multiple-slotvalues (setf (slota *mumble* 3) 'c)))) ;; should give an error on compile! (wrong number of args - slota is not multi-valued)
| 4,649 | Common Lisp | .lisp | 83 | 52.831325 | 166 | 0.698151 | Bradford-Miller/CL-LIB | 1 | 0 | 1 | LGPL-3.0 | 9/19/2024, 11:28:28 AM (Europe/Amsterdam) | 8f9f40363c83f867cc2404fd0278b99cf3b9aa8087580b5a5b3f3c77c72868b0 | 25,890 | [
-1
] |
25,891 | clos-facet-defs.lisp | Bradford-Miller_CL-LIB/packages/clos-facet-defs.lisp | (in-package :clos-facets)
(cl-lib:version-reporter "CL-LIB-CLOS-Facets-Defs" 0 2 ";; Time-stamp: <2011-10-21 10:36:10 millerb>"
"CVS: $Id: clos-facet-defs.lisp,v 1.3 2011/11/04 14:10:52 gorbag Exp $
;; development (fix comment)")
;; This portion of CL-LIB Copyright (C) 2003-2008 Bradford W. Miller
;;
;; This library is free software; you can redistribute it and/or modify it under the terms of the GNU
;; Lesser General Public License as published by the Free Software Foundation; either version 3.0 of
;; the License, or (at your option) any later version.
;; This library 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.
;; You should have received a copy of the GNU Lesser General Public License along with this library;
;; if not, see <http://www.gnu.org/licenses/>.
;;(deffacet name (superfacets &key all) body)
(deffacet value-type (() :all t :default t)
"Similar to a type declaration, but allows for reasoning about the
type, and in particular, stating the type of the eqivalence class of
the slot" )
(deffacet slot-values (() :all t :default :single)
"By default, slots are :slot-values :single, which means that they
have normal common-lisp semantics. If :slot-values :multiple, however,
the slot has multiple-values, that is, setting a slot multiple times
does NOT overwrite prior values, and one can read off the different
values (or rewrite specific values) by using the place optional
parameter on the various CLOS slot functions, such as slot-value)" )
| 1,696 | Common Lisp | .lisp | 26 | 62.615385 | 102 | 0.751202 | Bradford-Miller/CL-LIB | 1 | 0 | 1 | LGPL-3.0 | 9/19/2024, 11:28:28 AM (Europe/Amsterdam) | 06fec10a22bfbe52dbc7f9d258971401f571b8e4fc47f5f9b34267cccd78c561 | 25,891 | [
-1
] |
25,892 | resources-tests.lisp | Bradford-Miller_CL-LIB/packages/resources-tests.lisp | (in-package CL-LIB)
(cl-lib:version-reporter "CL-LIB-Resources Tests" 5 18 ";; Time-stamp: <2020-01-05 17:17:17 Bradford Miller(on Aragorn.local)>"
"new")
;; 5.18 1/ 5/20 In lispworks, make sure we specifically refer to cl-lib version of resources
;; 5.16. 2/17/19 5am testing (new)
;; This portion of CL-LIB Copyright (C) 2019 Bradford W. Miller
;;
;; This library is free software; you can redistribute it and/or modify it under the terms of the GNU
;; Lesser General Public License as published by the Free Software Foundation; either version 3.0 of
;; the License, or (at your option) any later version.
;; This library 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.
;; You should have received a copy of the GNU Lesser General Public License along with this library;
;; if not, see <http://www.gnu.org/licenses/>.
;; miller - Brad Miller ([email protected])
(5am:def-suite resources-tests :description "Test suite for resources package")
(5am:in-suite resources-tests)
;; following the API spec from resources.lisp.
;; for the purposes of testing, we will create two kinds of resources, one without args (homogenious resource)
;; and one with two arguments. The former will cons up vectors of a fixed size, and the latter will cons up arrays of
;; the specified dimensions.
(defun clear-fixed-resource (r)
(setf (aref r 0) nil)
(setf (aref r 1) nil)
(setf (aref r 2) nil)
(setf (aref r 3) nil)
(setf (aref r 4) nil))
(cl-lib::defresource (test-fixed-resource () :initial-copies 5 :initializer clear-fixed-resource)
(make-array (list 5) :element-type t :initial-element nil))
(5am:test allocate-fixed-resources "Test that we can allocate the fixed resources, in excess of the pool"
(let ((foo1 (allocate-test-fixed-resource))
(foo2 (allocate-test-fixed-resource))
(foo3 (allocate-test-fixed-resource))
(foo4 (allocate-test-fixed-resource))
(foo5 (allocate-test-fixed-resource))
(foo6 (allocate-test-fixed-resource)))
;; make them unique
(setf (aref foo1 2) 1)
(setf (aref foo2 2) 2)
(setf (aref foo3 2) 3)
(setf (aref foo4 2) 4)
(setf (aref foo5 2) 5)
(setf (aref foo6 2) 6)
;; make sure they are different
(is (not (eq foo1 foo2)))
(is (not (eq foo2 foo3)))
(is (not (eq foo3 foo4)))
(is (not (eq foo4 foo5)))
(is (not (eq foo5 foo6)))
;; at this point, all resources should be in use
(cl-lib::map-resource #'(lambda (object in-use)
(is in-use))
'test-fixed-resource)
;; deallocate one resource and check that it was the only one marked to not be in use
(deallocate-test-fixed-resource foo4)
(cl-lib::map-resource #'(lambda (object in-use)
(cond
((eq foo4 object)
(is (not in-use))
(is (null (aref object 2)))) ; should have been cleared!
(t
(is in-use)))) ; everyone else should still be in-use
'test-fixed-resource)
;; now when we allocate an object, we should get back that one
(progfoo (allocate-test-fixed-resource)
;; it should be eq to our old foo4 (not a new one)
(is (eq foo4 foo))
;; and all should be in-use again
(cl-lib::map-resource #'(lambda (object in-use)
(is in-use))
'test-fixed-resource))))
;;
(5am:test clear-fixed-resource
(clear-test-fixed-resource)
;; should all be unallocated
(cl-lib::map-resource #'(lambda (object in-use)
(is (not in-use)))
'test-fixed-resource))
;; ok, now lets try the same with a variable resource.
(defun clear-variable-resource (r a1 a2)
(dotimes (i1 a1)
(dotimes (i2 a2)
(setf (aref r i1 i2) 0))))
(cl-lib::defresource (test-variable-resource (a1 a2) :initializer clear-variable-resource)
(make-array (list a1 a2) :element-type t :initial-element 0))
(5am:test allocate-variable-resources "Test that we can allocate the variable resources, in excess of the pool"
(let ((foo1 (allocate-test-variable-resource 2 3))
(foo2 (allocate-test-variable-resource 3 2))
(foo3 (allocate-test-variable-resource 4 3))
(foo4 (allocate-test-variable-resource 3 4))
(foo5 (allocate-test-variable-resource 1 1))
(foo6 (allocate-test-variable-resource 7 2)))
;; sign them
(setf (aref foo1 0 0) 1)
(setf (aref foo2 0 0) 2)
(setf (aref foo3 0 0) 3)
(setf (aref foo4 0 0) 4)
(setf (aref foo5 0 0) 5)
(setf (aref foo6 0 0) 6)
;; make sure they are different
(is (not (eq foo1 foo2)))
(is (not (eq foo2 foo3)))
(is (not (eq foo3 foo4)))
(is (not (eq foo4 foo5)))
(is (not (eq foo5 foo6)))
;; at this point, all resources should be in use
(cl-lib::map-resource #'(lambda (object in-use)
(is in-use))
'test-variable-resource)
;; deallocate one resource and check that it was the only one marked to not be in use
(deallocate-test-variable-resource foo4)
(cl-lib::map-resource #'(lambda (object in-use)
(cond
((eq foo4 object)
(is (not in-use))
(is (null (aref object 0 0)))) ; should have been cleared!
(t
(is in-use)))) ; everyone else should still be in-use
'test-variable-resource)
;; now allocate an object with a DIFFERENT size, and we should get something new
(progfoo (allocate-test-variable-resource 7 2)
;; it should NOT be eq to our old foo4 (not a new one)
(is (not (eq foo4 foo)))
;; and original foo4 should not be in use
(cl-lib::map-resource #'(lambda (object in-use)
(if (eq object foo4)
(is (not in-use))
(is in-use)))
'test-variable-resource))
;; now when we allocate an object that has foo4's spec, we should get back that one
(progfoo (allocate-test-variable-resource 3 4)
;; it should be eq to our old foo4 (not a new one)
(is (eq foo4 foo))
;; and all should be in-use again
(cl-lib::map-resource #'(lambda (object in-use)
(is in-use))
'test-variable-resource))))
;;
(5am:test clear-variable-resource
(clear-test-variable-resource)
;; should all be unallocated
(cl-lib::map-resource #'(lambda (object in-use)
(is (not in-use)))
'test-variable-resource))
| 7,312 | Common Lisp | .lisp | 145 | 38.993103 | 128 | 0.581503 | Bradford-Miller/CL-LIB | 1 | 0 | 1 | LGPL-3.0 | 9/19/2024, 11:28:28 AM (Europe/Amsterdam) | 54aa29d6df5bf0f62cdc5dccf294036f71645c58e94d5e00147645c4a57fab18 | 25,892 | [
-1
] |
25,893 | initializations-tests.lisp | Bradford-Miller_CL-LIB/packages/initializations-tests.lisp | ;; if FiveAM is loaded, then set up some tests.
(in-package :cl-lib-tests)
(cl-lib:version-reporter "CL-LIB-Initializations Tests" 5 17 ";; Time-stamp: <2019-10-26 20:28:02 Bradford Miller(on Aragorn.local)>"
"5am testing")
;; 5.17 10/26/19 make sure we generate a new initialization name each time we run the test
;; 5.16. 2/17/19 5am testing (new)
;; This portion of CL-LIB Copyright (C) 2019 Bradford W. Miller
;;
;; This library is free software; you can redistribute it and/or modify it under the terms of the GNU
;; Lesser General Public License as published by the Free Software Foundation; either version 3.0 of
;; the License, or (at your option) any later version.
;; This library 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.
;; You should have received a copy of the GNU Lesser General Public License along with this library;
;; if not, see <http://www.gnu.org/licenses/>.
;; miller - Brad Miller ([email protected])
(def-suite initialization-tests :description "Test suite for initializations package")
(in-suite initialization-tests)
;; modify example from our original code to allow for us to check that it works.
(defvar *test-var* 0)
(defvar *test-init-list* nil)
(test init-once
"test that :once initialization runs once (by name)"
(let ((test-name (string (gensym "test-init-once"))))
(setq *test-var* 0)
(add-initialization test-name '(setq *test-var* 1) '(:once))
(is (= 1 *test-var*))
(add-initialization test-name '(setq *test-var* 2) '(:once))
(is (= 1 *test-var*))))
(test init-lists
"test that user initialization lists work"
(let ((test-name (string (gensym "test-init-lists"))))
(setq *test-var* 40)
(add-initialization test-name '(incf *test-var* 2) () '*test-init-list*)
;; haven't run initializations yet, so should be 40
(is (= 40 *test-var*))
(initializations '*test-init-list*)
;; now incremented
(is (= 42 *test-var*))
(initializations '*test-init-list*)
;; since we haven't reset, it shouldn't run a second time
(is (= 42 *test-var*))
(reset-initializations '*test-init-list*)
(is (= 42 *test-var*))
(initializations '*test-init-list*)
(is (= 44 *test-var*))))
| 2,424 | Common Lisp | .lisp | 47 | 47.787234 | 134 | 0.696444 | Bradford-Miller/CL-LIB | 1 | 0 | 1 | LGPL-3.0 | 9/19/2024, 11:28:28 AM (Europe/Amsterdam) | a2e9c74467b9d60ead808445e238c263f51ce08327828e76a1a323d3515b14bf | 25,893 | [
-1
] |
25,894 | popup-console.lisp | Bradford-Miller_CL-LIB/packages/popup-console.lisp | (cl-lib:version-reporter "CL-LIB-Popup Console" 5 7 ";; Time-stamp: <2021-12-16 13:24:55 gorbag>"
"CVS: $Id: popup-console.lisp,v 1.1.1.1 2007/11/26 15:13:24 gorbag Exp $
;; documentation")
;; 5.1 5/18/07 Title Option (LispWorks Native Windows (CAPI))
;;; Copyright (C) 2005 by Bradford W. Miller and Raytheon Corporation.
;;; Unlimited non-commercial use is granted to the end user, other rights to
;;; the non-commercial user are as granted by the GNU LIBRARY GENERAL PUBLIC LICENCE
;;; version 2 which is incorporated here by reference.
;;; 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 Library General Public License for more details.
;;; You should have received a copy of the Gnu Library General Public License
;;; along with this program; if not, write to the Free Software
;;; Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
;;; Written 6/2005 by Bradford W. Miller [email protected]
;; The motivation for this package, initially, was the lack of a distiguished *error-output* in LispWorks,
;; that is, unlike allegro, access to file descriptor 2 was not available, and so programs that are intended
;; to be pipes have no place to put an error, other than a file.
;;
;; This package allows one to create a stream into a popup console window and bind *error-output* or pretty much
;; anything else to it.
;;
;; The initial implementation uses CAPI (since I'm on LispWorks), however, the port to CLIM should be straightforward
;; (and I'm sure I'll get around to it ;-), since they are more similar than different.
;;
;; How to use:
;; First, call (create-console). By default, a read-only console is created, suitable for displaying errors
;; as your program prints them, (create-console :rw) will put up an editor buffer (read/write).
;; In either case, a console object is returned, which is needed for the following calls. Optionally, you can
;; specify a second argument, which will be the title of the window.
;;
;; (console-stream console) returns a stream associated with a console, e.g., the thing to format to.
;;
;; (format-console console format-string &rest args) is format for a console.
;;
;; (read-line-console console &optional eof-error-p eof-value) is read-line for a console, but the console
;; argument is required.
;;
;; That's it! Simple and straightforward.
(defpackage cl-lib-console
(:use #:common-lisp #+lispworks #:capi #:mp)
(:export #:create-console #:destroy-console #:console-stream #:format-console #:read-line-console)
(:documentation "The motivation for this package, initially, was the lack of a distiguished *error-output* in LispWorks,
that is, unlike allegro, access to file descriptor 2 was not available, and so programs that are intended
to be pipes have no place to put an error, other than a file.
This package allows one to create a stream into a popup console window and bind *error-output* or pretty much
anything else to it.
How to use:
First, call (create-console). By default, a read-only console is created, suitable for displaying errors
as your program prints them, (create-console :rw) will put up an editor buffer (read/write).
In either case, a console object is returned, which is needed for the following calls. Optionally, you can
specify a second argument, which will be the title of the window.
\(console-stream console) returns a stream associated with a console, e.g., the thing to format to.
\(format-console console format-string &rest args) is format for a console.
\(read-line-console console &optional eof-error-p eof-value) is read-line for a console, but the console
argument is required."))
(in-package cl-lib-console)
;; right now, this all assumes lispworks.
#-lispworks
(error "Popup Console has not been ported outside the Lispworks/CAPI environment yet!")
;; definitions
(define-interface console ()
((console-type :initform :ro :reader console-type))
)
(define-interface popup-console-r/o (console)
((console-type :initform :ro))
(:panes
(console collector-pane
:enabled nil
:accessor console-pane
:visible-min-width '(:character 80)
:visible-min-height '(:character 12)))
(:default-initargs :title "Popup Console R/O"))
(define-interface popup-console-r/w (console)
((console-type :initform :rw))
(:panes
(console interactive-pane
:enabled t
:accessor console-pane
:visible-min-width '(:character 80)
:visible-min-height '(:character 24)))
(:default-initargs :title "Popup Console R/W"))
;; main functions
(defun create-console (&optional (type :ro) (title (format nil "Popup Console ~A" type)))
"Makes sure the environment is ready for popping up a window; two kinds of consoles are available, :ro and :rw, default :ro"
;; check environment
(initialize-console-environment)
;; create window
(let ((console (initialize-console-window type :title title)))
(display console)
console))
(defun destroy-console (console)
"Console is no longer needed"
(destroy console))
(defun console-stream (console)
"Return the stream of a console"
(case (console-type console)
(:ro
(collector-pane-stream (console-pane console))) ;; with luck, suitable for binding to *error-output*
(:rw
(interactive-pane-stream (console-pane console)))))
(defun format-console (console format-string &rest args)
"Like format (oh if only that were a generic function!), but for consoles."
(apply #'format (console-stream console) format-string args))
(defun read-line-console (console &optional (eof-error-p t) eof-value)
"read-line for a console; really can just call read-line on the console stream!"
(assert (eql (console-type console) :rw) () "Can't read from a display-only console")
(read-line (console-stream console) eof-error-p eof-value))
;; helper functions
(defun initialize-console-environment ()
(unless mp::*multiprocessing*
(mp:initialize-multiprocessing))
#+(and cocoa lispworks7)
(x-utils:ensure-motif-libraries))
(defun initialize-console-window (type &key (min-width 200) (title nil title-p))
(apply #'make-instance
(case type
(:ro
'popup-console-r/o)
(:rw
'popup-console-r/w))
:visible-min-width min-width (if title-p (list :title title))))
(pushnew :cl-lib-console *features*)
| 6,569 | Common Lisp | .lisp | 124 | 49.274194 | 126 | 0.726536 | Bradford-Miller/CL-LIB | 1 | 0 | 1 | LGPL-3.0 | 9/19/2024, 11:28:28 AM (Europe/Amsterdam) | cb5ad403f05a0d4df314e31b760f05dab0c2458e4c24de91f17fed21f38059a6 | 25,894 | [
-1
] |
25,895 | s-package.lisp | Bradford-Miller_CL-LIB/packages/SERIES/s-package.lisp | ;;;;-*- Mode: lisp; Package: (SERIES :use "COMMON-LISP" :colon-mode :external) -*-
;;;; The package initialization stuff is done here now, instead of in s-code.lisp. This is based a comment by Bruno Haible who said
;;;;
;;;; "The important point is that the packages setup when you compile
;;;; a file must be identical to the packages setup when you load the
;;;; file.... What will help, 100%, is to have a file which issues
;;;; all the necessary `defpackage' forms, and make sure this file is
;;;; loaded before anything else and before any `compile-file'.
;;;; $Id: s-package.lisp,v 1.16 2008/11/28 20:38:30 rtoy Exp $
;;;;
;;;; $Log: s-package.lisp,v $
;;;; Revision 1.16 2008/11/28 20:38:30 rtoy
;;;; Bug ID: 2212396
;;;;
;;;; Update for CCL, which doesn't have :mcl in *features* anymore.
;;;;
;;;; Revision 1.15 2008/10/27 16:25:58 rtoy
;;;; Bug 2165712: Export COLLECT-IGNORE functionality
;;;;
;;;; s-code.lisp:
;;;; o Add better docstring for COLLECT-IGNORE.
;;;;
;;;; s-package.lisp:
;;;; o Export COLLECT-IGNORE
;;;;
;;;; s-doc.txt:
;;;; o Document COLLECT-IGNORE.
;;;;
;;;; Revision 1.14 2008/10/27 14:24:53 rtoy
;;;; Support SCL. Just add scl conditionalizations where we have cmucl
;;;; ones, and convert uppercase symbols and symbol-names to use
;;;; symbol-name and uninterned symbols. This is to support scl's default
;;;; "modern" mode.
;;;;
;;;; Changes from Stelian Ionescu.
;;;;
;;;; Revision 1.13 2008/10/27 14:19:23 rtoy
;;;; Add support for ecl.
;;;;
;;;; (From Stelian Ionescu.)
;;;;
;;;; Revision 1.12 2004/12/15 17:18:57 rtoy
;;;; Apply fixes from Hannu Koivisto to support sbcl. Also added asdf
;;;; support. His comments:
;;;;
;;;;
;;;; * series.asd:
;;;; * Initial checkin.
;;;; * series.system:
;;;; * Removed logical pathname stuff and made this "self-sufficient", i.e. it is
;;;; sufficient to just load it; no need to edit pathname translations.
;;;; * Removed s-install from series system; we certainly don't want Series to
;;;; install itself to CL-USER whenever the system is compiled/loaded.
;;;;
;;;; * s-test.lisp:
;;;; * Replaced all uses of defconstant with series::defconst-once.
;;;;
;;;; * s-package.lisp:
;;;; * sb-cltl2 module is now required at compile time too.
;;;;
;;;; * s-code.lisp:
;;;; * (defconst-once) New macro.
;;;; * Replaced all uses of defconstant with it.
;;;;
;;;; * RELEASE-NOTES:
;;;; * Installation instructions based on system definition files.
;;;; * Updated the list of contributors.
;;;; * Some cosmetic changes.
;;;;
;;;; Revision 1.11 2003/06/08 12:53:21 rtoy
;;;; From Alexey Dejneka:
;;;;
;;;; o Add support for SBCL
;;;; o Import COMPILER-LET from SBCL.
;;;;
;;;; Revision 1.10 2001/12/23 17:11:17 rtoy
;;;; COMPILER-LET is in the EXT package in Clisp now.
;;;;
;;;; Revision 1.9 2001/12/23 16:54:44 rtoy
;;;; Make series support Allegro "modern" lisp with its case-sensitive
;;;; reader. Mostly just making every that needs to be lower case actually
;;;; lower case. The tests still work.
;;;;
;;;; Revision 1.8 2000/09/22 15:58:39 rtoy
;;;; Add support for MCL (from Rainer Joswig).
;;;;
;;;; Revision 1.7 2000/03/28 10:23:49 matomira
;;;; polycall et all are now tail recursive.
;;;; LETIFICATION WORKS COMPLETELY!!
;;;;
;;;; Revision 1.8 2000/03/14 10:48:10 matomira
;;;; Workaround for ACL 5.0.1 TAGBODY bug added.
;;;; ALL-TIME SERIES BUG FIX: wrappers now inserted more precisely.
;;;; Abstracted use of wrapper component of frags.
;;;; GENERATOR deftyped to CONS, not LIST, when necessary.
;;;;
;;;; Revision 1.7 2000/03/11 17:36:34 matomira
;;;; Added eval-when compatibility magic.
;;;;
;;;; Revision 1.6 2000/03/03 19:17:15 matomira
;;;; Series 2.0 - Change details in RELEASE-NOTES.
;;;;
;;;; Revision 1.4 1999/12/01 16:09:05 toy
;;;; Need to import compiler-let from the extensions package in CMUCL.
;;;;
;;;; Revision 1.3 1999/09/14 20:19:43 toy
;;;; Export the new function collect-stream.
;;;;
;;;; Revision 1.2 1999/07/02 20:38:13 toy
;;;; Forgot a few items from s-code.lisp, and had to put the in-package
;;;; stuff back into s-code.lisp.
;;;;
;;;; Revision 1.1 1999/07/02 19:52:32 toy
;;;; Initial revision
;;;;
;;; Add a feature to say if we are a Lisp that can hack ansi-cl style
;;; stuff, as far as series goes anyway. This implies:
;;; ansi style packages (DEFPACKAGE, CL not LISP as main package)
;;;
;;; if you don't have this you need to make the LISP package have CL
;;; as a nickname somehow, in any case.
;;;
#+gcl
(eval-when (compile load eval)
(unless (find-package "CL")
(rename-package "LISP" "COMMON-LISP" '("LISP" "CL"))))
;;; Note this is really too early, but we need it here
#+(or draft-ansi-cl draft-ansi-cl-2 ansi-cl allegro cmu scl sbcl Genera Harlequin-Common-Lisp CLISP mcl ccl)
(cl:eval-when (load eval compile)
(cl:pushnew ':series-ansi cl:*features*))
#+allegro
(cl:eval-when(compile load eval)
;; Simple way to figure out if we are running Allegro modern lisp
;; with its case-sensitive reader.
(when (find-package "cl")
(cl:pushnew ':allegro-modern cl:*features*)))
#+sbcl
(eval-when (:execute :load-toplevel :compile-toplevel)
(require :sb-cltl2))
(defpackage #:series
(:use #:cl)
(:export
;;(2) readmacros (#M and #Z)
;;(5) declarations and types (note dual meaning of series)
#:optimizable-series-function #:off-line-port ;series
#:series-element-type #:propagate-alterability
#:indefinite-extent
;;(10) special functions
#:alter #:to-alter #:encapsulated #:terminate-producing
#:next-in #:next-out
#:generator
#:gatherer #:result-of
#:gather-next #:gather-result #:gatherlet #:gathering
#:fgather-next #:fgather-result #:fgatherlet #:fgathering
;;(55) main line functions
#:make-series #:series #:scan #:scan-multiple #:scan-range
#:scan-sublists #:scan-fn #:scan-fn-inclusive #:scan-lists-of-lists
#:scan-lists-of-lists-fringe #:scan-file #:scan-stream #:scan-hash #:scan-alist
#:scan-plist #:scan-symbols #:collect-fn #:collect #:collect-append
#:collect-nconc #:collect-file #:collect-alist #:collect-plist
#:collect-hash #:collect-length #:collect-stream
#:collect-sum #:collect-product #:collect-max #:collect-min
#:collect-last #:collect-first #:collect-nth
#:collect-and #:collect-or #:collect-ignore
#:previous #:map-fn #:iterate #:mapping
#:collecting-fn #:cotruncate #:latch #:until #:until-if #:positions
#:choose #:choose-if #:spread #:expand #:mask #:subseries #:mingle
#:catenate #:split #:split-if #:producing #:chunk
;;(5) variables
#:*series-expression-cache*
#:*last-series-loop*
#:*last-series-error*
#:*suppress-series-warnings*
)
(:shadow
#:let #:let* #:multiple-value-bind #:funcall #:defun
#+(or cmu scl) #:collect #+(or cmu scl) #:iterate)
#+Harlequin-Common-Lisp
(:import-from "LISPWORKS" "COMPILER-LET")
#+Genera
(:import-from "LISP" "COMPILER-LET")
#+allegro
(:import-from #:cltl1 #:compiler-let)
#+CLISP
(:import-from "EXT" "COMPILER-LET")
#+(or cmu scl)
(:import-from :ext #:compiler-let)
#+(or mcl ccl)
(:import-from "CCL" "COMPILER-LET")
#+sbcl
(:import-from "SB-CLTL2" "COMPILER-LET")
#+ecl
(:import-from "SI" "COMPILER-LET")
)
#-(or series-ansi)
(export ;74 total concepts in the interface
'(;(2) readmacros (#M and #Z)
;(5) declarations and types (note dual meaning of series)
indefinite-extent
optimizable-series-function off-line-port ;series
series-element-type propagate-alterability
;(10) special functions
alter to-alter encapsulated terminate-producing
next-in next-out generator gatherer result-of
gather-next gather-result fgather-next fgather-result
gathering fgathering gatherlet fgatherlet
;(55) main line functions
make-series series scan scan-multiple scan-range scan-sublists scan-fn
scan-fn-inclusive scan-lists-of-lists scan-lists-of-lists-fringe scan-file
scan-stream scan-hash scan-alist scan-plist scan-symbols collect-fn collect
collect-append collect-nconc collect-file collect-alist collect-plist
collect-hash collect-length
collect-sum collect-product collect-max collect-min
collect-last collect-first collect-nth collect-and collect-or
previous map-fn iterate mapping collecting-fn cotruncate
latch until until-if positions choose choose-if
spread expand mask subseries mingle catenate split split-if
producing chunk
;(5) variables
*series-expression-cache*
*last-series-loop*
*last-series-error*
*suppress-series-warnings*))
#-(or series-ansi)
(eval-when (compile load eval)
(in-package "SERIES" :use '("LISP"))
(shadow '(let let* multiple-value-bind funcall defun eval-when #+(or cmu scl) collect #+(or cmu scl) iterate))
) ; end of eval-when
#-(or series-ansi)
(cl:eval-when (compile load eval)
(defmacro eval-when ((&rest times) &body body)
`(cl:eval-when ,(append
(when (member :compile-toplevel times)
'(compile))
(when (member :load-toplevel times)
'(load))
(when (member :execute times)
'(eval)))
,@body))
) ; end of eval-when
| 9,186 | Common Lisp | .lisp | 240 | 35.758333 | 132 | 0.685154 | Bradford-Miller/CL-LIB | 1 | 0 | 1 | LGPL-3.0 | 9/19/2024, 11:28:28 AM (Europe/Amsterdam) | f1f22dce3570f44ebdc30824b4dc550c8c804cdd222a7b0ac59bf3852d5aa790 | 25,895 | [
-1
] |
25,896 | s-code.lisp | Bradford-Miller_CL-LIB/packages/SERIES/s-code.lisp | ;-*- Mode: lisp; syntax:ANSI-COMMON-LISP; Package: (SERIES :use "COMMON-LISP" :colon-mode :external) -*-
;;;; The standard version of this program is available from
;;;;
;;;; http://series.sourceforge.net/
;;;;
;;;; If you obtained this file from somewhere else, or copied the
;;;; files a long time ago, you might consider copying them from the
;;;; above web site now to obtain the latest version.
;;;; NO PATCHES TO OTHER BUT THE LATEST VERSION WILL BE ACCEPTED.
;;;;
;;;; $Id: s-code.lisp,v 1.110 2010/06/11 02:16:02 rtoy Exp $
;;;;
;;;; This is Richard C. Waters' Series package.
;;;; This started from his November 26, 1991 version.
;;;;
;;;; $Log: s-code.lisp,v $
;;;; Revision 1.110 2010/06/11 02:16:02 rtoy
;;;; Changes to make series work with ccl.
;;;;
;;;; o Remove the eval-when around the defstructs. (Could this be a bug in
;;;; ccl?) This works fine with cmucl and clisp.
;;;; o Define the generator type for ccl too.
;;;; o Remove the double definition of the foundation-series type for cmucl
;;;; and clisp. Not needed anymore with cmucl 20a and clisp 2.47.
;;;;
;;;; Revision 1.109 2010/06/04 14:21:06 rtoy
;;;; Feature request 2295778 - don't ignore fill-pointer
;;;; Patch 2298394 - patch for #2295778
;;;;
;;;; s-code.lisp:
;;;; s-test.lisp:
;;;; o Patch applied
;;;;
;;;; Revision 1.108 2008/10/27 16:25:58 rtoy
;;;; Bug 2165712: Export COLLECT-IGNORE functionality
;;;;
;;;; s-code.lisp:
;;;; o Add better docstring for COLLECT-IGNORE.
;;;;
;;;; s-package.lisp:
;;;; o Export COLLECT-IGNORE
;;;;
;;;; s-doc.txt:
;;;; o Document COLLECT-IGNORE.
;;;;
;;;; Revision 1.107 2008/10/27 14:24:53 rtoy
;;;; Support SCL. Just add scl conditionalizations where we have cmucl
;;;; ones, and convert uppercase symbols and symbol-names to use
;;;; symbol-name and uninterned symbols. This is to support scl's default
;;;; "modern" mode.
;;;;
;;;; Changes from Stelian Ionescu.
;;;;
;;;; Revision 1.106 2007/08/08 15:07:45 rtoy
;;;; Change default test for SCAN-ALIST to EQL instead of EQ.
;;;;
;;;; Revision 1.105 2007/08/08 13:36:56 rtoy
;;;; s-code.lisp:
;;;; o Update docstrings
;;;;
;;;; s-doc.txt:
;;;; o Add documentation for COLLECT-PRODUCT, COLLECT-STREAM
;;;; o Correct the documentation for COLLECT-MAX and COLLECT-MIN.
;;;;
;;;; Revision 1.104 2007/08/08 03:42:43 rtoy
;;;; s-code.lisp:
;;;; o Update docstrings with more descriptive strings.
;;;;
;;;; s-doc.txt:
;;;; o Document SCAN-STREAM.
;;;;
;;;; Revision 1.103 2007/07/31 21:14:11 rtoy
;;;; Make the #Z reader signal an error if we are trying to create an
;;;; infinite literal series. Series doesn't support that.
;;;;
;;;; Revision 1.102 2007/07/10 17:45:46 rtoy
;;;; s-code.lisp:
;;;; o Add an optimizer for SERIES and update appropriately for the normal
;;;; path and the optimized path. This is needed so that (series t nil)
;;;; returns #z(t nil t nil ...) instead of #z(list t nil list t nil ...)
;;;;
;;;; s-test.lisp:
;;;; o Add two tests for SERIES. The tests need some work, but are based
;;;; on the errors reported by Szymon 'tichy' on comp.lang.lisp on Jul 7,
;;;; 2007.
;;;;
;;;; Revision 1.101 2007/02/06 21:10:38 rtoy
;;;; Get rid of a warning message. Don't know why the warning is done at
;;;; all.
;;;;
;;;; Revision 1.100 2005/12/13 14:40:30 rtoy
;;;; Lispworks wants an eval-when around coerce-maybe-fold. From Chris
;;;; Dean, 2005/12/09.
;;;;
;;;; Revision 1.99 2005/11/15 15:07:57 rtoy
;;;; ANSI CL says a declaration cannot also be the name of a type, so
;;;; remove the declaration for SERIES.
;;;;
;;;; Revision 1.98 2005/01/27 04:19:33 rtoy
;;;; Fix for bug 434120.
;;;;
;;;; s-code.lisp:
;;;; o scan* should initialize the index to -1 instead of 0, to keep in
;;;; step with scan.
;;;;
;;;; s-test.lisp:
;;;; o Add test from the bug report.
;;;;
;;;; Revision 1.97 2005/01/26 18:37:34 rtoy
;;;; Fix bug reported by Dirk Gerrits, series-users, 2005-01-16.
;;;;
;;;; s-code.lisp:
;;;; o ALTER was not handling some cases where the frag had multiple
;;;; ALTERABLE forms that matched the var. Adjust ALTER so that all
;;;; matching alterable forms are placed in the body. This only works
;;;; for optimized series. Unoptimized series still has the bug.
;;;;
;;;; s-test.lisp:
;;;; o Add :if-exists :supersede when opening files for output.
;;;; o Add a test for the ALTER bug reported by Dirk Gerrits.
;;;;
;;;; Revision 1.96 2004/12/15 17:18:53 rtoy
;;;; Apply fixes from Hannu Koivisto to support sbcl. Also added asdf
;;;; support. His comments:
;;;;
;;;;
;;;; * series.asd:
;;;; * Initial checkin.
;;;; * series.system:
;;;; * Removed logical pathname stuff and made this "self-sufficient", i.e. it is
;;;; sufficient to just load it; no need to edit pathname translations.
;;;; * Removed s-install from series system; we certainly don't want Series to
;;;; install itself to CL-USER whenever the system is compiled/loaded.
;;;;
;;;; * s-test.lisp:
;;;; * Replaced all uses of defconstant with series::defconst-once.
;;;;
;;;; * s-package.lisp:
;;;; * sb-cltl2 module is now required at compile time too.
;;;;
;;;; * s-code.lisp:
;;;; * (defconst-once) New macro.
;;;; * Replaced all uses of defconstant with it.
;;;;
;;;; * RELEASE-NOTES:
;;;; * Installation instructions based on system definition files.
;;;; * Updated the list of contributors.
;;;; * Some cosmetic changes.
;;;;
;;;; Revision 1.95 2003/06/08 12:52:40 rtoy
;;;; From Alexey Dejneka:
;;;;
;;;; o Add support for SBCL
;;;; o Fix a missing initialization of temp.
;;;;
;;;; Revision 1.94 2003/01/21 20:12:40 rtoy
;;;; Add support for CMUCL 18e which no longer has
;;;; pcl::walk-form-macroexpand. It's walker::macroexpand-all.
;;;;
;;;; Revision 1.93 2002/12/12 04:27:41 rtoy
;;;; Add support for a macrolet code-walker for Clisp.
;;;;
;;;; Revision 1.92 2002/12/11 04:03:26 rtoy
;;;; o Update /allowed-generic-opts/ to include SYSTEM::READ-ONLY for CLISP
;;;; 2.29.
;;;; o Modify COMPUTE-SERIES-MACFORM-1 and COMPUTE-SERIES-MACFORM-2 so that
;;;; CMUCL doesn't try to dump functions directly to a FASL file. Fixes
;;;; bug 498418: cmucl doesn't like dumping functions.
;;;;
;;;; Revision 1.91 2002/12/10 19:36:32 rtoy
;;;; Previous patch failed some tests. Let's try this
;;;; again. PROMOTE-SERIES returns an extra arg telling us what it did. We
;;;; use that to decide if we want the car or not of the item.
;;;;
;;;; Revision 1.90 2002/12/10 17:55:46 rtoy
;;;; Bug [ 516952 ] only optimized split-if works
;;;;
;;;; A gross hack to fix this has been applied. The wrong things were
;;;; passed to pos-if in some situations.
;;;;
;;;; Revision 1.89 2002/06/03 17:53:14 rtoy
;;;; From Joe Marshall:
;;;;
;;;; I found a bug in `scan-fn-opt' that caused an unbound variable
;;;; when the initialization thunk in scan-fn refers to a lexical
;;;; variable, and there is a test function.
;;;;
;;;; The existing code calls `handle-fn-call' to invoke the thunks
;;;; for scanning. handle-fn-call keeps track of free variable references.
;;;; When calling it the last time, you pass in T as the last argument.
;;;;
;;;; In the case where there was a test expression, however, the
;;;; order of calling handle-fn-call changes making the *second* to last
;;;; call have the T argument, rather than the last. By re-ordering the
;;;; way scan-fn-opt expands the thunks, this is fixed.
;;;;
;;;; Revision 1.88 2002/03/29 23:53:38 rtoy
;;;; Should not macroexpand declarations? I think this is right. I think
;;;; I did it right, but needs more testing.
;;;;
;;;; Revision 1.87 2001/12/23 16:54:44 rtoy
;;;; Make series support Allegro "modern" lisp with its case-sensitive
;;;; reader. Mostly just making every that needs to be lower case actually
;;;; lower case. The tests still work.
;;;;
;;;; Revision 1.86 2001/08/31 15:51:54 rtoy
;;;; Some changes from Joe Marshall for Allegro which apparently doesn't
;;;; fold constants in coerce. These changes only apply to Allegro.
;;;;
;;;; Revision 1.85 2001/04/10 17:22:33 rtoy
;;;; o Change series printer to output items one at a time instead of
;;;; gathering up everything before printing.
;;;; o Add more detailed doc strings for some functions.
;;;;
;;;; Revision 1.84 2001/04/09 22:18:47 rtoy
;;;; o Random re-indents so I can read the code better
;;;; o The latest versions of CMUCL's PCL have a better code walker that
;;;; allows us to do a macroexpand, ala lispworks.
;;;; o For CMUCL, use its list pretty-printer for printing out series.
;;;; It looks much better. But may be a problem if the series is
;;;; infinite. We won't get any output at all. (I think the original
;;;; would produce output and just never stop.)
;;;;
;;;; Revision 1.83 2001/04/09 19:52:34 rtoy
;;;; Stupid typo commenting (too much) stuff out.
;;;;
;;;; Revision 1.82 2001/04/07 20:14:31 rtoy
;;;; o remove-aux-if was inadvertently defined twice (should have been
;;;; remove-aux-if-not)
;;;; o remove-aux-if and remove-aux-if-not don't appear to be used
;;;; anywhere, so comment them out for now. Remember to remove them
;;;; later.
;;;;
;;;; Revision 1.81 2001/04/07 15:35:51 rtoy
;;;; scan-stream didn't work when not optimized, due to a typo. The core
;;;; of scan-stream should now be identical to the core of scan-file.
;;;;
;;;; Revision 1.80 2000/10/10 21:03:12 rtoy
;;;; Oops. It's cl:let, not just plain let.
;;;;
;;;; Revision 1.79 2000/10/10 15:02:27 rtoy
;;;; Fix up the lifting code to handle all variables except #:SEQ.
;;;; (There's some code in collect that initializes a SEQ var with (if SEQ
;;;; SEQ <do something else>), which I can't lift up because then SEQ would
;;;; be undefined.)
;;;;
;;;; Change the default for *lift-out-vars-p* to be T.
;;;;
;;;; Revision 1.78 2000/10/07 20:02:10 rtoy
;;;; Comment and clean up code added in previous update.
;;;;
;;;; Revision 1.77 2000/10/06 23:03:01 rtoy
;;;; First cut at trying to lift some variable initializations into the
;;;; enclosing LET.
;;;;
;;;; Basically, we look for something like
;;;;
;;;; (let (out-1 out-2)
;;;; (setq out-1 <init-1>)
;;;; (setq out-2 <init-2>)
;;;; <stuff>)
;;;;
;;;; and try to convert that to
;;;;
;;;; (let ((out-1 <init-1>) (out-2 <init-2>))
;;;; <stuff>)
;;;;
;;;; right after series has completed all of the macroexpansions it wants.
;;;;
;;;; Because this may be buggy, you can enable this feature by setting
;;;; *lift-out-vars-p* to T. It defaults to NIL.
;;;;
;;;; Note: this can cause CMUCL sometimes to produce a compile warning
;;;; that constant folding failed. (Often caused by trying to compute
;;;; array-total-size of a known constant list.)
;;;;
;;;; Revision 1.76 2000/10/01 23:07:28 rtoy
;;;; o Add some comments.
;;;; o Add a template for LOCALLY. (MCL works now!!!!)
;;;; o Move the OPTIF macro before it's first use in EOPTIF-Q. Seems that
;;;; this is required according to the CLHS. (Noticed by Rainer Joswig.)
;;;;
;;;; Thanks to Rainer for testing this on MCL. MCL passes all of the
;;;; tests!
;;;;
;;;; Revision 1.75 2000/09/30 21:44:41 rtoy
;;;; Bug #115738:
;;;;
;;;; Use remove-if-not instead of delete-if-not in delete-aux-if-not. This
;;;; was causing CLISP to fail test 530.
;;;;
;;;; (I'm not sure about this. It seems there's some shared list structure
;;;; with CLISP that doesn't happen in CMUCL. However, I think it's safe
;;;; to cons up a new list instead of destructively modifying the
;;;; original.)
;;;;
;;;; Revision 1.74 2000/09/05 15:54:09 rtoy
;;;; Fix bug 113625: scan doesn't scan constants very well.
;;;;
;;;; Solution: If it's a symbol, take the value of the symbol. (Not sure
;;;; this is quite correct, but it works and the other tests pass without
;;;; problems.)
;;;;
;;;; Revision 1.73 2000/06/26 18:11:26 rtoy
;;;; Fix for bug #108331: collect 'vector sometimes returns results in
;;;; reverse order. Example is (collect 'vector (scan '(1 2 3))).
;;;;
;;;; Revision 1.72 2000/06/26 15:28:19 rtoy
;;;; DECODE-SEQ-TYPE was getting BASE-STRING and STRING mashed together,
;;;; and didn't even handle BASE-STRING. They are slightly different:
;;;; BASE-STRING is composed of BASE-CHAR's and STRING is composed of
;;;; CHARACTER's.
;;;;
;;;; Revision 1.71 2000/03/28 10:23:49 matomira
;;;; polycall et all are now tail recursive.
;;;; LETIFICATION WORKS COMPLETELY!!
;;;;
;;;; Revision 1.86 2000/03/28 10:19:04 matomira
;;;; polycall et al. are now tail recursive.
;;;; LETIFICATION WORKS COMPLETELY!
;;;;
;;;; Revision 1.85 2000/03/27 17:21:14 matomira
;;;; Fixed eval-on-first-cycle for letification.
;;;; Improved clean-code so it does not miss completely unused variables.
;;;;
;;;; Revision 1.83 2000/03/25 21:44:26 matomira
;;;; Avoided gratuitous consig in values-lists.
;;;;
;;;; Revision 1.80 2000/03/23 23:01:56 matomira
;;;; NEW FEATURES:
;;;; ------------
;;;; - (collect 'set
;;;; Collects a series into a list removing any duplicates in the most efficient way possible.
;;;; - (collect 'ordered-set
;;;; Collects a series into a list removing any duplicates but keeping the original series order.
;;;; - SCAN now allows to drop the type specifier for any source expression
;;;; [:cltl2-series reactivates the old 'list assumption]
;;;; - SCAN now can scan multidimensional arrays in row-major order.
;;;;
;;;; IMPROVEMENTS:
;;;; ------------
;;;; - Better code generation
;;;; . Some fixnum declarations were further constrained.
;;;; . Optimized scanning of constant sequences.
;;;; . Somewhat optimized scanning of "empty" vectors, ie,
;;;; declared to be of constant 0 length, like in
;;;; (collect (scan '(vector t 0) <gimme-a-huge-array-to-throw-away>)
;;;; now gives you NIL generating/executing less instructions.
;;;; [<gimme-a-huge-array-to-throw-away> is still executed if not constantp,
;;;; though]
;;;; . Variables of type NULL are replaced by constant NILs.
;;;;
;;;; BUG FIXES:
;;;; ---------
;;;; - Some incorrect fixnum declarations were relaxed.
;;;; - Improved some declarations to avoid spurious range warnings regarding
;;;; dead code by not-so-smart compilers.
;;;;
;;;; Revision 1.79 2000/03/21 17:18:56 matomira
;;;; Reinstated plain generation support.
;;;;
;;;; Revision 1.78 2000/03/21 15:26:12 matomira
;;;; Fixed letified merge-frags bug.
;;;; Adapted handle-dflow and non-series-merge for letification.
;;;; Spawned list->frag1 from list->frag.
;;;; define-optimizable-series-function uses list->frag1 to support letification.
;;;; Still can't handle all initial bindings because off-line handling seems to
;;;; move prologs into TAGBODYs.
;;;;
;;;; Revision 1.75 2000/03/18 20:12:52 matomira
;;;; Improved code generated by compute-series-macform-2 when trigger is t.
;;;;
;;;; Revision 1.74 2000/03/18 19:14:45 matomira
;;;; Improved merging when letified.
;;;; Last version with series library definitions not requiring letification.
;;;;
;;;; Revision 1.73 2000/03/18 18:05:24 matomira
;;;; Full letification works.
;;;;
;;;; Revision 1.72 2000/03/17 19:24:23 matomira
;;;; MERGE-FRAGS no longer depends on frag component order.
;;;; purity component of frag is now just a symbol.
;;;; Abstracted use of prolog component of frags.
;;;; Prolog letification almost works. Need to adapt MERGE-FRAGS still.
;;;;
;;;; Revision 1.71 2000/03/15 18:40:35 matomira
;;;; LOCALLY and letification works.
;;;;
;;;; Revision 1.70 2000/03/15 09:05:39 matomira
;;;; Temporary NULL-OR wrap for some declarations.
;;;;
;;;; Revision 1.69 2000/03/14 10:48:09 matomira
;;;; Workaround for ACL 5.0.1 TAGBODY bug added.
;;;; ALL-TIME SERIES BUG FIX: wrappers now inserted more precisely.
;;;; Abstracted use of wrapper component of frags.
;;;; GENERATOR deftyped to CONS, not LIST, when necessary.
;;;;
;;;; Revision 1.68 2000/03/11 17:36:33 matomira
;;;; Added eval-when compatibility magic.
;;;;
;;;; Revision 1.67 2000/03/11 15:35:44 matomira
;;;; Fixed worsen-purity.
;;;;
;;;; Revision 1.66 2000/03/10 12:49:27 matomira
;;;; Letification works.
;;;; Started purity analysis.
;;;;
;;;; Revision 1.65 2000/03/09 13:28:03 matomira
;;;; Almost there with letification.
;;;; Activated GENERATOR deftype also for :excl.
;;;;
;;;; Revision 1.64 2000/03/08 18:20:35 matomira
;;;; Fixed fragL instead of *fragL bug in COLLECT.
;;;;
;;;; Revision 1.63 2000/03/08 17:58:24 matomira
;;;; Fixed mixed CL: before FUNCALL in DESTARRIFY.
;;;;
;;;; Revision 1.62 2000/03/08 12:30:53 matomira
;;;; Continued work on letification.
;;;;
;;;; Revision 1.61 2000/03/07 13:47:23 matomira
;;;; Removed gratuitous sorting in CODIFY.
;;;;
;;;; Revision 1.60 2000/03/07 08:54:20 matomira
;;;; Abstracted all uses of a frag's aux component.
;;;;
;;;; Revision 1.59 2000/03/06 18:24:35 matomira
;;;; Replaced IF by WHEN in non-output code when possible.
;;;; Abstracted use of aux frag field.
;;;;
;;;; Revision 1.58 2000/03/06 12:33:14 matomira
;;;; Simplified inserted aux var initialization.
;;;;
;;;; Revision 1.57 2000/03/06 12:11:53 matomira
;;;; Fixed declaration handling in GATHERING.
;;;;
;;;; Revision 1.56 2000/03/05 16:21:56 matomira
;;;; Fixed missing CL: before FUNCALL bug.
;;;; Removed NULL-ORs by using THE.
;;;; Renamed old fragL as *fragL.
;;;; New fragL does not do *type* substitution.
;;;;
;;;; Revision 1.55 2000/03/03 19:17:14 matomira
;;;; Series 2.0 - Change details in RELEASE-NOTES.
;;;;
;;;; Revision 1.51 2000/02/23 15:27:02 toy
;;;; o Fernando added an indefinite-extent declaration and uses
;;;; it in the one place where it's needed.
;;;; o Fernando renamed split-assignment to detangle2 and
;;;; corrected some bugs in my version.
;;;;
;;;; Revision 1.50 2000/02/22 23:37:22 toy
;;;; Remove the cmu version from scan-range. It was generating bad
;;;; initialization code for things like (scan-range :length 10 :type
;;;; 'single-float).
;;;;
;;;; Revision 1.49 2000/02/22 22:25:51 toy
;;;; o One of Fernando's uses of dynamic-extent was wrong, as Fernando
;;;; points out.
;;;;
;;;; o CLISP apparently has a bug in loop such that split-assignment is
;;;; broken. Replace that with an equivalent do loop.
;;;;
;;;; Revision 1.48 2000/02/22 15:21:38 toy
;;;; Fernando added dynamic-extent declarations wherever needed.
;;;;
;;;; Revision 1.47 2000/02/11 14:45:42 toy
;;;; Let's not use fix-types for CMU in optimize-producing. This means the
;;;; compiler can't optimize things as well as it could, and I (RLT) want
;;;; to see these warnings.
;;;;
;;;; Revision 1.46 2000/02/10 17:15:11 toy
;;;; Fix a typo that got in the last few patches: LET should really be
;;;; CL:LET. (From Fernando.)
;;;;
;;;; Revision 1.45 2000/02/09 22:46:00 toy
;;;; Changed all occurrences of defunique to be just defun and added a
;;;; comment on where the function is called.
;;;;
;;;; Revision 1.44 2000/02/08 17:08:36 toy
;;;; o As discussed with Fernando, the "optional" type is renamed to
;;;; null-or.
;;;; o Cleaned up and indented some of the comments.
;;;;
;;;; Revision 1.43 2000/02/04 23:05:57 toy
;;;; A few more changes from Fernando:
;;;;
;;;; o All functions called from a single site are defined with DEFUNIQUE
;;;; for documentation purposes (and eventual inlining via DEFEMBEDDED).
;;;; o Fixed the long standing bug that install uninterned everything that
;;;; it didn't like. Shadowing import is used now.
;;;;
;;;; There were some other changes that I (RLT) don't understand.
;;;;
;;;; Revision 1.41 2000/02/04 16:34:30 toy
;;;; o Some more changes from Fernando. This fixes some bugs that show up
;;;; in the test suite. The test suite now passes on CMUCL.
;;;;
;;;; o Fixed up some declarations that used the optional type when, in
;;;; fact, it didn't. (Hope I got these all right.)
;;;;
;;;; Revision 1.40 2000/02/03 17:30:08 toy
;;;; Two major fixes:
;;;;
;;;; o Bug in collect (missing set of parens)
;;;; o Change some defconstants back to defvar. (Tickles CMUCL inf loop).
;;;;
;;;; Revision 1.39 2000/02/02 21:31:44 toy
;;;; Here are the changes that Fernando made. I (RLT) don't claim to
;;;; understand everything that was changed or why.
;;;;
;;;; 1. Removed 1 redundant eval-when
;;;; 2. Sorted functions so that it can be loaded w/o `undefined function'
;;;; warnings.
;;;; 3. Added inline declarations for all functions called from a single
;;;; site.
;;;; 4. Sorted functions so that inlining will work even if a compiler does
;;;; not inline forward references to functions defined in the same
;;;; file.
;;;; 5. Setup eval-when's so that it can be compiled w/o having to load the
;;;; source first.
;;;; 6. Simplified redundant (OR NULL T) to T
;;;; 7. Simplified redundant #'(lambda (x) (foo x)) to #'foo where foo is a
;;;; function.
;;;; 8. Fixed so it won't complain when LispWorks adds
;;;; CLOS::VARIABLE-REBINDING declarations after CLOS macro
;;;; transformations (general support provided via the constant
;;;; allowed-generic-opts).
;;;; 9. Added support for MACROLET on LispWorks (necessary because of CLOS
;;;; macro transformations).
;;;; 10. Only declare variables as (OR foo NULL) on implementations that
;;;; won't allow to store NIL otherwise (currently, only CMUCL).
;;;; 11. Added specialization to series declarations (eg: (SERIES FIXNUM)).
;;;; 12. Do more precise type propagation in PRODUCING forms.
;;;; 13. Allow `SETF like SETQ' in PRODUCING forms.
;;;; 14. Added COLLECT-PRODUCT.
;;;; 15. Extended SETQ-P to take into account multiassignments (not used
;;;; yet). This should still be trivially generalized to support PSETQ
;;;; and SETF, BTW.
;;;; 16. Added DEFTYPE for GENERATOR so that LispWorks and CMUCL won't
;;;; complain "because it's not a list" (IT IS!!)
;;;; 17. Replaced PROCLAIMS with DECLAIMS.
;;;; 18. Replaced DEFVARs with DEFCONSTANTs where appropriate.
;;;; 19. Removed function namespace pollution by defS-generated code.
;;;;
;;;; Revision 1.38 2000/01/20 18:19:21 toy
;;;; Merged 1.32.2.2 (Fernando's changes) with 1.37.
;;;; I hope I got this right.
;;;;
;;;; Revision 1.32.2.2 2000/01/20 18:05:26 toy
;;;; Merged the changes between 1.32 and 1.37 into this revision.
;;;; This should merge my changes with Fernando's.
;;;;
;;;; Revision 1.32.2.1 2000/01/20 17:51:45 toy
;;;; Checking in the changes from Fernando Mato Mira <[email protected]>
;;;; with the hope of merging our two versions together.
;;;;
;;;; Revision 1.32 1999/07/02 20:37:39 toy
;;;; Moved the package stuff out to a separate file.
;;;;
;;;; Revision 1.31 1999/07/02 15:09:49 toy
;;;; o Need explicit package qualifier for multiple-value-bind in
;;;; init-elem.
;;;; o Reordered some of the tests in init-elem.
;;;;
;;;; Revision 1.30 1999/07/01 16:44:23 toy
;;;; A comment was in the wrong place.
;;;;
;;;; Revision 1.29 1999/07/01 14:15:39 toy
;;;; o "Pekka P. Pirinen" <[email protected]> supplied a new version
;;;; of aux-init (and init-elem). This is probably better. I added one
;;;; additional case.
;;;;
;;;; o Added simple-base-string to the tests in decode-seq-type. (Needed
;;;; by the new aux-init.
;;;;
;;;; Revision 1.28 1999/06/30 19:34:49 toy
;;;; "Pekka P. Pirinen" <[email protected]> says:
;;;;
;;;; "Tests 289, 290, 417, and 426 [on Liquid CL] fail because of
;;;; incorrect type decls generated in ADD-PHYSICAL-OUT-INTERFACE.
;;;; The variable NEW-OUT is used for two conflicting purposes; The
;;;; fix is to split it into two."
;;;;
;;;; Thanks!
;;;;
;;;; Revision 1.27 1999/04/29 22:06:49 toy
;;;; Fix some problems in aux-init not handling some strings and
;;;; bit-vectors correctly.
;;;;
;;;; Revision 1.26 1999/04/23 17:51:24 toy
;;;; For CMUCL, decode-seq-type didn't handle base-string types. Make it
;;;; work.
;;;;
;;;; In aux-init, change the test for simple-string to be string instead.
;;;;
;;;; Revision 1.25 1999/04/15 17:09:41 toy
;;;; Rework aux-init once again. The bit-vector entry goes away, and the
;;;; entry for vector and simple-array are changed to create the proper
;;;; types when the length is not given. I hope this is the last change
;;;; here! :-)
;;;;
;;;; Revision 1.24 1999/04/15 16:35:54 toy
;;;; In aux-init, the bit-vector entry is actually applicable to all Lisps
;;;; because bit-vectors would get initialized to #() instead of #*, which
;;;; is wrong. Remove the CMU conditionalization.
;;;;
;;;; Revision 1.23 1999/04/13 16:51:32 toy
;;;; o Back up the gensym changes made in 1.21 because CLISP doesn't like
;;;; it.
;;;; o type-expand for CLISP is in the LISP package.
;;;; o For CMUCL, in aux-init need to check for bit-vector before
;;;; simple-array because simple-bit-vector was done as simple-array
;;;; instead of bit-vector, which is wrong.
;;;;
;;;; Revision 1.22 1999/04/09 12:32:26 toy
;;;; Add definition of canonical-type for CLISP.
;;;;
;;;; Revision 1.21 1999/04/08 21:46:08 toy
;;;; Use gensym instead of gentemp, which is deprecated in ANSI CL.
;;;;
;;;; Revision 1.20 1999/04/08 21:41:16 toy
;;;; Add CLISP to the Series-ANSI. Then need to import COMPILER-LET.
;;;;
;;;; In aux-init, the bit-vector entry is only for CMUCL which
;;;; canonicalizes (vector bit) into bit-vector.
;;;;
;;;; Revision 1.19 1999/04/06 18:36:13 toy
;;;; Some fixes from Arthur Lemmens <[email protected]>:
;;;; MAKE-SEQUENCE was being called with things like (BIT-VECTOR BIT) and
;;;; (STRING STRING-CHAR). Change DECODE-SEQ-TYPE to convert BIT-VECTOR's
;;;; and STRING's to the the underlying array types. Also change
;;;; STRING-CHAR to CHARACTER.
;;;;
;;;; This change necessitates adding a BIT-VECTOR case in AUX-INIT. (This
;;;; is probably only need by CMUCL where CANONICAL-TYPE actually does
;;;; something.)
;;;;
;;;; Revision 1.18 1998/06/12 20:45:23 toy
;;;; An addition to scan-hash for CLISP. This reduces consing and should
;;;; be at least as fast. From Bruno Haible.
;;;;
;;;; Also, defstruct alter-fn needs to be defined twice for CLISP and
;;;; probably also for CMUCL. From Brun Haible.
;;;;
;;;; Revision 1.17 1998/06/10 18:59:51 toy
;;;; Fixed long-standing bug in scan-range where the initial values of the
;;;; loop variables didn't match the specified :type. I'm not sure this is
;;;; the correct solution, but it seems to produce the desired macro
;;;; expansions. I would be interested in a better solution, if possible.
;;;;
;;;; Revision 1.16 1998/06/08 17:34:59 toy
;;;; Couple of small changes for CLISP.
;;;;
;;;; Revision 1.15 1998/05/26 16:23:25 toy
;;;; One last fix from Reginald: Don't make series a declaration. With
;;;; this fix, this should now run correctly for lispworks.
;;;;
;;;; Revision 1.14 1998/05/24 19:19:22 toy
;;;; Fixes from Reginald S. Perry were incompletely applied: Forgot to
;;;; import compiler-let and messed up a fix for uninterning SERIES for
;;;; Harlequin.
;;;;
;;;; Revision 1.13 1998/05/21 15:18:27 toy
;;;; Added a few fixes from "Reginald S. Perry" <[email protected]> to make
;;;; this work with LWW.
;;;;
;;;; Revision 1.12 1997/10/02 13:36:45 toy
;;;; Forgot to export scan-stream.
;;;;
;;;; Revision 1.11 1997/10/02 13:25:18 toy
;;;; Added canonical-type function to extract out the "real" type if
;;;; something has been deftype'd. Changed code to support this new
;;;; function.
;;;;
;;;; Do a better job in decode-seq-type. Needed for CMUCL to complain
;;;; less.
;;;;
;;;; Added scan-stream series function. Just like scan-file, except that
;;;; we have a stream instead of a file name.
;;;;
;;;; Revision 1.10 1997/01/16 14:38:27 toy
;;;; Took out part of Tim's last change: Removed tests for :defpackage
;;;; feature. Gcl with M. Kantrowitz's defpackage doesn't work and I'm too
;;;; lazy to figure out why.
;;;;
;;;; Revision 1.9 1997/01/16 14:26:44 toy
;;;; Some more patches from Tim ([email protected]): Conditionalize on
;;;; :defpackage too for package stuff.
;;;;
;;;; Revision 1.8 1997/01/16 14:23:59 toy
;;;; Put in changes from Tim ([email protected]) to conditionalize on
;;;; Series-ANSI.
;;;;
;;;; Revision 1.7 1997/01/16 14:20:23 toy
;;;; GCL normally doesn't have defpackage, so don't use defpackage form.
;;;; It also doesn't have a "CL" package, so rename "LISP" to
;;;; "COMMON-LISP" with appropriate nicknames.
;;;;
;;;; Revision 1.6 1997/01/13 17:47:19 toy
;;;; Added some changes from Tim Bradshaw ([email protected]):
;;;; Replace "LISP:" with "CL:"
;;;; Added :import-from for Genera and Allegro.
;;;; With these changes, everything still works under CMUCL.
;;;;
;;;; Revision 1.5 1997/01/13 16:04:11 toy
;;;; Don't install the package on load. Let the user do it himself.
;;;;
;;;; Revision 1.4 1997/01/10 22:37:03 toy
;;;; A patch from Tim Bradshaw that fixes a bug. The code walker
;;;; improperly handles nth-value. Doesn't seem to have any affect in
;;;; CMUCL but can be seen in others like lispm.
;;;;
;;;; Revision 1.3 1997/01/07 19:09:30 toy
;;;; Changed aux-init to initialize variables better. I think it handles
;;;; just about all cases now.
;;;;
;;;; Modified clean-dcls to handle simple-arrays.
;;;;
;;;; Changed collect so that it handles types better by passing the correct
;;;; type to fragL. This allows better optimization by the compiler (at
;;;; least for CMUCL).
;;;;
;;;; Added code at the end so that the package is installed whenever it's
;;;; loaded. You don't have to explicitly install the package anymore.
;;;; However, there's a bug: It assumes you were originally in the USER
;;;; package. This needs to be fixed.
;;;;
;;;; Revision 1.2 1997/01/07 18:58:51 toy
;;;; Changes from Paul Werkowski to make series work/run under CMUCL.
;;;; Raymond Toy added the defpackage stuff. There are probably other
;;;; changes here, but I wasn't careful to keep everything straight,
;;;; unfortunately.
;;;;
;;;;
;------------------------------------------------------------------------
;;;; Copyright Massachusetts Institute of Technology, Cambridge, Massachusetts.
;;;; Permission to use, copy, modify, and distribute this software and
;;;; its documentation for any purpose and without fee is hereby
;;;; granted, provided that this copyright and permission notice
;;;; appear in all copies and supporting documentation, and that the
;;;; name of M.I.T. not be used in advertising or publicity pertaining
;;;; to distribution of the software without specific, written prior
;;;; permission. M.I.T. makes no representations about the suitability
;;;; of this software for any purpose. It is provided "as is" without
;;;; express or implied warranty.
;;;; M.I.T. DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
;;;; INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
;;;; FITNESS, IN NO EVENT SHALL M.I.T. BE LIABLE FOR ANY SPECIAL,
;;;; INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER
;;;; RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
;;;; ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
;;;; ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
;;;; OF THIS SOFTWARE.
;;;;------------------------------------------------------------------------
;;;; This file implements efficient computation with series
;;;; expressions in Common Lisp. The functions in this file
;;;; are documented in Appendices A and B of Common Lisp: the Language,
;;;; Second Edition, Guy L. Steele Jr, Digital press, 1990,
;;;; and in even greater detail in
;;;; MIT/AIM-1082 and MIT/AIM-1083 both dated December 1989
;;;; These reports can be obtained by writing to:
;;;;
;;;; Publications
;;;; MIT AI Laboratory
;;;; 545 Tech. Sq.
;;;; Cambridge MA 02139
;;;; This file attempts to be as compatible with standard Common Lisp
;;;; as possible. It has been tested on the following Common Lisps to
;;;; date (1/18/89).
;;;;
;;;; Symbolics CL version 8.
;;;; LUCID CL version 3.0.2 on a sun.
;;;; Allegro CL version 1.2.1 on a Macintosh.
;;;; LispWorks CL version 2.1.
;;;;
;;;; This version has been tested on
;;;;
;;;; CMUCL 18b
;;;; Lispworks CL
;;;; Allegro CL 5.0
;;;;
;;;; The companion file "STEST.LISP" contains several hundred tests.
;;;; You should run these tests after the first time you compile this
;;;; file on a new system.
;;;;
;;;; The companion file "SDOC.TXT" contains brief documentation.
#+(and series-ansi)
(in-package :series)
#-(or series-ansi)
(eval-when (compile load eval)
(in-package "SERIES")
) ; end of eval-when
(eval-when (:compile-toplevel :load-toplevel :execute)
(defvar *suppress-series-warnings* nil
"Suppress warnings when the restrictions are violated.")
(defvar *series-expression-cache* t
"Avoids multiple expansions")
(defvar *last-series-loop* nil
"Loop most recently created by SERIES.")
(defvar *last-series-error* nil
"Info about error found most recently by SERIES.")
;(pushnew :series-plain *features*)
;;; END OF TUNABLES
(defmacro defconst-once (name value &optional documentation)
"Like `defconstant' except that if the variable already has a
value, the old value is not clobbered."
`(defconstant ,name (if (boundp ',name) (symbol-value ',name) ,value)
,@(when documentation (list documentation))))
;; SERIES::INSTALL changes this
(defvar *series-implicit-map* nil
"T enables implicit mapping in optimized expressions")
(defconst-once /ext-conflicts/
#+(or cmu scl) '(collect iterate)
#+allegro-v6.1 '(until)
#-(or cmu scl allegro-v6.1) '())
(defconst-once /series-forms/
'(let let* multiple-value-bind funcall defun)
"Forms redefined by Series.")
#+:gcl
(declaim (declaration dynamic-extent)) ; Man, is GCL broken!
(declaim (declaration indefinite-extent))
(declaim (declaration optimizable-series-function off-line-port
propagate-alterability))
) ; end of eval-when
;;; Generic stuff that should be moved to/imported from EXTENSIONS
;; mkant EXTENSIONS should push :EXTENSIONS in *FEATURES*!!!
(cl:defun atom-or-car (x)
(if (listp x)
(car x)
x))
(cl:defun array-fill-pointer-or-total-size (seq)
(if (array-has-fill-pointer-p seq)
(fill-pointer seq)
(array-total-size seq)))
(eval-when (:compile-toplevel :load-toplevel :execute)
(deftype nonnegative-fixnum ()
`(mod ,most-positive-fixnum))
(deftype nonnegative-integer ()
`(integer 0))
(deftype positive-integer ()
`(integer 1))
(deftype -integer (m &optional (n nil) (under 1))
`(integer ,(- m under) ,@(when n `(,n))))
(deftype integer+ (m &optional (n nil) (over 1))
`(integer ,m ,@(when n `(,(+ n over)))))
(deftype integer- (m &optional (n nil) (over 1))
`(integer ,m ,@(when n `(,(- n over)))))
(deftype -integer- (m &optional (n nil) (over 1) (under 1))
`(integer ,(- m under) ,@(when n `(,(- n over)))))
(deftype mod+ (n &optional (over 1))
`(mod ,(+ n over)))
(deftype null-or (&rest types)
`(or null ,@types))
(deftype uninitialized (typ)
`(null-or ,typ))
(deftype defaulted (typ)
`(null-or ,typ))
(deftype -vector-index ()
`(-integer- 0 ,array-total-size-limit))
(deftype vector-index ()
`(integer- 0 ,array-total-size-limit))
(deftype vector-index+ ()
`(integer 0 ,array-total-size-limit))
(deftype -vector-index+ ()
`(-integer 0 ,array-total-size-limit))
#-:extensions
(progn
(defmacro when-bind ((symbol predicate) &body body)
"Binds the symbol to predicate and executes body only if predicate
is non-nil."
`(cl:let ((,symbol ,predicate))
(when ,symbol
,@body)))
(defmacro bind-if ((symbol predicate) then &optional else)
"Binds the symbol to predicate and executes body only if predicate
is non-nil."
`(cl:let ((,symbol ,predicate))
(if ,symbol
,then
,@(when else `(,else)))))
(defmacro bind-if* ((symbol predicate) then &body else)
"Binds the symbol to predicate and executes body only if predicate
is non-nil."
`(cl:let ((,symbol ,predicate))
(if ,symbol
,then
,@(when else
`(,(if (cdr else)
`(progn ,@else)
else))))))
) ; end of progn
;; DEBUG
(defmacro definline (&rest args) `(cl:defun ,@args))
;; Define an inline function
;; Comment out the #+:ignore line to inline stuff
#+:ignore
(defmacro definline (name &rest args)
`(progn
(declaim (inline ,name))
(cl:defun ,name ,@args)))
(cl:defun eq-car (thing item)
(and (consp thing) (eq (car thing) item)))
(cl:defun copy-list-last (orig)
(if orig
(cl:let* ((lastcons (list nil))
(lst lastcons))
(do ((remains orig (cdr remains)))
((not (consp remains)) (values (cdr lst) (rplacd lastcons remains)))
(setq lastcons (setf (cdr lastcons) (cons (car remains) nil)))))
(values nil nil)))
(cl:defun nmerge-1 (l1 l2)
(do ((x l1 (cdr x))
(y l2 (cdr y))
z)
((or (endp x) (endp y)) (when (endp x) (rplacd z y)))
(rplaca x (nconc (car x) (car y)))
(setq z x))
l1)
(cl:defun nmerge (l1 l2)
(cond ((null l1) l2)
((null l2) l1)
(t (nmerge-1 l1 l2))))
(cl:defun noverlap (n l1 l2)
"Overlap l2 over the last n components of n1."
(cond ((eql n 0) (nconc l1 l2))
((null l1) l2)
(t
(cl:let ((n1 (length l1)))
(if (<= n n1)
(cl:let ((l (last l1 n)))
(nmerge-1 l l2)
l1)
(cl:let* ((n2 (length l2))
(nt (+ n1 n2)))
(cond ((>= n nt) (nconc l2 (make-list (- n nt)) l1))
(t
(cl:let ((l (nthcdr (- n n1) l2)))
(do ((x l (cdr x))
(y l1 (cdr y))
z)
((or (endp x) (endp y)) (when (endp x) (rplacd z y)))
(rplaca x (nconc (car y) (car x)))
(setq z x)))))
l2))))))
(cl:defun n-gensyms (n &optional (root (symbol-name '#:g)))
"Generate n uninterned symbols with basename root"
(do ((i n (1- i))
(l nil (cons (gensym root) l)))
((zerop i) l)))
(defmacro valuate (&rest args)
`(cl:multiple-value-call #'values ,@args))
(defmacro multiple-value-setf (places vals)
(cl:let* ((n (length places))
(vars (n-gensyms n)))
`(cl:multiple-value-bind ,vars ,vals
(values
,@(mapcar #'(lambda (p v) `(setf ,p ,v)) places vars)))))
#+:ignore
(cl:defun polyapply (fun args)
(declare (dynamic-extent args))
(if args
(cl:let ((d (cdr args)))
(if d
(valuate (cl:funcall fun (car args)) (polyapply fun (cdr args)))
(cl:funcall fun (car args))))
(values)))
(cl:defun polyapply (fun args)
(declare (dynamic-extent args))
(cl:labels ((polyapply-1 (args &rest results)
(declare (dynamic-extent args results))
(cl:let ((d (cdr args)))
(if d
(cl:multiple-value-call #'polyapply-1
d
(values-list results) (cl:funcall fun (car args)))
(valuate (values-list results) (cl:funcall fun (car args)))))))
(if args
(polyapply-1 args)
(values))))
(declaim (inline polycall))
(cl:defun polycall (fun &rest args)
(declare (dynamic-extent args))
(polyapply fun args))
(defmacro multiple-value-polycall (fun vals)
`(cl:multiple-value-call #'polycall ,fun ,vals))
(cl:defun 2mapcar (fun orig)
(if orig
(cl:let* ((lastcons1 (list nil))
(lastcons2 (list nil))
(lst1 lastcons1)
(lst2 lastcons2))
(do ((remains orig (cdr remains)))
((not (consp remains)) (values (cdr lst1) (cdr lst2)))
(multiple-value-setq (lastcons1 lastcons2)
(multiple-value-setf ((cdr lastcons1) (cdr lastcons2))
(multiple-value-polycall #'list
(cl:funcall fun (car remains)))))))
(values nil nil)))
(cl:defun 3mapcar (fun orig)
(if orig
(cl:let* ((lastcons1 (list nil))
(lastcons2 (list nil))
(lastcons3 (list nil))
(lst1 lastcons1)
(lst2 lastcons2)
(lst3 lastcons3))
(do ((remains orig (cdr remains)))
((not (consp remains)) (values (cdr lst1) (cdr lst2) (cdr lst3)))
(multiple-value-setq (lastcons1 lastcons2 lastcons3)
(multiple-value-setf ((cdr lastcons1) (cdr lastcons2) (cdr lastcons3))
(multiple-value-polycall #'list
(cl:funcall fun (car remains)))))))
(values nil nil nil)))
(cl:defun 2mapcan (fun orig)
(if orig
(cl:let* ((lastcons1 (list nil))
(lastcons2 (list nil))
(lst1 lastcons1)
(lst2 lastcons2))
(do ((remains orig (cdr remains)))
((not (consp remains)) (values (cdr lst1) (cdr lst2)))
(multiple-value-setq (lastcons1 lastcons2)
(multiple-value-polycall
#'last
(multiple-value-setf ((cdr lastcons1) (cdr lastcons2))
(multiple-value-polycall #'list
(cl:funcall fun (car remains))))))))
(values nil nil)))
(cl:defun 3mapcan (fun orig)
(if orig
(cl:let* ((lastcons1 (list nil))
(lastcons2 (list nil))
(lastcons3 (list nil))
(lst1 lastcons1)
(lst2 lastcons2)
(lst3 lastcons3))
(do ((remains orig (cdr remains)))
((not (consp remains)) (values (cdr lst1) (cdr lst2) (cdr lst3)))
(multiple-value-setq (lastcons1 lastcons2 lastcons3)
(multiple-value-polycall
#'last
(multiple-value-setf ((cdr lastcons1) (cdr lastcons2) (cdr lastcons3))
(multiple-value-polycall #'list
(cl:funcall fun (car remains))))))))
(values nil nil nil)))
(cl:defun nsubst-inline (new-list old list &optional (save-spot nil))
(cl:let ((tail (member old list)))
(cond ((not tail) old)
(save-spot (rplacd tail (nconc new-list (cdr tail))))
(new-list (rplaca tail (car new-list))
(rplacd tail (nconc (cdr new-list) (cdr tail))))
((cdr tail) (rplaca tail (cadr tail))
(rplacd tail (cddr tail)))
(t (setq list (nbutlast list)))))
list)
;;Making unique variables.
;;Each call on this uses a different atom, so that you can tell
;;where a given variable came from when debugging.
(cl:defun new-var (atom)
(cl:let ((root (string atom)))
(when (not (eql (aref root (1- (length root))) #\-))
(setq root (concatenate 'string root "-")))
(gensym root)))
(cl:defun contains-p (item thing)
(do ((tt thing (cdr tt)))
((not (consp tt)) (eq tt item))
(when (contains-p item (car tt))
(return t))))
(cl:defun contains-any (items thing)
(do ((tt thing (cdr tt)))
((not (consp tt)) (member tt items))
(when (contains-any items (car tt))
(return t))))
;; some Common Lisps implement copy-tree tail recursively.
(cl:defun iterative-copy-tree (tree)
(if (not (consp tree))
tree
(prog (tail result ptr)
(setq tail (cdr tree))
(setq result (cons (iterative-copy-tree (car tree)) nil))
(setq ptr result)
L (when (not (consp tail))
(rplacd ptr tail)
(return result))
(rplacd ptr (cons (iterative-copy-tree (car tail)) nil))
(setq ptr (cdr ptr))
(setq tail (cdr tail))
(go L))))
;; Detangle a list into the odd positions, what is left from the
;; last odd position on, and the even positions [the first position
;; is 1]. (The list actually looks like a property list. We return
;; a list of the properties, a list of the last property/value pair,
;; and a list of values of the properties.
#+nil ; CLISP has bug in loop (?) and doesn't like this.
(cl:defun detangle2 (args)
(loop for d in args by #'cddr as b on args by #'cddr
collect d into vars
when (not (null (cdr b)))
collect (cadr b) into binds
finally (return (values vars b binds))))
(cl:defun detangle2 (args)
(cl:let ((vars '())
(binds '())
(lastbind '())
(more (cdr args)))
(if (null more)
(values args args nil)
(do* ((var-list args (cddr var-list))
(bind-list more (cdr var-list)))
((endp bind-list)
(values (nreverse vars)
(if (endp var-list) lastbind (cddr lastbind))
(nreverse binds)))
(setq lastbind var-list)
(push (first var-list) vars)
(push (first bind-list) binds)))))
;; FDMM: SETQ can make parallel assignments.
;; But SERIES does not take that into account yet.
(cl:defun setq-p (thing)
#+:ignore
(when (eq-car thing 'setq)
(when-bind (args (cdr thing))
(cl:multiple-value-bind (vars lastbind binds) (detangle2 args)
(when (and (not (null (cdr lastbind)))
(every #'symbolp vars))
(values vars binds)))))
;; Backward-compatible single-variable version
#+:ignore
(when (and (eq-car thing 'setq) (= (mod (length thing) 2) 1))
(cadr thing))
;; original version
(when (and (eq-car thing 'setq) (= (length thing) 3))
(cadr thing))
)
(cl:defun n-integers (n)
(do ((i (1- n) (1- i))
(l nil (cons i l)))
((minusp i) l)))
#+:ignore
(cl:defun n-integer-values (n)
(cl:labels ((n-integer-values-1 (n &rest args)
(declare (dynamic-extent args))
(cond ((> n 1) (cl:multiple-value-call #'n-integer-values-1
(1- n) (1- n) (values-list args)))
((= n 1) (valuate 0 (values-list args)))
(t (values)))))
(n-integer-values-1 n)))
(cl:defun n-integer-values (n)
(cl:labels ((n-integer-values-1 (n &rest args)
(declare (dynamic-extent args))
(cond ((> n 0) (apply #'n-integer-values-1 (1- n) (1- n) args))
(t (values-list args)))))
(n-integer-values-1 n)))
) ; end of eval-when
;;; Code generation utilities
(eval-when (:compile-toplevel :load-toplevel :execute)
(defmacro funcase ((binds funexpr) &rest cases)
(cl:let (var expr
(a (gensym)))
(if (consp binds)
(destructuring-bind (v &optional (e (gensym))) binds
(setq var v
expr e))
(setq var binds
expr (gensym)))
(cl:flet ((nameguard () `(and (eq ,a 'function) (symbolp (setq ,var (cadr ,expr)))))
(anonguard () `(setq ,var (cond ((eq ,a 'function) (cadr ,expr))
((eq ,a 'lambda) ,expr)
(t nil))))
(varguard () `(symbolp ,expr))
(compguard () `(and ,a (case ,a ((function lambda) nil) (t t))))
(elseguard () t))
(cl:flet ((compute-guard-1 (tag)
(ecase tag
(name (nameguard))
(anonymous (anonguard))
(variable (varguard))
(computed (compguard))
((t otherwise else) (elseguard)))))
(cl:flet ((compute-guard (tag)
(if (consp tag)
(cons 'or (mapcar #'compute-guard-1 tag))
(compute-guard-1 tag))))
`(cl:let* ((,expr ,funexpr)
(,a (when (consp ,expr) (car ,expr)))
,var)
(cond ,@(mapcar #'(lambda (x) (list* (compute-guard (car x)) (cdr x)))
cases))))))))
(cl:defun prognize (forms &optional (prognize-p t))
(if prognize-p
(values
(if (cdr forms)
`(progn ,@forms)
(car forms))
nil)
(values forms t)))
(cl:defun lister (wrapped-p)
(if wrapped-p
#'list*
#'list))
(cl:defun localize (decls forms wrapped-p)
(values
(cl:funcall (lister wrapped-p)
'locally
(cons 'declare decls)
forms)
nil))
(cl:defun prologize (prologs forms wrapped-prologs-p wrapped-p)
(cl:let ((body (if prologs
(cl:funcall (if wrapped-prologs-p
#'nconc
#'append)
(if wrapped-prologs-p
(apply #'append prologs)
prologs)
(if wrapped-p
forms
(progn
(setq wrapped-p t)
(list forms))))
forms)))
(values body wrapped-p)))
(cl:defun declarize (wrapper decls localdecls prologs forms wrapped-p &optional (prognize-p t) (wrapped-prologs-p nil))
(when decls
(setq decls (delete nil (cl:funcall wrapper decls))))
(when localdecls
(setq localdecls (delete nil (cl:funcall wrapper localdecls))))
(cl:multiple-value-bind (body wrapped-p)
(prologize prologs forms wrapped-prologs-p wrapped-p)
(if decls
(values
(if localdecls
(list
(cons 'declare decls)
(localize localdecls body wrapped-p))
(cl:funcall (lister wrapped-p)
(cons 'declare decls)
body))
t)
(if localdecls
(localize localdecls body wrapped-p)
(if wrapped-p
(prognize body prognize-p)
(values body nil))))))
(cl:defun destarrify-1 (base binds decls localdecls prologs forms
&optional (wrapper #'list) (prognize-p t) (wrapped-prologs-p nil))
(cl:let ((b (car binds))
(d (cdr binds)))
(if b
(values
(if d
(cl:multiple-value-bind (body wrapped-p)
(cl:multiple-value-call #'declarize
wrapper (car decls) (car localdecls) (car prologs)
(destarrify-1 base d (cdr decls) (cdr localdecls) (cdr prologs)
forms wrapper nil wrapped-prologs-p) ; do not prognize
nil ; do not prognize
nil)
(cl:funcall (lister wrapped-p)
base
(cl:funcall wrapper b)
body))
(cl:multiple-value-bind (body wrapped-p)
(declarize wrapper (car decls) (car localdecls) (car prologs) forms t nil nil) ; do not prognize
(cl:funcall (lister wrapped-p)
base (cl:funcall wrapper b) body)))
nil)
(if d
(cl:multiple-value-call #'declarize
wrapper (car decls) (car localdecls) (car prologs)
(destarrify-1 base d (cdr decls) (cdr localdecls) (cdr prologs)
forms wrapper prognize-p wrapped-prologs-p)
prognize-p nil)
(declarize wrapper decls localdecls prologs forms t prognize-p wrapped-prologs-p)))))
(cl:defun destarrify (base binds decls localdecls prologs forms &optional (wrapper #'list) (wrapped-prologs-p nil))
"Covert a BASE* form into a nested set of BASE forms"
;;(declare (dynamic-extent #'destarrify-1))
(if binds
(destarrify-1 base binds decls localdecls prologs forms wrapper t wrapped-prologs-p)
(prognize (prologize prologs forms wrapped-prologs-p t) t)))
(cl:defun compute-total-size (dims)
(cond ((consp dims)
(cl:let ((n 1))
(dolist (d dims)
(if (eq d '*)
(return-from compute-total-size nil)
(setq n (* n d))))
n))
((eq dims '*) nil)
(t 0)))
;;; DECODE-SEQ-TYPE
;;;
;;; DECODE-SEQ-TYPE tries to canonicalize the given type into the
;;; underlying type. It returns three values: the sequence type
;;; (string, vector, simple-array, sequence), the length of the
;;; sequence (or NIL if not known) and the element type of the
;;; sequence (or T if not known).
(cl:defun decode-seq-type (type)
(when (eq-car type 'quote)
(setq type (cadr type)))
(if type
(cond ((and (symbolp type)
(string= (string type) #.(string 'bag)))
(values 'bag nil t))
((and (consp type)
(symbolp (car type))
(string= (string (car type)) #.(string 'bag)))
(values 'bag nil (cadr type)))
((and (symbolp type)
(string= (string type) #.(string 'set)))
(values 'set nil t))
((and (consp type)
(symbolp (car type))
(string= (string (car type)) #.(string 'set)))
(values 'set nil (cadr type)))
((and (symbolp type)
(string= (string type) #.(string 'ordered-set)))
(values 'ordered-set nil t))
((and (consp type)
(symbolp (car type))
(string= (string (car type)) #.(string 'ordered-set)))
(values 'ordered-set nil (cadr type)))
(t
;; Hmm, should we use subtypep to handle these? Might be easier.
(cond ((eq type 'list)
(values 'list nil t))
((eq-car type 'list)
(values 'list nil (cadr type)))
((eq type 'sequence)
(values 'sequence nil t))
;; A STRING is canonicalized to (VECTOR CHARACTER)
((eq type 'string)
(values 'vector nil 'character))
((eq-car type 'string)
(values 'vector
(when (numberp (cadr type))
(cadr type))
'character))
;; But SIMPLE-STRING's are really (SIMPLE-ARRAY
;; CHARACTER (*))
((eq type 'simple-string)
(values 'simple-array nil 'character))
((eq-car type 'simple-string)
(values 'simple-array
(when (numberp (cadr type))
(cadr type))
'character))
;; A BASE-STRING is (VECTOR BASE-CHAR)
((eq type 'base-string)
(values 'vector nil 'base-char))
((eq-car type 'base-string)
(values 'vector
(when (numberp (cadr type))
(cadr type))
'base-char))
;; But SIMPLE-BASE-STRING's are really (SIMPLE-ARRAY
;; BASE-CHAR (*))
((or (eq type 'simple-base-string))
(values 'simple-array nil 'base-char))
((or (eq-car type 'simple-base-string))
(values 'simple-array
(when (numberp (cadr type))
(cadr type))
'base-char))
;; A BIT-VECTOR is (VECTOR BIT)
((eq type 'bit-vector)
(values 'vector nil 'bit))
((eq-car type 'bit-vector)
(values 'vector (if (numberp (cadr type)) (cadr type)) 'bit))
;; But a SIMPLE-BIT-VECTOR is really a
;; (SIMPLE-ARRAY BIT (*))
((eq type 'simple-bit-vector)
(values 'simple-array nil 'bit))
((eq-car type 'simple-bit-vector)
(values 'simple-array
(when (numberp (cadr type))
(cadr type))
'bit))
;; A VECTOR is just a VECTOR
((eq type 'vector)
(values 'vector nil t))
((eq-car type 'vector)
(values 'vector (if (numberp (caddr type)) (caddr type))
(if (not (eq (cadr type) '*))
(cadr type)
t)))
;; And a SIMPLE-VECTOR is just a SIMPLE-VECTOR
((eq type 'simple-vector)
(values 'simple-vector nil t))
((eq-car type 'simple-vector)
(values 'simple-vector (if (numberp (cadr type)) (cadr type)) t))
((eq type 'simple-array)
(values 'simple-array nil t))
((eq-car type 'simple-array)
(values 'simple-array
(when (caddr type)
(compute-total-size (caddr type)))
(if (not (eq (cadr type) '*))
(cadr type)
t)))
;; An ARRAY is an ARRAY. We treat arrays
;; essentially as 1D array, in row-major order.
((eq type 'array)
(values 'array nil t))
((eq-car type 'array)
(values 'array
(when (caddr type)
(compute-total-size (caddr type)))
(if (not (eq (cadr type) '*))
(cadr type)
t)))
;; Everything else is a sequence
(t
(values 'sequence nil t)))))
(values 'sequence nil t))) ; "SEQUENCE" - It might be a multidimensional array
(declaim (inline retuns-list-p))
(cl:defun retuns-list-p (expr)
(or (null expr) (lister-p expr)))
(cl:defun lister-p (expr)
(when-bind (a (and (consp expr) (car expr)))
(case a
((cons list
push pushnew
last
copy-list make-list append nconc member butlast nbutlast revappend nreconc
rplaca rplacd
mapcar mapcan mapl maplist mapcon
assoc pairlis acons copy-alist assoc-if assoc-if-not
subst subst-if subst-if-not
nsubst nsubst-if nsubst-if-not
sublis nsublis
intersection nintersection set-difference nset-difference
adjoin union nunion set-exclusive-or nset-exclusive-or
get-properties ldiff) expr)
(quote (when (listp (cadr expr)) expr))
(collect (when (or (not (cadddr expr))
(case (decode-seq-type (caddr expr))
((list bag set ordered-set) t)
(t nil)))
expr))
(list* (when (or (caddr expr) (retuns-list-p (cadr expr)))
expr))
(copy-seq (when (retuns-list-p (cadr expr))
expr))
(t nil))))
(cl:defun matching-scan-p (expr pred)
(cl:let (a)
(and (eq-car expr 'scan)
(or (and (setq a (cadr expr)) (not (caddr expr)) (cl:funcall pred a))
(and (setq a (caddr expr)) (cl:funcall pred a))))))
) ; end of eval-when
#-allegro
(eval-when (:compile-toplevel :load-toplevel :execute)
(defmacro coerce-maybe-fold (thing type)
`(coerce ,thing ,type))
)
#+allegro
(eval-when (:compile-toplevel :load-toplevel :execute)
;;; Here are some changes from Joe Marshall who says that "Franz
;;; Allegro doesn't fold constants in coerce, so you end up calling it
;;; a *lot*. This alleviates a fair amount of the pain."
;;;
;;; Constant folding
;;;
;;; The basic problem is that Allegro returns NIL
;;; for (constantp '(+ 2 3))
;;; The function (foldable-constant-expression-p '(+ 2 3) nil)
;;; returns T.
(defconst-once /foldable-operator-table/ (make-hash-table))
(defconst-once /unfoldable-operator-table/ (make-hash-table))
(defmacro declare-foldable-constant-operators (&rest names)
`(eval-when (:compile-toplevel :load-toplevel :execute)
(dolist (name (quote (,@names)))
(setf (gethash name /foldable-operator-table/) t))))
(defmacro declare-unfoldable-constant-operators (&rest names)
`(eval-when (:compile-toplevel :load-toplevel :execute)
(dolist (name (quote (,@names)))
(setf (gethash name /unfoldable-operator-table/) t))))
(declare-foldable-constant-operators
* + - / /= 1+ 1- < <= = > >=
abs acos acosh alpha-char-p alphanumericp arrayp ash asin asinh atan atanh atom
assert
block both-case-p byte
caaaar caaadr caaar caadar caaddr caadr caar cadaar cadadr cadar caddar cadddr caddr
cadr car cdaaar cdaadr cdaar cdadar cdaddr cdadr cdar cddaar cddadr
cddar cdddar cddddr cdddr cddr cdr ceiling char-code char-downcase char-equal
char-greaterp char-int char-lessp char-name char-not-equal char-not-greaterp
char-not-lessp char-upcase char/= char< char<= char= char> char>= character
characterp cis code-char coerce complex complexp concatenate conjugate
consp constantp cos cosh
denominator digit-char digit-char-p double-float
eighth endp eq eql equal equalp evenp exp expt
fceiling ffloor fifth first float float-digits float-precision float-radix float-sign
floatp floor fourth fround ftruncate
gcd graphic-char-p
identity imagpart integer-decode-float integer-length integerp isqrt
keywordp
lcm ldb ldb-test length listp list-length locally log logand logandc1 logandc2
logbitp logcount logeqv logior lognand lognor lognot logorc1 logorc2 logtest
logxor lower-case-p
max min minusp mod
name-char ninth not null numberp numerator
oddp
phase plusp progn
rationalp realp realpart rem rest round
seventh sin single-float sinh sixth sqrt standard-char-p string-equal string-greaterp
string-lessp string-not-equal string-not-greaterp string-not-lessp string/= string<
string<= string= string> string>= stringp symbolp
tailp tan tanh tenth third truncate typep
zerop
)
;; a few macros that aren't worth the bother
;; to walk, stuff that we know won't fold, etc.
(declare-unfoldable-constant-operators
case
cons
check-type
do
dolist
dotimes
ecase
lambda
loop
random)
(cl:defun foldable-constant-expression-p (expression env)
(or (constantp expression env)
(and
(consp expression)
(cl:let ((operator (car expression))
(operands (cdr expression)))
(cond ((symbolp operator)
(case operator
;; AND can be folded if first arg is foldable
(and (or (null operands)
(and (foldable-constant-expression-p (first operands) env)
(cl:let ((value (eval (first operands))))
(or (null value)
(null (cdr operands))
(foldable-constant-expression-p `(and ,@(rest operands)) env))))))
;; COND can be folded if first clause is foldable
(cond (or (null operands)
(and (foldable-constant-expression-p (car (first operands)) env)
(cl:let ((value (eval (car (first operands)))))
(if value
(foldable-constant-expression-p* (cdr (first operands)) env)
(foldable-constant-expression-p `(cond ,@(rest operands)) env))))))
(declare t)
;; IF can be folded if condition is foldable
(if (and (foldable-constant-expression-p (first operands) env)
(cl:let ((condition (eval (first operands))))
(if condition
(foldable-constant-expression-p (second operands) env)
(foldable-constant-expression-p (third operands) env)))))
;; CL:LET can be folded if all the bindings are foldable,
;; and the body is foldable.
((cl:let cl:let*) (and (every (lambda (binding)
(or (not (consp binding))
(foldable-constant-expression-p (second binding) env)))
(car operands))
(foldable-constant-expression-p* (rest operands) env)))
;; OR can be folded if the first arg is foldable
(or (or (null operands)
(and (foldable-constant-expression-p (first operands) env)
(cl:let ((value (eval (first operands))))
(or value
(null (cdr operands))
(foldable-constant-expression-p `(or ,@(rest operands)) env))))))
;; THE can be folded if the value clause is foldable
(the (foldable-constant-expression-p (second operands) env))
;; UNLESS can be folded if the condition is foldable
(unless (and (foldable-constant-expression-p (first operands) env)
(cl:let ((condition (eval (first operands))))
(or condition
(foldable-constant-expression-p* (cdr operands) env)))))
;; WHEN can be folded if the condition is foldable
(when (and (foldable-constant-expression-p (first operands) env)
(cl:let ((condition (eval (first operands))))
(or (null condition)
(foldable-constant-expression-p* (cdr operands) env)))))
;; Otherwise, look it up in the table.
(t
(unless (gethash operator /unfoldable-operator-table/)
#||
(cond ((gethash operator /foldable-operator-table/)
(foldable-constant-expression-p* operands env))
((foldable-constant-expression-p* operands env)
(warn "Couldn't fold ~s ~s" operator operands)
nil)
(t nil))
||#
(and (gethash operator /foldable-operator-table/)
(foldable-constant-expression-p* operands env))))))
;; A literal lambda can be folded if it is in operator
;; position, all its arguments are foldable, and its body
;; is foldable
((and (consp operator)
(eq (car operator) 'lambda)
(foldable-constant-expression-p* operands env))
(foldable-constant-expression-p* (cddr operator) env))
;; nothing else is foldable
(t nil))))))
(cl:defun foldable-constant-expression-p* (forms env)
(every (lambda (form)
(foldable-constant-expression-p form env))
forms))
(cl:defun fold-constant-expression (expression &optional expected-type)
(cl:let ((value (eval expression)))
(when (and expected-type
(not (typep value expected-type)))
(warn "While folding expression ~s, ~
the value ~s was not of the expected type ~s."
expression value expected-type))
#||
;; 99% of folding involves a symbol constant.
(unless (or (symbolp expression)
(and (consp expression)
(eq (car expression) 'quote))
(and (consp expression)
(eq (car expression) 'the)
(or (numberp (third expression))
(symbolp (third expression))))
(eq expression value))
(format t "~&Folding ~s => ~s" expression value))
||#
value))
(cl:defun fold-if-possible (form env &optional expected-type)
"Return either FORM or it's folded value if one can be computed.
If expected type is given and form is folded, but does not equal
the expected type, a warning is issued and form is returned unfolded."
(cl:let ((is-constant (foldable-constant-expression-p form env)))
(if is-constant
(cl:let ((value (fold-constant-expression form)))
(if (and expected-type
(not (typep value expected-type)))
(progn
(warn "While folding expression ~s, ~
the value ~s was not of the expected type ~s."
form value expected-type)
form)
value))
form)))
(cl:defun expression-is-constant-equal-to (form env value)
(eq (fold-if-possible form env) value))
(defmacro coerce-maybe-fold (&environment env thing type)
(if (and (foldable-constant-expression-p thing env)
(foldable-constant-expression-p type env))
(coerce (fold-constant-expression thing)
(fold-constant-expression type))
`(coerce ,thing ,type)))
) ; end eval-when
(cl:defun extract-declarations (forms)
"Grab all the DECLARE expressions at the beginning of the list forms"
(cl:let ((decls nil))
(do* ((r forms (cdr r))
(i (car r) (car r)))
((not (eq-car i 'declare)) (values decls r))
(push i decls))))
(cl:defun collect-decls (category decls)
(mapcan #'(lambda (d)
(remove-if-not #'(lambda (x)
(string-equal (string-upcase (symbol-name (car x)))
(string-upcase (symbol-name category))))
(cdr d)))
decls))
(cl:defun collect-other-decls (category decls)
(mapcan #'(lambda (d)
(remove-if #'(lambda (x)
(string-equal (string-upcase (symbol-name (car x)))
(string-upcase (symbol-name category))))
(cdr d)))
decls))
(cl:defun merge-decs (decls)
(when decls
(mapcan #'cdr decls)))
(cl:defun collect-declared (category decls)
"Given a list of DECLARE forms, concatenate all declarations of the same category, with DECLAREs and category removed"
(merge-decs (collect-decls category decls)))
(cl:defun dynamize-vars (vars forms test)
(cl:multiple-value-bind (declarations body) (extract-declarations forms)
(cl:let ((indef (collect-declared 'indefinite-extent declarations))
(notindecls (collect-other-decls 'indefinite-extent declarations)))
(values
`(,@(when-bind (dynvars (set-difference vars indef :test test))
`((declare ,(cons 'dynamic-extent dynvars))))
,@(when-bind (indefvars (set-difference indef vars :test test))
`((declare ,(cons 'indefinite-extent indefvars))))
,@(when notindecls
`((declare ,@notindecls))))
body))))
(cl:defun variable-p (thing)
"Return T if thing is a non-keyword symbol different from T and NIL"
(and thing (symbolp thing) (not (eq thing t)) (not (keywordp thing))))
(cl:defun simple-quoted-lambda (form)
(or (and (eq-car form 'cl:function)
(eq-car (cadr form) 'cl:lambda)
(every #'variable-p (cadr (cadr form))))
(and (eq-car form 'cl:lambda)
(every #'variable-p (cadr form)))))
(cl:defun simple-quoted-lambda-arguments (form)
(ecase (car form)
(cl:function (cadr (cadr form)))
(cl:lambda (cadr form))))
(cl:defun simple-quoted-lambda-body (form)
(ecase (car form)
(cl:function (cddr (cadr form)))
(cl:lambda (cddr form))))
(cl:defun nullable-p (typ)
(or (member typ '(t null list boolean))
(and (consp typ)
(cl:let ((a (car typ)))
(or (eq a 'null-or)
(eq a 'list)
(and (eq a 'or)
(some #'nullable-p (cdr typ))))))))
(cl:defun make-nullable (typ)
"Make a type specifier of the form: (or FOO NULL)"
(if (nullable-p typ)
typ
`(null-or ,typ)))
(cl:defun type-or-list-of-type (typ)
"Make a type specifier of the form: (or FOO (list FOO))"
`(or ,typ list))
(cl:defun never (&rest stuff)
"Always returns NIL"
(declare (ignore stuff)) nil)
(cl:defun make-general-setq (vars value)
(cond ((= (length vars) 0) value)
((= (length vars) 1) `(setq ,(car vars) ,value))
((and (eq-car value 'values)
(= (length (cdr value)) (length vars)))
`(psetq ,@(mapcan #'list vars (cdr value))))
(t `(multiple-value-setq ,vars ,value))))
(cl:defun pos (&rest bools)
(declare (dynamic-extent bools))
(do ((bs bools (cdr bs))
(i 0 (1+ i)))
((null bs) i)
(when (car bs)
(return i))))
(cl:defun pos-if (item &rest fns)
(declare (dynamic-extent fns))
(do ((fs fns (cdr fs))
(i 0 (1+ i)))
((null fs) i)
(when (cl:funcall (car fs) item)
(return i))))
(cl:defun forceL (n list)
(declare (type fixnum n)
(type list list))
(if (= n (length list))
list
(cl:let* ((new (make-list n :initial-element nil))
(ptr new))
(do ((i (min n (length list)) (1- i)))
((zerop i))
(rplaca ptr (pop list))
(pop ptr))
new)))
;;;; SERIES-specific code
(cl:defun install (&key (pkg *package*) (macro t) (shadow t) (implicit-map nil)
(remove nil) (shadow-extensions shadow))
(setq *series-implicit-map* implicit-map)
(when (not (packagep pkg)) (setq pkg (find-package pkg)))
(cl:let ((spkg (find-package :series)))
(when (not remove)
(when macro
(set-dispatch-macro-character #\# #\Z (cl:function series-reader))
(set-dispatch-macro-character #\# #\M (cl:function abbreviated-map-fn-reader)))
(when (not (eq pkg spkg))
;;This is here because UNTIL and COLLECT are loop clauses.
(cl:multiple-value-bind (sym code) (find-symbol (symbol-name '#:until) pkg)
(when (and sym (eq code :internal)
(not (boundp sym)) (not (fboundp sym)) (null (symbol-plist sym)))
(unintern sym pkg)))
(cl:multiple-value-bind (sym code) (find-symbol (symbol-name '#:collect) pkg)
(when (and sym (eq code :internal)
(not (boundp sym)) (not (fboundp sym)) (null (symbol-plist sym)))
(unintern sym pkg)))
#+(or cmu scl Harlequin-Common-Lisp)
(unintern 'series :common-lisp-user)
(shadowing-import /ext-conflicts/ pkg)
(use-package :series pkg)
(when shadow (shadowing-import /series-forms/ pkg))
(unless shadow-extensions
(when /ext-conflicts/
(cl:let* ((ext (find-package :extensions))
(syms (mapcar #'(lambda (s)
(find-symbol (symbol-name s) ext))
/ext-conflicts/)))
(shadowing-import syms pkg))))
))
(when (and remove (member spkg (package-use-list pkg)))
(unuse-package :series pkg)
(dolist (sym (intersection (union /series-forms/ /ext-conflicts/)
(package-shadowing-symbols pkg)))
(unintern sym pkg))))
t)
(eval-when (:compile-toplevel :load-toplevel :execute)
;;Internally used special variables. Every one is collected here except some
;;scan templates used in macro expansion.
(defvar *optimize-series-expressions* t)
(defvar *in-series-expr* nil
"the topmost series expression")
(defvar *testing-errors* nil
"Used only be the file of tests")
(defvar *not-straight-line-code* nil
"not-nil if nested in non-straight-line code")
(declaim (special *graph* ;list of frags in expression
*renames* ;alist of variable renamings
*user-names* ;series::let var names used by user
*env* ;environment of containing series macro call
*call* ;bound to whole form when running optimizer
*being-setqed* ;T if in the assignment part of a setq
*fn* ;FN being scanned over code
*type* ;Communicates types to frag instantiations
*limit* ;Communicates limits to frag instantiations
*frag-arg-1* ;Communicates arg to frag instantiations
*frag-arg-2* ;Communicates arg to frag instantiations
))
;; DEBUG
;;
;; With these two assigments you can use (SERIES::PROCESS-TOP <quoted form>)
;; to view series expansions:
;; (setq series::*renames* nil) (setq series::*env* nil)
;; *renames* has three kinds of entries on it. Each is a cons of a
;; variable and something else: (type 1 cannot ever be setqed.)
;;
;; 1- a ret, var is a series::let var or a series::lambda var. You
;; can tell between the two because series::lambda var frags are not
;; in *graph*.
;;
;; 2- a new var, var is an aux var.
;;
;; 3- nil, var is rebound and protected from renaming.
(defconst-once /short-hand-types/
'(array atom bignum bit bit-vector character common compiled-function
complex cons double-float fixnum float function hash-table integer
keyword list long-float nil null number package pathname random-state
ratio rational readtable sequence short-float simple-array
simple-bit-vector simple-string simple-vector single-float standard-char
stream string string-char symbol t vector series)
"table 4.1 from CLTL")
(defvar *standard-function-reader* (get-dispatch-macro-character #\# #\'))
;;;; ---- ERROR REPORTING ----
;; HELPER
(cl:defun report-error (info)
(setq *last-series-error* info)
(loop (unless info (return nil))
(if (stringp (car info))
(format *error-output* (pop info))
(write (pop info) :stream *error-output* :escape t :pretty t
:level nil :length nil :case :upcase))))
(cl:defun ers (id &rest args) ;Fatal errors.
(declare (dynamic-extent args))
(when *testing-errors*
(throw :testing-errors id))
(if *in-series-expr*
(report-error (list* "~&Error " id " in series expression:~%"
*in-series-expr* (copy-list args)))
(report-error (list* "~&Error " id (copy-list args))))
(error ""))
(cl:defun wrs (id always-report-p &rest args) ;Warnings.
(declare (dynamic-extent args))
(when (or always-report-p (not *suppress-series-warnings*))
(report-error (list* "~&Warning " id
" in series expression:~%"
(or *in-series-expr*
(and (boundp '*not-straight-line-code*)
*not-straight-line-code*))
(copy-list args)))
;; What is this for? Why do we want to print out this warning
;; when *testing-errors* is NIL? Remove this. Tests still pass.
#+nil
(when (not *testing-errors*)
(warn ""))))
;; HELPER
(cl:defun rrs (id &rest args) ;Restriction violations.
(declare (dynamic-extent args))
(when (not *suppress-series-warnings*)
(report-error (list* "~&Restriction violation " id
" in series expression:~%"
(or *in-series-expr* *not-straight-line-code*)
(copy-list args)))
(when (not *testing-errors*)
(warn "")))
(throw :series-restriction-violation nil))
;;;; ---- UTILITIES FOR MANIPULATING FRAGMENTS ----
(defvar end 'end "used to force copying of frag lists")
;The key internal form is an entity called a frag (short for fragment).
(defstruct (frag (:conc-name nil) (:type list) :named)
(code :||) ;the surface code corresponding to this, for error messages
(marks 0) ;mark bits used in sweeps over a graph
(must-run nil) ;indicates contains computation that must be run completely
(args nil) ;a list of sym structures for the args of the frag.
(rets nil) ;a list of sym structs for the return values of the frag.
(aux nil) ;the auxiliary variables if any and their types.
(alterable nil) ;specifications for alterable outputs
(prolog nil) ;list of forms (without labels).
(body nil) ;list of forms (possibly containing labels).
(epilog nil) ;list of forms (without labels).
(wrappers nil) ;functions that wrap forms around the whole loop.
(impure nil) ;whether this is referentially transparent or not (nil (referentially transparent (but movement constrained by series flow); t (not at all); :args, if it depends on args; :mutable, if it depends on mutable arguments that could be literal or private; :context, if movable depending on the whole expr(mutables that cannot be literal or private))
)
;; CMUCL 18b BUG fixnup macro - KEEP IN SYNC WITH THE ABOVE!!
#+:cmu18
(defmacro frag-wrappers (f) `(nth 11 ,f))
#-:cmu18
(defmacro frag-wrappers (f) `(wrappers ,f))
;; what whould be nil if loop wrapper only
(declaim (inline add-wrapper))
(cl:defun add-wrapper (frag wrap-fn &optional (what t))
(push `(,wrap-fn ,what) (wrappers frag)))
(declaim (inline wrapper-function))
(cl:defun wrapper-function (w)
(car w))
(declaim (inline wrapper-type))
(cl:defun wrapper-type (w)
(cadr w))
(declaim (inline loop-wrapper-p))
(cl:defun loop-wrapper-p (w)
(eq (wrapper-type w) :loop))
(declaim (inline epilog-wrapper-p))
(cl:defun epilog-wrapper-p (w)
(eq (wrapper-type w) :epilog))
#+:series-plain
(progn
;;; Prologs
(defmacro doprolog ((v prologs) &body body)
`(dolist (,v ,prologs)
,@body))
(declaim (inline makeprolog))
(cl:defun makeprolog (prologlist)
prologlist)
(declaim (inline flatten-prolog))
(cl:defun flatten-prolog (prologs)
prologs)
(declaim (inline mapprolog))
(cl:defun mapprolog (fun prologs)
(mapcar fun prologs))
(declaim (inline 2mapprolog))
(cl:defun 2mapprolog (fun prologs)
(2mapcar fun prologs))
(declaim (inline 3mapprolog))
(cl:defun 3mapprolog (fun prologs)
(3mapcar fun prologs))
(declaim (inline first-prolog-block))
(cl:defun first-prolog-block (prologs)
prologs)
(declaim (inline last-prolog-block))
(cl:defun last-prolog-block (prologs)
prologs)
(declaim (inline find-prolog))
(cl:defun find-prolog (var prologs)
(assoc var prologs))
(declaim (inline delete-prolog))
(cl:defun delete-prolog (var prologs)
(delete var prologs :key #'car))
(declaim (inline delete-last-prolog))
(cl:defun delete-last-prolog (prologs)
(nbutlast prologs))
(declaim (inline delete-prolog-if))
(cl:defun delete-prolog-if (p prologs)
(delete-if p prologs))
(declaim (inline remove-prolog-if))
(cl:defun remove-prolog-if (p prologs)
(remove-if p prologs))
(declaim (inline add-prolog))
(cl:defun add-prolog (frag p)
(push p (prolog frag)))
(declaim (inline prolog-append))
(cl:defun prolog-append (p l)
(append p l))
(declaim (inline prolog-length))
(cl:defun prolog-length (p)
(length p))
(declaim (inline merge-prologs))
(cl:defun merge-prologs (p1 p2)
(nconc p1 p2))
;;; Auxs
(defmacro doaux ((v auxs) &body body)
`(dolist (,v ,auxs)
,@body))
(declaim (inline makeaux))
(cl:defun makeaux (auxlist)
auxlist)
(declaim (inline flatten-aux))
(cl:defun flatten-aux (auxs)
auxs)
(declaim (inline mapauxn))
(cl:defun mapauxn (fun auxs)
(mapcar fun auxs))
(declaim (inline mapaux))
(cl:defun nmapaux (fun auxs)
(mapcan fun auxs))
(declaim (inline mapaux))
(cl:defun mapaux (fun auxs)
(mapcar fun auxs))
(declaim (inline 2mapaux))
(cl:defun 2mapaux (fun auxs)
(2mapcar fun auxs))
(declaim (inline 3mapaux))
(cl:defun 3mapaux (fun auxs)
(3mapcar fun auxs))
(declaim (inline first-aux-block))
(cl:defun first-aux-block (auxs)
auxs)
(declaim (inline find-aux))
(cl:defun find-aux (var auxs)
(assoc var auxs))
(declaim (inline delete-aux))
(cl:defun delete-aux (var auxs)
(delete var auxs :key #'car))
(declaim (inline delete-aux-if))
(cl:defun delete-aux-if (p auxs)
(delete-if p auxs))
#|
(declaim (inline remove-aux-if))
(cl:defun remove-aux-if (p auxs)
(remove-if p auxs))
|#
(declaim (inline segregate-aux))
(cl:defun segregate-aux (p auxs)
(values (remove-if-not p auxs) (remove-if p auxs)))
(cl:defun add-aux (frag var typ &optional (val nil val-p))
(push (if val-p
`(,var ,typ ,val)
`(,var ,typ))
(aux frag)))
)
#-:series-plain
(progn
;;; Prologs
(defmacro doprolog ((v prologs) &body body)
(cl:let ((b (gensym)))
`(dolist (,b ,prologs)
(dolist (,v ,b)
,@body))))
(declaim (inline makeprolog))
(cl:defun makeprolog (prologlist)
(when prologlist
(list prologlist)))
(declaim (inline flatten-prolog))
(cl:defun flatten-prolog (prologs)
(apply #'append prologs))
(declaim (inline mapprolog))
(cl:defun mapprolog (fun prologs)
(mapcan #'(lambda (b) (mapcar fun b)) prologs))
(declaim (inline 2mapprolog))
(cl:defun 2mapprolog (fun prologs)
(2mapcar #'(lambda (b) (2mapcar fun b)) prologs))
(declaim (inline 3mapprolog))
(cl:defun 3mapprolog (fun prologs)
(3mapcar #'(lambda (b) (3mapcar fun b)) prologs))
(declaim (inline first-prolog-block))
(cl:defun first-prolog-block (prologs)
(car prologs))
(declaim (inline last-prolog-block))
(cl:defun last-prolog-block (prologs)
(car (last prologs)))
(cl:defun add-prolog (frag p)
(cl:let ((prologs (prolog frag)))
(if prologs
(progn
(push p
(car prologs))
prologs)
(setf (prolog frag) (makeprolog (list p))))))
(cl:defun prolog-append (prologs l)
(if l
(if prologs
(cl:let* ((p (copy-list prologs))
(la (last p)))
(rplaca la (append (car la) l))
p)
(makeprolog l))
prologs))
(cl:defun prolog-length (p)
(cl:let ((x 0))
(dolist (l p)
(setq x (+ x (length l))))
x))
(declaim (inline merge-prologs))
(cl:defun merge-prologs (p1 p2)
(nmerge p1 p2))
(declaim (inline find-prolog))
(cl:defun find-prolog (var prologs)
(dolist (b prologs)
(when-bind (a (assoc var b))
(return a))))
(declaim (inline delete-prolog))
(cl:defun delete-prolog (var prologs)
(mapcar #'(lambda (b) (delete var b :key #'car)) prologs))
(declaim (inline delete-last-prolog))
(cl:defun delete-last-prolog (prologs)
(cl:let ((l (last prologs)))
(rplaca l (nbutlast (car l)))
prologs))
(declaim (inline remove-prolog-if))
(cl:defun remove-prolog-if (p prologs)
(mapcar #'(lambda (b) (remove-if p b)) prologs))
;;; Local variable handling (Auxs)
(defmacro doaux ((v auxs) &body body)
(cl:let ((b (gensym)))
`(dolist (,b ,auxs)
(dolist (,v ,b)
,@body))))
(declaim (inline makeaux))
(cl:defun makeaux (auxlist)
(when auxlist
(list auxlist)))
(declaim (inline flatten-aux))
(cl:defun flatten-aux (auxs)
(apply #'append auxs))
(declaim (inline mapauxn))
(cl:defun mapauxn (fun auxs)
(mapcan #'(lambda (b) (mapcar fun b)) auxs))
(declaim (inline mapaux))
(cl:defun nmapaux (fun auxs)
(mapcar #'(lambda (b) (mapcan fun b)) auxs))
(declaim (inline mapaux))
(cl:defun mapaux (fun auxs)
(mapcar #'(lambda (b) (mapcar fun b)) auxs))
(declaim (inline 2mapaux))
(cl:defun 2mapaux (fun auxs)
(2mapcar #'(lambda (b) (2mapcar fun b)) auxs))
(declaim (inline 3mapaux))
(cl:defun 3mapaux (fun auxs)
(3mapcar #'(lambda (b) (3mapcar fun b)) auxs))
(declaim (inline first-aux-block))
(cl:defun first-aux-block (auxs)
(car auxs))
(cl:defun add-aux (frag var typ &optional (val nil val-p))
(cl:let ((auxs (aux frag))
(entry (if val-p
`(,var ,typ ,val)
`(,var ,typ))))
(if auxs
(progn
(push entry
(car auxs))
auxs)
(setf (aux frag) (makeaux (list entry))))))
(declaim (inline find-aux))
(cl:defun find-aux (var auxs)
(dolist (b auxs)
(when-bind (a (assoc var b))
(return a))))
(declaim (inline delete-aux))
(cl:defun delete-aux (var auxs)
(mapcar #'(lambda (b) (delete var b :key #'car)) auxs))
(declaim (inline delete-aux-if))
(cl:defun delete-aux-if (p auxs)
(mapcar #'(lambda (b) (delete-if p b)) auxs))
(declaim (inline delete-aux-if-not))
(cl:defun delete-aux-if-not (p auxs)
(mapcar #'(lambda (b) (remove-if-not p b)) auxs))
#|
(declaim (inline remove-aux-if))
(cl:defun remove-aux-if (p auxs)
(mapcar #'(lambda (b) (remove-if p b)) auxs))
(declaim (inline remove-aux-if-not))
(cl:defun remove-aux-if-not (p auxs)
(mapcar #'(lambda (b) (remove-if-not p b)) auxs))
|#
(declaim (inline segregate-aux))
(cl:defun segregate-aux (p auxs)
(2mapcar #'(lambda (b) (values (remove-if-not p b) (remove-if p b))) auxs))
)
;;; Prologs
(declaim (inline first-prolog))
(cl:defun first-prolog (prologs)
(car (first-prolog-block prologs)))
(cl:defun append-prolog (frag p)
(setf (prolog frag)
(prolog-append (prolog frag) p)))
;;; Auxs
(declaim (inline first-aux))
(cl:defun first-aux (auxs)
(car (first-aux-block auxs)))
(declaim (inline add-literal-aux))
(cl:defun add-literal-aux (frag var typ val)
(add-aux frag var typ val))
(cl:defun add-nonliteral-aux (frag var typ val)
(add-aux frag var typ #-:series-plain val)
#+:series-plain
(push `(setq ,var ,val) (prolog frag)))
(cl:defun simplify-aux (auxs)
(mapaux #'(lambda (v)
(cl:let ((d (cddr v)))
(if (and d (not (constantp (car d))))
`(,(car v) ,(cadr v))
v)))
auxs))
(cl:defun aux->prolog (auxs)
(nmapaux #'(lambda (v)
(cl:let ((d (cddr v)))
(when (and d (not (constantp (car d))))
`((setq ,(car v) ,(car d))))))
auxs))
;;; There cannot be any redundancy in or between the args and aux.
;;; Each ret variable must be either on the args list or the aux list.
;;; The args and ret have additional data as discussed below. The aux
;;; is just a list of lists of a symbol and a type specifier. Every
;;; symbol used in a frag which could possible clash with other frags
;;; (eg args, rets, aux, and also labels) must be gensyms and unique
;;; in the whole world.
;;;
;;; The order of the args is important when the frag is first
;;; instantiated and funcalled. However, it does not matter after
;;; that. Similarly, the order of the rets also matters at the time it
;;; is instantiated, and at the time that a whole expression is turned
;;; into one frag, but it does not matter at other times.
;;;
;;; There are two basic kinds of frags, series frags and non-series
;;; frags. A non-series frag is a frag which just has a simple
;;; computation which has to be performed only once. The rets and
;;; args must be non-series values, and the body and epilog must be
;;; empty. (The code below maintains the invariant that if all the
;;; ports of a frag are non-series then the body and epilog are
;;; empty.)
;;;
;;; A frag has three internal parts so that a wide variety of
;;; fragmentary series functions can be compressed into a single frag.
;;;
;;; Inside frags there is a label which has a special meaning.
;;; END is used as the label after the end of the loop created. If the
;;; body of a fragment contains (go END) then the fragment is an
;;; active terminator.
;;;
;;; If a programmer uses these symbols in his program, very bad things
;;; could happen. However, it is in the series package, so there
;;; should not be any conflict problems. the code in this file
;;; assumes in many places that no symbol in the "SERIES" package can
;;; possibly clash with a user symbol.
;;;
;;; The code field is used solely to generate error messages.
;;; However, it is never the less very important. In particular, it
;;; is important that the code field only contain things that were
;;; actually in the user's source code. It is also important that it
;;; always contain something.
;;;
;;; There are several reasons why the code might end up being
;;; something the user did not write. The foremost reason is macro
;;; expansion. It might be the result of some expansion that turns
;;; into a frag. To fix this, my-macroexpand saves the first form
;;; before macro expansion, and puts that in the code field. To make
;;; this work, it must be the case that every macro that can possibly
;;; expand into something that will trigger the process of converting
;;; an expression into a loop must call PROCESS-TOP. To ensure this
;;; it must be the case that every macro the user can type must be
;;; defined with defS or DEFUN with an OPTIMIZABLE-SERIES-FUNCTION
;;; declaration. (Note it is fine for things the user cannot type
;;; anyway to be defined with defmacro.) (Unfortunately, the end user
;;; can break this rule if they define a new collector with DEFMACRO,
;;; but you cannot make everything work. At least all they will see
;;; is things generated by their own macro)
(cl:defun annotate (code frag)
(when (frag-p frag)
(setf (code frag) code))
frag)
;;; Considerable effort is expended to see that the code field usually
;;; contains code that makes sense to the user. Extensive testing
;;; indicates that it never ends up containing :||, and that the code it
;;; contains always is part of the code the user types except that an
;;; optional argument can end up having the default value which ends up
;;; in the annotation.
;;;
;;; Each arg and ret has the following parts.
(defstruct (sym (:conc-name nil) (:type list) :named)
(back-ptrs (make-array 2 :initial-element nil))
(var nil) ;gensymed variable.
(series-var-p nil) ;T if holds a series.
(off-line-spot nil) ;if off-line, place to insert the computation.
(off-line-exit nil) ;if non-passive input, label to catch exit.
)
;;; If there is an on-line-spot, it must appear in the frag code exactly
;;; once at top level. It cannot be nested in a form. It also can only be
;;; referred to from a single input or output.
;;; A number of functions depend on the fact that frags and syms are list
;;; structures which can be traversed by functions like nsubst. The
;;; following three circular pointers are hidden in an array so they
;;; won't be followed. (Note that ins only have prv and rets only have
;;; nxts, as a result, they can both be stored in the same place. two
;;; names are used in order to enhance the readability of the program.)
(defmacro fr (s) ;back pointer to containing frag.
`(aref (back-ptrs ,s) 0))
(defmacro nxts (s) ;list of destinations of dflows starting here.
`(aref (back-ptrs ,s) 1))
(defmacro prv (s) ;the single source of dflow to here.
`(aref (back-ptrs ,s) 1))
;;; The sym vars are symbols which appear in the body of the frag
;;; where they should. All of the symbols must be unique in all the
;;; world. Every instance of the symbol anywhere must be a use of the
;;; symbol.
;;;
;;; Output variables can be freely read and written. Input variables
;;; can be read freely, but cannot ever be written.
;;;
;;; These restrictions guarantee that when frags are combined, it is
;;; OK to rename the input var of one to be the output var of the
;;; other. In addition, the creator of an output can depend on the
;;; output variable being unchanged by the user(s). However, this is
;;; not the main point. More critical is the situation where two frags
;;; use the same value. The second frag can be sure that the first
;;; frag did not mess up the value. (Side-effects could still cause
;;; problems. The user must guard against destroying some other
;;; fragment's internal state.)
;;;
;;; In the interest of good output code, some work is done to simplify
;;; things when frags are merged. If an output is of the form (setq
;;; out c) where c is T, nil, or a number, then c is substituted
;;; directly for the input. Substitution is also applied if c is a
;;; variable which is not bound in the destination frag. In addition,
;;; other kinds of constants are substituted if they are only used in
;;; one place. A final pass gets rid of setqs to variables that are
;;; never used for anything.
(defmacro free-out (s) ;var output is assigned to if any.
`(off-line-exit ,s))
;;; only inputs can have off-line exits, so we can reuse the same
;;; field for this. if an output is assigned to a variable on
;;; *renames*, the variable is recorded here. This is used in some
;;; situations to hook up data flow correctly. It also indicates a
;;; few additional things.
;;;
;;; (A) you cannot every kill this ret, because you may need it even if
;;; you do not need it for dflow by nesting of expressions.
;;;
;;; (B) if you have it still existing at the end of everything, because
;;; it was never used, then this is something to issue a warning about,
;;; but it is not a value to be returned by the expression as a whole.
;;;
;;; The third key internal form is a graph of frags. This is
;;; represented in an indirect way. The special variable *graph*
;;; contains a list of all of the frags in the series expression
;;; currently being processed. The order of the frags in this list is
;;; vitally important. It corresponds to their lexical order in the
;;; input expression and controls the default way things with no data
;;; flow between them are ordered when combined. In addition, many of
;;; the algorithms depend on the fact that the order in *graph* is
;;; compatible with the data flow in that there can never be data flow
;;; from a frag to an earlier frag in the list.
;;;
;;; Subexpressions and regions within the expression as a whole are
;;; delineated by setting marking bits in the frags in the region.
;;;
;;; lambda-series makes special frags for arguments which are not in
;;; the list *graph*. They exist to record info about the arguments
;;; and to preserve an invariant that every input of every frag in
;;; *graph* must have data flow ending on it. A related invariant
;;; states that if a frag in *graph* has a ret then this ret must be
;;; used either by having dflow from it, or as an output of the
;;; expression as a whole. Unused rets are removed from frags when
;;; the frags are created.
;;;
;;; for the purposes of testing whether a subexpression is strongly
;;; connected to its outputs, a frag with no rets is considered to be
;;; an output of the subexpression.
(cl:defun non-series-p (frag)
(and (notany #'series-var-p (rets frag))
(notany #'series-var-p (args frag))))
;; this assumes that every instance of one of series's funny labels is
;; really an instance of that label made by the macros below.
(cl:defun branches-to (label tree)
(cond ((and (eq-car tree 'tagbody) (member label tree)) nil)
((and (eq-car tree 'go) (eq-car (cdr tree) label)) t)
(t (do ((tt tree (cdr tt)))
((not (consp tt)) nil)
(when (branches-to label (car tt))
(return t))))))
#+:series-plain
(cl:defun prolog-branches-to (label frag)
(branches-to label (prolog frag)))
#-:series-plain
(cl:defun prolog-branches-to (label frag)
(some #'(lambda (p) (branches-to label p)) (prolog frag)))
(cl:defun active-terminator-p (frag)
(or (prolog-branches-to end frag)
(branches-to end (body frag))))
;; This gets rid of duplicate labs in a row.
(cl:defun clean-labs (frag stmtns)
(cl:let ((alist nil))
(do ((l stmtns (cdr l))) ((not (consp (cdr l))))
CLEANL (when (and (car l) (symbolp (car l))
(cadr l) (symbolp (cadr l)))
(push (cons (pop (cdr l)) (car l)) alist)
(go CLEANL)))
(nsublis alist frag)))
(cl:defun apply-wrappers (wrps code &optional (test #'identity))
(dolist (wrp wrps)
(when (cl:funcall test wrp)
(setq code (cl:funcall (eval (wrapper-function wrp)) code))))
code)
(cl:defun wrap-code (wrps code &optional (test #'identity))
(if (cdr code)
(setq code (cons 'progn code))
(setq code (car code)))
(list (apply-wrappers wrps code test)))
(cl:defun clean-tagbody-redundancy (expr)
(if expr
(cl:let ((a (car expr)))
(if (and (eq-car a 'go)
(eq (cadr a) (cadr expr)))
(values (rplacd (cdr expr) (clean-tagbody-redundancy (cddr expr)))
t)
(cl:multiple-value-bind (remaining cleaned) (clean-tagbody-redundancy (cdr expr))
(if cleaned
(values (rplacd expr remaining) t)
(values expr nil)))))
(values nil nil)))
(cl:defun clean-tagbody-deadcode (expr)
(if expr
(cl:let ((a (car expr)))
(if (eq-car a 'go)
(cl:let ((remaining (member-if #'symbolp (cdr expr))))
(values (rplacd expr (and remaining (rplacd remaining (clean-tagbody-deadcode (cdr remaining)))))
t))
(cl:multiple-value-bind (remaining cleaned) (clean-tagbody-deadcode (cdr expr))
(if cleaned
(values (rplacd expr remaining) t)
(values expr nil)))))
(values nil nil)))
(cl:defun clean-tagbody-body (expr)
(when expr
(cl:let ((cleaned t))
(clean-tagbody-deadcode expr)
;; This should be done better, with the list reversed
(tagbody
L
(cl:multiple-value-setq (expr cleaned) (clean-tagbody-redundancy expr))
(if cleaned (go L)))
(if (every #'symbolp expr)
nil
(if (every #'(lambda (x) (or (symbolp x) (eq-car x 'go))) expr)
(cl:let ((tags (remove-if-not #'symbolp expr))
(stms (remove-if #'symbolp expr)))
(setq cleaned nil)
(dolist (s tags)
(unless (find-if #'(lambda (x) (eq (cadr x) s)) stms)
(setq expr (delete s expr))
(setq cleaned t)))
(if cleaned
(clean-tagbody-body expr)
expr))
expr)))))
(cl:defun clean-tagbody (expr)
(when-bind (body (clean-tagbody-body (cdr expr)))
(if (cdr body)
(cons 'tagbody body)
(car body))))
;; This takes a series frag all of whose inputs and outputs are
;; non-series things and makes it into a non-series frag.
(cl:defun maybe-de-series (frag &optional (prologize t))
(when (non-series-p frag)
(cl:let ((bod (body frag)))
(when (or bod (epilog frag))
(cl:let ((loop nil)
(wrps (wrappers frag)))
(when bod
(when (not (active-terminator-p frag))
(wrs 29 nil "~%Non-terminating series expression:~%" (code frag)))
(cl:let ((lab (new-var 'll)))
(setq loop (clean-tagbody
`(tagbody ,lab ,@bod (go ,lab)
,@(when (branches-to end bod) `(,end))
))))
(when (and wrps loop)
(setq loop (apply-wrappers wrps loop #'loop-wrapper-p))))
(when wrps
(setf (wrappers frag) (delete-if #'loop-wrapper-p wrps)))
(cl:let ((ending (if loop
(append (list loop) (epilog frag))
(epilog frag))))
(if prologize
(progn
(append-prolog frag ending)
(setf (body frag) nil))
(setf (body frag) ending)))
(setf (epilog frag) nil)
(clean-labs frag (cdr loop))))))
frag)
;; hacking marks
(cl:defun reset-marks (&optional (value 0))
(dolist (f *graph*)
(setf (marks f) value)))
(cl:defun mark (mask frag) ;sets bits on
(setf (marks frag) (logior mask (marks frag))))
(cl:defun marked-p (mask frag) ;checks that all bits are on
(zerop (logandc2 mask (marks frag))))
(defmacro dofrags ((var . mask) &body body) ;mask should be a constant
(when mask
(setq body `((when (marked-p ,(car mask) ,var) ,@ body))))
`(dolist (,var *graph*) ,@ body))
(cl:defun worsen-purity (p1 p2)
(if p1
(if p2
(ecase p1
((t) t)
(:context (if (eq p2 t) t :context))
(:fun p2)
(:args (if (eq p2 :fun)
:args
p2))
(:mutable (if (or (eq p2 :fun)
(eq p2 :args))
:mutable
p2)))
p1)
p2))
;; many of the functions in this file depend on the fact that frags
;; and syms are list structures.
;; But at least, the following function does not depend anymore on the
;; exact position of parts of these structures. I hope no other one still does.
;; BTW, note that the CL manual guarantees that these
;; positions would be correct in all implementations.
(cl:defun merge-frags (frag1 frag2)
(when (must-run frag1) (setf (must-run frag2) t))
#+:series-plain
(progn
(setf (aux frag2) (nconc (aux frag1) (aux frag2)))
(setf (prolog frag2) (nconc (prolog frag1) (prolog frag2))))
#-:series-plain
(cl:let ((a1 (aux frag1))
(a2 (aux frag2))
(p1 (prolog frag1))
(p2 (prolog frag2)))
(if (some #'(lambda (i)
(some #'(lambda (o)
(member i (nxts o)))
(rets frag1)))
(args frag2))
(progn
(when (or p1 p2)
(setf (prolog frag2)
(nconc (if a1
(or p1 (make-list (length a1)))
p1)
(if a2
(or p2 (make-list (length a2)))
p2))))
(when (or a1 a2)
(setf (aux frag2)
(nconc (if p1
(or a1 (make-list (length p1)))
a1)
(if p2
(or a2 (make-list (length p2)))
a2)))))
(progn
(setf (prolog frag2)
(noverlap 1 (if a1
(or p1 (make-list (length a1)))
p1)
(if a2
(or p2 (make-list (length a2)))
p2)))
(setf (aux frag2)
(noverlap 1 (if p1
(or a1 (make-list (length p1)))
a1)
(if p2
(or a2 (make-list (length p2)))
a2))))))
(mapc #'(lambda (s) (setf (fr s) frag2)) (rets frag1))
(mapc #'(lambda (s) (setf (fr s) frag2)) (args frag1))
(setf (args frag2) (nconc (args frag1) (args frag2)))
(setf (rets frag2) (nconc (rets frag1) (rets frag2)))
(setf (alterable frag2) (nconc (alterable frag1) (alterable frag2)))
(setf (body frag2) (nconc (body frag1) (body frag2)))
(setf (epilog frag2) (nconc (epilog frag1) (epilog frag2)))
(setf (wrappers frag2) (nconc (wrappers frag1) (wrappers frag2)))
(setf (impure frag2) (worsen-purity (impure frag1)
(impure frag2)))
frag2)
(cl:defun find-gensyms (tree &optional (found nil))
(do ((tt tree (cdr tt)))
((not (consp tt))
(if (and (symbolp tt) (null (symbol-package tt)))
(adjoin tt found)
found))
(setq found (find-gensyms (car tt) found))))
(cl:defun copy-ptrs (sym frag)
(setf (back-ptrs sym) (make-array 2))
(setf (nxts sym) nil)
(setf (fr sym) frag))
(cl:defun copy-fragment (frag)
(cl:let* ((alist (mapcar #'(lambda (v) (cons v (gensym (root v))))
(find-gensyms frag)))
(new-frag (list* 'frag (code frag)
(nsublis alist (iterative-copy-tree (cddr frag))))))
(dolist (a (args new-frag))
(copy-ptrs a new-frag))
(dolist (r (rets new-frag))
(copy-ptrs r new-frag))
new-frag))
(cl:defun frag->list (frag)
(setq frag (copy-list frag))
(setf (rets frag) (copy-tree (mapcar #'cddr (rets frag))))
(setf (args frag) (copy-tree (mapcar #'cddr (args frag))))
(cl:let ((gensyms (find-gensyms frag)))
(sublis (mapcar #'(lambda (v) (cons v (new-var (root v)))) gensyms)
(cons gensyms (iterative-copy-tree (cddddr frag))))))
(cl:defun root (symbol)
(cl:let* ((string (string symbol))
(pos (position #\- string :start (min (length string) 1))))
(if pos
(subseq string 0 (1+ pos))
(concatenate 'string string "-"))))
(cl:defun list->sym (list frag)
(cl:let ((s (make-sym :var (car list) :series-var-p (cadr list)
:off-line-spot (caddr list)
:off-line-exit (cadddr list)
)))
(setf (fr s) frag)
s))
(cl:defun list->frag1 (list)
(cl:let* ((alist (mapcar #'(lambda (v) (cons v (gensym (root v)))) (pop list)))
(frag (list* 'frag :|| 0 nil
(nsublis alist (iterative-copy-tree list)))))
(setf (args frag) (mapcar #'(lambda (s) (list->sym s frag)) (args frag)))
(setf (rets frag) (mapcar #'(lambda (s) (list->sym s frag)) (rets frag)))
(values frag alist)))
(cl:defun list->frag (list)
(cl:multiple-value-bind (frag alist) (list->frag1 list)
(setf (aux frag) (makeaux (aux frag)))
(setf (prolog frag) (makeprolog (prolog frag)))
(values frag alist)))
;; Special form for defining series functions directly in the internal
;; form. The various variables and the exit label must be unique in
;; the body. The exit label must be END. Also everything is arranged
;; just as it is in an actual frag structure.
(cl:defun literal-frag (stuff) ;(args rets aux alt prolog body epilog wraprs impure)
(cl:let ((gensyms (nconc (mapcar #'car (nth 0 stuff))
(mapcar #'car (nth 2 stuff)))))
(dolist (f (nth 5 stuff))
(when (symbolp f)
(push f gensyms)))
(list->frag (cons gensyms stuff))))
(defmacro delete1 (thing list)
`(setf ,list (delete1a ,thing ,list)))
(cl:defun delete1a (item list)
(if (eq item (car list))
(cdr list)
(do ((l list (cdr l)))
((null (cdr list)))
(when (eq item (cadr l))
(rplacd l (cddr l))
(return list)))))
(cl:defun pusharg (arg frag)
(setf (fr arg) frag)
(setf (args frag) (cons arg (args frag))))
(cl:defun +arg (arg frag)
(setf (fr arg) frag)
(setf (args frag) (nconc (args frag) (list arg)))) ;needed by cotruncate
(cl:defun -arg (arg)
(delete1 arg (args (fr arg))))
(cl:defun +ret (ret frag)
(setf (fr ret) frag)
(setf (rets frag) (nconc (rets frag) (list ret)))) ;needed by coerce-to-type
(cl:defun delete-ret (ret frag)
(delete1 ret (rets frag)))
(cl:defun -ret (ret)
(delete1 ret (rets (fr ret))))
(cl:defun kill-ret (ret)
(when (off-line-spot ret)
(setf (body (fr ret))
(nsubst-inline nil (off-line-spot ret) (body (fr ret)))))
(when (and (not (series-var-p ret))
(every #'(lambda (r) (or (eq r ret) (series-var-p r)))
(rets (fr ret))))
(setf (must-run (fr ret)) t)) ;signal must run to cause any side-effects.
(-ret ret))
(cl:defun +frag (frag)
(setf *graph* (nconc *graph* (list frag))) ;needed to keep order right
frag)
(cl:defun -frag (frag)
(delete1 frag *graph*)
(setf (marks frag) 0) ;important so dofrags will notice deletions
frag)
(cl:defun +dflow (source dest)
(push dest (nxts source))
(setf (prv dest) source))
(cl:defun -dflow (source dest)
(delete1 dest (nxts source))
(setf (prv dest) nil))
(cl:defun all-nxts (frag)
(apply #'append (mapcar #'(lambda (r) (nxts r)) (rets frag))))
(cl:defun all-prvs (frag)
(delete nil (mapcar #'(lambda (a) (prv a)) (args frag))))
(cl:defun yes (call) (declare (ignore call)) t)
(cl:defun no (call) (declare (ignore call)) nil)
);end of eval-when
;;;; ---- FUNCTIONS FOR CODE WALKING ----
;;; M-&-R takes in a piece of code. It assumes CODE is a semantic
;;; whole. Ie, it is something which could be evaled (as opposed to a
;;; disembodied cond clause). It scans over CODE macroexpanding all of
;;; the parts of it, and performing renames as specified by *RENAMES*.
;;; M-&-R puts entries on the variable *RENAMES* which block the
;;; renaming of bound variables.
;;;
;;; M-&-R also calls FN (if any) on every subpart of CODE (including
;;; the whole thing) which could possibly be evaluated. The result of
;;; consing together all of the results of FN is returned. Ie, the
;;; result is isomorphic to the input with each part replaced with
;;; what FN returned. This is done totally by copying. The input is
;;; not altered.
;;;
;;; In addition, M-&-R checks to see that the code isn't setqing
;;; variables it shouldn't be.
;;;
;;; In order to do the above, M-&-R has to be able to understand
;;; fexprs. It understands fexprs by having a description of each of
;;; the standard ones (see below). It will not work on certain weird
;;; ones.
;;;
;;; fexprs are understood by means of templates which are (usually
;;; circular) lists of function names. These fns are called in order
;;; to processes the various fields of the fexpr. The template can be
;;; a single fn in which case this fn is called to process the fexpr
;;; as a whole.
(defmacro make-template (head rest)
`(cl:let ((h (append ',head nil))
(r (append ',rest nil)))
(nconc h r r)))
(defmacro deft (name head rest)
`(setf (get ',name 'scan-template) (make-template ,head ,rest)))
;; These two should de DEFCONSTANTs, but CMUCL gets confused by
;; circularity. This happens when you load up series and then try to
;; reload series. CMUCL tries to compare the old value with the new
;; value to see if they differ. If the objects are circular, CMUCL
;; gets stuck.
(defvar /expr-template/ (make-template (q) (e)))
(defvar /eval-all-template/ (make-template () (e)))
;; Sample LispWorks' MACROLET walking
;;
;; CL-USER 1> (defmacro foo (x)
;; `(bar ,x))
;; FOO
;;
;; CL-USER 2> (walker:walk-form '(macrolet ((bar (x) `(print ,x)))
;; (foo 3)))
;; (MACROLET ((BAR (X) (LIST (QUOTE PRINT) X)))
;; (PRINT 3))
;;
;; CL-USER 3> (walker:walk-form '(macrolet ((bar (x) `(print ,x)))
;; (macrolet ((baz (x) `(bar ,x)))
;; (baz 3))))
;; (MACROLET ((BAR (X) (LIST (QUOTE PRINT) X)))
;; (MACROLET ((BAZ (X) (LIST (QUOTE BAR) X)))
;; (PRINT 3)))
;;
;; CL-USER 4> (walker::walk-form '(macrolet ((bar (x) `(print ,x)))
;; (macrolet ((baz (x) `(bar ,x))
;; (froboz (x) `(format t ,x)))
;; (baz 3)
;; (froboz 5))))
;; (MACROLET ((BAR (X) (LIST (QUOTE PRINT) X)))
;; (MACROLET ((BAZ (X) (LIST (QUOTE BAR) X))
;; (FROBOZ (X) (LIST (QUOTE FORMAT) T X)))
;; (PRINT 3)
;; (FORMAT T 5)))
;;
;; Expand a MACROLET form
(cl:defun expand-macrolet (code)
;; LispWork's WALKER can handle MACROLET. Remove the expanded
;; MACROLET still sticking around - Seems correct (see
;; above). Optimization hint: Walking once and just removing
;; MACROLETs later?
;;
;; CMUCL's PCL walker behaves like LispWorks.
;;
;; Clisp's walker doesn't leave the macrolet forms around so it's a
;; little easier.
#+:lispworks
(loop
(unless (and (listp code)
(case (car code)
((cl:macrolet cl:symbol-macrolet) t)
(t nil)))
(return code))
(setq code (cons 'progn (cddr (walker::walk-form code)))))
#+(and cmu (not :cmu18e))
(cl:let ((pcl::walk-form-macroexpand-p t))
(loop
(unless (and (listp code)
(case (car code)
((cl:macrolet cl:symbol-macrolet) t)
(t nil)))
(return code))
(setq code (cons 'progn (cddr (walker::walk-form code))))))
#+(and cmu :cmu18e)
(loop
(unless (and (listp code)
(case (car code)
((cl:macrolet cl:symbol-macrolet) t)
(t nil)))
(return code))
(setq code (cons 'progn (cddr (walker::macroexpand-all code)))))
#+clisp
(loop
(unless (and (listp code)
(case (car code)
((cl:macrolet cl:symbol-macrolet) t)
(t nil)))
(return code))
(cl:let ((SYSTEM::*FENV* nil) (SYSTEM::*vENV* nil))
(setq code (list 'progn (sys::%expand-form code)))))
#-(or :lispworks :cmu :clisp)
code)
;; on lispm '(lambda ...) macroexpands to (function (lambda ...)) ugh!
(cl:defun my-macroexpand (original-code)
(cl:let ((code original-code))
(setq code (expand-macrolet code))
(cl:let ((flag (not (frag-p original-code))) head temp)
(loop
(when (not (and flag (consp code)))
(return code))
(when (setq temp (or (and (symbolp (setq head (car code)))
(get head 'my-macro))
(and (consp head)
(symbolp (car head))
(get (car head) 'my-macro))))
(setq code (expand-macrolet (cl:funcall temp code))))
(when (not (symbolp (setq head (car code))))
(return code))
(loop
(when (not (get (setq head (car code)) 'series-optimizer))
(return nil))
(when (not *in-series-expr*)
(when (and *not-straight-line-code*
(cl:funcall (get head 'returns-series) code))
(rrs 20 "~%Not straight-line code~%" *not-straight-line-code*))
(return nil))
(cl:let ((*call* code))
(setq code (expand-macrolet (apply (get head 'series-optimizer) (cdr code))))))
(when (frag-p code)
(annotate original-code code)
(return code))
(when (get (car code) 'scan-template)
(return code))
;; protects from any macro side-effects
(when (eq code original-code)
(setq code (expand-macrolet (iterative-copy-tree code))))
(multiple-value-setq (code flag)
(macroexpand-1 code *env*))
(setq code (expand-macrolet code))
))))
;; special macro-like forms to handle setq forms. Note psetq is
;; already a macro.
(cl:defun my-lambda-macro (form)
(if (not (consp (car form)))
form
(cl:let ((args (cadar form))
(body (cddar form))
(vals (cdr form)))
(if (and (every #'(lambda (a)
(and (symbolp a) (not (member a lambda-list-keywords))))
args)
(= (length args) (length vals)))
`(let ,(mapcar #'list args vals) . ,body)
form))))
(setf (get 'lambda 'my-macro) #'my-lambda-macro)
(cl:defun my-setq-macro (form)
(cond ((null (cdr form)) nil)
((cdddr form)
`(progn ,@(do ((l (cdr form) (cddr l))
(r nil (cons `(setq ,(car l) ,(cadr l)) r)))
((null l) (nreverse r)))))
(t form)))
(setf (get 'setq 'my-macro) #'my-setq-macro)
(cl:defun m-&-r (code &optional (*fn* nil))
(cl:let ((*being-setqed* nil))
(m-&-r1 code)))
(defconst-once /fexprs-not-handled/ '(flet labels #-:lispworks macrolet))
(defconst-once /expr-like-special-forms/
'(multiple-value-call multiple-value-prog1 progn progv the throw
;;some simple additions for lispm
*catch multiple-value-return progw return-list
variable-boundp variable-location variable-makunbound)
"special forms that can be treated like ordinary functions.
e.g., they have the same template as expr-template.")
(cl:defun not-expr-like-special-form-p (sym)
(and #-series-ansi(special-form-p sym)
#+series-ansi(special-operator-p sym)
(not (member sym /expr-like-special-forms/))))
(cl:defun m-&-r2 (code template)
(if (not (listp template))
(cl:funcall template code)
(mapcar #'(lambda (tm c) (cl:funcall tm c)) template code)))
(cl:defun m-&-r1 (code)
(cl:let ((*renames* *renames*))
(setq code (my-macroexpand code))
(when (symbolp code)
(setq code (or (cdr (assoc code *renames*)) code)))
(when *fn*
(setq code (cl:funcall *fn* code)))
(if (not (consp code))
code
(cl:let* ((head (car code))
(template (and (symbolp head) (get head 'scan-template))))
;;(format t "code = ~A~%" code)
(when (or (member head /fexprs-not-handled/)
(and (not-expr-like-special-form-p head) (null template))
(and *in-series-expr* (eq head 'multiple-value-call)))
(rrs 6 "~%The form " head " not allowed in SERIES expressions."))
#+nil
(let ((*print-circle* t))
(format t "template = ~A~%" template))
(m-&-r2 code
(if (symbolp head)
(or template /expr-template/)
/eval-all-template/))))))
;; This macro-expands everything in the code making sure that all free
;; variables (that are not free in the whole series expression) are
;; appropriately changed to gensyms. It returns the new code plus
;;
;; (a) list of pairs of internal var gensyms and external values.
;; Typically, dflow should be inserted from the external values to
;; ports made with these gensyms.
;;
;; (b) list of pairs of output gensyms and the actual var names they modify.
;; (c) list of vars from the list CHECK-SETQ that are setqed.
;;
;; If the state argument is supplied, it contains lists of input and
;; output info that is used to initialize things. error messages are
;; issued if a series value is used in an improper context.
(cl:defun handle-non-series-stuff (code &optional (state nil) (check-setq nil))
(cl:let ((free-ins (car state)) (free-outs (cadr state)) (setqed nil))
(setq code
(m-&-r code
#'(lambda (cd)
(when (and check-setq (symbolp cd) *being-setqed*
(member cd check-setq))
(setq setqed (adjoin cd setqed)))
(cl:let ((c (if (frag-p cd)
(retify cd)
cd))
temp)
(when (sym-p c)
(if *being-setqed*
(if (setq temp (assoc c free-outs))
(setq c (car (cdr temp)))
(cl:let ((new (if (setq temp (assoc c free-ins))
(car (cdr temp))
(new-var 'freeout)))
(v (car (rassoc cd *renames*))))
(push (cons c (cons new v)) free-outs)
(setq c new)))
(if (setq temp (assoc c free-ins))
(setq c (car (cdr temp)))
(cl:let ((arg (if (setq temp (assoc c free-outs))
(car (cdr temp))
(new-var 'freein))))
(when (series-var-p c)
(when *not-straight-line-code*
(rrs 20 "~%Not straight line code~%" code))
(when (not *in-series-expr*)
(rrs 12 "~%Series var " (car (rassoc c *renames*))
" referenced in nested non-series LAMBDA.")))
(push (cons c (cons arg c)) free-ins)
(setq c arg)))))
c))))
(values code (mapcar #'cdr free-ins) (mapcar #'cdr free-outs)
setqed (list free-ins free-outs))))
;;; ---- TURNING EXPRESSIONS INTO FRAGS (FRAGMENTATION) ----
;; This parses code down to fundamental chunks creating a graph of the
;; expression. Note that macroexpanding and renaming is applied while
;; this happens. (`fragmentation')
;; FRAGMENTATION
(cl:defun decode-type-arg (type &optional (allow-zero nil))
(cond ((eq type '*) '*)
((eq-car type 'values)
(when (and (not allow-zero) (equal type '(values)))
(ers 62
"~%The type (VALUES) specified where at least one value required."))
(subst t '* (cdr type)))
((and (not (symbolp type)) (functionp type))
(ers 70 "~%Function supplied where type expected."))
(t (list type))))
;; FRAGMENTATION
(cl:defun pass-through-frag (rets)
(cl:let ((frag (make-frag)))
(dolist (ret rets)
(cl:let* ((series-p (series-var-p ret))
(in (new-var 'passin))
(in-sym (make-sym :var in :series-var-p series-p))
(out-sym (make-sym :var in :series-var-p series-p)))
(+arg in-sym frag)
(+ret out-sym frag)
(+dflow ret in-sym)))
(+frag frag)))
;; FRAGMENTATION
;;
;; note this can assume that the vars are gensyms that they only
;; appear where they are really used. HERE with the way if works,
;; because it will not catch nested lets!
;; This is only called from isolate-non-series
(cl:defun map-exp (exp vars)
(cl:let ((prolog-exps nil)
(new-aux nil))
(cl:labels ((map-exp0 (exp) ;can assume exp contains vars
(cond ((symbolp exp) exp)
((eq (car exp) 'if) exp)
((not-expr-like-special-form-p (car exp))
(ers 99 "~%Implicit mapping cannot be applied to the special form "
(car exp)))
(t `(,(car exp)
,@(mapcar #'(lambda (x)
(cond ((contains-any vars x) (map-exp0 x))
((or (symbolp x)
(constantp x)
(eq-car x 'cl:function)
(eq-car x 'cl:lambda)) x)
(t (cl:let ((v (new-var 'm)))
(push v new-aux)
(push `(setq ,v ,x) prolog-exps)
v))))
(cdr exp)))))))
(declare (dynamic-extent #'map-exp0))
(cl:let ((body-exp (map-exp0 exp)))
(values (nreverse prolog-exps) body-exp (nreverse new-aux))))))
;; FRAGMENTATION
;;
;; note that this does implicit mapping when appropriate. Note also
;; that it only maps the absolute minimum necessary. This is to
;; ensure that things will come out the same no matter how they were
;; syntactically expresssed in the input. Also mapping of special
;; forms other than if is not allowed. If it were it could lead to all
;; kinds of problems with binding scopes and scopes for gos and the
;; like.
;; This is called only from fragify
(cl:defun isolate-non-series (n code)
(cl:multiple-value-bind (exp free-ins free-outs)
(handle-non-series-stuff code)
(cl:let* ((vars (n-gensyms n (symbol-name '#:out-)))
(mapped-inputs nil)
(frag (make-frag :aux (makeaux (mapcar #'(lambda (v) (list v t)) vars)))))
(dolist (entry free-ins)
(cl:let ((arg (make-sym :var (car entry))))
(when (and *series-implicit-map* (series-var-p (cdr entry)))
(push (car entry) mapped-inputs)
(setf (series-var-p arg) t))
(+arg arg frag)
(+dflow (cdr entry) arg)))
(dolist (v vars)
(+ret (make-sym :var v :series-var-p mapped-inputs) frag))
(when (zerop n)
(setf (must-run frag) t))
(if (null mapped-inputs)
(setf (prolog frag) (makeprolog (list (make-general-setq vars exp))))
(cl:multiple-value-bind (prolog-exps body-exp new-aux)
(map-exp exp mapped-inputs)
(when prolog-exps
(setf (prolog frag) (makeprolog prolog-exps))
(dolist (a new-aux)
(add-aux frag a t)))
(setf (body frag) (list (make-general-setq vars body-exp)))))
(dolist (entry free-outs)
(cl:let ((new (make-sym :var (car entry)
:series-var-p mapped-inputs))
(v (cdr entry)))
(when (not (find (car entry) (args frag) :key #'var))
(add-aux frag (car entry) t))
(setf (free-out new) v)
(+ret new frag)
(rplacd (assoc v *renames*) new)))
(+frag frag))))
;; FRAGMENTATION
(cl:defun fragify (code type)
(cl:let* ((expansion (my-macroexpand code))
(ret (when (symbolp expansion)
(cdr (assoc expansion *renames*))))
(types (decode-type-arg type t)))
(coerce-to-types types
(cond ((frag-p expansion) expansion) ;must always make a new frag
((sym-p ret) (annotate code (pass-through-frag (list ret))))
((eq-car expansion 'the)
(fragify (caddr expansion) (cadr expansion)))
((eq-car expansion 'values)
;; It used to map over the cdr of CODE here, which is
;; obviously not right -- for instance in the case where
;; (NTH-VALUE 0 x) --> (VALUES x) but it maps over (0 x)
;; and then thinks there is more than one value. However
;; I'm not sure it's right to just blithly map over the
;; expansion either...
(cl:let ((rets (mapcar #'(lambda (form)
(car (rets (fragify form t))))
(cdr expansion))))
(when (and (cdr rets) (some #'series-var-p rets))
(rrs 7 "~%VALUES returns multiple series:~%" code))
(annotate code (pass-through-frag rets))))
(t (annotate code (isolate-non-series
(if (listp types)
(length types)
1)
expansion)))))))
;; Have to be careful not to macroexpand things twice. If you did, you
;; could get two copies of some frags on *graph*. Note that a type of
;; '* means any number of arguments.
(cl:defun retify (code &optional (type t))
(if (sym-p code)
code ;might have been retified/fragified before.
(cl:let* ((expansion (my-macroexpand code))
(ret (when (symbolp expansion)
(cdr (assoc expansion *renames*)))))
(if (sym-p ret)
ret
(car (rets (fragify expansion type)))))))
;;; What the following is doing with the free variables may not be
;;; quite right. All in all, it is pretty scary if you refer to local
;;; lexical vars in a fn in a series expression. HERE Note that for
;;; the moment, Series does not realize that you have used a variable
;;; if this is the only way you use it.
(cl:defun process-fn (code)
(cl:let ((*in-series-expr* nil) (*not-straight-line-code* nil)
(*user-names* nil) (*renames* *renames*))
(cl:multiple-value-bind (fn free-ins free-outs)
(handle-non-series-stuff code)
(dolist (f free-ins)
(setq fn (nsubst (var (cdr f)) (car f) fn)))
(dolist (f free-outs)
(setq fn (nsubst (cdr f) (car f) fn)))
fn)))
;;; ---- MACROEXPANSION TEMPLATES ----
;; The following are the fns allowed in templates.
(cl:defun fun (code) (if (not (consp code)) code (process-fn code)))
;; This handles binding lists for FLET.
(cl:defun fbind-list (args)
(mapcar #'fun args))
;; This handles binding lists for LET.
(cl:defun bind-list (args sequential &aux (pending nil))
(prog1 (mapcar #'(lambda (arg)
(cl:let* ((val-p (and (consp arg) (cdr arg)))
(new-val (when val-p
(m-&-r1 (cadr arg))))
(var (if (consp arg)
(car arg)
arg)))
(if sequential
(push (list var) *renames*)
(push (list var) pending))
(if val-p
(list (car arg) new-val)
arg)))
args)
(setq *renames* (append pending *renames*))))
(cl:defun arg-list (args)
(mapcar #'(lambda (arg)
(cl:let* ((vars (vars-of arg))
(val-p (and (consp arg) (cdr arg)))
(new-val (when val-p
(m-&-r1 (cadr arg)))))
(setq *renames* (append (mapcar #'list vars) *renames*))
(if val-p
(list* (car arg) new-val (cddr arg))
arg)))
args))
(cl:defun q (code) code)
(cl:defun e (code) (m-&-r1 code))
(cl:defun ex (code)
(cl:let* ((*not-straight-line-code* *in-series-expr*)
(*in-series-expr* nil))
(m-&-r2 code /expr-template/)))
(cl:defun el (code)
(cl:let* ((*not-straight-line-code* *in-series-expr*)
(*in-series-expr* nil))
(m-&-r1 code)))
(cl:defun elm (code)
(if *series-implicit-map*
(m-&-r1 code)
(el code)))
(cl:defun s (code) (cl:let ((*being-setqed* t)) (m-&-r1 code)))
(cl:defun b (code) (bind-list code nil))
(cl:defun b* (code) (bind-list code t))
(cl:defun a (code) (arg-list code))
(cl:defun lab (code) (if (symbolp code) code (el code)))
(cl:defun f (code) (fbind-list code))
(cl:defun compiler-let-template (form)
(cl:let ((symbols (mapcar #'(lambda (p) (if (consp p) (car p) p)) (cadr form)))
(values (mapcar #'(lambda (p) (when (consp p) (eval (cadr p)))) (cadr form)))
(body (cddr form)))
(progv symbols values
(e (if (null (cdr body))
(car body)
(list* 'let nil body))))))
(setf (get 'compiler-let 'scan-template) #'compiler-let-template)
;;; templates for special forms. Note that the following are not
;;; handled
;;;
;;; COMPILER-LET FLET LABELS MACROLET but must not macroexpand.
;;;
;;; FLET and DECLARE in particular are macros in lucid and messed
;;; things up by expanding at the wrong time.
(deft block (q q) (el))
(deft catch (q e) (el))
;;
;; I (RLT) changed this. I don't think the rest of a declaration
;; should be macro-expanded at all. Is this right? Did I do this
;; right?
;;(deft declare (q) (ex)) ;needed by xerox cl
(deft declare (q) (q))
(deft eval-when (q q) (e))
(deft function (q fun)())
(deft go (q q) ())
(deft if (q e) (elm))
(deft cl:let (q b) (e))
(deft cl:let* (q b*) (e))
(deft multiple-value-call (q) (e))
(deft multiple-value-prog1 (q) (e))
(deft progn (q) (e))
(deft progv (q) (e))
(deft quote (q q) ())
(deft return-from (q q) (e))
(deft setq (q) (s e))
(deft tagbody (q) (lab))
(deft the (q q) (e))
(deft throw (q) (e))
(deft unwind-protect (q) (el))
(deft lambda (q a) (e))
(deft flet (f) (e))
(deft compiler-let (q) (e))
(deft macrolet (q) (e))
(deft labels (f) (e))
(deft type (q q) (e))
(deft setf (q) (e)) ;fixes weird interaction with lispm setf
(deft locally (q) (e))
#+symbolics
(cl:eval-when (eval load)
(cl:defun WSLB (list)
(prog1 (EX list) (push (list (car list)) *renames*)))
(deft LET-IF (Q E B) (E))
(deft scl:WITH-STACK-LIST (Q WSLB) (E))
(deft scl:WITH-STACK-LIST* (Q WSLB) (E)))
;;; ---- TYPE HANDLING ----
;; TYPING
(cl:defun some-series-type-p (type)
(cl:flet ((s-car-p (typ)
(eq-car typ 'series)))
(declare (dynamic-extent #'s-car-p))
(or (s-car-p type)
(and (or (eq-car type 'or)
(eq-car type 'and))
(some #'s-car-p (cdr type))))))
;; TYPING
(cl:defun deserialize-type (type)
(cl:let ((cartyp (car type)))
(cl:flet ((upgrade-type (typ)
(if (eq-car typ 'series)
(cadr typ)
typ)))
(declare (dynamic-extent #'upgrade-type))
(if (eq cartyp 'series)
(cadr type)
(if (or (eq cartyp 'or)
(eq cartyp 'and))
(cons cartyp (mapcar #'upgrade-type (cdr type)))
type)))))
;; TYPING
(cl:defun truefy-type (type)
(cl:flet ((star2t (typ)
(if (eq typ '*)
t
typ)))
(declare (dynamic-extent #'star2t))
(typecase type
(list (cl:let ((cartyp (car type)))
(if (or (eq cartyp 'or)
(eq cartyp 'and))
(cons cartyp (mapcar #'star2t (cdr type)))
type)))
(t (star2t type)))))
;; TYPING
;; this is also used by PROTECT-FROM-SETQ in an odd way.
(cl:defun coerce-to-type (type ret)
(when (eq type 'series)
(setq type '(series t)))
(when (not (eq type t))
(when (and (not (some-series-type-p type))
(series-var-p ret))
(wrs 30 t "~%Series encountered where not expected."))
(when (some-series-type-p type)
(when (not (series-var-p ret))
(wrs 31 t "~%Non-series value encountered where series expected."))
(setq type (deserialize-type type))
(setq type (truefy-type type)))
(cl:let ((aux (find-aux (var ret) (aux (fr ret)))))
(when (and aux (not (subtypep (cadr aux) type)))
(setf (cadr aux) type)))))
;; This is only used by fragify
(cl:defun coerce-to-types (types frag)
(when (not (eq types '*))
(cl:let ((n (length types))
(current-n (length (rets frag))))
(cond ((= n current-n))
((< n current-n)
(mapc #'(lambda (r) (when (not (free-out r)) (kill-ret r)))
(nthcdr n (rets frag))))
(t (dolist (v (n-gensyms (- n current-n) (symbol-name '#:xtra-)))
(+ret (make-sym :var v) frag)
(add-literal-aux frag v t nil))))
(mapc #'coerce-to-type types (rets frag))))
frag)
;;;; ---- PHYSICAL REPRESENTATIONS FOR SERIES AND GENERATORS ----
;;; The following structure is used as the physical representation for
;;; a series. It is a structure so that it can print itself and get
;;; read in. The only operation on it is to get it to return a a
;;; generator object. The only operation on a generator object is
;;; NEXT-IN.
;;; Physical series are of two kinds basic and image. A basic series
;;; has three parts
;;;
;;; GEN-FN is a fn that generates new values. When called with no
;;; args, must either return a list of the next value, or nil
;;; indicating no more values to return. (If there is an alter
;;; function, then each value is actually a list of the fundamental
;;; value and any additional information needed by the alter function.
;;; NEXT-IN only returns the fundamental value in any case.)
;;;
;;; DATA-SO-FAR cons of NIL and data generated by GEN-FN so far. The
;;; last cdr is a flag that tells you whether the end has been
;;; reached. If it is t there is still more to get, if it is NIL you
;;; are done. (The NIL car is needed so that new elements can allways
;;; be added by side effect.)
;;;
;;; ALTER-FN is a fn that alters elements (or NIL if none). Must be a
;;; function that when called with a new item as its first arg and any
;;; additional information computed by the GEN-FN as its other
;;; arguments does the alteration.
;;;
;;; Image series compute one series from another without requiring any
;;; mutable internal state. The also have four parts.
;;;
;;; BASE-SERIES the series the image series is based on. The elements
;;; of the image are some simple function of the elements of the base.
;;; (The base can be another image series.)
;;;
;;; IMAGE-FN is a function with no changing internal state that will
;;; get the next full item of the series given a generator of the base
;;; series. It must behave the same as BASIC-DO-NEXT-IN.
;;;
;;; IMAGE-DATUM Some non-null value that can be used by the IMAGE-FN
;;; when deciding what to do. This often saves having to have the
;;; IMAGE-FN be a closure. It is passed as the second argument to the
;;; IMAGE-FN.
;;;
;;; ALTER-FN same as for a basic series.
(defstruct (foundation-series (:conc-name nil))
(alter-fn nil))
(defstruct (basic-series (:include foundation-series)
(:conc-name nil)
(:print-function print-series))
(gen-fn nil) data-so-far)
(defstruct (image-series (:include foundation-series)
(:conc-name nil)
(:print-function print-series))
image-fn image-base (image-datum nil))
(eval-when (:compile-toplevel :load-toplevel :execute)
(defmacro make-phys (&key (gen-fn nil) (alter-fn nil) (data-list t))
`(make-basic-series :gen-fn ,gen-fn :alter-fn ,alter-fn
:data-so-far (cons nil ,data-list)))
(cl:defun series-p (x)
(or (basic-series-p x) (image-series-p x)))
(deftype series (&rest type)
(declare (ignore type))
`(satisfies series-p))
(deftype series-element-type (var)
(declare (ignore var))
t)
;;; A generator is a data structure with the following parts. For
;;; speed in symbolics lisp, it is implement as a list.
;;;
;;; GEN-BASE is the series the generator is generating the elements
;;; of.
;;;
;;; GEN-BASE is one of two things depending on what kind of series the
;;; GEN-BASE is.
;;;
;;; For basic-series, it starts out as the data-so-far and is cdr'ed
;;; down as the elemnts are used. Also additional elements are
;;; tagged on to the end as needed. Sharing is used so that when
;;; elements are added here, they are automaticaly added onto the
;;; data-so-far of the series itself and to any other generators for
;;; this series as well.
;;;
;;; For image-series, it is a generator for the the IMAGE-BASE.
;;;
;;; In either of the cases above, the GEN-BASE becomes NIL when the
;;; generator is exhausted.
;;;
;;; CURRENT-ALTER-INFO is the list of information that is needed to
;;; alter the last element generated. (If the base has no alter-fn,
;;; then this is nil.)
(defstruct (generator (:conc-name nil) (:type list))
gen-state gen-base (current-alter-info nil))
#+(or :lispworks :cmu :scl :excl :sbcl :ccl)
(deftype generator () 'cons)
(cl:defun generator (s)
(make-generator
:gen-base s
:gen-state
(cond ((image-series-p s) (generator (image-base s)))
((basic-series-p s) (data-so-far s))
(t (ers 60 "~%GENERATOR applied to something that is not a series.")))))
(cl:defun generator-check (form)
(when *in-series-expr*
(rrs 24 "~%Using GENERATOR blocks optimization " form))
(cons 'generator0 (cdr form)))
(setf (get 'generator 'series-optimizer) #'generator-check)
(setf (get 'generator 'returns-series) #'no)
(cl:defun generator0 (s)
(make-generator
:gen-base s
:gen-state
(cond ((image-series-p s) (generator (image-base s)))
((basic-series-p s) (data-so-far s))
(t (ers 60 "~%GENERATOR applied to something that is not a series.")))))
;; This function interfaces to generators. No optimization ever
;; happens to generators except in the function PRODUCING. The next
;; element of the generator is returned each time DO-NEXT-IN is
;; called. If there are no more elements, the functional argument is
;; funcalled. It is an error to call DO-NEXT-IN again later.
;; This returns the next full entry in a generator, or sets the
;; gen-state to NIL indicating the generator is exhausted.
(cl:defun basic-do-next-in (g)
(when (gen-state g)
(cl:let ((full-current
(cond ((image-series-p (gen-base g))
(prog1 (cl:funcall (image-fn (gen-base g))
(gen-state g)
(image-datum (gen-base g)))
(when (null (gen-state (gen-state g)))
(setf (gen-state g) nil))))
(t (when (eq (cdr (gen-state g)) t)
(setf (cdr (gen-state g))
(cl:funcall (gen-fn (gen-base g)))))
(pop (gen-state g))
(car (gen-state g))))))
(cond ((alter-fn (gen-base g))
(setf (current-alter-info g) (cdr full-current))
(car full-current))
(t full-current)))))
(cl:defun do-next-in (g at-end &optional (alter nil alterp))
(cl:let ((current (basic-do-next-in g)))
(cond ((null (gen-state g)) (cl:funcall at-end))
(alterp
(apply (cond ((alter-fn (gen-base g)))
(t (ers 65 "~%Alter applied to an unalterable form.")))
alter (current-alter-info g)))
(t current))))
(defmacro next-in (generator &rest actions)
`(do-next-in ,generator #'(lambda () ,@ actions)))
;; The following is an example of an image function. It selects the
;; datum-th part of the full item of the base series as the item of
;; the image series.
(cl:defun image-of-datum-th (g datum)
(nth datum (basic-do-next-in g)))
(cl:defun values-lists (n series-of-lists &optional (alterers nil))
(multiple-value-polycall
#'(lambda (i)
(make-image-series :alter-fn (pop alterers)
:image-fn #'image-of-datum-th
:image-datum i
:image-base series-of-lists))
(n-integer-values n)))
#-cmu
(cl:defun print-series (series stream depth)
(cl:let ((generator (generator series)))
(write-string "#Z(" stream)
(do ((first-p t nil)
(i (cond (*print-length*) (t -1)) (1- i)))
(nil)
(cl:let ((element (next-in generator (return nil))))
(when (not first-p)
(write-char #\space stream))
(when (zerop i)
(write-string "..." stream) (return nil))
(write element :stream stream
:level (when *print-level*
(- *print-level* depth)))))
(write-char #\) stream)))
;; If we have a Common Lisp pretty-printer, we should use that to
;; print out series because that probably does a better job than this
;; routine would. We basically print out series as if it were a list
;; of items.
#+(or cmu scl)
(cl:defun print-series (series stream depth)
(cl:let ((generator (generator series))
(first-p t)
(items 0))
(pprint-logical-block (stream nil :prefix "#Z(" :suffix ")")
(loop
(cl:let ((element (next-in generator (return nil))))
(if first-p
(setf first-p nil)
(write-char #\Space stream))
(if (and *print-length*
(>= items *print-length*))
(progn
(princ "..." stream)
(pprint-newline :fill stream)
(return))
(progn
(write element :stream stream
:level (when *print-level*
(- *print-level* depth)))
(incf items)
(pprint-newline :fill stream))))))))
) ; end of eval-when
;;;; ---- TURNING AN EXPRESSION INTO A GRAPH ----
;;; The form below has to be called to set things up right, before
;;; processing of a series expression can proceed.
;;; should have some general error catching thing but common lisp has
;;; none.
(defmacro starting-series-expr (call body)
`(cl:let ((*renames* nil)
(*user-names* nil)
(*not-straight-line-code* nil)
(*in-series-expr* ,call))
,body))
;; assumes opt result cannot be NIL
(defmacro top-starting-series-expr (call opt non-opt)
(cl:let ((res (gensym)))
`(cl:let ((,res (catch :series-restriction-violation (starting-series-expr ,call ,opt))))
(if ,res
(values ,res t)
(values ,non-opt nil)))))
;; FRAGMENTATION
;; Main fragmentation function
;; This is only called from process-top
(cl:defun graphify (code &optional (return-type '*))
(cl:let ((*graph* nil))
(fragify code return-type)
*graph*))
(cl:defun check-off-line-ports (frag vars off-line-ports)
(do ((vars vars (cdr vars))
(args (args frag) (cdr args)))
((null args))
(if (off-line-spot (car args))
(when (not (member (car vars) off-line-ports))
(wrs 40 t "~%The input " (car vars) " unexpectedly off-line."))
(when (member (car vars) off-line-ports)
(wrs 41 t "~%The input " (car vars) " unexpectedly on-line."))))
(do ((i 0 (1+ i))
(rets (rets frag) (cdr rets)))
((null rets))
(if (off-line-spot (car rets))
(when (not (member i off-line-ports))
(wrs 42 t "~%The " i "th output unexpectedly off-line."))
(when (member i off-line-ports)
(wrs 43 t "~%The " i "th output unexpectedly on-line.")))))
(cl:defun vars-of (arg)
(cond ((member arg lambda-list-keywords) nil)
((not (consp arg)) (list arg))
(t (cons (if (consp (car arg))
(cadar arg)
(car arg))
(copy-list (cddr arg))))))
;; Important that this allows extra args and doesn't check.
(cl:defun apply-frag (frag values)
(mapc #'(lambda (v a) (+dflow (retify v) a)) values (args frag))
(+frag frag))
(cl:defun funcall-frag (frag &rest values)
(apply-frag frag values))
;; Macroexpansion may result in unexpected arcana we should let through.
(defconst-once /allowed-generic-opts/
'(optimize
#+:lispworks (CLOS::VARIABLE-REBINDING)
#+:clisp system::read-only))
;; This takes a list of forms that may have documentation and/or
;; declarations in the initial forms. It parses the declarations and
;; returns the remaining forms followed by the parsed declarations.
;; The list allowed-dcls specifies what kinds of declarations are
;; allowed. Error messages are given if any other kind of declaration
;; is found. Each allowed-dcl must be one of the symbols declared
;; special below.
(cl:defun decode-dcls (forms allowed-dcls)
(cl:let ((doc nil) (ignores nil) (types nil) (props nil)
(opts nil) (off-line-ports nil) (no-complaints nil)
(generic-opts nil))
(declare (special doc ignores types props opts off-line-ports no-complaints generic-opts))
(loop
(when (and (member 'doc allowed-dcls)
(null doc) (stringp (car forms)) (cdr forms))
(setq doc (pop forms)))
(when (not (eq-car (car forms) 'declare)) (return nil))
(dolist (d (cdr (pop forms)))
(cond ((and (eq (car d) 'type)
(member 'types allowed-dcls))
(dolist (v (cddr d)) (push (cons v (cadr d)) types)))
((and (or (member (car d) /short-hand-types/)
(and (listp (car d)) (member (caar d) /short-hand-types/)))
(member 'types allowed-dcls))
(dolist (v (cdr d)) (push (cons v (car d)) types)))
((and (eq (car d) 'optimizable-series-function)
(member 'opts allowed-dcls))
(setq opts (cond ((cadr d)) (t 1))))
((and (eq (car d) 'ignore)
(member 'ignores allowed-dcls))
(setq ignores (append (cdr d) ignores)))
((and (eq (car d) 'propagate-alterability)
(member 'props allowed-dcls))
(push (cdr d) props))
((and (eq (car d) 'off-line-port)
(member 'off-line-ports allowed-dcls))
(setq off-line-ports (append off-line-ports (cdr d))))
((not (member 'no-complaints allowed-dcls))
(if (member (car d) /allowed-generic-opts/)
(setq generic-opts (nconc generic-opts (list d)))
(rrs 1 "~%The declaration " d " blocks optimization.")))
(t (setq no-complaints (nconc no-complaints (list d)))))))
(values-list (cons forms (mapcar #'symbol-value allowed-dcls)))))
;;;; ---- MERGING A GRAPH ----
;;; This proceeds in several phases
;;; (1) check for series/non-series type conflicts. This operates in
;;; one of two different ways depending on the value of
;;; *SERIES-IMPLICIT-MAP*. If this control variable is non-nil then:
;;; (a) If a frag that does not process any series at all
;;; (i.e., came from totally non-series stuff in the source) receives
;;; a series for any of its inputs, then it was implicitly mapped
;;; by isolate-non-series. (Note, if the output is not connected to
;;; anything, it is marked as being forced to run.)
;;; (b) If a non-series is supplied where a series is expected, we
;;; coerce it into an infinite series of the single value.
;;; Whether or not *SERIES-IMPLICIT-MAP* is non-nil we then:
;;; (a) if a series is supplied where a non-series is expected,
;;; issue a restriction violation warning.
;;; It would not be in the spirit of things to create a physical series.
;;; And would be very hard to boot.
;;; (b) if a non-series is supplied where a series is expected,
;;; assume that this non-series item is really a physical series and
;;; add a physical interface. (Note this cannot happen when
;;; *SERIES-IMPLICIT-MAP* is non-nil.)
;;; (2) Do substitutions to get rid of trivial frags representing constant values and
;;; references to variables.
;;; (2.5) get rid of dead code.
;;; (3) Scan the graph to find places where the expression can be split because it is
;;; in disconnected places or there is an isolated dflow touching a non-series
;;; or off-line port. If the graph cannot be split, then it consists solely of
;;; dflow connecting on-line ports. A list structure is created showing all of
;;; the split points that will be merged in the next step.
;;; (4) The structure created above is evaluated doing a sequence of merge steps
;;; that reduces the whole expression to a single frag.
;;;
;;; since implicit mapping is a bit tricky, but quite possibly the
;;; must useful single part of the series macro package, it deserves a
;;; few words. To understand what happens, some initial definitions
;;; are necessary. First, a compile-time-known series function is one
;;; of the predefiend series functions or a function DEFUNed with an
;;; optimizable-series-function declaration. (There may be lots of
;;; other functions around manipulating series, but that is not
;;; relevant to the implicit mapping that is going on here.) A
;;; compile-time-known series value is a series output of a
;;; compile-time-known series function or such an output bound to a
;;; variable by one of the forms below. A compile-time-known series
;;; input is a series input of a compile-time-known series function.
;;;
;;; Every non-compile-time-known function that receives a
;;; compile-time-known series value as an input is mapped. Note that
;;; once a non-compile-time-known function is mapped, the result is a
;;; compile-time-known series function this may cause ;more mapping to
;;; occur. Special forms are never mapped. This is flagged as an
;;; error if it appears that it needs to be done. Note that
;;; non-series functions that appear in a context where their value is
;;; not used, are flagged to indicate that they must be run anyway.
;;; This carries through it they are mapped.
;;;
;;; In addition to the above, any non-series value that appears where
;;; a series is expected is automatically converted into an infinite
;;; series of that value. If you side-effects are involved, you might
;;; want multiple evaluation. However, you will have to specifically
;;; indicate this using map-fn or something. (This may not be the
;;; best default in many ways, but it is the only way to make things
;;; come out the same without depending on the exact syntactic form of
;;; the input. For instance note that INCF expands into a let in some
;;; lisps and this would force the let to be in a separate expression
;;; even though it does not look like it at first glance.)
;;; As an example of all the above consider the following.
#|
(let* ((x (car (scan '((1) (2) (3)))))
(y (1+ x))
(z (collect-sum (* x y))))
(print (list x y 4))
(print z)
(collect (list x (catenate #Z(a) (gensym)))))
|#
;;; is equivalent to
#|
(let* ((x (#Mcar (scan '((1) (2) (3)))))
(y (#M1+ x))
(z (collect-sum (#M* x y))))
(collect-last (#Mprint (#Mlist x y (series 4))))
(print z)
(collect (#Mlist x (catenate #Z(a) (series (gensym))))))
|#
;;; Note that compile-time-known series functions are never
;;; mapped. Therefore (collect (collect (scan (scan x)))) is not
;;; equivalent to (collect (mapping ((y (scan x))) (collect (scan
;;; y)))). You have to write the latter if you want it. Also while
;;; series/non-series conflicts are less likely to arise, there is no
;;; guarantee that the restrictions will be satisfied after implicit
;;; mapping is applied.
;;; UTILITIES
(eval-when (:compile-toplevel :load-toplevel :execute)
(cl:defun do-alter-prop (value gen)
(if (alter-fn (gen-base gen))
(cons value (current-alter-info gen))
value))
;; alter-info has priority
(cl:defun out-value (ret alter-prop flag-off-line?)
(cl:let* ((var (var ret))
(alter-info (cdr (assoc var (alterable (fr ret))))))
(values (cond (alter-info `(list ,var ,@ (cdr alter-info)))
(alter-prop `(do-alter-prop ,var ,(cdr alter-prop)))
((and flag-off-line? (off-line-spot ret)) `(list ,var))
(t var))
(cond (alter-info
(cl:let ((alter (new-var 'alter)))
`#'(lambda (,alter ,@(cdr alter-info))
,(subst alter '*alt* (car alter-info)))))
(alter-prop `(alter-fn ,(car alter-prop)))))))
;; This is used to allow a fragment to accept a physical series in
;; lieu of one computed be another frag.
(cl:defun add-physical-interface (arg)
(cl:let ((frag (fr arg))
(var (var arg))
(off-line-spot (off-line-spot arg))
(off-line-exit (off-line-exit arg))
(series (new-var 'series))
(generator (new-var 'generator)))
(setf (var arg) series)
(setf (series-var-p arg) nil)
(setf (off-line-spot arg) nil)
(setf (off-line-exit arg) nil)
(add-aux frag var t)
(add-nonliteral-aux frag generator 'generator `(generator ,series))
(if (not off-line-spot)
(push `(setq ,var (next-in ,generator (go ,end))) (body frag))
(setf (body frag)
(nsubst-inline
`((setq ,var (next-in ,generator
(go ,(cond (off-line-exit) (t end))))))
off-line-spot (body frag))))
generator))
;; This turns a series output into a non-series output returning a
;; physical series. (Note this assumes that if alterability is being
;; propogated, the corresponding input has already been changed
;; using add-physical-interface. Alter-prop is a cons of the new
;; input var (a physical series) and the var holding the generator.)
(cl:defun add-physical-out-interface (ret alter-prop)
(cl:let* ((frag (fr ret))
(off-line-spot (off-line-spot ret))
(new-list (new-var 'list))
(new-out (new-var 'out)))
(cl:multiple-value-bind (out-value alterer) (out-value ret alter-prop nil)
(cl:let* ((new-body-code `((push ,out-value ,new-list)))
(new-epilog-code
`(setq ,new-out (make-phys :data-list (nreverse ,new-list)
:alter-fn ,alterer))))
(setf (var ret) new-out)
(setf (series-var-p ret) nil)
(setf (off-line-spot ret) nil)
(add-literal-aux frag new-list 'list '())
(add-aux frag new-out 'series)
(if (not off-line-spot)
(setf (body frag) (nconc (body frag) new-body-code))
(setf (body frag)
(nsubst-inline new-body-code off-line-spot (body frag))))
(push new-epilog-code (epilog frag))
frag))))
) ; end of eval-when
;;;; (1) CHECK-FOR SERIES/NON-SERIES CONFLICTS.
;; This is only called from do-coercion
(cl:defun series-coerce (a)
(when (off-line-spot a)
(nsubst nil (off-line-spot a) (fr a)))
(setf (series-var-p a) nil))
;; This is only called from do-coercion
(cl:defun add-dummy-source-frag (frag)
(cl:let* ((ret (car (rets frag)))
(args (nxts ret))
(new-ret (car (rets (pass-through-frag (rets frag))))))
(dolist (a args)
(-dflow ret a)
(+dflow new-ret a))
(annotate (code frag) (fr new-ret))
(setq *graph* ;frag was stuck on wrong end
(cons (fr new-ret) (delete (fr new-ret) *graph*)))))
;; This is only called from mergify
(cl:defun do-coercion ()
(reset-marks 1)
(cl:let ((lambda-arg-frags nil))
(dofrags (f)
(dolist (a (args f))
(cl:let ((ret (prv a)))
(when (and (series-var-p ret) (not (series-var-p a)))
(rrs 13 "~%Series to non-series data flow from:~%" (code (fr ret))
"~%to:~%" (code (fr a))))
(when (not (marked-p 1 (fr ret)))
(push (fr ret) lambda-arg-frags)
(when (and (not (series-var-p ret)) (series-var-p a))
(setf (series-var-p ret) t)
(dolist (aa (nxts ret))
(when (not (series-var-p aa))
(rrs 14 "~%The optimizable series function input "
(code (fr ret))
" used as a series value by~%" (code (fr a))
"~%and as a non-series value by~%"
(code (fr aa)))))))
(when (and (not (series-var-p ret)) (series-var-p a))
(cond (*series-implicit-map* (series-coerce a))
(t (wrs 28 nil "~%Non-series to series data flow from:~%"
(code (fr ret)) "~%to:~%" (code (fr a)))
(add-physical-interface a))))))
;;might have to de-series if a physical interface was required for
;;every series input.
(maybe-de-series f))
(dolist (f lambda-arg-frags)
(when (and (series-var-p (car (rets f)))
(cdr (nxts (car (rets f)))))
(add-dummy-source-frag f)))))
;;;; (2) DO SUBSTITUTIONS
(eval-when (:compile-toplevel :load-toplevel :execute)
(cl:defun not-contained (items &rest things)
(cl:let ((found-once nil))
(cl:labels ((look-at (tree)
(cond ((symbolp tree)
(when-bind (found (car (member tree items)))
(push found found-once)))
(t (do ((tt tree (cdr tt)))
((not (consp tt)) nil)
(look-at (car tt)))))))
(declare (dynamic-extent #'look-at))
(dolist (thing things)
(look-at thing)))
(set-difference items found-once)))
(cl:defun not-contained-twice (items &rest things)
(cl:let ((found-once nil) (found-twice nil))
(cl:labels ((look-at (tree)
(cond ((symbolp tree)
(when-bind (found (car (member tree items)))
(if (member found found-once)
(pushnew found found-twice)
(push found found-once))))
(t (do ((tt tree (cdr tt)))
((not (consp tt)) nil)
(look-at (car tt)))))))
(declare (dynamic-extent #'look-at))
(dolist (thing things)
(look-at thing)))
(values (set-difference items found-twice) (set-difference items found-once))))
) ; end of eval-when
;; This is VERY conservative. Note if you substitute variables too
;; freely, you can run into troubles with binding scopes and setqs of
;; the variables in other places, but just using temporary vars is
;; guaranteed to have the right semantics all of the time. Any decent
;; compiler will then minimize the number of variables actually used
;; at run time.
;; This is only called from mergify
(cl:defun do-substitution (&aux code ret killable)
(dofrags (f)
(when (and (= (length (rets f)) 1)
(not (off-line-spot (car (rets f))))
(null (args f))
(null (epilog f))
(= 1 (prolog-length (setq code (prolog-append (prolog f) (body f)))))
(eq (var (setq ret (car (rets f)))) (setq-p (setq code (car (first-prolog-block code)))))
(or (constantp (setq code (caddr code)))
(and (eq-car code 'function) (symbolp (cadr code)))))
(setq killable (not (null (nxts ret))))
(dolist (arg (nxts ret))
(cond ((and (not (off-line-spot arg))
(not (contains-p (var arg) (rets (fr arg))))
(cond ((or (and (eq-car code 'function) (symbolp (cadr code)))
(and (symbolp code) (null (symbol-package code))) ;gensyms
(keywordp code) ;keywords
(characterp code)
(numberp code) (null code) (eq code t)) t)
((constantp code)
(and (null (cdr (nxts (car (rets f)))))
(not-contained-twice (list (var arg))
(list (prolog (fr arg))
(body (fr arg))
(epilog (fr arg))))))))
(nsubst code (var arg) (fr arg))
(-dflow ret arg)
(-arg arg))
(t (setq killable nil))))
(when killable
(-frag f)))))
;;;; (2.5) KILL DEAD CODE
;; This is only called from kill-dead-code
(cl:defun reap-frag (frag)
(dolist (a (args frag))
(cl:let ((r (prv a)))
(-dflow r a)
(when (null (nxts r)) (kill-ret r))))
(setq *graph* (delete frag *graph*)))
;; This is only called from mergify
(cl:defun kill-dead-code ()
(setq *graph* (nreverse *graph*))
(dofrags (f)
(dolist (r (rets f))
(when (and (free-out r) (null (nxts r)))
(kill-ret r)))
(when (not (or (rets f) (must-run f)))
(reap-frag f)))
(setq *graph* (nreverse *graph*)))
;;;; --- PORT HANDLING ---
(cl:defun find-on-line (syms)
(do ((s syms (cdr s)) (r nil))
((null s) (nreverse r))
(when (and (series-var-p (car s)) (null (off-line-spot (car s))))
(push (car s) r))))
(cl:defun make-inputs-off-line (frag off-line-exit)
(dolist (in (find-on-line (args frag)))
(when (not (marked-p 1 (fr (prv in)))) ;needed by check-termination
(cl:let ((-X- (new-var '-xx-)))
(setf (off-line-spot in) -X-)
(setf (off-line-exit in) off-line-exit)
(setf (body frag) `(,-X- ,@(body frag)))))))
(cl:defun make-outputs-off-line (frag)
(dolist (out (find-on-line (rets frag)))
(when (or (null (nxts out))
(some #'(lambda (in)
(not (marked-p 1 (fr in)))) ;needed by check-termination
(nxts out)))
(cl:let ((-X- (new-var '-x-)))
(setf (off-line-spot out) -X-)
(setf (body frag) `(,@(body frag) ,-X-))))))
(cl:defun make-ports-off-line (frag off-line-exit)
(make-inputs-off-line frag off-line-exit)
(make-outputs-off-line frag))
;;;; --- CODE GENERATION ---
(eval-when (:compile-toplevel :load-toplevel :execute)
;;; This tries to get a correct init in situations where NIL won't do.
;; This function converts a type to a "canonical" type. Mainly meant
;; to handle things that have been deftype'd. We want to convert that
;; deftype'd thing to the underlying Lisp type.
#+(or cmu scl)
(cl:defun canonical-type (type)
(kernel:type-specifier (c::specifier-type (if (and (not (atom type))
(eq 'quote (first type)))
(cdr type)
type))))
#+CLISP
(cl:defun canonical-type (type)
(ext:type-expand type))
#-(or cmu scl CLISP)
(cl:defun canonical-type (type)
type)
;; [email protected]:
;; Actually, to be correct, we need to be more careful about how we
;; init things because CLtL2 says it's wrong and CMU Lisp complains
;; and fails if we don't init things correctly. In particular, we
;; need to handle the case of arrays, strings, and "(member t)" that
;; is used in a few places. I think all cases that occur in the test
;; suite are handled here.
;; fdmm: LOCALLY makes this unnecessary. Return NIL whenever not sure it works.
(cl:defun init-elem (type)
(cl:let ((var-type (canonical-type type)))
(cond ((subtypep var-type 'complex)
(cond ((atom var-type) ;; Plain old complex
#C(0.0 0.0))
((and (eq-car var-type 'complex)
(cdr var-type))
;; Can find elem-type.
(complex (coerce-maybe-fold 0 (cadr var-type))))
(t
nil
;; BUG: Can't find elem-type, hope COERCE knows better.
#+:ignore
(coerce-maybe-fold 0 var-type))))
((subtypep var-type 'number)
(coerce-maybe-fold 0 var-type))
((subtypep var-type 'cons)
nil
#+:ignore
(cond ((atom var-type)
''(nil))
((and (eq-car var-type 'cons) (cdr var-type))
`',(cons (init-elem (cadr var-type))
(init-elem (caddr var-type))))
(t
;; BUG: Can't find elem-type, try random value.
''(nil))))
((typep nil var-type)
;; Use NIL as the initializer if the resulting type would
;; be t for the given implementation.
nil)
((subtypep var-type 'sequence)
nil
;;#+:ignore ; I can't ignore (at least in CMUCL)!! Why?
(cl:multiple-value-bind (arr len elem-type)
(decode-seq-type `',var-type)
(declare (ignore arr elem-type))
;; BUG: Only as good as DECODE-SEQ-TYPE.
(make-sequence var-type (or len 0))))
((subtypep var-type 'array)
nil
;; THIS IS PLAINLY WRONG FOR NON-SEQUENCE ARRAYS!!!
;; KEEPING CODE JUST FOR EVENTUAL SPECIAL-CASING
;; Heuristic: assume they mean vector.
;; BUG: fails if DECODE-SEQ-TYPE fails to find the right elem type!
#+:ignore
(cl:multiple-value-bind (arr len elem-type)
(decode-seq-type `',var-type)
(declare (ignore arr))
;; Probably no length, as that case is caught by previous branch
(make-sequence `(vector ,elem-type ,(or len 0)) (or len 0))))
((eq t (upgraded-array-element-type var-type))
;; Use NIL as the initializer if the resulting type would
;; be t for the given implementation.
nil)
(t
nil
;; BUG: Try to hack it through MAKE-SEQUENCE. This could fail.
#+:ignore
(aref (make-sequence `(vector ,var-type) 1) 0)))))
(cl:defun aux-init (aux)
(destructuring-bind (var-name &optional (var-type t) (var-value nil value-provided-p))
aux
(list var-name (if value-provided-p
var-value
(init-elem var-type)))))
;; This is only called from clean-code
(cl:defun clean-code1 (suspicious prologs code)
(cl:let ((dead nil))
(cl:labels ((clean-code2 (prev-parent parent code &aux var)
(tagbody
R (when (setq var (car (member (setq-p code) suspicious)))
(push var dead)
(rplaca parent (setq code (caddr code)))
(when (or (symbolp code) ; Symbol macros should have already expanded
(constantp code))
(cond ((consp (cdr parent))
(rplaca parent (cadr parent))
(rplacd parent (cddr parent))
(setq code (car parent))
(go R)) ;do would skip the next element
(prev-parent (pop (cdr prev-parent)))))))
(when (consp code)
(clean-code2 nil code (car code))
(do ((tt code (cdr tt)))
((not (and (consp tt) (consp (cdr tt)))) nil)
(clean-code2 tt (cdr tt) (cadr tt))))))
(declare (dynamic-extent #'clean-code2))
#+:series-plain
(clean-code2 nil nil prologs)
#-:series-plain
(dolist (p prologs)
(clean-code2 nil nil p))
(clean-code2 nil nil code) ;depends on code not being setq at top.
dead)))
(cl:defun clean-code (aux prologs code)
(cl:multiple-value-bind (goes aux) (segregate-aux #'(lambda (v) (eq (cadr v) 'null)) aux)
;; Let's get rid of silly constant NIL variables first
(when goes
(setq goes (mapauxn #'(lambda (v) (cons (car v) nil)) goes))
(clean-code1 (mapcar #'car goes) prologs code)
(when prologs
(setq prologs (nsublis goes prologs)))
(when code
(setq code (nsublis goes code))))
#+:series-plain
(cl:let ((suspicious (not-contained (mapauxn #'car aux) prologs code)))
(when suspicious
(setq aux (delete-aux-if #'(lambda (v) (member (car v) suspicious)) aux)))
(multiple-value-setq (suspicious goes)
(not-contained-twice (mapauxn #'car aux) prologs code))
(setq suspicious (set-difference suspicious goes))
(when suspicious
(setq suspicious (clean-code1 suspicious prologs code))
(setq goes (nconc goes suspicious)))
(values (delete-aux-if #'(lambda (v) (member (car v) goes)) aux) prologs code))
#-:series-plain
(do ((unfinished t))
((not unfinished) (values aux prologs code))
(cl:multiple-value-bind (bound unbound) (segregate-aux #'cddr aux)
(setq unbound (delete nil unbound))
(cl:let ((suspicious (delete-aux-if-not #'(lambda (v)
(cl:let ((val (caddr v)))
(or (symbolp val) ; Symbol macros should have already expanded
(constantp val))))
bound)))
(setq goes (not-contained (mapauxn #'car suspicious)
(mapauxn #'caddr bound) prologs code))
(setq unfinished goes)
(setq aux (delete-aux-if #'(lambda (v) (member (car v) goes)) aux))
(multiple-value-setq (suspicious goes)
(not-contained-twice (mapauxn #'car unbound)
(mapauxn #'caddr aux) prologs code))
(setq suspicious (set-difference suspicious goes))
(when suspicious
(setq suspicious (clean-code1 suspicious prologs code))
(setq goes (nconc goes suspicious)))
(when goes
(setq unfinished goes)
(setq aux (delete-aux-if #'(lambda (v) (member (car v) goes)) aux))))))))
(cl:defun propagate-types (expr aux &optional (input-info nil))
(do ((tt expr (cdr tt)))
((not (consp tt)) nil)
(do () ((not (eq-car (car tt) 'series-element-type)))
(when-bind (info (cdr (assoc (cadar tt) input-info)))
(rplaca tt info)
(return nil))
(setf (car tt)
(cond ((cadr (find-aux (cadar tt) aux)))
(t t))))
(when (consp (car tt)) (propagate-types (car tt) aux))))
(cl:defun compute-binds-and-decls (aux)
(doaux (v aux)
(propagate-types (cdr v) aux))
(3mapaux #'(lambda (v)
(if (atom v)
(values v nil nil)
(destructuring-bind (var-name &optional (typ t) (var-value nil value-provided-p))
v
;; Sometimes the desired type is quoted. Remove the
;; quote. (Is this right?)
(when (and (listp typ)
(eq 'quote (car typ)))
(setq typ (cadr typ)))
(if (eq typ t)
(values
(if value-provided-p
`(,var-name ,var-value)
var-name)
nil
nil)
(cl:let ((localtyp nil))
(or value-provided-p
(setq var-value (init-elem typ)))
(or var-value
;; That the ones allowing nil show no explicit initializers should
;; be enough to indicate they should be considered unititialized.
;; Let's not penalize implementations not so good at LOCALLY,
;; nor generate gratuitous compilation overhead.
(typep nil typ) ;(and (typep nil typ) value-provided-p)
(if value-provided-p
(setq typ `(null-or ,typ))
(setq localtyp `(type ,typ ,var-name) typ nil)))
(values (if (or value-provided-p var-value)
`(,var-name ,var-value)
var-name)
(when typ `(type ,typ ,var-name))
localtyp))))))
aux))
(cl:defun codify-2 (aux prologs code)
(cl:multiple-value-bind (binds decls localdecls) (compute-binds-and-decls aux)
#+:series-plain
(cl:multiple-value-bind (body wrapped-p)
(declarize #'identity (delete nil decls) (delete nil localdecls) prologs code t nil)
(if binds
(cl:funcall (lister wrapped-p) 'cl:let binds body)
(if wrapped-p
(prognize body)
body)))
#-:series-plain
(destarrify 'cl:let binds decls localdecls prologs code #'identity t)))
(cl:defun codify-1 (aux prologs code)
(cl:multiple-value-call #'codify-2 (clean-code aux prologs code)))
) ; end of eval-when
;;;; (4) DO MERGING
;;; The merging of frags into a single frag follows the pattern of
;;; splitting determined above. At the leaves of the tree of splits
;;; are subexpressions where some number of frags are connected solely
;;; by on-line series data flow. All these frags are combined into a
;;; single frag in one step. As long as every termination point is
;;; connected to every output point, this is a trivial operation. If
;;; not, flags and such have to be inserted to ensure that the result
;;; will have the property that all of the outputs are produced as
;;; soon as ANY input runs out of elements.
;;;
;;; After this is done, things proceed by doing two different kinds of
;;; mergings based on the two different types of splitting. One case
;;; is particularly simple. Merging frags connect by non-series data
;;; flow or no data flow at all, is trivial.
;;;
;;; Merging frags connected by series dflow touching at least one
;;; off-line port is where the key difficulties lie. There are three
;;; areas of trouble. First, things have to be carefully arranged so
;;; that termination will work out right in situations where not every
;;; termination point is connected to every output. Second, if an
;;; off-line output is connected to an off-line input, one of the
;;; frags has to be turned inside out.
;;;
;;; Third, operations concerning these issues and even the simple
;;; cases of off-line merging can convert extraneous on-line ports
;;; (one not directly participating in the merging) into off-line
;;; ports.
;;;
;;; (One issue here is that we must be sure that this port is
;;; isolated. We know it is, because it cannot be an extraneous port
;;; on the frag unless it is either a port on the expression as a
;;; whole (and therefore touched by no dflow) or touched by isolated
;;; dflow.)
;;;
;;; When conversion to off-line happens as part of the internal course
;;; of events, it indicates that the code is going to get messy, but
;;; need not concern the user. (In fact, the code may even be quite
;;; efficient, it will just look like a real mess.) Note that if you
;;; are just writing a simple series expression that neither reads nor
;;; writes a series as a whole, there will be no externally visible
;;; series ports, and you need not worry about this issue.
;;;
;;; However, when you are defining a new series functions, there are
;;; external series ports. Given that on-line ports are much more
;;; usable than off-line ones, it is unfortunate that doing odd things
;;; with the termination (for example) can make all your ports be
;;; off-line.
;;;
;;; Two cases are always simple. If an extraneous input or output
;;; carries a non-series value, then there is never a problem. If it
;;; is an input than it must be available from the very start of
;;; computation and therefore will always be readable no matter how
;;; the frags are combined. If the port is an output, then it does
;;; not need to be available until after everything is done, and the
;;; strongly connected check insures that it will be eventually
;;; computed.
;;;
;;; Things are also basically simple if an extraneous input or output
;;; is off-line. In this situation, a specific marker says exactly
;;; where connected computation should be put, and this marker will
;;; always end up in an appropriate place no matter how the fragments
;;; are combined. The only thing which requires care is making sure
;;; that these markers stay at top level.
;;;
;;; One problem case, however, is that it is possible for an off-line
;;; output to be used by an off-line input. This can cause a splitting
;;; to happen that ends up in a situation where an off-line output is used
;;; both internally and externally. If so, the output has to be
;;; preserved the first time it is used so that it can be used again.
;;;
;;; On the other hand, if an extraneous input or output is on-line,
;;; significant complexities can arise. If an extraneous port is
;;; on-line then it may have to be changed into an off-line
;;; port. Fortunately, things are arranged so that a graph is never
;;; split by breaking an on-line to on-line data flow. However, an
;;; on-line port can be on one end of a broken data flow.
;;; Nevertheless, most instances of extraneous on-line ports come from
;;; weird lambda-series bodies. Except in simple situations extraneous
;;; on-line ports are not supported unless they come from complete
;;; expressions.
;;;
;;; Consider the simplest mergings first.
;;;
;;; Two frags are connected by non-series dflow (or no dflow). (When
;;; processing complete series expressions it will always be the case
;;; that both frags are non-series frags. Further, the way splitting
;;; happens guarantees that any series ports are direct ports of the
;;; expression as a whole.)
;;;
;;; Merging is trivial as long as at least one of the frags is
;;; non-series. If one has series ports, it can be left totally
;;; alone. The other can be placed entirely in the prolog (if it is
;;; first) or epilog.
;;;
;;; If both frags are series frags, things are complex. You must
;;; evaluate the first one first and completely to get the non-series
;;; output(s) (if any) that are used by the second. This will force
;;; the first frag to make all its outputs normally. Then you have to
;;; evaluate the other one. To do this, one frag or the other has to
;;; be severely distorted. This process will make all of the series
;;; ports on the modified frag be off-line.
;;;
;;; The program below converts the first frag into a tight loop that
;;; runs in the beginning of the body. (This is essential to preserve
;;; the invariant that off-line-spots are only in bodies, but it makes
;;; a real mess and forces all the series inputs off-line. Also note
;;; the way the prolog of the other frag has to be moved.) (Note that
;;; the off-line ports created are isolated, because they are on the
;;; outside of the expression as a whole.)
;; This is used for the variable renaming part of all kinds of dflow.
;; Rets must be saved either if they have no dflow from them (they are
;; outputs of the whole top level expression) or if there is a dflow
;; to a frag that is not currently being dealt with. The functional
;; argument specifies which dflow are which.
(cl:defun handle-dflow (source handle-this-dflow &optional (kill-dflow t))
(cl:let ((killable nil)
(deadargs nil)
(deadflows nil))
(dolist (ret (rets source))
(cl:let ((ret-killable (not (null (nxts ret)))))
(dolist (arg (nxts ret))
(cond ((not (cl:funcall handle-this-dflow ret arg))
(setq ret-killable nil))
(t (nsubst (var ret) (var arg) (fr arg))
(if kill-dflow
(-dflow ret arg)
(push (cons ret arg) deadflows))
(-arg arg)
(push arg deadargs)
)))
(when ret-killable
(if kill-dflow
(-ret ret))
(push ret killable))))
(values killable deadargs deadflows)))
;; This is only called from non-series-merge
(cl:defun implicit-epilog (frag)
(setf (epilog frag) (flatten-prolog (merge-prologs (aux->prolog (aux frag))
(prolog frag))))
(setf (prolog frag) nil)
(setf (aux frag) (simplify-aux (aux frag)))
frag)
;; This is only called from non-series-merge
(cl:defun eval-on-first-cycle (frag arg-frag)
(cl:let ((b (new-var 'b))
(c (new-var 'c))
(lab (new-var 's))
(flag (new-var 'terminate)))
(make-ports-off-line frag nil)
(dolist (a (args frag))
(when (and (series-var-p a) (null (off-line-exit a)))
(setf (off-line-exit a) b)))
(make-inputs-off-line arg-frag nil)
(nsubst b end frag)
(setf (body frag)
`((if ,flag (go ,c))
,@(flatten-prolog (merge-prologs (aux->prolog (aux frag)) (prolog frag)))
,lab ,@(body frag) (go ,lab)
,b ,@(epilog frag) (setq ,flag t)
,@(flatten-prolog (merge-prologs (aux->prolog (aux arg-frag))
(prolog arg-frag)))
,c))
(setf (aux arg-frag) (simplify-aux (aux arg-frag)))
(setf (aux frag) (simplify-aux (aux frag)))
(add-aux frag flag 'boolean nil)
(setf (prolog frag) nil)
(setf (prolog arg-frag) nil)
(setf (epilog frag) nil)))
;; This is only called from non-series-merge-list
(cl:defun non-series-merge (ret-frag arg-frag)
(cl:multiple-value-bind (killable deadargs deadflows)
(handle-dflow ret-frag
#'(lambda (r a) (declare (ignore r)) (eq (fr a) arg-frag))
nil) ; We'll kill rets after merging
(when (not (non-series-p ret-frag))
(if (non-series-p arg-frag)
(implicit-epilog arg-frag)
(eval-on-first-cycle ret-frag arg-frag)))
(dolist (a deadargs)
(pusharg a (fr a)))
(cl:let ((result (merge-frags ret-frag arg-frag)))
(dolist (r killable)
(-ret r))
(dolist (f deadflows)
(-dflow (car f) (cdr f)))
(dolist (a deadargs)
(-arg a))
result)))
(cl:defun non-series-merge-list (&rest frags)
(declare (dynamic-extent frags))
(cl:let ((frag (pop frags)))
(loop (when (null frags)
(return frag))
(setq frag (non-series-merge frag (pop frags))))))
;;; A graph of many frags is connected solely by on-line data
;;; flow. (Here, even when operating on complete series expressions,
;;; it is expected that there are extraneous series inputs and
;;; outputs, and that internally used series ports can be used outside
;;; as well. However, every external use must be isolated.)
;;;
;;; Here things are in general simple, and everything can just be
;;; merged together in an order compatible with the dflow and
;;; everything will be fine and all of the extraneous ports will be
;;; left alone.
;;;
;;; However, if there are any termination points that are not
;;; connected to every output point, we have a problem. Things have
;;; to be altered so that these termination points don't prematurely
;;; stop things they should not stop. This is done by inserting flags
;;; that delay termination until the correct time. This is done as
;;; follows.
;;;
;;; (1) find each termination point and output point. Test each
;;; termination point to see whether it is total (i.e., is connected
;;; to every output and therefore calls for stopping everything.)
;;; Total termination points can act by simply branching to END when
;;; they trigger.
;;;
;;; If a termination point is not total, then a flag has to be
;;; gensymed corresponding to it and the point has to be changed so
;;; that it sets the flag (which starts with a value of NIL) to t
;;; instead of branching when exit occures. For non-total termination
;;; points that are series inputs, this means that the input will have
;;; to become an off-line port that catches termination.
;;;
;;; (2) for each non-total termination point we have to figure out
;;; what frags it controls. First, frags the termination point has
;;; data flow to are forced to stop when it stops. Second, once EVERY
;;; output a frag has data flow to has been completed, the frag can
;;; stop too.
;;;
;;; (In addition, we must note that once every frag has stopped, the
;;; loop as a whole should stop. If there is at least one total
;;; termination point and there is at least one output point that is
;;; controlled only by total termination points, then we don't have to
;;; do anything special. When a total termination point stops
;;; everything stops and we always have to continue computing as long
;;; as none of the total termination points have stopped. However, if
;;; the above is not the case, we have to add a new termination test
;;; that checks to see if all of the outputs have completed, and stop
;;; everything.)
;;;
;;; (2a) follow the dflow from each non-total termination point and
;;; note that the termination point itself, and every frag you reach
;;; must stop as soon as the termination point does. This is done by
;;; adding FLAG into the list of control flags for each frag. (This
;;; list is an implicit OR that specifies when to STOP executing the
;;; frag)
;;;
;;; (2b) Start at each output point and get the set of flags that
;;; control it. Follow the dflow backward from each output point and
;;; note what frags feed into it. Once this is done, create a new
;;; entry (AND (OR . output-flag-set1) (OR . output-flag-set2) ...) in
;;; the list of control flags.
;;;
;;; The above can be done in two highly efficient marking sweeps. The
;;; first of which also determines whether there are any non-total
;;; termination points we have to worry about.
;;;
;;; Finally, we simplify each of the control expressions and do the
;;; merging inserting the correct tests of flags. (I could think
;;; about sorting the frags as much as possible consistent with dflow
;;; so that adjacent frags have the same expressions, however, this
;;; might be bad with respect to side-effects.)
;;; flag meanings
;;; 1- marks region of interest.
;;; 2- marks places to start output point sweep.
;;; 4- marks places to start termination point sweep.
;;; 4- mark individual output points and termination points.
;; This is only called from check-termination
(cl:defun make-set-flag-rather-than-terminate (frag)
(cl:let* ((B (new-var 'bb))
(C (new-var 'cc))
(flag (new-var 'terminated)))
(make-ports-off-line frag nil)
(dolist (a (args frag))
(when (and (series-var-p a) (not (off-line-exit a)))
(setf (off-line-exit a) B)))
(nsubst B end (body frag))
(add-literal-aux frag flag 'boolean nil)
(setf (body frag) (nconc (body frag) `((go ,C) ,B (setq ,flag t) ,C)))
flag))
;; the challenge here is making as simple a test as possible
(cl:defun make-test (and-of-ors)
(if (null and-of-ors)
t
(cl:let ((top-level-or nil) (residual-and-of-ors nil))
(dolist (f (car and-of-ors))
(when (every #'(lambda (or) (member f or)) (cdr and-of-ors))
(push f top-level-or)
(setq and-of-ors (mapcar #'(lambda (or) (remove f or)) and-of-ors))))
(when (member nil and-of-ors) (setq and-of-ors nil))
(dolist (or and-of-ors)
(when (notany #'(lambda (other-or)
(and (not (eq or other-or)) (subsetp other-or or)))
and-of-ors)
(push or residual-and-of-ors)))
(setq residual-and-of-ors
(mapcar #'(lambda (or)
(if (cdr or)
`(or . ,or)
(car or)))
residual-and-of-ors))
(when residual-and-of-ors
(push `(and . ,(nreverse residual-and-of-ors)) top-level-or))
(cond ((null top-level-or) nil)
((null (cdr top-level-or)) (car top-level-or))
(t `(or . ,(nreverse top-level-or)))))))
;; this function assumes that on-line-merge will merge frags in the
;; order they are on *graph*.
;; This is only called from on-line-merge
(cl:defun check-termination (*graph*)
(block nil
(cl:let ((counter 8.) (all-term-counters 0)
(outputs nil) (terminations nil)
(problem-terminations nil) all-terminated conditions current-label)
(dofrags (f 1)
(when (or (must-run f)
(some #'(lambda (r)
(or (null (nxts r))
(some #'(lambda (a) (not (marked-p 1 (fr a))))
(nxts r))))
(rets f)))
(push (list counter f) outputs)
(mark (+ 2 counter) f)
(setq counter (* 2 counter)))
(when (or (active-terminator-p f)
(some #'(lambda (a)
(and (series-var-p a)
(not (off-line-exit a))
(not (marked-p 1 (fr (prv a))))))
(args f)))
(push (list counter f) terminations)
(mark (+ 4 counter) f)
(setq all-term-counters (+ all-term-counters counter))
(setq counter (* 2 counter))))
;;; first sweep to test connection of terms to outputs.
(dofrags (f 5) ; 5 = 1+4
(cl:let ((current-marks (logandc1 2 (marks f)))) ;strips out 2 bit
(dolist (a (all-nxts f))
(when (marked-p 1 (fr a))
(mark current-marks (fr a))))))
(dolist (oentry outputs)
(when (not (marked-p all-term-counters
(cadr oentry))) ;99% of time will be marked
(dolist (tentry terminations)
(when (not (marked-p (car tentry) (cadr oentry)))
(pushnew tentry problem-terminations)))))
(when (null problem-terminations)
(return nil))
;;; make the flags and get them initialized
(dolist (tentry problem-terminations)
(cl:let ((flag (make-set-flag-rather-than-terminate (cadr tentry))))
(dolist (oentry outputs)
(when (marked-p (car tentry) (cadr oentry))
(push flag (cddr oentry))))))
;;; second sweep to test connection of everything to outputs.
(cl:let ((*graph* (reverse *graph*)))
(dofrags (f 3) ; 3 = 1+2
(cl:let ((current-marks (logandc1 4 (marks f)))) ;strips out 4 bit
(dolist (a (all-prvs f))
(when (marked-p 1 (fr a))
(mark current-marks (fr a)))))))
(setq all-terminated (make-test (mapcar #'cddr outputs)))
(when all-terminated
(push `(if ,all-terminated (go ,end)) (body (car *graph*))))
;;; add conditionalization to each frag
(setq conditions
(mapcar #'(lambda (f)
(make-test
(mapcar #'cddr
(remove-if-not #'(lambda (e)
(marked-p (car e) f))
outputs))))
*graph*))
;; could do some sorting here based on similarity between
;; conditions.
(dotimes (i (length *graph*))
(cl:let ((condition (elt conditions i))
(frag (elt *graph* i)))
(when (not (equal condition all-terminated))
(make-outputs-off-line frag)
;inputs are termination points and are already off-line if need be.
(when (or (= i 0) (not (equal condition (elt conditions (1- i))))
(find (elt *graph* (1- i)) problem-terminations :key #'cadr))
(setq current-label (new-var 'skip))
(push `(if ,condition (go ,current-label)) (body frag)))
(when (or (= i (1- (length *graph*)))
(not (equal condition (elt conditions (1+ i))))
(find frag problem-terminations :key #'cadr))
(setf (body frag) (nconc (body frag) `(,current-label))))))) )))
(cl:defun on-line-merge (*graph*) ;merge everything, all dflow is on-line.
(if (null (cdr *graph*))
(car *graph*)
(cl:let ((frag nil))
(reset-marks 1)
(check-termination *graph*)
(dofrags (f)
(handle-dflow f
#'(lambda (r a) (declare (ignore r)) (marked-p 1 (fr a))))
(if (null frag)
(setq frag f)
(setq frag (merge-frags frag f))))
(reset-marks 0)
(maybe-de-series frag))))
;;; Two frags are connected by dflow touching at least one off-line
;;; port. (Even in complete expressions, there can be extraneous
;;; series ports. (e.g., going to other subexpressions created in
;;; other splits.) However, any dflow touching these ports must be
;;; isolated.) Note that if the output port is on-line there may be
;;; other dflow starting on it other than the one in question.
;;;
;;; The first difficulty in this case involves termination. With
;;; regard to the second frag, there is no problem. If the second
;;; frag is the first to stop, then it must have produced all its
;;; outputs. If the first frag is the first to stop, then it must
;;; have produced all its outputs which either means that the second
;;; must also stop, or the second will catch the termination of the
;;; first.
;;;
;;; Further there is no trouble with the first frag as long as either
;;; (1) the second frag has no termination points other than the one
;;; in question (i.e., has no series inputs without off-line-exits
;;; other than possibly the one in question and cannot by itself
;;; terminate) or (2) the first frag does not have any output points
;;; other than the one in question (i.e., has no other outputs, and
;;; does not have the must-run flag set) and this output is not used
;;; anywhere other than by the input in question. In case (1) running
;;; the second frag forces the complete running of the first frag. In
;;; case (2), it does not matter if the first frag is run completely
;;; or not.
;;;
;;; If neither of the cases above applies, we have to do some hard
;;; work. We know that the destination frag is a termination point
;;; and either, (a) the source frag has a non-series output or has the
;;; must-run flag set or (b) there is data flow from series outputs of
;;; the source frag to more than one place (i.e., either fan out from
;;; one, or dflow from two different ones).
;;;
;;; In case (a) things are simple, we just have to change the
;;; destination frag so that it always reads all of the elements of
;;; the input in question. This can be done by catching the
;;; termination of the frag caused by other things, and using a flag
;;; to force execution to continue until the input runs out. This
;;; transformation causes all the other series ports to become
;;; off-line.
;;;
;;; Case (b) is more complex, the source frag might not be able to
;;; terminate at all, and even if it can, it might not terminate soon
;;; enough. We must look at all of the destinations of dflow from it
;;; (not just the one we are looking at now) and see which ones of
;;; them are termination points. What we want is for the source to
;;; terminate exactly when all of the destinations terminate (if
;;; ever). If at least one of the destinations is not a termination
;;; point, then we can proceed exactly as in case (a). If none of
;;; them are, then we can still proceed the same, but we have to add a
;;; test to the first frag that causes termination as soon as all of
;;; the destinations have stopped. This requires flags to be set in
;;; the destinations.
;;;
;;; (Note that we could probably use simpler frags and things if we
;;; figured out all the places where we were going to have to do this
;;; before merging the on-line subexpressions in the first place.
;;; However, this would make the code more complex and is not worth
;;; doing given that it is rather unlikely for series expressions to
;;; have more than one output in any case. Note that the prior
;;; version of this macro package just outlawed every problematical
;;; case. Doing things with more efficiency is a possible future
;;; research direction.)
;;;
;;; The second difficulty involves actually doing the merging.
;;;
;;; A- The ret is off-line and the arg is on-line There are two
;;; basic ways in which this can be handled.
;;;
;;; A1- The most straightforward way is to insert the arg frag into
;;; the off-line-spot in the ret-frag. This is very simple and
;;; allows on-line inputs and outputs of the ret-frag to remain
;;; unchanged. However, on-line inputs and outputs of the arg-frag
;;; are forced to become off-line.
;;;
;;; A2- The ret-frag is turned inside out and converted into an
;;; enumerator, which has on-line data flow to the arg-frag. This
;;; requires the use of a flag variable, and the making off-line of
;;; any on-line inputs or outputs of the ret-frag. However, it
;;; allows any extraneous inputs and outputs of the arg-frag to
;;; remain unchanged.
;;;
;;; If either of the two frags has no extraneous on-line ports, then
;;; the appropriate combination method above is used and everything
;;; works out great. If they both have extraneous on-line ports, then
;;; which every one has fewer of these ports has them changed to
;;; off-line ports and the appropriate process above is then applied.
;;;
;;; In either case, special care has to be taken to insure that the
;;; off-line output will still exist if it is used some place other
;;; than in the arg-frag. (It is possible that it will exist, but will
;;; get changed to on-line. This does not cause confusion since the
;;; input it is connected to must be off-line--otherwise there would
;;; be only one dflow from the output.)
;;;
;;; B- The ret is on-line and the arg is off-line. This case is
;;; closely analogous to the one above. Again, there are two basic
;;; ways to proceed.
;;;
;;; B1- The most straightforward way is to insert the ret frag into
;;; the off-line-spot in the arg-frag. This has the feature that it
;;; is very simple and allows all on-line inputs and outputs of the
;;; arg-frag to remain unchanged. However, on-line inputs and outputs
;;; of the ret-frag are forced to become off-line.
;;;
;;; B2- The arg-frag is turned inside out and converted into a
;;; reducer which receives on-line data flow from the ret-frag. This
;;; requires the use of a flag variable, and it forces off-line any
;;; extraneous on-line inputs or outputs of the arg-frag. However,
;;; it allows any extraneous inputs and outputs of the ret-frag to
;;; remain unchanged.
;;;
;;; If either of the two frags has no extraneous ports, then the
;;; appropriate combination method above is used and everything works
;;; out great. If the both have extraneous ports then whichever has
;;; fewer has them changed to off-line and things proceed as above.
;;;
;;; C- the ret and arg are both off-line. Here it is not possible
;;; to simultaneously substitute the frags into each other.
;;; However, it is possible to combine them after A2 is applied to
;;; the ret-frag or B2 is applied to the arg-frag. Again this
;;; presents two options and it is possible to preserve either the
;;; extraneous ports of the ret-frag or the arg-frag, but not both.
;;;
;;; Note we have to be prepared for the general case more often than
;;; you might expect, because the combination process can cause ports
;;; to become off-line.
(cl:defun some-other-termination (arg)
(or (active-terminator-p (fr arg))
(plusp (count-if #'(lambda (a)
(and (not (eq a arg))
(series-var-p a)
(not (off-line-exit a))))
(args (fr arg))))))
(cl:defun count-on-line (frag)
(+ (length (find-on-line (args frag))) (length (find-on-line (rets frag)))))
(cl:defun make-read-arg-completely (arg &optional (cnt nil))
(cl:let* ((frag (fr arg))
(terminates-p (branches-to end (body frag)))
(B (when terminates-p (new-var 'bbb)))
(C (new-var 'ccc))
(flag (new-var 'ready-to-terminate)))
(make-ports-off-line frag nil)
(when terminates-p
(dolist (a (args frag))
(when (and (not (eq a arg)) (not (off-line-exit a)))
(setf (off-line-exit a) B)))
(nsubst B end (body frag)))
(add-literal-aux frag flag 'boolean nil)
(setf (body frag)
(nsubst-inline (if (not (off-line-exit arg))
`(,@(when terminates-p
`((go ,C) ,B ,@(if cnt `((if (null ,flag) (decf ,cnt))))
(setq ,flag t)))
,C ,(off-line-spot arg) (if ,flag (go ,C)))
(cl:let ((CF (new-var 'CF))
(CD (new-var 'CD))
(exit (off-line-exit arg)))
(setf (off-line-exit arg) CF)
`(,@(when terminates-p `((go ,C) ,B (if ,flag (go ,end)) (setq ,flag t)))
,C ,(off-line-spot arg) (go ,CD)
,CF (if ,flag (go ,end)) (setq ,flag t) (go ,exit)
,CD (if ,flag (go ,C)))))
(off-line-spot arg) (body frag)))))
(cl:defun convert-to-enumerator (ret off-line-exit)
(cl:let ((frag (fr ret)))
(make-ports-off-line frag off-line-exit)
(cl:let* ((tail (member (off-line-spot ret) (body frag)))
(head (ldiff (body frag) tail))
(flag (new-var 'flg))
(e (new-var 'e)))
(setf (off-line-spot ret) nil)
(add-literal-aux frag flag 'boolean nil)
(setf (body frag)
`((when (null ,flag) (setq ,flag t) (go ,e))
,@(cdr tail)
,e ,@ head)))
frag))
(cl:defun convert-to-reducer (arg)
(cl:let ((frag (fr arg)))
(make-outputs-off-line frag)
(cl:let* ((tail (member (off-line-spot arg) (body frag)))
(head (ldiff (body frag) tail))
(flag (new-var 'fl))
(M (new-var 'm))
(N (new-var 'n)))
(add-literal-aux frag flag 'boolean nil)
(setf (body frag)
`((if (null ,flag) (go ,M))
,N ,@(cdr tail)
,M ,@ head
(when (null ,flag) (setq ,flag t) (go ,N)))))
frag))
(cl:defun substitute-in-output (ret arg)
(cl:let ((ret-frag (fr ret))
(arg-frag (fr arg)))
(make-ports-off-line arg-frag (off-line-exit arg))
(setf (body ret-frag)
(nsubst-inline (body arg-frag) (off-line-spot ret) (body ret-frag)
(nxts ret)))
(setf (body arg-frag) nil)))
(cl:defun substitute-in-input (ret arg)
(cl:let ((ret-frag (fr ret))
(arg-frag (fr arg))
(ex (off-line-exit arg)))
(make-ports-off-line ret-frag ex)
(when ex
(dolist (a (args (fr ret)))
(when (and (series-var-p a) (not (off-line-exit a)))
(setf (off-line-exit a) ex)))
(nsubst ex end (body ret-frag)))
(setf (body arg-frag)
(nsubst-inline (body ret-frag) (off-line-spot arg) (body arg-frag)))
(setf (body ret-frag) nil)))
(cl:defun off-line-merge (ret-frag ret arg-frag arg)
(when (and (some-other-termination arg)
(or (> (length (rets ret-frag)) 1)
(must-run ret-frag)
(> (length (nxts ret)) 1)))
(cl:let ((destinations nil))
(dolist (r (rets ret-frag) nil)
(when (series-var-p r)
(setq destinations (append destinations (nxts ret)))))
(if (or (must-run ret-frag)
(not (every #'series-var-p (rets ret-frag)))
(not (every #'some-other-termination destinations)))
(make-read-arg-completely arg)
(cl:let ((cnt (new-var 'cnt)))
(add-literal-aux ret-frag cnt 'fixnum (length destinations))
(push `(if (zerop ,cnt) (go ,end)) (body ret-frag))
(dolist (a destinations)
(make-read-arg-completely a cnt))))))
(handle-dflow (fr ret) #'(lambda (r a) (declare (ignore r)) (eq (fr a) arg-frag)))
(cl:let* ((ret-rating (count-on-line ret-frag))
(arg-rating (count-on-line arg-frag)))
(cond ((not (off-line-spot arg))
(if (> arg-rating ret-rating)
(convert-to-enumerator ret nil)
(substitute-in-output ret arg)))
((not (off-line-spot ret))
(if (and (> ret-rating arg-rating) (null (off-line-exit arg)))
(convert-to-reducer arg)
(substitute-in-input ret arg)))
(t (cond ((and (> ret-rating arg-rating) (null (off-line-exit arg)))
(convert-to-reducer arg)
(substitute-in-output ret arg))
(t (convert-to-enumerator ret (off-line-exit arg))
(substitute-in-input ret arg))))))
(maybe-de-series (merge-frags ret-frag arg-frag)))
;;;; (3) DO SPLITTING
;;; Splitting cuts up the graph at all of the correct places, and
;;; creates a lisp expression which, when evaluated will merge
;;; everything together. Things area done this way so that all of the
;;; splitting will happen before any of the merging. This makes error
;;; messages better and allows all the right code motion to happen
;;; easily.
;; This splits the graph by dividing it into two parts (part1 and
;; part2) so that to-follow is in part1, there is no data flow from
;; part2 to part1 and all of the data flow from part1 to part2
;; satisfies the predicate CROSSABLE.
;;
;; The splitting is done by marker propagation (using the marker
;; 2). The algorithm used has the effect of minimizing part1, which
;; among other things, guarantees that it is fully connected.
(cl:defun split-after (frag crossable)
(mark 2 frag)
(cl:let ((to-follow (list frag)))
(loop (when (null to-follow)
(return nil))
(cl:let ((frag (pop to-follow)))
(dolist (a (args frag))
(cl:let* ((r (prv a)))
(when (= (marks (fr r)) 1) ;ie 1 but not 2
(push (fr r) to-follow)
(mark 2 (fr r)))))
(dolist (r (rets frag))
(dolist (a (nxts r))
(when (and (= (marks (fr a)) 1) ;ie 1 but not 2
(not (cl:funcall crossable r a)))
(push (fr a) to-follow)
(mark 2 (fr a))))))))
(cl:let ((part1 nil) (part2 nil))
(dofrags (f 1)
(if (marked-p 2 f)
(push f part1)
(push f part2)))
(reset-marks 0)
(values (nreverse part1) (nreverse part2))))
;;; This finds internal non-series dflows and splits the graph at that
;;; point. It may be necessary to cut more than one dflow when
;;; splitting. Therefore, no matter how we do things, it will always
;;; be possible that either of the parts will have more non-series
;;; dflow in it. To see this, note the following example:
#|(let ((e (scan x)))
(values (foo (reverse (collect e)))
(collect-last e (car (bar y))))) |#
;;; The order of frags on the graph is going to be scan, collect,
;;; reverse, foo, bar, car, collect-last. If you start on either the
;;; first frag, or the first non-series dflow, or the last frag, or
;;; the last dflow, there are going to be another non-series dflow in
;;; each half. (Note starting from the front, the non-series dflow
;;; from car to collect-last is going to be pulled into the first
;;; part. And in general, starting from the front puts lots of
;;; non-series dflow in the second part.)
;;;
;;; The best we can do is construct one part so that it is known that
;;; that part is connected. The method used here ensures that the
;;; first part is connected by minimizing it.
;;;
;;; Note there is an implicit assumption here that making a cut
;;; through a bundle of isolated non-series dflows cannot converted a
;;; non-isolated one into an isolated one. If this could happen, we
;;; would fail to detect some problems, and the overall theory would
;;; be overly strict.
;; This is only called from non-series-dflow-split
(cl:defun do-non-series-dflow-split (ret arg)
(cl:let ((frag1 (fr ret))
(frag2 (fr arg)))
(cl:multiple-value-bind (part1 part2)
(split-after frag1 #'(lambda (r a)
(declare (ignore r))
(not (series-var-p a))))
(when (member frag2 part1)
(rrs 21 "~%Constraint cycle passes through the non-series output ~
at the beginning of the data flow from:~%"
(code frag1) "~%to:~%" (code frag2)))
(setq part1 (non-series-dflow-split part1))
(setq part2 (disconnected-split part2))
`(dflow ,@(if (eq-car part1 'dflow)
(cdr part1)
(list part1))
,@(if (eq-car part2 'dflow)
(cdr part2)
(list part2))))))
;; HELPER
(defmacro doing-splitting (&body body)
`(cond ((null (cdr *graph*)) (list 'quote (car *graph*)))
(t (reset-marks 1) (prog1 (progn ,@ body) (reset-marks 0)))))
;; HELPER
(defmacro doing-splitting1 (&body body)
`(cond ((null (cdr *graph*)) *graph*)
(t (reset-marks 1) (prog1 (progn ,@ body) (reset-marks 0)))))
(cl:defun non-series-dflow-split (*graph*)
(doing-splitting1
(block top
(dofrags (f)
(dolist (ret (rets f))
(when (not (series-var-p ret))
(dolist (arg (nxts ret))
(when (marked-p 1 (fr arg))
(return-from top (do-non-series-dflow-split ret arg)))))))
*graph*)))
;; We have to do non-dflow splitting and non-series-dflow-splitting
;; separately in order to get error messages about non-isolated
;; non-series dflow right. This breaks the expression up at points
;; where there is no data flow between the subexpressions. Since the
;; size of part1 is minimized it is known that part1 must be fully
;; connected.
(cl:defun disconnected-split (*graph*)
(doing-splitting1
(cl:multiple-value-bind (part1 part2)
(split-after (car *graph*) #'(lambda (r a) (declare (ignore r a)) nil))
(cond ((null part2) (non-series-dflow-split part1))
(t (setq part1 (non-series-dflow-split part1))
(setq part2 (disconnected-split part2))
`(no-dflow ,part1
,@(if (eq-car part2 'no-dflow)
(cdr part2)
(list part2))))))))
;; The following breaks the expression up at all the points where
;; there is no series data flow between the subexpressions.
;; Non-series port isolation guarantees that this split is possible,
;; cutting only non-series dflows. (If there is no data flow, you
;; might not have to cut any data flow.) If *graph* is a complete
;; expression (i.e., one that does not have any series inputs or
;; outputs overall), then the subexpressions cannot have external
;; series inputs or outputs.
;;
;; Non-series splitting typically breaks the expression up into a
;; large number of fragments. Great care is taken to make sure that
;; these fragments will be reassembled without changing their order.
;; This is important so that the user's side-effects will look
;; reasonable. Careful attention has to be paid to the dflow
;; constraints when figuring out where to put the series
;; subexpressions. They are put where the last fn in them suggests,
;; within the limits of dflow.
;;
;; Note that the only way the user can write something that has some
;; side-effects is to write a side-effect expression that turns into a
;; non-series-computation (via isolate-non-series) or to write
;; something in a functional argument to a higher-order series
;; function. the functions here make things come out pretty well in
;; the first case; there is not much anybody could do about the second
;; case.
(definline order-num (frags)
(position (car (last frags)) *graph*))
(cl:defun reorder-frags (form)
(cond ((eq-car form 'dflow) (mapcan #'reorder-frags (cdr form)))
((eq-car form 'no-dflow)
(cl:let ((sublists (mapcar #'reorder-frags (cdr form)))
(result nil) min-num min-sublist)
(setq sublists
(mapcar #'(lambda (l) (cons (order-num (car l)) l)) sublists))
(loop (when (null (cdr sublists))
(return (nreconc result (cdr (car sublists)))))
(setq min-num (car (car sublists)) min-sublist (car sublists))
(dolist (sub (cdr sublists))
(when (< (car sub) min-num)
(setq min-num (car sub) min-sublist sub)))
(push (pop (cdr min-sublist)) result)
(if (null (cdr min-sublist))
(setq sublists (delete min-sublist sublists))
(setf (car min-sublist) (order-num (cadr min-sublist)))))))
(t (list form))))
;; At this next stage, we split based on off-line ports. (Note that all
;; non-series splitting must be totally complete at this time.) Several
;; other things are important to keep in mind. First, whenever we split on
;; an off-line output that has more than one dflow from it to on-line ports,
;; we insert a dummy identity frag so that there will be only one dflow from
;; the off-line port to on-line ports (the multiple dflows come from the
;; output of the dummy frag). There are three benefits to this. First,
;; doing this allows us to make the split cutting only one dflow arc. This
;; guarantees that both parts remain connected and therefore we don't have to
;; call disconnected-split again.
;;
;; Second, when checking for isolation when doing splitting at the
;; same time, we need to have the property that doing a split cannot
;; cause a non-isolated arc to become isolated. If we cut more than
;; one series dflow when splitting we could make something else be
;; isolated. Consider the program below.
#|(let ((e (split #'plusp (scan x))))
(collect (#M+ e (f (g e))))) |#
;; Note that the offline output of split is isolated, but neither the
;; input of f or the output of g is isolated. If you cut both dflows
;; from the split when doing a split, these two ports look isolated in
;; the part they are in.
;;
;; Third, the dummy frag helps keep things straight during later
;; merging. The key problem is that if there is more than one on-line
;; destination port, then we must make sure that they stay on-line,
;; because they may not be isolated. The dummy frag essentially
;; records the requirement that the destinations must keep in
;; synchrony.
;;
;; Note that when splitting, things will come out exactly the same no
;; matter which part is minimized, because the whole expression is
;; connected and there is no non-series dflow. As a result, there
;; cannot be more than one way to split the expression---Every
;; function must be forced to one half or the other.
;;
;; By the same argument used with regard to non-series dflow, either
;; part can still have off-line ports in it that have not been split
;; on.
;;
;; Note that even if the whole does not have any external series
;; ports, the two pieces can. At least one will be off-line, the
;; other can be on-line. Note that if the splitting is being done
;; based on an off-line input, then the output in part one can be used
;; in more than one place. In particular, it can be used by another
;; off-line input which is now still in part1. This forces complex
;; merging cases to be handled.
;; This is only called from off-line-split
(cl:defun insert-off-line-dummy-frag (ret args)
(cl:let* ((var (new-var 'oo))
(dummy-ret (make-sym :var var :series-var-p t))
(dummy-arg (make-sym :var var :series-var-p t))
(dummy-frag (make-frag :code (code (fr (car (nxts ret)))))))
(+arg dummy-arg dummy-frag)
(+ret dummy-ret dummy-frag)
(dolist (arg args)
(-dflow ret arg)
(+dflow dummy-ret arg))
(+dflow ret dummy-arg)
(cl:let ((spot (member (fr ret) *graph*)))
(rplacd spot (cons dummy-frag (cdr spot))))
(mark 1 dummy-frag) ;so is in currently being considered part.
dummy-arg))
;; This is only called from off-line-split
(cl:defun do-off-line-split (ret arg)
(cl:let ((frag1 (fr ret))
(frag2 (fr arg)))
(cl:multiple-value-bind (part1 part2)
(split-after frag1 #'(lambda (r a)
(and (eq r ret) (eq a arg))))
(when (member frag2 part1)
(if (off-line-spot arg)
(rrs 23 "~%Constraint cycle passes through the off-line input ~
at the end of the data flow from:~%"
(code frag1) "~%to:~%" (code frag2)))
(rrs 22 "~%Constraint cycle passes through the off-line output ~
at the start of the data flow from:~%"
(code frag1) "~%to:~%" (code frag2)))
`(off-line-merge ,(off-line-split part1) ',ret
,(off-line-split part2) ',arg))))
(cl:defun off-line-split (*graph*)
(doing-splitting
(block top
(dofrags (f)
(dolist (ret (rets f))
(cl:let ((args nil))
(dolist (arg (nxts ret))
(when (marked-p 1 (fr arg))
(cond ((off-line-spot arg)
(setq args (list arg))
(return nil))
((off-line-spot ret)
(push arg args)))))
(when args
(when (and (cdr args) (off-line-spot ret))
(setq args (list (insert-off-line-dummy-frag ret args))))
(return-from top (do-off-line-split ret (car args)))))))
`(on-line-merge ',*graph*))))
;; This is only called from do-splitting
(cl:defun non-series-split (*graph*)
(cl:let ((subexprs (disconnected-split *graph*)))
(setq subexprs (reorder-frags subexprs))
(cons 'non-series-merge-list
(mapcar #'off-line-split subexprs))))
;; Main splitting entry point
;; This is only called from mergify
(cl:defun do-splitting (*graph*)
(reset-marks 0)
(non-series-split *graph*))
;;;; TURNING A FRAG INTO CODE
;;; this takes a non-series frag and makes it into a garden variety
;;; chunk of code. It assumes that it will never be called on a frag
;;; with any inputs.
(eval-when (:compile-toplevel :load-toplevel :execute)
(cl:defun aux-ordering (a b)
(when (consp a) (setq a (car a)))
(when (consp b) (setq b (car b)))
(string-lessp (string a) (string b)))
(cl:defun use-user-names (aux loop)
(cl:let ((alist nil))
(doaux (v-info aux)
(cl:let* ((v (car v-info))
(u (cdr (assoc v *user-names*))))
(when (and u (not (contains-p u loop)) (not (rassoc u alist)))
(push (cons v u) alist))))
(when alist
(nsublis alist loop))))
(cl:defun liftable-var-p (var)
;; Is VAR the name of a variable we can lift? This says yes to
;; everything except #:SEQ-nnn variables.
(if (symbol-package var)
var
(cl:let ((var-name (symbol-name var)))
(when (>= (length var-name) 4)
(not (string-equal "SEQ-" (subseq var-name 0 4)))))))
(cl:defun find-out-vars (code)
;; If code looks something like (let (bindings) ...) we peek at the
;; bindings. Return a list of the variables being defined in the
;; bindings. (Ignore any intializations being done in the binding.)
(when (member (first code) '(let cl:let))
(destructuring-bind (let (&rest bindings) &rest body)
code
(declare (ignore let body))
(remove-if-not #'liftable-var-p
(mapcar #'(lambda (x)
(if (listp x)
(first x)
x))
bindings)))))
(cl:defun find-initializers (vars-to-init code)
;; We try to find initializers to the variables in VARS-TO-INIT. We
;; assume CODE looks like
;;
;; (let (#:out-1 #:out-2 ...)
;; (setq #:out-1 <init-1>)
;; (setq #:out-2 <init-2>)
;; <other stuff>
;; )
;;
;; We return an alist of the variable and the initializer from the
;; setq expression.
(do ((inits nil)
(list (cddr code) (rest list)))
((not (and (listp (first list))
(member (first (first list)) '(setq cl:setq declare cl:declare))))
;; Exit the loop if we've gone past the last setq, ignoring any
;; declare expressions
inits)
;;(format t "setq = ~A~%" (first list))
(cl:let ((name (find (second (first list)) vars-to-init)))
;;(format t "name = ~A~%" name)
(when name
;;(format t "init = ~%" (third (first list)))
(push (list name (third (first list)))
inits)))))
(cl:defun remove-initializers (inits code)
(do ((new-code '())
(list (cddr code) (rest list)))
((not (and (listp (first list))
(member (first (first list)) '(setq cl:setq declare cl:declare))))
(append new-code list))
;;(format t "looking at ~A~%" (first list))
;;(format t "new-code = ~A~%" new-code)
(unless (member (second (first list)) inits :key #'first)
;;(format t "saving ~A~%" (first list))
(setf new-code (append new-code (list (first list)))))))
;; Try to lift the initialization of out vars to the let. This is a
;; heuristic that I ([email protected]) hope works.
(cl:defun lift-out-vars (code)
;; We look for something like
;; (let (out-1 out-2)
;; (setq out-1 <init-1>)
;; (setq out-2 <init-2>)
;; <stuff>)
;; and try to convert that to
;;
;; (let ((out-1 <init-1>) (out-2 <init-2>))
;; <stuff>)
;;
;; This assumes that nothing but setq's of out variables occurs
;; between the binding and <stuff>.
(cl:let ((bindings (second code))
(out-vars (find-out-vars code)))
(when out-vars
;; There are output vars. Find the initializers associated with
;; those output vars.
(cl:let* ((inits (find-initializers out-vars code))
(new-bindings
(mapcar #'(lambda (v)
;; Create a new bindings
;; list that initializes the
;; variables appropriately.
(cl:let ((var (if (listp v) (first v) v)))
(or (assoc var inits :key #'(lambda (x)
(if (listp x)
(first x)
x)))
v)))
bindings)))
`(cl:let* ,new-bindings ,@(remove-initializers inits code))))))
;; Set this to non-NIL to activate LIFT-OUT-VARS when generating the
;; series expansion.
(defvar *lift-out-vars-p* t)
(cl:defun codify (frag)
(dolist (r (rets frag))
(when (series-var-p r)
(rrs 10 "~%Series value returned by~%" (code frag))))
(maybe-de-series frag nil)
(cl:let ((rets (mapcan #'(lambda (r)
(when (not (free-out r))
(list (var r))))
(rets frag)))
(aux (aux frag))
(prologs (prolog frag))
(code (body frag))
(wrps (wrappers frag)))
#+:series-plain
(progn
(setq code (prolog-append prologs code))
(setq prologs nil))
#+:series-plain
(when wrps
(setq code (wrap-code wrps code)))
(cl:let ((last-form (car (last (if code code (last-prolog-block prologs))))))
(if (and rets (null (cdr rets)))
(cl:let ((r (car rets)))
(cond ((and (eq-car last-form 'setq)
(eq-car (cdr last-form) r))
(if code
(setq code (delete last-form code))
(setq prologs (delete-last-prolog prologs)))
(when (and (not (contains-p r code))
#-:series-plain (not (contains-p r prologs))
)
(setq aux (delete-aux r aux)))
(setq rets (caddr last-form)))
(t (setq rets r))))
(setq rets `(values ,@ rets))))
(setq code (codify-1 aux prologs (nconc code (list rets))))
#-:series-plain
(when wrps
(setq code (car (wrap-code wrps (list code)))))
(use-user-names aux code)
(when *lift-out-vars-p*
(setf code (lift-out-vars code)))
(setq *last-series-loop* code)))
); end of eval-when
(eval-when (:compile-toplevel :load-toplevel :execute)
;; This is used when optimization is not possible.
;;
;; It makes one main physical frag that computes the series returned
;; by frag. (If there is more than one output, then several
;; subsidiary frags have to be created to pick the right values
;; out.)
;;
;; It assumes that actual-args must be a list of variables.
;; This is only called from frag->physical
(cl:defun precompute-frag->physical (frag alter-prop-alist)
(dolist (r (rets frag))
(when (series-var-p r)
(add-physical-out-interface r (cdr (assoc (var r) alter-prop-alist)))))
(cl:let ((*last-series-loop* nil) (*user-names* nil))
(declare (special *last-series-loop* *user-names*))
(codify frag)))
;; This is only called from series-frag->physical
(cl:defun f->p-off-line (i frag new-out out-values done flag)
(cl:let* ((ret (nth i (rets frag)))
(off-line-spot (off-line-spot ret))
(restart (new-var 'restart))
(out-value (if (null (cdr out-values))
(car out-values)
`(list ,@(mapcar #'(lambda (r o)
(when (eq r ret) o))
(rets frag) out-values))))
(new-body-code `((setq ,new-out (cons ,out-value t))
(setq ,flag ,i)
(go ,done)
,restart)))
(push `(if (= ,flag ,i) (go ,restart)) (body frag))
(setf (body frag) (nsubst-inline new-body-code off-line-spot (body frag)))))
;; This is only called from series-frag->physical
(cl:defun f->p-on-line (frag new-out out-values done flag)
(cl:let* ((out-value (if (null (cdr out-values))
(car out-values)
`(list ,@(mapcar #'(lambda (r o)
(when (not (off-line-spot r)) o))
(rets frag) out-values))))
(new-body-code `((setq ,new-out (cons ,out-value t))
,@(when flag
`((setq ,flag -1)))
(go ,done))))
(setf (body frag) (nconc (body frag) new-body-code))))
(cl:defun image-of-non-null-datum-th (g datum)
(cl:let (item)
(loop (setq item (nth datum (basic-do-next-in g)))
(when (or (null (gen-state g)) (not (null item)))
(return item)))))
(cl:defun car-image-of-non-null-datum-th (g datum)
(car (image-of-non-null-datum-th g datum)))
;; This is only called from frag->physical
(cl:defun series-frag->physical (frag alter-prop-alist)
(cl:let* ((out-values nil)
(alterers nil)
(done-on-line nil)
(new-out (new-var 'item))
(n (length (rets frag)))
(done (new-var 'done))
(rts (rets frag))
(flag (when (some #'off-line-spot rts)
(new-var 'flag)))
(label (when flag
(new-var 'l))))
(dolist (r (reverse rts))
(cl:multiple-value-bind (out-value alterer)
(out-value r (cdr (assoc (var r) alter-prop-alist)) (not (= n 1)))
(push out-value out-values)
(push alterer alterers)))
(when flag
(add-literal-aux frag flag 'fixnum -1)
(push label (body frag)))
(dotimes (i n)
(cond ((off-line-spot (nth i (rets frag)))
(f->p-off-line i frag new-out out-values done flag))
((not done-on-line)
(setq done-on-line t)
(f->p-on-line frag new-out out-values done flag))))
(cl:let* ((basic-out (new-var 'series-of-lists))
(code `(make-phys
:alter-fn ,(when (= n 1) (car alterers))
:gen-fn #'(lambda ()
(cl:let (,new-out)
(tagbody ,@(body frag)
,@(when (and flag (not done-on-line))
`((go ,label)))
,@(when (branches-to end (body frag)) `(,end))
,@(epilog frag)
(setq ,new-out nil)
,done)
,new-out)))))
(when (not (= n 1))
(setq code
`(cl:let ((,basic-out ,code))
(values
,@(mapcar
#'(lambda (i r a)
`(make-image-series
:alter-fn ,a
:image-base ,basic-out
:image-datum ,i
:image-fn ,(cond ((and (not a) (off-line-spot r))
'#'car-image-of-non-null-datum-th)
((notany #'off-line-spot (rets frag))
'#'image-of-datum-th)
(t '#'image-of-non-null-datum-th))))
(n-integers n) (rets frag) alterers)))))
(codify-1 (aux frag) (prolog frag) (list code)))))
(cl:defun frag->physical (frag actual-args &optional (force-precompute? nil))
(cl:let ((alter-prop-alist
(mapcar #'(lambda (a actual)
(prog1 (when (series-var-p a)
(list* (var a) actual
(add-physical-interface a)))
(nsubst actual (var a) frag)))
(args frag) actual-args)))
(setf (args frag) nil)
(if (or force-precompute? (wrappers frag)
(some #'(lambda (r) (not (series-var-p r))) (rets frag)))
(precompute-frag->physical frag alter-prop-alist)
(series-frag->physical frag alter-prop-alist))))
) ; end of eval-when
;; Main graph merging function
(cl:defun mergify (*graph*)
(reset-marks)
(do-coercion)
(do-substitution)
(kill-dead-code)
(cl:let ((splits (do-splitting *graph*)))
(eval splits)))
(cl:defun preprocess-body (arglist series-vars type-alist ignore-vars forms outs)
(cl:let* ((arg-frag-rets
(mapcar #'(lambda (a)
(cl:let* ((ret
(make-sym
:var (new-var 'arg)
:series-var-p
(not (null (member a series-vars)))))
(arg-frag (make-frag :code a)))
(+ret ret arg-frag)
(push (cons a ret) *renames*)
ret))
arglist))
(*graph* nil)
(last-form (car (last forms)))
(frag (progn (mapc #'(lambda (f) (fragify f '(values)))
(butlast forms))
(if (not (eq-car last-form 'values))
(fragify last-form
(if (not outs) '*
(cons 'values
(make-list outs
:initial-element t))))
(mapc #'(lambda (f) (fragify f '(values t)))
(cdr last-form)))
(mergify *graph*)))
(input-info nil))
(setf (args frag) ;get into the right order. Discard unused args.
(mapcan #'(lambda (ret a)
(cl:let ((arg (car (nxts ret))))
(cond ((null arg) ;input never used
(cond ((member a ignore-vars) nil)
(t #| ;HERE can get false positives.
(wrs 50 t "~%The input " a " never used.")|#
(list ret)))) ;assume was used anyway.
(t ;here probably want to pretend was not declared ignore.
(when (member a ignore-vars)
(wrs 51 t "~%The input " a
" declared IGNORE and yet used."))
(push (cons a `(series-element-type ,(var arg))) input-info)
(setf (prv arg) nil)
(dolist (a (cdr (nxts ret)))
;input used more than once.
(nsubst (var arg) (var a) (fr a)))
(list arg)))))
arg-frag-rets arglist))
(dolist (e type-alist)
(when (and (member (car e) arglist)
(eq-car (cdr e) 'series)
(cadr (cdr e))
(not (eq (cadr (cdr e)) t)))
(push (cons (car e) (cadr (cdr e))) input-info)))
(doaux (v (aux frag))
(propagate-types (cdr v) (aux frag) input-info))
frag))
(cl:defun compute-optimizable-series-fn (definer name lambda-list expr-list)
"Defines a series function, see lambda-series."
(cl:let ((call (list* definer name lambda-list expr-list))
(*optimize-series-expressions* t)
(*suppress-series-warnings* nil))
(dolist (v lambda-list)
(when (and (symbolp v) (not (eq v '&optional))
(member v lambda-list-keywords))
(ers 71 "~%Unsupported &-keyword " v " in OPTIMIZABLE-SERIES-FN arglist.")))
(top-starting-series-expr call
(cl:let ((vars nil) (rev-arglist nil))
(dolist (a lambda-list)
(cond ((not (member '&optional rev-arglist))
(push a rev-arglist)
(when (not (eq a '&optional))
(push a vars)))
(t (setq a (iterative-copy-tree a))
(setq vars (revappend (vars-of a) vars))
(push a rev-arglist))))
(setq vars (nreverse vars))
(dolist (v vars)
(when (not (variable-p v))
(ers 72 "~%Malformed OPTIMIZABLE-SERIES-FUNCTION argument " v ".")))
(cl:multiple-value-bind
(forms type-alist ignore-vars doc off-line-ports outs)
(decode-dcls expr-list '(types ignores doc off-line-ports opts))
(cl:let* ((series-vars
(mapcar #'car
(remove-if-not #'(lambda (e)
(or (eq (cdr e) 'series)
(eq-car (cdr e) 'series)))
type-alist)))
(frag (preprocess-body vars series-vars
type-alist ignore-vars forms outs))
(used-vars (mapcan #'(lambda (v)
(when (not (member v ignore-vars))
(list v)))
vars))
(series-p (some #'(lambda (r) (series-var-p r)) (rets frag)))
(frag-list (frag->list frag))
(dcls (when ignore-vars
`((ignore ,@ ignore-vars)))))
(check-off-line-ports frag vars off-line-ports)
(when (and (not series-p) (notany #'series-var-p (args frag)))
(wrs 44 t
"~%OPTIMIZABLE-SERIES-FUNCTION neither uses nor returns a series."))
`(,name ,(reverse rev-arglist)
,(if (not dcls) doc (cons doc `(declare . ,dcls)))
,(frag->physical frag used-vars)
:optimizer
(apply-frag (list->frag1 ',frag-list) (list ,@ used-vars))
:trigger ,(not series-p)))))
(cl:multiple-value-bind (forms decls doc)
(decode-dcls expr-list '(no-complaints doc opts))
`(,name ,lambda-list
,@(when doc (list doc))
,@(when decls `((declare ,@ decls)))
(compiler-let ((*optimize-series-expressions* nil)) ,@ forms))))))
(cl:defun define-optimizable-series-fn (name lambda-list expr-list)
(cl:multiple-value-bind (form opt-p)
(compute-optimizable-series-fn 'defun name lambda-list expr-list)
(if opt-p
(cons 'defS form)
(cons 'cl:defun form))))
(cl:defun undefine-optimizable-series-fn (name)
(when (symbolp name)
(remprop name 'series-optimizer)
(remprop name 'returns-series))
name)
;; EXTENSION
(defmacro defun (name lambda-list &environment *env* &body body)
(if (dolist (form body)
(cond ((and (stringp form) (eq form (car body))))
((and (consp form) (eq-car form 'declare))
(if (assoc 'optimizable-series-function (cdr form)) (return t)))
(t (return nil))))
(define-optimizable-series-fn name lambda-list body)
(progn (undefine-optimizable-series-fn name)
`(cl:defun ,name ,lambda-list
. ,body))))
#+symbolics(setf (gethash 'defun zwei:*lisp-indentation-offset-hash-table*)
'(2 1))
#+Symbolics
(setf (get 'defun 'zwei:definition-function-spec-parser)
(get 'cl:defun 'zwei:definition-function-spec-parser))
;;;; ---- DEFS ----
;;;; Macro to define arbitrary SERIES functions.
(eval-when (:compile-toplevel :load-toplevel :execute)
(cl:defun compute-prologing-macform (name body-code)
`(,name (&rest stuff)
(cons ',body-code stuff)))
(cl:defun compute-series-funform (name arglist doc dcl body-code opt-p)
`(,name ,arglist
,@(when doc (list doc))
,@(when dcl (list dcl))
(compiler-let ((*optimize-series-expressions* ,opt-p))
,body-code)))
(cl:defun compute-series-macform-2 (name arglist doc body-code trigger
local-p disc-expr opt-expr
unopt-expansion)
#-:symbolics (declare (ignore arglist))
(cl:let ((unopt (if (symbolp body-code)
`(cons ',body-code stuff)
unopt-expansion)))
`(,name (&whole call &rest stuff &environment *env*)
#+:symbolics (declare (zl:arglist ,@(copy-list arglist)))
,@(when doc (list doc))
,(if trigger
`(if ,(if (eq trigger t)
'*optimize-series-expressions*
`(and *optimize-series-expressions* ,trigger))
,(if local-p
(cl:let ((retprop (gensym))
(optprop (gensym))
(result (gensym)))
`(cl:let ((,retprop (get ',name 'returns-series))
(,optprop (get ',name 'series-optimizer)))
(setf (get ',name 'returns-series) (function ,disc-expr))
(setf (get ',name 'series-optimizer) (function ,opt-expr))
(setq ,result (process-top call))
(setf (get ',name 'series-optimizer) ,optprop)
(setf (get ',name 'returns-series) ,retprop)
,result))
`(process-top call))
,unopt)
unopt))))
(cl:defun compute-series-macform-1 (name arglist body-code body-fn trigger
local-p disc-expr opt-expr)
(compute-series-macform-2 name arglist nil body-code trigger
local-p disc-expr opt-expr
`(list* 'cl:funcall ',body-fn stuff)))
;; It's a macro and body can refer to it
(cl:defun compute-series-macform (name arglist doc dcl body-code body-fn trigger
local-p disc-expr opt-expr)
(compute-series-macform-2 name arglist doc body-code trigger
local-p disc-expr opt-expr
`(macrolet (,(compute-series-macform-1
name arglist body-code body-fn trigger
local-p disc-expr opt-expr))
`(cl:flet (,',(compute-series-funform
body-fn arglist doc dcl body-code nil))
(,',body-fn ,@stuff)))))
;;The body runs when optimization is not happening.
;;The optimizer runs when optimization is happening.
;;The trigger says whether or not a series expression is beginning.
;; it forces NAME to be a macro instead of a function.
;;The discriminator says whether or not series are being returned.
(cl:defun defS-1 (name arglist doc body optimizer trigger discriminator local-p)
(cl:let* ((body-code body)
(dcl (when (consp doc)
(prog1 (cdr doc) (setq doc (car doc)))))
(opt-code (or optimizer body))
(body-fn (cond ((symbolp body-code) body-code)
(trigger (new-var (string name)))))
(desc-fn (cond (discriminator nil)
(trigger 'no)
(t 'yes)))
(opt-arglist ;makes up for extra level of evaluation.
(mapcar #'(lambda (a)
(if (and (listp a) (listp (cdr a)))
(list* (car a) `(copy-tree ',(cadr a)) (cddr a))
a))
arglist))
(disc-expr (if discriminator
`(lambda (call) ,discriminator)
desc-fn))
(opt-expr `(lambda ,@(cdr (compute-series-funform
nil opt-arglist nil dcl opt-code t)))))
(values (cond (trigger
(cons 'defmacro (compute-series-macform
name arglist doc dcl body-code body-fn trigger
local-p disc-expr opt-expr)))
((symbolp body-code)
(cons 'defmacro
(compute-prologing-macform name body-code)))
((not (symbolp body-code))
(cons 'cl:defun
(compute-series-funform
name arglist doc dcl body-code nil))))
disc-expr
opt-expr)))
(defmacro defS (name arglist doc body &key optimizer trigger discriminator)
(cl:multiple-value-bind (topdef
discriminator-expr
optimizer-expr)
(defS-1 name arglist doc body optimizer trigger discriminator nil)
`(eval-when (:compile-toplevel :load-toplevel :execute)
,topdef
(setf (get ',name 'returns-series) (cl:function ,discriminator-expr))
(setf (get ',name 'series-optimizer) (cl:function ,optimizer-expr))
',name)))
;; PROTOTYPE VERSION ONLY - DO NOT USE YET
(defmacro slet1 (def &body forms)
(if def
(destructuring-bind (name arglist doc body &key optimizer trigger discriminator) def
(cl:multiple-value-bind (topdef
discriminator-expr
optimizer-funform)
(defS-1 name arglist doc body optimizer trigger discriminator t)
(declare (ignore discriminator-expr optimizer-funform))
(list* (case (car topdef)
((defmacro) 'macrolet)
((cl:defun) 'cl:flet))
(list (cdr topdef))
forms)))
`(progn ,@forms)))
;; DO NOT USE YET
(defmacro slet* (defs &body forms)
(destarrify 'slet1 defs nil nil nil forms))
) ;end of eval-when for defS
;;;; ---- fragL ----
(cl:defun apply-literal-frag (frag-and-values)
(apply-frag (literal-frag (car frag-and-values)) (cdr frag-and-values)))
(eval-when (:compile-toplevel :load-toplevel :execute)
;; this forms are useful for making code that comes out one way in the
;; body and another way in the optimizer
(defmacro optif (f1 f2)
`(if *optimize-series-expressions* ,f1 ,f2))
(defmacro eoptif (f1 f2)
(if *optimize-series-expressions* f1 f2))
(defmacro eoptif-q (f1 f2)
(optif `,f1 `,f2))
(defmacro optif-q (f1 f2)
`(optif ',f1 ',f2))
(defmacro non-optq (x) `(eoptif ,x (list 'quote ,x)))
(defmacro optq (x) `(eoptif ',x ,x))
(cl:defun apply-physical-frag (stuff args)
(frag->physical (literal-frag stuff)
args))
(cl:defun funcall-physical-frag (stuff &rest args)
(frag->physical (literal-frag stuff)
args))
(declaim (inline unopt-fragl))
(cl:defun unopt-fragl (stuff)
(apply-physical-frag stuff (mapcar #'car (car stuff))))
(cl:defun opt-fragl (stuff inputs)
`(apply-literal-frag
(list ,stuff
,@inputs)))
(cl:defun fragl-2 (stuff args)
(optif
(opt-fragl `(quote ,stuff) args)
(apply-physical-frag stuff args)))
#|
(cl:defun fragl-2 (stuff args)
(optif
`(apply-literal-frag (list (quote ,stuff) ,args))
(apply-physical-frag stuff args)))
|#
(cl:defmacro efragl (a stuff)
(optif
`(funcall-frag (literal-frag (cons ',a ,stuff)) ,@(mapcar #'car a))
(apply-physical-frag (cons a (eval stuff)) (mapcar #'car a))))
(declaim (inline fragl-1))
(cl:defun fragl-1 (stuff)
(fragl-2 stuff (mapcar #'car (car stuff))))
(cl:defun sublis-limits (tree)
(sublis `((*limit* . ,most-positive-fixnum)
(most-positive-fixnum . ,most-positive-fixnum)
(array-total-size-limit . ,array-total-size-limit)
(array-dimension-limit . ,array-dimension-limit))
tree))
(cl:defun *fragl-1 (stuff)
(optif
(opt-fragl (if (not (contains-p '*type* stuff))
(if (not (contains-p '*limit* stuff))
`(quote ,stuff)
`(subst *limit* '*limit* ',stuff))
(if (not (contains-p '*limit* stuff))
`(subst *type* '*type* ',stuff)
`(sublis `((*type* . ,*type*)
(*limit* . ,*limit*))
',stuff)))
(mapcar #'car (car stuff)))
(unopt-fragl (list* (car stuff)
(cadr stuff)
(mapcar #'(lambda (data)
(if (or (eq (cadr data) '*type*)
(eq-car (cadr data)
'series-element-type))
(list* (car data) t (cddr data))
(list* (car data)
(sublis-limits (cadr data))
(cddr data))))
(caddr stuff))
(sublis-limits (cdddr stuff))))))
) ;end of eval-when for fragl-1
(defmacro fragl (&rest stuff)
#+symbolics (declare (scl:arglist args rets aux alt prolog body epilog wraprs))
#-:series-plain
(fragl-1 stuff)
#+:series-plain
(cl:let ((a (caddr stuff)))
(apply #'fragl-1
(car stuff) (cadr stuff) (simplify-aux a) (cadddr stuff)
(nconc (aux->prolog a) (car (cddddr stuff)))
(cdr (cddddr stuff))
)))
(defmacro *fragl (&rest stuff)
#+symbolics (declare (scl:arglist args rets aux alt prolog body epilog wraprs))
#-:series-plain
(*fragl-1 stuff)
#+:series-plain
(cl:let ((a (caddr stuff)))
(apply #'*fragl-1
(car stuff) (cadr stuff) (simplify-aux a) (cadddr stuff)
(nconc (aux->prolog a) (car (cddddr stuff)))
(cdr (cddddr stuff))
)))
;;;; ---- COLLECT ----
;; We put this SERIES function here so the compiler doesn't think it's
;; a function while compiling gatherers.
;; seq-type must be a subtype of SEQUENCE or BAG.
;; API
(defS collect (seq-type &optional (items nil items-p))
"(collect [type] series)
Creates a sequence containing the elements of SERIES. The TYPE
argument specifies the type of sequence to be created. This type must
be a proper subtype of sequence. If omitted, TYPE defaults to LIST. "
(cl:let (*type* limit el-type)
(unless items-p ;it is actually seq-type that is optional
(setq items seq-type)
(setq seq-type (optq 'list)))
(multiple-value-setq (*type* limit el-type)
(decode-seq-type (non-optq seq-type)))
(cond ((eq *type* 'list)
(or (matching-scan-p items #'lister-p)
(fragl ((items t)) ((lst))
((lastcons cons (list nil))
(lst list))
()
((setq lst lastcons))
((setq lastcons (setf (cdr lastcons) (cons items nil))))
((setq lst (cdr lst)))
()
nil
)))
((eq *type* 'bag)
(or (matching-scan-p items #'lister-p)
(fragl ((items t)) ((lst))
((lst list nil))
()
()
((setq lst (cons items lst)))
()
()
nil)))
((eq *type* 'set)
(fragl ((items t)) ((lst))
((table t (make-hash-table))
(lst list nil))
()
()
((setf (gethash items table) t))
((with-hash-table-iterator (next-entry table)
(loop (cl:multiple-value-bind (more key) (next-entry)
(unless more (return lst))
(push key lst)))))
() nil))
((eq *type* 'ordered-set)
(fragl ((items t)) ((lst))
((table t (make-hash-table))
(lastcons cons (list nil))
(lst list))
()
((setq lst lastcons))
((cl:multiple-value-bind (val found)
(gethash items table)
(declare (ignore val))
(unless found
(setf (gethash items table) t)
(setq lastcons (setf (cdr lastcons) (cons items nil))))))
((setq lst (cdr lst)))
() nil))
(limit
;; It's good to have the type exactly right so CMUCL can
;; optimize better.
(setq *type* (if (consp (cadr seq-type))
(cadr seq-type)
seq-type))
(efragl
((seq-type) (items t) (limit))
`(((seq))
((seq ,(optif *type* 'sequence))
(index vector-index+ 0))
()
(#-(or :cmu :scl)
(setq seq (make-sequence seq-type limit))
;; For some reason seq isn't initialized when
;; *optimize-series-expressions* is nil and this
;; errors out in CMUCL. This makes sure seq is
;; initialized to something.
#+(or :cmu :scl)
(setq seq (if seq
seq
(make-sequence seq-type limit)))
)
((setf (aref seq (the vector-index index)) items) (incf index))
()
()
nil
)))
((not (eq *type* 'sequence)) ;some kind of array with no dimension
;; It's good to have the type exactly right so CMUCL can
;; optimize better.
(setq *type* (if (eq *type* 'simple-array)
(list *type* el-type '(*))
(list *type* el-type)))
(bind-if* (l (matching-scan-p items #'lister-p))
(apply-literal-frag
`((()
((seq))
((seq (null-or ,*type*)))
()
()
()
((cl:let* ((lst ,l)
(num (length lst)))
(declare (type nonnegative-integer num))
(setq seq (make-sequence ,seq-type num))
(dotimes (i num)
(setf (aref seq i) (pop lst)))))
()
nil
)
))
(setq *type* (make-nullable *type*))
(efragl ((seq-type) (items t))
`(((seq))
((seq ,(optif *type* 'sequence) nil)
(lst list))
()
()
((setq lst (cons items lst)))
((cl:let ((num (length lst)))
(declare (type nonnegative-integer num))
(setq seq (make-sequence seq-type num))
(do ((i (1- num) (1- i))) ((minusp i))
(setf (aref seq i) (pop lst)))))
()
nil
))))
(t
(fragl ((seq-type) (items t)) ((seq))
((seq t)
(limit (null-or nonnegative-integer)
(cl:multiple-value-bind (x y)
(decode-seq-type (list 'quote seq-type))
(declare (ignore x))
y)) ; y is not restricted to fixnum!
(lst list nil))
()
()
((setq lst (cons items lst)))
((cl:let ((num (length lst)))
(declare (type nonnegative-integer num))
(setq seq (make-sequence seq-type (or limit num)))
(do ((i (1- num) (1- i))) ((minusp i))
(setf (elt seq i) (pop lst)))))
()
nil
))))
:trigger t)
;;;; ---- GATHERERS ----
;;; The following functions support gatherers. No optimization ever
;;; applies to gatherers except in PRODUCING and GATHERING. A
;;; gatherer is a function of two arguments. If the second argument
;;; is NIL, the first argument is added into the accumulator of the
;;; gatherer. If the second argument is not NIL, the accumulated
;;; result is returned. It is an error to call the gatherer again
;;; after the accumulated result has been returned.
(eval-when (:compile-toplevel :load-toplevel :execute)
(defmacro gather-next (gatherer item)
`(cl:funcall ,gatherer ,item nil))
(defmacro gather-result (gatherer)
`(cl:funcall ,gatherer nil t))
) ; end of eval-when
(cl:defun next-out (gatherer item)
(gather-next gatherer item)
nil)
(cl:defun result-of (gatherer)
(gather-result gatherer))
;; this assumes the frag is a one-in one-out collector and that if
;; there are wrappers, they are only relevant to the epilog.
(cl:defun gathererify (frag)
(when (off-line-spot (car (args frag)))
(convert-to-reducer (car (args frag))))
(cl:let ((code `(tagbody ,@(body frag)))
(ecode `(progn ,@(epilog frag)))
(wrps (wrappers frag)))
(setq ecode (apply-wrappers wrps ecode #'epilog-wrapper-p))
(setf (wrappers frag) (delete-if #'epilog-wrapper-p wrps))
(codify-1 (aux frag)
(prolog frag)
`((function (lambda (,(var (car (args frag))) result-p)
(cond ((null result-p) ,code)
(t ,ecode ,(var (car (rets frag)))))))))))
(cl:defun frag-for-collector (collector *env*)
(cl:let ((frag
(top-starting-series-expr collector
(progn
(when (not (eq-car collector 'lambda))
(cl:let ((x (new-var 'gatherer)))
(setq collector `(lambda (,x) (,collector ,x)))))
(cl:multiple-value-bind (forms type-alist ignore-vars outs)
(decode-dcls (cddr collector) '(types ignores opts))
(cl:let* ((series-vars
(mapcar #'car
(remove-if-not
#'(lambda (e)
(or (eq (cdr e) 'series)
(eq-car (cdr e) 'series)))
type-alist))))
(preprocess-body (cadr collector) series-vars
type-alist ignore-vars forms outs))))
nil)))
(when (not (and (frag-p frag)
(= 1 (length (args frag)))
(series-var-p (car (args frag)))
(= 1 (length (rets frag)))
(not (series-var-p (car (rets frag))))))
(ers 61 "~%Input to GATHERER fails to be one-input one-output collector."))
frag))
(cl:defun gather-sanitize (collector)
(cl:let ((x (new-var 'gather)))
`#'(lambda (,x) (funcall ,collector (scan (collect ,x))))))
(cl:defun gatherlet-1 (binder bindifier decls var-collector-pairs *env* body)
(cl:let* ((frags (mapcar #'(lambda (p) (frag-for-collector (cadr p) *env*))
var-collector-pairs))
(stuff (mapcar #'gathererify frags))
(fns (mapcar #'(lambda (p s) (cons (car p) (cl:funcall bindifier
(cl:let ((f (car (last s))))
(if (and (listp f)
(eq (car f) 'locally))
(car (last f))
f)))))
var-collector-pairs stuff))
(fullbody `(,binder ,fns ,@decls ,@body)))
(dolist (s (reverse stuff))
(cl:let ((f (car (last s))))
(setq fullbody (nconc (butlast s)
(list (if (and (listp f)
(eq (car f) 'locally))
(nconc (butlast f) (list fullbody))
fullbody))))))
(cl:let ((wrps (mapcan #'(lambda (f)
(prog1 (frag-wrappers f) (setf (wrappers f) nil)))
frags)))
(setq fullbody (apply-wrappers wrps fullbody)))
fullbody))
(cl:defun gathering-1 (binder bindifier result-op decls var-collector-pairs *env* body)
(cl:let ((returns (mapcar #'(lambda (p) `(,result-op ,(car p)))
var-collector-pairs)))
(gatherlet-1 binder bindifier decls var-collector-pairs *env*
`(,@body ,(if (= (length returns) 1)
(car returns)
`(values ,@returns))))))
(eval-when (:load-toplevel :execute)
(defmacro fgather-next (gatherer item)
`(,gatherer ,item nil))
(defmacro fgather-result (gatherer)
`(,gatherer nil t))
(defmacro gatherer (collector &environment *env*)
(unless (or (eq-car collector 'function)
(eq-car collector 'lambda))
(cl:let ((x (new-var 'gather)))
(setq collector
`#'(lambda (,x)
(cl:funcall ,collector (cl:funcall #'scan (collect ,x)))))))
(cl:let ((frag (frag-for-collector (if (eq-car collector 'function)
(cadr collector)
collector) *env*)))
(when (wrappers frag)
(cl:let ((x (new-var 'gather)))
(setq frag (frag-for-collector
`(lambda (,x) (funcall ,collector (scan (collect ,x))))
*env*))))
(gathererify frag)))
(defmacro gatherlet (var-collector-pairs &environment *env* &body body)
(gatherlet-1 'cl:let #'list nil var-collector-pairs *env* body))
(defmacro fgatherlet (var-collector-pairs &environment *env* &body body)
(gatherlet-1 'cl:flet #'cdadr nil var-collector-pairs *env* body))
(defmacro gathering (var-collector-pairs &environment *env* &body forms)
(cl:multiple-value-bind (decls body)
#+:cltl2-series (values nil forms)
#-:cltl2-series (dynamize-vars (mapcar #'car var-collector-pairs) forms #'eq)
(gathering-1 'cl:let #'list 'gather-result decls var-collector-pairs *env* body)))
(defmacro fgathering (var-collector-pairs &environment *env* &body forms)
(cl:multiple-value-bind (decls body)
#+:cltl2-series (values nil forms)
#-:cltl2-series (dynamize-vars (mapcar #'(lambda (x)
`(function ,(car x)))
var-collector-pairs)
forms
#'equal)
(gathering-1 'cl:flet #'cdadr 'fgather-result decls var-collector-pairs *env* body)))
) ; end of eval-when
;;;; ---- SERIES FUNCTION LIBRARY ----
(cl:defun process-top (call)
(when (and *series-expression-cache*
(not (hash-table-p *series-expression-cache*)))
(setq *series-expression-cache* (make-hash-table :test #'eq)))
(cl:let ((cached-value (and *series-expression-cache*
(gethash call *series-expression-cache*))))
(cond (cached-value)
(t (setq cached-value
(top-starting-series-expr call
(codify (mergify (graphify call)))
`(compiler-let ((*optimize-series-expressions* nil)) ,call)))
(when *series-expression-cache*
(setf (gethash call *series-expression-cache*) cached-value))
cached-value))))
;; The next few things are optimizers that hang on standard symbols.
;;
;; Note the cludging we have to do when the first var is a let-series
;; var. This is necessary in case this value is going to have to be a
;; return value as well. We really should have done something better
;; about specifing free variable outputs so that this mess would not
;; be necessary.
(cl:defun my-multi-setq (vars value form)
(cl:let* ((type (if (null (cdr vars))
t
`(values ,@(make-list (length vars) :initial-element t))))
(frag (fragify value type)))
(dolist (out (rets frag))
(cl:let* ((v (pop vars))
(entry (assoc v *renames*)))
(cond (entry
(rplacd entry out)
(setf (free-out out) v)
(when (eq out (car (rets frag)))
(cl:let* ((v (new-var 'copy))
(ret (make-sym :var v :series-var-p (series-var-p out)))
(assignment `((setq ,v ,(var out)))))
(setf (fr ret) frag)
(push ret (rets frag))
(add-aux frag v t)
(cond ((off-line-spot out)
(setf (off-line-spot ret) (new-var '-C-))
(setf (body frag)
(nsubst-inline `(,@ assignment
,(off-line-spot ret)
,(off-line-spot out))
(off-line-spot out) (body frag))))
((series-var-p out)
(setf (body frag) (append (body frag) assignment)))
((or (body frag) (epilog frag))
(setf (epilog frag) (append (epilog frag) assignment)))
(t (append-prolog frag assignment))))))
((series-var-p out)
(rrs 11 "~%series value assigned to free variable~%" form))
(t (if (or (body frag) (epilog frag))
(setf (epilog frag)
(append (epilog frag) `((setq ,v ,(var out)))))
(append-prolog frag `((setq ,v ,(var out)))))
(when (not (eq out (car (rets frag))))
(kill-ret out))))))
frag))
(cl:defun setq-opt (var exp)
(my-multi-setq (list var) exp `(setq ,var ,exp)))
(setf (get 'setq 'series-optimizer) #'setq-opt)
(setf (get 'setq 'returns-series) #'no) ;here should be better than this
(cl:defun multiple-value-setq-opt (vars exp)
(my-multi-setq vars exp `(multiple-value-setq ,vars ,exp)))
(setf (get 'multiple-value-setq 'series-optimizer) #'multiple-value-setq-opt)
(setf (get 'multiple-value-setq 'returns-series) #'no) ;here should be better than this
(cl:defun produces-optimizable-series (original-code)
(cl:let ((flag t) pred (code original-code))
(loop
(cond ((not (and flag (consp code) (symbolp (car code))))
(return nil))
((eq (car code) 'values)
(return (some #'produces-optimizable-series (cdr code))))
((eq (car code) 'the)
(return (produces-optimizable-series (caddr code))))
(t
(setq pred (get (car code) 'returns-series))
(cond (pred
(return (cl:funcall pred code)))
((not-expr-like-special-form-p (car code))
(return nil))
((not (macro-function (car code)))
(return (some #'produces-optimizable-series (cdr code))))
(t
(when (eq code original-code)
(setq code (iterative-copy-tree code)))
(multiple-value-setq (code flag) (macroexpand-1 code *env*)))))))))
;; EXTENSION
(defS funcall (function &rest expr-list) "" cl:funcall
:optimizer
(cond ((and (eq-car function 'function) (symbolp (cadr function))
(get (cadr function) 'series-optimizer))
(cons (cadr function) expr-list))
((not (simple-quoted-lambda function))
(list* 'cl:funcall function expr-list))
((not (= (length expr-list)
(length (simple-quoted-lambda-arguments function))))
(ers 67 "~%Wrong number of args to funcall:~%" (cons function expr-list)))
(t `(let ,(mapcar #'list (simple-quoted-lambda-arguments function) expr-list)
,@(simple-quoted-lambda-body function))))
:trigger
(cl:let* ((function (my-macroexpand (cadr call)))
(expr-list (cddr call)))
(or (and (eq-car function 'function) (symbolp (cadr function))
(get (cadr function) 'series-optimizer))
(and (simple-quoted-lambda function)
(some #'produces-optimizable-series expr-list))))
:discriminator
(cl:let* ((function (my-macroexpand (cadr call))))
(or (and (eq-car function 'function) (symbolp (cadr function))
(get (cadr function) 'series-optimizer))
(and (simple-quoted-lambda function)
(produces-optimizable-series
(car (last (simple-quoted-lambda-body function))))))))
; Binding forms processing
;; HELPER
(cl:defun normalize-pair (p allow-multiple-vars)
(cond ((variable-p p) (list (list p) nil))
((and (consp p) (variable-p (car p)) (= (length p) 2))
(list (list (car p)) (cadr p)))
((and (consp p) (variable-p (car p)) (= (length p) 1))
(list (list (car p)) nil))
((and allow-multiple-vars (consp p) (consp (car p))
(every #'variable-p (car p))
(= (length p) 2)) p)
(t (ers 66 "~%Malformed binding pair " p "."))))
(cl:defun process-let-series-pair (p type-alist allow-multiple-vars)
(setq p (normalize-pair p allow-multiple-vars))
(cl:let* ((vars (car p))
(types (mapcar #'(lambda (v) (or (cdr (assoc v type-alist)) t))
vars))
(rets
(if (= (length vars) 1)
(list (retify (cadr p) (car types)))
(rets (fragify (cadr p) `(values ,@ types))))))
(mapcar #'(lambda (v r)
(push (cons (var r) v) *user-names*)
(setf (free-out r) v)
(cons v r))
vars rets)))
(cl:defun process-let-forms (forms)
(mapc #'(lambda (f) (fragify f '(values))) (butlast forms))
(fragify (car (last forms)) '*)) ;forces NIL if no forms.
(cl:defun process-let-series-body (ignore-vars forms alist)
(cl:let* ((initial-alist (mapcar #'(lambda (e) (cons (car e) (cdr e))) alist))
(frag (process-let-forms forms)))
(mapc #'(lambda (old new)
(cond ((and (eq (cdr old) (cdr new)) ;not setqed.
(null (nxts (cdr new)))) ;current value not used.
(if (not (member (car old) ignore-vars))
nil #| ;HERE can get false positives.
(wrs 52 t "~%The variable "
(car old) " is unused in:~%" *call*)|#))
((member (car old) ignore-vars)
(wrs 53 t "~%The variable " (car old)
" is declared IGNORE and yet used in:~%" *call*))))
initial-alist alist)
frag))
;; EXTENSION
(defS multiple-value-bind (vars values &rest body) "" cl:multiple-value-bind
:optimizer
(cl:multiple-value-bind (forms type-alist ignore-vars opt-decls)
(decode-dcls body '(types ignores generic-opts))
(declare (ignore opt-decls))
(cl:let* ((bindings (process-let-series-pair (list vars values)
type-alist t))
(*renames* (revappend bindings *renames*)))
(process-let-series-body ignore-vars forms bindings)))
:trigger (produces-optimizable-series (caddr call))
:discriminator (produces-optimizable-series (car (last call))))
#+symbolics(setf (gethash 'multiple-value-bind
zwei:*lisp-indentation-offset-hash-table*)
'(1 3 2 1))
(setf (get 'cl:multiple-value-bind 'series-optimizer)
(get 'multiple-value-bind 'series-optimizer))
(setf (get 'cl:multiple-value-bind 'returns-series)
(get 'multiple-value-bind 'returns-series))
;; EXTENSION
(defS let (pairs &rest body) "" cl:let
:optimizer
(cl:multiple-value-bind (forms type-alist ignore-vars opt-decls)
(decode-dcls body '(types ignores generic-opts))
(declare (ignore opt-decls))
(cl:let* ((bindings (mapcan #'(lambda (p)
(process-let-series-pair p type-alist nil))
pairs))
(*renames* (revappend bindings *renames*)))
(process-let-series-body ignore-vars forms bindings)))
:trigger
(dolist (pair (cadr call) nil)
(when (and (consp pair) (cdr pair) (produces-optimizable-series (cadr pair)))
(return t)))
:discriminator (produces-optimizable-series (car (last call))))
#+symbolics(setf (gethash 'let zwei:*lisp-indentation-offset-hash-table*)
'(1 1))
(setf (get 'cl:let 'series-optimizer) (get 'let 'series-optimizer))
(setf (get 'cl:let 'returns-series) (get 'let 'returns-series))
;; EXTENSION
(defS let* (pairs &rest body) "" cl:let*
:optimizer
(cl:multiple-value-bind (forms type-alist ignore-vars opt-decls)
(decode-dcls body '(types ignores generic-opts))
(declare (ignore opt-decls))
(cl:let* ((old-top *renames*)
(*renames* *renames*))
(dolist (p pairs)
(setq *renames*
(nconc (process-let-series-pair p type-alist nil) *renames*)))
(process-let-series-body ignore-vars forms (ldiff *renames* old-top))))
:trigger
(dolist (pair (cadr call) nil)
(when (and (consp pair) (cdr pair) (produces-optimizable-series (cadr pair)))
(return t)))
:discriminator (produces-optimizable-series (car (last call))))
#+symbolics(setf (gethash 'let* zwei:*lisp-indentation-offset-hash-table*)
'(1 1))
(setf (get 'cl:let* 'series-optimizer) (get 'let* 'series-optimizer))
(setf (get 'cl:let* 'returns-series) (get 'let* 'returns-series))
;; Next we have the definitions of the basic higher order functions.
(declaim (special *state*))
;; Helping functions
(cl:defun list-of-next (at-end list-of-generators)
(mapcar #'(lambda (g) (do-next-in g at-end)) list-of-generators))
(cl:defun values-of-next (at-end list-of-generators)
(polyapply #'(lambda (g) (do-next-in g at-end)) list-of-generators))
;; HELPER
;;
;; If function is not a simple quoted function, then a non-series
;; input is added to frag, and a parameter is added to params so that
;; the function will get processed right.
(cl:defun handle-fn-arg (frag function params)
(unless (or (and (eq-car function 'function)
(or (symbolp (cadr function))
(and (eq-car (cadr function) 'lambda)
(every #'(lambda (a)
(and (symbolp a)
(not (member a lambda-list-keywords))))
(cadr (cadr function))))))
(and (eq-car function 'lambda)
(every #'(lambda (a)
(and (symbolp a)
(not (member a lambda-list-keywords))))
(cadr function))))
(cl:let ((fn-var (new-var 'function)))
(+arg (make-sym :var fn-var) frag)
(setq params (nconc params (list function)))
(setq function fn-var)))
(values function params))
;; HELPER
;;
;; This makes code for `(multiple-value-setq ,out-vars (funcall ,fn ,@
;; in-vars)). It always returns a list of a single statement. Also,
;; any free references to series::let vars are made non-series inputs
;; of frag and hooked up to the right things. (Note macro expansion
;; has to be done in a nested context so that nested series
;; expressions will be ok.) (Note also that this has to bypass what
;; usually happens when macroexpanding function quoted things. Things
;; should be sructured differently so that this is not necessary.)
(cl:defun handle-fn-call (frag out-vars fn in-vars &optional (last? nil))
(declare (type list out-vars)
(type list in-vars))
(cl:let ((*in-series-expr* nil) (*not-straight-line-code* nil)
(*user-names* nil) (*renames* *renames*) (fn-quoted? nil))
(when (eq-car fn 'lambda)
(setq fn-quoted? t))
(when (eq-car fn 'function)
(setq fn-quoted? t)
(setq fn (cadr fn)))
(cl:multiple-value-bind (fn free-ins free-outs setqed state)
(handle-non-series-stuff fn *state*)
(declare (ignore setqed))
(setq *state* state)
(when last?
(dolist (entry free-ins)
(cl:let ((arg (make-sym :var (car entry))))
(+arg arg frag)
(+dflow (cdr entry) arg)))
(dolist (entry free-outs)
(cl:let ((new (make-sym :var (car entry)))
(v (cdr entry)))
(when (not (find (car entry) (args frag) :key #'var))
(add-aux frag (car entry) t))
(setf (free-out new) v)
(+ret new frag)
(rplacd (assoc v *renames*) new))))
(setq fn (if (not fn-quoted?)
`(cl:funcall ,fn)
`(,fn)))
(cond ((null out-vars) `((,@ fn ,@ in-vars)))
((= (length out-vars) 1)
`((setq ,(car out-vars) (,@ fn ,@ in-vars))))
(t `((multiple-value-setq ,out-vars (,@ fn ,@ in-vars))))))))
;; HELPER
(cl:defun must-be-quoted (type)
(declare (type (or list symbol) type))
(cond ((eq-car type 'quote) (cadr type))
((member type '(t nil)) type)
(t (rrs 2 "~%Non-quoted type " type "."))))
;; API
(defS map-fn (type function &rest args)
"(map-fn type function &rest series-inputs)
The higher-order function map-fn supports the general concept of
mapping. The TYPE argument is a type specifier indicating the type of
values returned by FUNCTION. The values construct can be used to
indicate multiple types; however, TYPE cannot indicate zero values. If
TYPE indicates m types , then map-fn returns m series T1, ..., Tm,
where Ti has the type (series ). The argument FUNCTION is a
function. The remaining arguments (if any) are all series. "
(cl:let ((n (length (decode-type-arg type))))
(setq args (copy-list args))
(cond ((= n 1)
(fragl ((function) (args)) ((items t))
((items t)
(list-of-generators list (mapcar #'generator args)))
()
()
((setq items (cl:multiple-value-call function
(values-of-next #'(lambda () (go end))
list-of-generators))))
()
()
:fun ; Assumes impure function for now
))
(t (values-lists n (apply #'map-fn t
#'(lambda (&rest vals)
(multiple-value-list
(apply function vals)))
args)))))
:optimizer
(cl:let* ((types (decode-type-arg (must-be-quoted type)))
(params nil)
(frag (make-frag :impure :fun))
(in-vars (n-gensyms (length args) (symbol-name '#:m-)))
(out-vars (n-gensyms (length types) (symbol-name '#:items-)))
(*state* nil))
(dolist (var out-vars)
(+ret (make-sym :var var :series-var-p t) frag))
(setf (aux frag)
(makeaux (mapcar #'list out-vars types)))
(multiple-value-setq (function params)
(handle-fn-arg frag function params))
(setq params (mapcar #'retify (nconc params args)))
(dolist (var in-vars)
(+arg (make-sym :var var :series-var-p t) frag))
(setf (body frag) (handle-fn-call frag out-vars function in-vars t))
(apply-frag frag params)))
;; OPTIMIZER
(cl:defun scan-fn-opt (wrap-fn inclusive-p type init step
&optional (test nil test-p))
(cl:let* ((types (decode-type-arg (must-be-quoted type)))
(params nil)
(frag (make-frag :impure :fun))
(state-vars (n-gensyms (length types) (symbol-name '#:state-)))
(out-vars (n-gensyms (length types) (symbol-name '#:items-)))
(*state* nil))
(when wrap-fn
(add-wrapper frag wrap-fn))
(dolist (var out-vars)
(+ret (make-sym :var var :series-var-p t) frag))
(setf (aux frag)
(makeaux (append (mapcar #'list state-vars types)
(mapcar #'list out-vars types))))
(multiple-value-setq (init params) (handle-fn-arg frag init params))
(multiple-value-setq (step params) (handle-fn-arg frag step params))
(when test-p
(multiple-value-setq (test params)
(handle-fn-arg frag test params)))
(setq params (mapcar #'retify params))
(setf (prolog frag) (makeprolog (handle-fn-call frag state-vars init
nil)))
(cl:let ((output-expr `(setq ,@(mapcan #'list out-vars state-vars))))
(if (not inclusive-p)
(setf (body frag)
`(,@(if test-p
`((if ,(car (handle-fn-call frag nil test
state-vars))
(go ,end))))
,output-expr
,(car (handle-fn-call frag state-vars step state-vars
t))))
(cl:let ((done (new-var 'd)))
(add-literal-aux frag done 'boolean nil)
(setf (body frag)
`((if ,done (go ,end))
,(car (handle-fn-call frag (list done) test state-vars))
,output-expr
(if (not ,done)
,(car (handle-fn-call frag state-vars step state-vars
t))))))))
(apply-frag frag params)))
;; OPTIMIZER
(cl:defun collect-fn-opt (wrap-fn type inits function &rest args)
(declare (type list args))
(cl:let* ((types (decode-type-arg (must-be-quoted type)))
(params nil)
(frag (make-frag :impure :fun))
(in-vars (n-gensyms (length args) (symbol-name '#:items-)))
(out-vars (n-gensyms (length types) (symbol-name '#:c-)))
(*state* nil))
(when wrap-fn
(add-wrapper frag wrap-fn))
(dolist (var out-vars)
(+ret (make-sym :var var) frag))
(setf (aux frag)
(makeaux (mapcar #'list out-vars types)))
(multiple-value-setq (inits params) (handle-fn-arg frag inits params))
(multiple-value-setq (function params) (handle-fn-arg frag function params))
(setq params (mapcar #'retify (nconc params args)))
(dolist (var in-vars)
(+arg (make-sym :var var :series-var-p t)
frag)) ;must be before other possible args
(setf (prolog frag) (makeprolog (handle-fn-call frag out-vars inits nil)))
(setf (body frag)
(handle-fn-call frag out-vars function (append out-vars in-vars) t))
(apply-frag frag params)))
;; needed because collect is a macro
(cl:defun basic-collect-list (items)
(compiler-let ((*optimize-series-expressions* nil))
(fragl ((items t)) ((lst))
((lastcons cons (list nil))
(lst list))
()
((setq lst lastcons))
((setq lastcons (setf (cdr lastcons) (cons items nil))))
((setq lst (cdr lst)))
()
nil
)))
(cl:defun scan-multi-out->scan-list-out (fn type init step test)
(compiler-let ((*optimize-series-expressions* nil))
(cl:let ((n (length (decode-type-arg type))))
(cl:flet ((new-init () (forceL n (multiple-value-list (cl:funcall init))))
(new-step (state) (forceL n (multiple-value-list (apply step state))))
(new-test (state) (apply test state)))
(declare (indefinite-extent #'new-init #'new-step #'new-test))
(cl:funcall fn t #'new-init #'new-step #'new-test)))))
(defmacro encapsulated-macro (encapsulating-fn scanner-or-collector)
(unless (or (eq-car encapsulating-fn 'function)
(eq-car encapsulating-fn 'lambda))
(ers 68 "~%First ENCAPSULATING arg " encapsulating-fn
" is not quoted function."))
(cond ((and (or (eq-car scanner-or-collector 'scan-fn)
(eq-car scanner-or-collector 'scan-fn-inclusive))
(= (length scanner-or-collector) 5))
(cl:let ((body `(basic-collect-list
(scan-multi-out->scan-list-out
#',(car scanner-or-collector)
,@(cdr scanner-or-collector)))))
`(cl:let ((data ,(cl:funcall (eval encapsulating-fn) body)))
(values-lists (length (car data)) (scan data)))))
((eq-car scanner-or-collector 'collect-fn)
(cl:funcall (eval encapsulating-fn) scanner-or-collector))
(t (ers 69 "~%Malformed second arg to ENCAPSULATING arg "
scanner-or-collector "."))))
;; API
(defS encapsulated (encapsulating-fn scanner-or-collector)
"Specifies an encapsulating form to be used with a scanner or collector."
encapsulated-macro
:optimizer
(progn
(unless (or (eq-car encapsulating-fn 'function)
(eq-car encapsulating-fn 'lambda))
(ers 68 "~%First ENCAPSULATING arg " encapsulating-fn
" is not quoted function."))
(cond ((and (or (eq-car scanner-or-collector 'scan-fn)
(eq-car scanner-or-collector 'scan-fn-inclusive))
(= (length scanner-or-collector) 5))
(apply #'scan-fn-opt encapsulating-fn
(eq-car scanner-or-collector 'scan-fn-inclusive)
(cdr scanner-or-collector)))
((eq-car scanner-or-collector 'collect-fn)
(apply #'collect-fn-opt encapsulating-fn (cdr scanner-or-collector)))
(t (ers 69 "~%Malformed second arg to ENCAPSULATING arg "
scanner-or-collector "."))))
:trigger t
:discriminator (or (eq-car (caddr call) 'scan-fn)
(eq-car (caddr call) 'scan-fn-inclusive)))
;;needed because collect-fn is macro
(cl:defun basic-collect-fn (inits function &rest args)
(declare (dynamic-extent args))
(declare (type list args))
(cl:flet ((gen-unopt ()
(compiler-let ((*optimize-series-expressions* nil))
(fragl ((inits) (function) (args))
((result))
((result t (cl:funcall inits))
(list-of-generators list (mapcar #'generator args)))
()
()
((setq result (cl:multiple-value-call function
result
(values-of-next #'(lambda () (go end))
list-of-generators))))
()
()
:fun ; assumes function is impure for now
))))
(eoptif-q
(funcase (fun inits)
((name anonymous)
(efragl ((function) (args))
`(((result))
((result t (,(if (symbolp fun) fun (process-fn fun))))
(list-of-generators list (mapcar #'generator args)))
()
()
((setq result (cl:multiple-value-call function
result
(values-of-next #'(lambda () (go end))
list-of-generators))))
()
()
:fun ; assumes function is impure for now
)))
(t
(funcase (f function)
((name anonymous)
(efragl ((inits) (args))
`(((result))
((result t (cl:funcall inits))
(list-of-generators list (mapcar #'generator args)))
()
()
((setq result (cl:multiple-value-call (function ,f)
result
(values-of-next #'(lambda () (go end))
list-of-generators))))
()
()
:fun ; assumes function is impure for now
)))
(t
(gen-unopt)))))
(gen-unopt))))
;; API
(defS collect-fn (type inits function &rest args)
"(collect-fn type init-function function &rest args)
Computes a cumulative value by applying FUNCTION to the elements of ITEMS.
INIT-FUNCTION specifies the initial value(s). Like COLLECTING-FN, but
only the last element of each series is returned."
(cl:let ((n (length (decode-type-arg type))))
(setq args (copy-list args))
(cond ((= n 1) (apply #'basic-collect-fn inits function args))
(t (values-list
(apply #'basic-collect-fn
#'(lambda ()
(forceL n (multiple-value-list (cl:funcall inits))))
#'(lambda (state &rest args)
(declare (dynamic-extent args))
(forceL n (multiple-value-list
(apply function (nconc state args)))))
args)))))
:optimizer
(apply #'collect-fn-opt nil type inits function args)
:trigger t)
;;; Hint to users: to avoid inits, add an extra init that acts like a flag.
;; API
(defS collecting-fn (type inits function &rest args)
"(collecting-fn type init function &rest series-inputs)
Computes cumulative values by applying FUNCTION to the elements of
ITEMS. TYPE specifies the type of values returned by FUNCTION. INIT
is a function that returns the initial values for the series. The
output, t1,..., tm, are computed as follows:
(values t1[0] ... tm[0] =
(multiple-value-call function (funcall init) s1[0] ... sn[0])
(values t1[j] ... tm[j] =
(funcall function t1[j-1] ... tm[j-1] s1[j] ... sn[j])
where s1[j],...,sn[j] are the j'th elements of the n input series.
"
(cl:let ((n (length (decode-type-arg type))))
(setq args (copy-list args))
(cond ((= n 1)
(fragl ((inits) (function) (args)) ((result t))
((result t (cl:funcall inits))
(list-of-generators list (mapcar #'generator args)))
()
()
((setq result (cl:multiple-value-call function
result
(values-of-next #'(lambda () (go end))
list-of-generators))))
()
()
:fun ; assumes function is impure for now
))
(t (values-lists n
(apply #'collecting-fn t
#'(lambda ()
(forceL n (multiple-value-list (cl:funcall inits))))
#'(lambda (state &rest args)
(declare (dynamic-extent args))
(forceL n (multiple-value-list
(apply function (append state args)))))
args)))))
:optimizer
(cl:let* ((types (decode-type-arg (must-be-quoted type)))
(params nil)
(frag (make-frag :impure :fun))
(in-vars (n-gensyms (length args) (symbol-name '#:items-)))
(out-vars (n-gensyms (length types) (symbol-name '#:c-)))
(*state* nil))
(dolist (var out-vars)
(+ret (make-sym :var var :series-var-p t) frag))
(setf (aux frag)
(makeaux (mapcar #'list out-vars types)))
(multiple-value-setq (inits params) (handle-fn-arg frag inits params))
(multiple-value-setq (function params) (handle-fn-arg frag function params))
(setq params (mapcar #'retify (nconc params args)))
(dolist (var in-vars)
(+arg (make-sym :var var :series-var-p t) frag))
(setf (prolog frag) (makeprolog (handle-fn-call frag out-vars inits nil)))
(setf (body frag)
(handle-fn-call frag out-vars function (append out-vars in-vars) t))
(apply-frag frag params)))
;; API
(defS scan-fn (type init step &optional (test nil test-p))
"(scan-fn type init step &optional test)
Enumerates a series. TYPE specifies the type of the value(s) returned
by INIT and STEP. The elements are computed as follows:
(values t1[0] ... tm[0]) = (funcall init)
(values t1[j] ... tm[j]) = (funcall step t1[j-1] ... tm[j-1])
where t1, ..., tm are the output series.
If TEST is not specified, the output is unbounded. If TEST is
specified, the output is terminated when (funcall tests t1[j]
... tm[j]) is non-NIL. The elements that cause termination are
not part of the output."
(cl:let ((n (length (decode-type-arg type))))
(when (not test-p)
(setq test #'never))
(cond ((= n 1)
(fragl ((init) (step) (test)) ((prior-state t))
((state t (cl:funcall init))
(prior-state t))
()
()
((if (cl:funcall test state) (go end))
(prog1 (setq prior-state state)
(setq state (cl:funcall step state))))
()
()
:fun ; assumes init step and test are impure for now
))
(t (cl:let ((data (scan-multi-out->scan-list-out
#'scan-fn type init step test)))
(values-lists n data)))))
:optimizer
(if test-p
(scan-fn-opt nil nil type init step test)
(scan-fn-opt nil nil type init step)))
;; API
(defS scan-fn-inclusive (type init step test)
"(scan-fn-inclusive type init step &optional test)
Enumerates a series. TYPE specifies the type of the value(s) returned
by INIT and STEP. The elements are computed as follows:
(values t1[0] ... tm[0]) = (funcall init)
(values t1[j] ... tm[j]) = (funcall step t1[j-1] ... tm[j-1])
where t1, ..., tm are the output series.
If TEST is not specified, the output is unbounded. If TEST is
specified, the output is terminated when (funcall tests t1[j]
... tm[j]) is non-NIL. The elements that cause termination are
part of the output."
(cl:let ((n (length (decode-type-arg type))))
(cond ((= n 1)
(fragl ((init) (step) (test)) ((prior-state t))
((state t (cl:funcall init))
(prior-state t) (done t nil))
()
()
((if done (go end))
(setq done (cl:funcall test state))
(prog1 (setq prior-state state)
(if (not done) (setq state (cl:funcall step state)))))
()
()
:fun ; assumes init step and test are impure for now
))
(t (cl:let ((data (scan-multi-out->scan-list-out
#'scan-fn-inclusive type init step test)))
(values-lists n data)))))
:optimizer
(scan-fn-opt nil t type init step test))
;;; various easy ways of doing mapping
;; CODEGEN
(cl:defun mapit (type fn args)
(if (not (symbolp fn))
`(map-fn ',type (function ,fn) ,@ args)
(cl:let ((vars (do ((a args (cdr a))
(l nil (cons (gensym "V-") l)))
((null a) (return l)))))
`(map-fn ',type (function (lambda ,vars (,fn ,@ vars))) ,@ args))))
;; put on #M
(cl:defun abbreviated-map-fn-reader (stream subchar arg)
(declare (ignore stream subchar))
(case arg
((nil) '\#M) ;the macros actually do the work.
(1 '\#1M)
(2 '\#2M)
(3 '\#3M)
(4 '\#4M)
(5 '\#5M)
(otherwise
(error "The numeric argument to #M must be between 1 and 5 inclusive"))))
; (set-dispatch-macro-character #\# #\M (cl:function abbreviated-map-fn-reader))
(defmacro \#M (fn &rest args) (mapit t fn args))
(defmacro \#1M (fn &rest args) (mapit t fn args))
(defmacro \#2M (fn &rest args) (mapit '(values t t) fn args))
(defmacro \#3M (fn &rest args) (mapit '(values t t t) fn args))
(defmacro \#4M (fn &rest args) (mapit '(values t t t t) fn args))
(defmacro \#5M (fn &rest args) (mapit '(values t t t t t) fn args))
;; API
(defS collect-ignore (items)
"(collect-ignore series)
Like COLLECT, but any output that would have been returned is
discarded. In particular, no results are consed at all."
(fragl ((items t)) (nil) () () () () () () nil)
:trigger t)
(defmacro iterate-mac (var-value-list &rest body)
"Applies BODY to each element of the series"
`(collect-ignore (mapping ,var-value-list ,@ body)))
;; API
(defS iterate (var-value-list &rest body)
"(iterate ({({var | ({var}*)} value)}*) {declaration}* {form}*)
Applies BODY to each element of the series, like MAPPING, but results
are discarded."
iterate-mac
:optimizer
`(iterate-mac ,var-value-list ,@ body)
:trigger t)
#+symbolics(setf (gethash 'iterate zwei:*lisp-indentation-offset-hash-table*)
'(1 1))
;; API
(defS mapping (var-value-list &rest body)
"(mapping ({({var | ({var}*)} value)}*) {declaration}* {form}*)
The macro MAPPING makes it easy to specify uses of MAP-FN where TYPE
is t and the FUNCTION is a literal lambda. The syntax of mapping is
analogous to that of let. The binding list specifies zero or more
variables that are bound in parallel to successive values of
series. The value part of each pair is an expression that must produce
a series. The declarations and forms are treated as the body of a
lambda expression that is mapped over the series values. A series of
the first values returned by this lambda expression is returned as the
result of mapping."
mapping-mac
:optimizer
(cl:let* ((bindings (mapcan #'(lambda (p) (process-let-series-pair p nil t))
var-value-list))
(*renames* (revappend bindings *renames*)))
(process-let-series-body nil
`((map-fn t #'(lambda ,(mapcar #'car bindings) ,@ body)
,@(mapcar #'car bindings)))
bindings)))
#+symbolics
(setf (gethash 'mapping zwei:*lisp-indentation-offset-hash-table*)
'(1 1))
;; only used when optimization not possible.
(defmacro mapping-mac (var-value-list &body body)
(setq var-value-list (mapcar #'(lambda (p) (normalize-pair p t)) var-value-list))
(cond ((every #'(lambda (p) (null (cdar p))) var-value-list)
`(map-fn t
#'(lambda ,(mapcar #'caar var-value-list) ,@ body)
,@(mapcar #'cadr var-value-list)))
((null (cdr var-value-list))
`(multiple-value-bind ,@(car var-value-list)
(map-fn t #'(lambda ,(copy-list (caar var-value-list)) ,@ body)
,@(copy-list (caar var-value-list)))))
(t `(apply #'map-fn t
#'(lambda ,(apply #'append (mapcar #'car var-value-list))
,@ body)
(nconc ,@(mapcar #'(lambda (p)
(if (null (cdar p))
`(list ,(cadr p))
`(forceL ,(length (car p))
(multiple-value-list
,(cadr p)))))
var-value-list))))))
;This allows you to specify more or less arbitrary transducers.
;; HELPER
;; This is only called from optimize-producing
(cl:defun protect-from-setq (in type)
(cl:let ((frag (fr in))
(var (var in))
(new (new-var 'in)))
(coerce-to-type type in) ;why am I doing this?
(if (not (series-var-p in))
(add-nonliteral-aux (fr in) var type new)
(progn
(add-aux (fr in) var type)
(if (not (off-line-spot in))
(push `(setq ,var ,new) (body frag))
(nsubst-inline `((setq ,var ,new)) (off-line-spot in) (body frag) t))))
(setf (var in) new)))
;; CHECKER
(cl:defun validate-producing (output-list input-list body)
(when (not (and (every #'(lambda (f) (eq-car f 'declare)) (butlast body))
(eq-car (car (last body)) 'loop)
(eq-car (cadr (car (last body))) 'tagbody)))
(ers 73 "~%PRODUCING body not of the form ({DECL}* (LOOP (TAGBODY ...)))~%"
(list* 'producing output-list input-list body)))
(when (null output-list)
(ers 74 "~%PRODUCING fails to have any outputs~%"
(list* 'producing output-list input-list body)))
(mapc #'(lambda (p) (normalize-pair p nil)) output-list)
(mapc #'(lambda (p) (normalize-pair p nil)) input-list)
(cl:let ((visited-inputs nil) (visited-outputs nil))
(dolist (f (cdadar (last body)))
(cond ((and (eq-car f 'setq)
(eq-car (caddr f) 'next-in))
(when (not (and (null (cdddr f))
(cadr (caddr f)) (symbolp (cadr (caddr f)))
(find (cadr (caddr f)) input-list
:key #'(lambda (e) (when (consp e) (car e))))
(not (member (cadr (caddr f)) visited-inputs))
(cddr (caddr f))))
(ers 75 "~%Malformed NEXT-IN call: " (caddr f)))
(push (cadr (caddr f)) visited-inputs))
((eq-car f 'next-out)
(when (not (and (null (cdddr f))
(member (cadr f) output-list)
(not (member (cadr f) visited-outputs))))
(ers 76 "~%Malformed NEXT-OUT call: " f))
(push (cadr f) visited-outputs))))
(values visited-inputs visited-outputs)))
;; TRANSLATOR
(cl:defun basic-prod-form->frag-body (forms input-alist series-output-alist)
(setq forms ;this is dangerous, should be done more safely.
(subst `(go ,end) `(terminate-producing) forms :test #'equal))
(cl:let ((revbody nil)
(state :prolog)
(epilog-start
(do ((l (cons nil (reverse forms)) (cdr l)))
((or (null (cdr l)) (not (eq-car (cadr l) 'next-out)))
(car l)))))
(dolist (f forms)
(cl:flet ((xform-assignment (destination from)
(list destination
(if (eq-car from 'next-in)
(cl:let* ((source (cadr from))
(arg (cdr (assoc source input-alist)))
(actions (cddr from))
(e (new-var 'ee))
(d (new-var 'dd))
(-x- (new-var '-xxx-)))
(setf (series-var-p arg) t)
(cond ((and (eq state :prolog)
(equal actions '((terminate-producing)))))
((equal actions '((terminate-producing)))
(setf (off-line-spot arg) -x-) (push -x- revbody))
(t (setq state :middle)
(setf (off-line-spot arg) -x-)
(setf (off-line-exit arg) e)
(setq revbody
(append (reverse `(,-x- (go ,d) ,e ,@ actions ,d))
revbody))))
(var arg))
(progn
(setq state :middle)
from)))))
(declare (dynamic-extent #'xform-assignment))
(cond ((and (consp f) (case (car f) ((setq) t))) ; setf removed for now
(cl:multiple-value-bind (vars lastbind binds) (detangle2 (cdr f))
(unless (cdr lastbind)
(ers 50 "~%missing value in assignment: " f))
;; setf still not supported - need to make caller setf-aware
(cl:let ((expr (cons 'setq ; should be setf
(mapcan #'xform-assignment vars binds))))
;;(format t "~s" expr)
(push expr revbody))))
;; need to first make caller psetf-aware probably
#+:ignore
((and (consp f) (case (car f) ((psetq psetf) t)))
(cl:multiple-value-bind (vars lastbind binds) (detangle2 (cdr f))
(unless (cdr lastbind)
(ers 50 "~%missing value in assignment: " f))
(push (cons 'psetf (mapcan #'xform-assignment vars binds))
revbody)))
((eq-car f 'next-out)
(setq state (if (or (eq state :epilog) (eq f epilog-start))
:epilog
:middle))
(cl:let* ((ret (cdr (assoc (cadr f) series-output-alist)))
(-x- (new-var '-xxxx-)))
(setf (series-var-p ret) t)
(push `(setq ,(var ret) ,(caddr f)) revbody)
(when (not (eq state :epilog))
(setf (off-line-spot ret) -x-)
(push -x- revbody))))
(t (setq state :middle)
(push f revbody)))))
(nreverse revbody)))
;; OPTIMIZER
(cl:defun optimize-producing (output-list input-list body)
(cl:let ((series-ins (validate-producing output-list input-list body)))
(cl:multiple-value-bind (bod type-alist propagations)
(decode-dcls body '(types props))
;;#+:cmu
#+nil
(cl:flet ((fix-types (var)
(cons (car var) (make-nullable (cdr var)))))
(declare (dynamic-extent #'fix-types))
(setq type-alist (mapcar #'fix-types type-alist)))
(cl:let* ((forms (cdadar bod))
(frag (make-frag :impure t))
(input-alist nil)
(series-output-alist nil)
(*renames* *renames*)
(new-renames *renames*))
(dolist (p (append (remove-if-not #'consp output-list) input-list))
(setq p (normalize-pair p nil))
(cl:let* ((value (retify (cadr p)
(or (cdr (assoc (caar p) type-alist)) t)))
(arg (make-sym :var (gensym (root (caar p)))
:series-var-p
(not (null (member (caar p) series-ins))))))
(+arg arg frag)
(+dflow value arg)
(setf (free-out value) (caar p))
(push (cons (caar p) (var arg)) new-renames)
(push (cons (caar p) arg) input-alist)))
(setq *renames* new-renames) ;note let-like binding semantics
(dolist (p output-list)
(if (consp p)
(+ret (make-sym :var (var (cdr (assoc (car p) input-alist)))) frag)
(cl:let ((ret (make-sym :var (gensym (root p)) :series-var-p t))
(type (cdr (assoc p type-alist))))
(cl:flet ((upgrade-type (typ)
(if (eq-car typ 'series)
(cadr typ)
typ)))
(declare (dynamic-extent #'upgrade-type))
(if (eq-car type 'series)
(setq type (cadr type))
(if (eq-car type 'or)
(setq type (cons 'or (mapcar #'upgrade-type (cdr type))))
(setq type t))))
(+ret ret frag)
(add-aux frag (var ret) type)
(push (cons p (var ret)) *renames*)
(push (cons p ret) series-output-alist))))
(cl:let* ((label-alist nil) (new-forms nil))
(dolist (f forms)
(cond ((not (symbolp f)) (push f new-forms))
(t (cl:let ((new (gensym (root f))))
(push (cons `(go ,f) `(go ,new)) label-alist)
(push new new-forms)))))
(when label-alist
(setq forms (sublis label-alist (nreverse new-forms) :test #'equal))))
(cl:let ((*in-series-expr* nil)
(*not-straight-line-code* nil)
(body (basic-prod-form->frag-body
forms input-alist series-output-alist)))
;;(format t "~S" body)
(cl:multiple-value-bind (bod free-ins free-outs setqed)
(handle-non-series-stuff `(progn ,@ body) nil
(mapcar #'(lambda (s) (var (cdr s)))
input-alist))
(setf (body frag) (cdr bod))
(dolist (entry free-ins)
(cl:let ((arg (make-sym :var (car entry))))
(+arg arg frag)
(+dflow (cdr entry) arg)))
(dolist (entry free-outs)
(cl:let ((new (make-sym :var (car entry)))
(v (cdr entry)))
(when (not (find (car entry) (args frag) :key #'var))
(add-aux frag (car entry) t))
(setf (free-out new) v)
(+ret new frag)
(rplacd (assoc v *renames*) new)))
(dolist (v setqed)
(protect-from-setq
(cdr (find-if #'(lambda (s)
(eq v (var (cdr s))))
input-alist))
(or (cdr (assoc (car (rassoc v *renames*))
type-alist))
t))))
;bit of a cludge the way the following bashes things into the old style of stuff.
(dolist (pair propagations)
(cl:let ((input (cdr (assoc (car pair) input-alist)))
(output (cdr (assoc (cadr pair) series-output-alist))))
(when (and input output)
(setf (var output) (var input)))))
(+frag frag))))))
;; API
(defS producing (output-list input-list &rest body)
"(producing output-list input-list {declaration}* {form}*
PRODUCING computes and returns a group of series and non-series outputs
given a group of series and non-series inputs.
The OUTPUT-LIST has the same syntax as the binding list of a LET. The
names of the variables must be distinct from each other and from the names
of the variables in the INPUT-LIST. If there are N variables in the
OUTPUT-LIST, PRODUCING computes N outputs. There must be at least one
output variable. The variables act as the names for the outputs and can be
used in either of two ways. First, if an output variable has a value
associated with it in the OUTPUT-LIST, then the variable is treated as
holding a non-series value. The variable is initialized to the indicated
value and can be used in any way desired in the body. The eventual output
value is whatever value is in the variable when the execution of the body
terminates. Second, if an output variable does not have a value associated
with it in the OUTPUT-LIST, the variable is given as its value a gatherer
that collects elements. The only valid way to use the variable in the body
is in a call on NEXT-OUT. The output returned is a series containing these
elements. If the body never terminates, this series is unbounded.
The INPUT-LIST also has the same syntax as the binding list of a LET.
The names of the variables must be distinct from each other and the names
of the variables in the OUTPUT-LIST. The values can be series or
non-series. If the value is not explicitly specified, it defaults to NIL.
The variables act logically both as inputs and state variables and can be
used in one of two ways. First, if an input variable is associated with a
non-series value, then it is given this value before the evaluation of the
body begins and can be used in any way desired in the body. Second, if an
input variable is associated with a series, then the variable is given a
generator corresponding to this series as its initial value. The only
valid way to use the variable in the body is in a call on NEXT-IN.
"
non-opt-producing
:optimizer
(optimize-producing output-list input-list body)
:trigger
(dolist (pair (caddr call) nil)
(when (and (consp pair) (cdr pair) (produces-optimizable-series (cadr pair)))
(return t)))
:discriminator
(dolist (pair (cadr call) nil)
(when (not (consp pair))
(return t))))
#+symbolics
(setf (gethash 'producing zwei:*lisp-indentation-offset-hash-table*)
'(2 1))
(defmacro terminate-producing ()
"Causes the containing call on producing to terminate."
`(go ,end))
;; This turns a producing form into a frag that fits the requirements
;; of a frag well enough that we can call FRAG->PHYSICAL on it. The
;; key to this is that we only keep the series inputs and outputs, and
;; we know exactly where they can be used.
(defmacro non-opt-producing (output-list input-list &body body)
(cl:let ((series-inputs (validate-producing output-list input-list body)))
(cl:multiple-value-bind (bod props) (decode-dcls body '(props no-complaints))
(setq input-list
(mapcar #'(lambda (p)
(if (consp p)
p
(list p nil)))
input-list))
(cl:let* ((forms (cdadar bod))
(frag (make-frag :code `(producing ,output-list ,input-list
,@ body)
:impure t))
(input-alist nil)
(series-output-alist nil))
(dolist (in series-inputs)
(cl:let* ((v (new-var 'inpt))
(arg (make-sym :var v :series-var-p t)))
(+arg arg frag)
(push (cons in arg) input-alist)))
(dolist (out output-list)
(cl:let* ((prop-input (dolist (p props nil)
(when (eq (cadr p) out)
(return (car p)))))
(v (cond (prop-input
(var (cdr (assoc prop-input input-alist))))
((consp out) (car out))
(t (new-var 'out))))
(ret (make-sym :var v :series-var-p (not (consp out)))))
(+ret ret frag)
(unless prop-input
(add-aux frag v t))
(if (not (consp out))
(push (cons out ret) series-output-alist)
(add-prolog frag `(setq ,(car out) ,(cadr out))))))
(setf (body frag)
(basic-prod-form->frag-body forms input-alist series-output-alist))
`(cl:let ,input-list
,(frag->physical frag series-inputs (some #'consp output-list)))))))
;; The alter form found probably refers to vars which are not OLD
;; itself. For this to be OK, we must be sure that these variables
;; must never be renamed. To ensure that, we must ensure that none of
;; these variables are ever inputs. (Aux variables are not renamed
;; and return variables are not renamed as long as they are not also
;; inputs.) This requires care on the part of all standard functions
;; that are alterable (i.e. scan) and particularly in to-alter which
;; would be much easier to write if it just passed the inputs through.
;;
;; This is ok because outputs never get renamed. Also the input old
;; to the frag most likely never gets used, but this makes sure that
;; the dflow is logically correct.
(cl:defun find-alter-form (ret)
(cl:let* ((v (var ret))
(form (cadr (assoc v (alterable (fr ret))))))
(if form
form
(dolist (a (args (fr ret)))
(when (or (eq v (var a))
(equal (prolog (fr ret)) (makeprolog `((setq ,v ,(var a))))))
(return (find-alter-form (prv a))))))))
;; I'm leaving the above as a reference. It turns out that in some
;; cases such as the following:
;; (defstruct vec x y z)
;; (defun scan-vec (vec)
;; (declare (optimizable-series-function))
;; (to-alter (make-series (vec-x vec) (vec-y vec) (vec-z vec))
;; #'(lambda (new-value index v)
;; (ecase index
;; (0 (setf (vec-x v) new-value))
;; (1 (setf (vec-y v) new-value))
;; (2 (setf (vec-z v) new-value))))
;; (scan-range :from 0)
;; (make-series vec vec vec)))
;; (let ((vec (make-vec :x 1 :y 2 :z 3)))
;; (alter (scan-vec vec) (series 0))
;; vec)
;;
;; that there are several forms in the alterable slot of the frag. So
;; we remove all forms that aren't for the current var and return all
;; forms so ALTER can drop them into the code.
;;
;; I'm not really sure this is all right, but we definitely need the
;; more than just the first match, as FIND-ALTER-FORM does.
(cl:defun find-alter-forms (ret)
(cl:let* ((v (var ret))
(forms (remove-if-not #'(lambda (item)
(eql v (car item)))
(alterable (fr ret)))))
(if forms
forms
(dolist (a (args (fr ret)))
(when (or (eq v (var a))
(equal (prolog (fr ret)) (makeprolog `((setq ,v ,(var a))))))
(return (find-alter-forms (prv a))))))))
;; API
#+nil
(defS alter (destinations items)
"Alters the values in DESTINATIONS to be ITEMS."
(fragl ((destinations) (items t)) ((result))
((gen generator (generator destinations))
(result null nil))
()
()
((do-next-in gen #'(lambda () (go end)) items))
()
()
nil ; series dataflow constraint takes care
)
:optimizer
(cl:let ((ret (retify destinations)))
(when (not (series-var-p ret))
(rrs 5 "~%Alter applied to a series that is not known at compile time:~%"
*call*))
(format t "All alter forms:~%")
(write (find-alter-forms ret) :circle t)
(cl:let ((form (find-alter-form ret))
(frag (literal-frag '(((old t) (items t)) ((result)) ((result null))
()
((setq result nil))
()
()
()
nil ; series dataflow constraint takes care
))))
(unless form
(ers 65 "~%Alter applied to an unalterable series:~%" *call*))
(setf (body frag) (list (subst (var (cadr (args frag))) '*alt* form)))
(apply-frag frag (list ret items))))
:trigger t)
;; The old version above is left for a reference.
(defS alter (destinations items)
"Alters the values in DESTINATIONS to be ITEMS."
(fragl ((destinations) (items t)) ((result))
((gen generator (generator destinations))
(result null nil))
()
()
((do-next-in gen #'(lambda () (go end)) items))
()
()
nil ; series dataflow constraint takes care
)
:optimizer
(cl:let ((ret (retify destinations)))
(when (not (series-var-p ret))
(rrs 5 "~%Alter applied to a series that is not known at compile time:~%"
*call*))
(cl:let ((all-forms (find-alter-forms ret))
(frag (literal-frag '(((old t) (items t)) ((result)) ((result null))
()
((setq result nil))
()
()
()
nil ; series dataflow constraint takes care
))))
(unless all-forms
(ers 65 "~%Alter applied to an unalterable series:~%" *call*))
;; Look through all forms that match and do the appropriate
;; thing so that the body has all alterable forms we need. See
;; comments for FIND-ALTER-FORMS.
(setf (body frag) (mapcar #'(lambda (f)
(subst (var (cadr (args frag))) '*alt* (cadr f)))
all-forms))
(apply-frag frag (list ret items))))
:trigger t)
;; API
(defS to-alter (series alter-function &rest other-inputs)
"Specifies how to alter SERIES."
(progn (setq other-inputs (copy-list other-inputs))
(cl:let ((series (generator series))
(others (mapcar #'generator other-inputs)))
(make-phys
:gen-fn
#'(lambda ()
(block nil
(cons (cons (next-in series (return nil))
(mapcar #'(lambda (x) (next-in x (return nil)))
others))
t)))
:alter-fn
#'(lambda (alter &rest other-info)
(apply alter-function alter other-info)))))
:optimizer
(cl:let* ((params (list series))
(frag (make-frag))
(input-vars (n-gensyms (length other-inputs) (symbol-name '#:state-in-)))
(state-vars (n-gensyms (length other-inputs) (symbol-name '#:state-)))
(var (new-var 'items)))
(+ret (make-sym :var var :series-var-p t) frag)
(+arg (make-sym :var var :series-var-p t) frag)
(multiple-value-setq (alter-function params)
(handle-fn-arg frag alter-function params))
(mapc #'(lambda (in-var state-var)
(+arg (make-sym :var in-var :series-var-p t) frag)
(add-aux frag state-var t)
(push `(setq ,state-var ,in-var) (body frag)))
input-vars state-vars)
(setq params (append params other-inputs))
(setf (alterable frag)
`((,var (cl:funcall ,alter-function *alt* ,@ state-vars) ,@ state-vars)))
(apply-frag frag params)))
;; API
(defS series (expr &rest expr-list)
"(series arg &rest args)
Creates an infinite series that endlessly repeats the given items in
the order given."
(cond ((null expr-list)
(fragl ((expr)) ((expr t)) () () () () () () :args))
(t (cl:let ((full-expr-list
(optif `(,expr ,@ expr-list)
(cons expr (copy-list expr-list)))))
(fragl ((full-expr-list)) ((items t))
((items t)
(lst list (copy-list full-expr-list)))
()
((setq lst (nconc lst lst)))
((setq items (car lst)) (setq lst (cdr lst)))
()
()
:args
))))
:optimizer
;; This is essentially identical to the above code except that
;; FULL-EXPR-LIST is (LIST <items>). Not 100% sure about this, but
;; unexpected things happen if we don't.
;;
;; Some examples (noted on comp.lang.lisp by Szymon 'tichy' on Sat,
;; Jul 7, 2007):
;; (positions (series t nil)) -> #z(0 1 2 3 4 6 7 10 12 13 ...)
;; (series t nil) -> #z(list t nil list t nil ...)
;;
;; I believe these are wrong. (How can I add such tests to the test
;; scripts?) The first test should return #z(0 2 4 6 8 10 ...) and
;; the second should return #z(t nil t nil ...)
;;
(cond ((null expr-list)
(fragl ((expr)) ((expr t)) () () () () () () :args))
(t (cl:let ((full-expr-list
(optif `(list ,expr ,@ expr-list)
(cons expr (copy-list expr-list)))))
(fragl ((full-expr-list)) ((items t))
((items t)
(lst list (copy-list full-expr-list)))
()
((setq lst (nconc lst lst)))
((setq items (car lst)) (setq lst (cdr lst)))
()
()
:args
)))))
;; API
(defS literal-series (seq) ""
(make-phys :data-list seq)
:optimizer
(+frag
(cl:let ((frag (literal-frag
'(() ((elements t)) ((listptr list) (elements t)) ()
() ((if (endp listptr) (go end))
(setq elements (car listptr))
(setq listptr (cdr listptr)))
()
()
nil)))) ; pure because seq is literal
(add-prolog frag `(setq ,(car (first-aux (aux frag))) ,seq))
frag)))
;; put on #Z
#+nil
(cl:defun series-reader (stream subchar arg)
(declare (ignore subchar arg))
`(literal-series ',(read stream t nil t)))
(cl:defun series-reader (stream subchar arg)
(declare (ignore subchar arg))
(cl:let ((items (read stream t nil t)))
(cl:unless (list-length items)
;; We have some kind of infinite list.
(ers 100 "~&Infinite literal series not supported"))
`(literal-series ',items)))
;; API
(defS make-series (item &rest item-list)
"Creates a series of the items."
(make-phys :data-list (cons item (copy-list item-list)))
:optimizer
(macroexpand `(scan (list ,item ,@ (copy-list item-list)))))
#-:old-scan-range
(progn
;; This deftype is used to appease the compiler (CMUCL) about an
;; unknown type when compiling scan-range. If someone has a better
;; way of getting scan-range to generate the correct initial values
;; without this hack, I'd love to have it.
(deftype *type* () t)
;; API
;; This version of scan-range fixes a long-standing bug that occurs
;; when :type is not 'number. Say :type is 'single-float. Then the
;; looping variables are declared to be single-float's, but the
;; variables end up being initialized with fixnums. This loses. To
;; fix this, the initializers are coerced to the correct type.
;; However, you need a reasonably smart compiler to do constant
;; folding so that you don't do the coercion every time through the
;; loop.
(defS scan-range (&key (from 0) (by 1)
(upto nil) (below nil)
(downto nil) (above nil)
(length nil) (type 'number))
"(scan-range &key (:start 0) (:by 1) (:type 'number) :upto :below
:downto :above :length)
The function SCAN-RANGE returns a series of numbers starting with the
:start argument (default integer 0) and counting up by the :by
argument (default integer 1). The :type argument (default number) is a
type specifier indicating the type of numbers in the series
produced. The :type argument must be a (not necessarily proper)
subtype of number. The :start and :by arguments must be of that
type.
One of the last five arguments may be used to specify the kind of end
test to be used; these are called termination arguments. If :upto is
specified, counting continues only so long as the numbers generated
are less than or equal to :upto. If :below is specified, counting
continues only so long as the numbers generated are less than
:below. If :downto is specified, counting continues only so long as
the numbers generated are greater than or equal to :downto. If :above
is specified, counting continues only so long as the numbers generated
are greater than :above. If :length is specified, it must be a
non-negative integer and the output series has this length.
If none of the termination arguments are specified, the output has
unbounded length. If more than one termination argument is specified,
it is an error. "
(cl:let ((*type* (optif (if (eq-car type 'quote)
(cadr type)
'number)
type)))
(when (> (length (delete nil (list upto below downto above length))) 1)
(ers 77 "~%Too many keywords specified in a call on SCAN-RANGE."))
(cond (upto
(*fragl ((from) (upto) (by)) ((numbers t))
((numbers *type* (coerce-maybe-fold (- from by) '*type*)))
()
()
((setq numbers (+ numbers (coerce-maybe-fold by '*type*)))
(if (> numbers upto) (go end)))
()
()
:args))
(below
(*fragl ((from) (below) (by)) ((numbers t))
((numbers *type* (coerce-maybe-fold (- from by) '*type*)))
()
()
((setq numbers (+ numbers (coerce-maybe-fold by '*type*)))
(if (not (< numbers below)) (go end)))
()
()
:args))
(downto
(*fragl ((from) (downto) (by)) ((numbers t))
((numbers *type* (coerce-maybe-fold (- from by) '*type*)))
()
()
((setq numbers (+ numbers (coerce-maybe-fold by '*type*)))
(if (< numbers downto) (go end)))
()
()
:args))
(above
(*fragl ((from) (above) (by)) ((numbers t))
((numbers *type* (coerce-maybe-fold (- from by) '*type*)))
()
()
((setq numbers (+ numbers (coerce-maybe-fold by '*type*)))
(if (not (> numbers above)) (go end)))
()
()
:args))
(length
(*fragl ((from) (length) (by)) ((numbers t))
((numbers *type* (coerce-maybe-fold (- from by) '*type*))
(counter fixnum length))
()
()
((setq numbers (+ numbers (coerce-maybe-fold by '*type*)))
(if (not (plusp counter)) (go end))
(decf counter))
()
()
:args))
(t (*fragl ((from) (by)) ((numbers t))
((numbers *type* (coerce-maybe-fold (- from by) '*type*)))
()
()
((setq numbers (+ numbers (coerce-maybe-fold by '*type*))))
()
()
:args)))))
)
;; API
#+:old-scan-range
(defS scan-range (&key (from 0) (by 1)
(upto nil) (below nil)
(downto nil) (above nil)
(length nil) (type 'number))
"Creates a series of numbers by counting from :FROM by :BY."
(cl:let ((*type* (optif (if (eq-car type 'quote)
(cadr type)
'number)
type)))
(when (> (length (delete nil (list upto below downto above length))) 1)
(ers 77 "~%Too many keywords specified in a call on SCAN-RANGE."))
(cond (upto
(*fragl ((from) (upto) (by)) ((numbers t))
((numbers *type* (- from by)))
()
()
((setq numbers (+ numbers by))
(if (> numbers upto) (go end)))
()
()
:args))
(below
(*fragl ((from) (below) (by)) ((numbers t))
((numbers *type* (- from by)))
()
()
((setq numbers (+ numbers by))
(if (not (< numbers below)) (go end)))
()
()
:args))
(downto
(*fragl ((from) (downto) (by)) ((numbers t))
((numbers *type* (- from by)))
()
()
((setq numbers (+ numbers by))
(if (< numbers downto) (go end)))
()
()
:args))
(above
(*fragl ((from) (above) (by)) ((numbers t))
((numbers *type* (- from by)))
()
()
((setq numbers (+ numbers by))
(if (not (> numbers above)) (go end)))
()
()
:args))
(length
(*fragl ((from) (length) (by)) ((numbers t))
((numbers *type* (- from by))
(counter fixnum length))
()
()
((setq numbers (+ numbers by))
(if (not (plusp counter)) (go end))
(decf counter))
()
()
:args))
(t (*fragl ((from) (by)) ((numbers t))
((numbers *type* (- from by)))
()
()
((setq numbers (+ numbers by)))
()
()
:args)))))
(defmacro null-scan (type)
`(efragl ()
`(((elements t))
((elements ,,type))
()
()
((go end))
()
()
nil)))
(defmacro limited-scan (type unopt-type-limit opt-type-limit unopt-limit &optional opt-limit)
`(eoptif-q
(*fragl ((seq) ,@(when opt-limit `((,opt-limit))))
((elements t))
((elements ,type)
(temp t seq)
(index (integer -1 ,@(when opt-type-limit `(,opt-type-limit))) -1))
((elements (setf (row-major-aref temp (the (integer- 0
,@(when opt-type-limit `(,opt-type-limit)))
index)) *alt*) temp index))
()
((incf index)
(locally
(declare (type (integer 0 ,opt-type-limit) index))
(if (= index ,(or opt-limit opt-type-limit)) (go end))
(setq elements (row-major-aref seq (the (integer- 0
,@(when opt-type-limit `(,opt-type-limit)))
index)))))
()
()
:mutable)
(*fragl ((seq) (,unopt-limit)) ((elements t))
((elements ,type)
(temp t seq)
(index (integer -1 ,@(when unopt-type-limit `(,unopt-type-limit))) -1))
((elements (setf (row-major-aref temp (the (integer- 0
,@(when unopt-type-limit `(,unopt-type-limit)))
index)) *alt*) temp index))
()
((incf index)
(locally
(declare (type (integer 0 ,@(when unopt-type-limit `(,unopt-type-limit))) index))
(if (= index ,unopt-limit) (go end))
(setq elements (row-major-aref seq (the (integer- 0
,@(when unopt-type-limit `(,unopt-type-limit)))
index)))))
()
()
:mutable)))
(defmacro list-scan (type)
`(efragl ((seq))
`(((elements t))
((elements ,,type)
(listptr list seq)
(parent list))
((elements (setf (car parent) *alt*) parent))
()
((if (endp listptr) (go end))
(setq parent listptr)
(setq elements (car listptr))
(setq listptr (cdr listptr)))
()
()
:mutable)))
;; API
(defS scan (seq-type &optional (seq nil seq-p))
"(scan [type] sequence)
SCAN returns a series containing the elements of sequence in
order. The type argument is a type specifier indicating the type of
sequence to be scanned; it must be a (not necessarily proper) subtype
of sequence. If type is omitted, it defaults to list."
(cl:let (type limit *limit* *type*)
(when (not seq-p) ;it is actually seq-type that is optional
(setq seq seq-type)
(setq seq-type #-:cltl2-series nil #+:cltl2-series (unless (constantp seq) (optq 'list))))
(multiple-value-setq (type limit *type*) (decode-seq-type (non-optq seq-type)))
(cond ((member type '(list bag))
(if (null seq)
(null-scan (eoptif-q *type* t))
(list-scan (eoptif-q *type* t))))
(limit
(setq *limit* limit)
(if (= *limit* 0)
(if (constantp seq)
(null-scan (eoptif *type* t))
(efragl ((seq))
`(((elements t))
((elements ,(eoptif-q *type* t))
(temp t seq))
()
()
((go end))
()
()
:args)))
(limited-scan *type* nil *limit* limit)))
((not (eq type 'sequence)) ;some kind of array
;; Check to see if SEQ is constant.
(if (constantp seq)
(cl:let ((thing (if (symbolp seq)
(symbol-value seq)
seq)))
;; THING should be either the SEQ or if SEQ is a
;; symbol, the value of the symbol.
(when (and (consp seq) (eq (car seq) 'quote))
(setq thing (cadr seq)))
(setq limit (array-fill-pointer-or-total-size thing))
(when (eq *type* t)
(setq *type* (array-element-type thing)))
(if (= limit 0)
(null-scan (eoptif-q *type* t))
(progn
(setq *limit* limit)
(limited-scan *type* array-total-size-limit *limit* limit))))
(efragl ((seq))
`(((elements t))
((elements ,(eoptif-q *type* t))
(temp t seq)
(limit vector-index+ (array-fill-pointer-or-total-size seq))
(index -vector-index+ -1))
((elements (setf (row-major-aref temp (the vector-index index)) *alt*) temp index))
()
((incf index)
(locally
(declare (type vector-index+ index))
(if (= index limit) (go end))
(setq elements (row-major-aref seq (the vector-index index)))))
()
()
:mutable))))
(t
(if (constantp seq)
(if (null seq)
(null-scan (eoptif-q *type* t))
(cl:let ((thing seq))
(when (eq-car seq 'quote)
(setq thing (cadr seq)))
(when (and (eq *type* t) (not (listp thing)))
(setq *type* (array-element-type thing)))
(setq limit
(if (listp thing)
(length thing)
(array-total-size thing)))
(if (= limit 0)
(null-scan (eoptif-q *type* t))
(if (consp thing)
(list-scan (eoptif-q *type* t))
(progn
(setq *limit* limit)
(limited-scan *type* array-total-size-limit *limit* limit))))))
#-:cltl2-series
(if (lister-p seq)
(list-scan (if *optimize-series-expressions* *type* t))
(efragl ((seq-type) (seq)) ;dummy type input avoids warn
`(((elements t))
((elements ,(eoptif-q *type* t))
(parent list)
(listptr list)
(temp array)
(limit vector-index+)
(index -vector-index -1)
(lstp boolean))
((elements (if lstp
(setf (car parent) *alt*)
(setf (row-major-aref temp (the vector-index index)) *alt*))
parent temp index lstp))
((if (setq lstp (listp seq))
(setq listptr seq
temp #())
(locally
(declare (type array seq))
(setq temp seq)
(setq limit (array-fill-pointer-or-total-size seq)))))
((if lstp
(progn
(if (endp listptr) (go end))
(setq parent listptr)
(setq elements (car listptr))
(setq listptr (cdr listptr)))
(progn
(incf index)
(locally
(declare (type array seq) (type vector-index index))
(if (>= index limit) (go end))
(setq elements (the *type* (row-major-aref seq index)))))))
()
()
:mutable)))
#+:cltl2-series
(efragl ((seq-type) (seq)) ;dummy type input avoids warn
`(((elements t))
((elements ,(eoptif-q *type* t))
(temp sequence seq)
(limit nonnegative-integer (length seq))
(index (integer -1) -1))
((elements (setf (elt temp (the nonnegative-integer index)) *alt*)
temp index))
()
((incf index)
(locally
(declare (type nonnegative-integer index))
(if (>= index limit) (go end))
(setq elements (elt seq index))))
()
()
:mutable))
)))))
;; HELPER
(cl:defun promote-series (series)
(cond ((not (alter-fn series))
(values series nil))
(t (setq series (if (image-series-p series)
(copy-image-series series)
(copy-basic-series series)))
(setf (alter-fn series) nil)
(values series t))))
;; API
(defS cotruncate (&rest items-list)
"(cotruncate &rest series)
Truncates the inputs so that they are all no longer than the shortest one."
(values-lists (length items-list)
(apply #'map-fn t #'list (mapcar #'promote-series items-list))
(mapcar #'alter-fn items-list))
:optimizer
(cl:let* ((args (copy-list items-list))
(vars (n-gensyms (length args) (symbol-name '#:cotrunc-)))
(ports (mapcar #'(lambda (v) (list v t)) vars)))
(apply-frag
(literal-frag `(,ports ,(copy-list ports) nil nil nil nil nil nil nil))
args)))
;; API
(defS scan* (seq-type seq)
"Enumerates a series of the values in SEQ without checking for the end."
(cl:multiple-value-bind (type limit *type*)
(decode-seq-type (non-optq seq-type))
(declare (ignore limit))
(cond ((member type '(list bag))
(efragl ((seq))
`(((elements t))
((elements ,(eoptif-q *type* t))
(listptr list seq)
(parent list))
((elements (setf (car parent) *alt*) parent))
()
((setq parent listptr)
(setq elements (car listptr))
(setq listptr (cdr listptr)))
()
()
:mutable)))
((not (eq type 'sequence)) ;some kind of array
(efragl ((seq))
`(((elements t))
((elements ,(eoptif-q *type* t))
(temp array seq)
(index -vector-index -1))
((elements (setf (row-major-aref temp (the vector-index index)) *alt*) temp index))
()
((incf index)
(setq elements
(row-major-aref seq (the vector-index index))))
()
()
:mutable)))
(t (efragl ((seq-type) (seq)) ;dummy type input avoids warn
`(((elements t))
((elements ,(eoptif-q *type* t))
(temp t seq)
(index nonnegative-integer 0))
((elements (setf (elt temp index) *alt*) temp index))
()
((setq elements (elt seq index))
(incf index))
()
()
:mutable))))))
;; HELPER
(cl:defun decode-multiple-types-arg (type n)
(cond ((or (not (eq-car type 'quote))
(not (eq-car (cadr type) 'values)))
(make-list n :initial-element type))
(t (when (not (= (length (cdadr type)) n))
(ers 78 "~%SCAN-MULTIPLE: type and number of sequences conflict."))
(mapcar #'(lambda (x) `(quote ,x)) (cdadr type)))))
;; API
(defS scan-multiple (type sequence &rest sequences)
"(scan-multiple type first-seq &rest more-sequences)
Like several calls to SCAN, but scans multiple sequences in parallel
efficiently."
(cl:let ((types (mapcar #'cadr
(decode-multiple-types-arg (list 'quote type)
(1+ (length sequences))))))
(apply #'cotruncate
(scan (car types) sequence)
(mapcar #'scan* (cdr types) sequences)))
:optimizer
(cl:let ((types (decode-multiple-types-arg type (1+ (length sequences)))))
`(cotruncate (scan ,(car types) ,sequence)
,@(mapcar #'(lambda (type seq) `(scan* ,type ,seq))
(cdr types) sequences))))
;; API
(defS scan-sublists (lst)
"(scan-sublists list)
Creates a series of the sublists in a list.
(SCAN-SUBLISTS '(A B C)) => #Z((A B C) (B C) (C)) "
(fragl ((lst)) ((sublists t))
((sublists list)
(lstptr list lst))
()
()
((if (endp lstptr) (go end))
(setq sublists lstptr)
(setq lstptr (cdr lstptr)))
()
()
:mutable))
;; API
(defS scan-alist (alist &optional (test #'eql))
"(scan-alist alist &optional (test #'eql))
Creates two series containing the keys and values in an alist."
(fragl ((alist) (test)) ((keys t) (values t))
((alistptr list alist)
(keys t) (values t) (parent list))
((keys (setf (car parent) *alt*) parent)
(values (setf (cdr parent) *alt*) parent))
()
(L (if (null alistptr) (go end))
(setq parent (car alistptr))
(setq alistptr (cdr alistptr))
(if (or (null parent)
(not (eq parent (assoc (car parent) alist :test test))))
(go L))
(setq keys (car parent))
(setq values (cdr parent)))
()
()
:mutable))
;; API
(defS scan-plist (plist)
"(scan-plist plist)
Creates two series containing the indicators and values in a plist."
(fragl ((plist)) ((indicators t) (values t))
((indicators t) (values t)
(plistptr list plist)
(parent list))
((indicators (setf (car parent) *alt*) parent)
(values (setf (cadr parent) *alt*) parent))
()
(L (if (null plistptr) (go end))
(setq parent plistptr)
(setq indicators (car plistptr))
(setq plistptr (cdr plistptr))
(setq values (car plistptr))
(setq plistptr (cdr plistptr))
(do ((ptr plist (cddr ptr)))
((eq (car ptr) indicators)
(if (not (eq ptr parent)) (go L)))))
()
()
:mutable))
;; API
(defS scan-lists-of-lists (tree &optional (test #'atom test-p))
"(scan-lists-of-lists lists-of-lists &optional (leaf-test 'atom))
Creates a series of the nodes in a tree, in preorder order. LEAF-TEST
returns non-NIL if a node is a leaf node."
(if test-p
(fragl ((tree) (test)) ((nodes t))
((nodes t)
(state list (list tree)))
()
()
((if (null state) (go end))
(setq nodes (car state))
(setq state (cdr state))
(when (not (or (atom nodes) (cl:funcall test nodes)))
(do ((ns nodes (cdr ns))
(r nil (cons (car ns) r)))
((not (consp ns))
(setq state (nreconc r state))))))
()
()
:mutable)
(fragl ((tree)) ((nodes t))
((nodes t)
(state list (list tree)))
()
()
((if (null state) (go end))
(setq nodes (car state))
(setq state (cdr state))
(when (not (atom nodes))
(do ((ns nodes (cdr ns))
(r nil (cons (car ns) r)))
((not (consp ns))
(setq state (nreconc r state))))))
()
()
:mutable)))
;; API
(defS scan-lists-of-lists-fringe (tree &optional (test #'atom test-p))
"(scan-lists-of-lists-fringe lists-of-lists &optional (leaf-test 'atom)
Creates a series of the leaves of a tree, in preorder order. LEAF-TEST
returns non-NIL if a node is a leaf node."
(if test-p
(fragl ((tree) (test)) ((leaves t))
((leaves t) (parent list)
(state list (list (list tree))))
((leaves (setf (car parent) *alt*) parent))
()
(L (if (null state) (go end))
(setq leaves (car state))
(setq state (cdr state))
(setq parent leaves)
(setq leaves (car leaves))
(when (not (or (atom leaves) (cl:funcall test leaves)))
(do ((ns leaves (cdr ns))
(r nil (cons ns r)))
((not (consp ns)) (setq state (nreconc r state))))
(go L)))
()
()
:mutable)
(fragl ((tree)) ((leaves t))
((leaves t) (parent list)
(state list (list (list tree))))
((leaves (setf (car parent) *alt*) parent))
()
(L (if (null state) (go end))
(setq leaves (car state))
(setq state (cdr state))
(setq parent leaves)
(setq leaves (car leaves))
(when (not (atom leaves))
(do ((ns leaves (cdr ns))
(r nil (cons ns r)))
((not (consp ns)) (setq state (nreconc r state))))
(go L)))
()
()
:mutable)))
;; API
#-symbolics
(defS scan-symbols (&optional (package nil))
"(scan-symbols (&optional (package *package*))
Creates a series of the symbols in PACKAGE (which defaults to *PACKAGE*)."
(fragl ((package)) ((symbols t))
((symbols symbol)
(lst list nil))
()
((do-symbols (s (or package *package*)) (push s lst)))
((if (null lst) (go end))
(setq symbols (car lst))
(setq lst (cdr lst)))
()
()
:context)) ; package can change -
; Movement should only be allowed if no unknown functions
; and constrained by thread sync and package operations
;; API
#+symbolics ;see do-symbols
(defS scan-symbols (&optional (package nil))
"Creates a series of the symbols in PACKAGE."
(fragl ((package))
((symbols t))
((index t) (state t) (symbols symbol))
()
((multiple-value-setq (index symbols state)
(si:loop-initialize-mapatoms-state (or package *package*) nil)))
((if (multiple-value-setq (nil index symbols state)
(si:loop-test-and-step-mapatoms index symbols state))
(go end)))
()
()
:context)) ; package can change
; Movement should only be allowed if no unknown functions
; and constrained by thread sync and package operations
;; API
(defS scan-file (name &optional (reader #'read))
"(scan-file file-name &optional (reader #'read)
SCAN-FILE opens the file named by the string FILE-NAME and applies the
function READER to it repeatedly until the end of the file is
reached. READER must accept the standard input function arguments
input-stream, eof-error-p, and eof-value as its arguments. (For
instance, reader can be read, read-preserving-white-space, read-line,
or read-char.) If omitted, READER defaults to READ. SCAN-FILE returns
a series of the values returned by READER, up to but not including the
value returned when the end of the file is reached. The file is
correctly closed, even if an abort occurs. "
(fragl ((name) (reader)) ((items t))
((items t)
(lastcons cons (list nil))
(lst list))
()
((setq lst lastcons)
(with-open-file (f name :direction :input)
(cl:let ((done (list nil)))
(loop
(cl:let ((item (cl:funcall reader f nil done)))
(when (eq item done)
(return nil))
(setq lastcons (setf (cdr lastcons) (cons item nil)))))))
(setq lst (cdr lst)))
((if (null lst) (go end))
(setq items (car lst))
(setq lst (cdr lst)))
()
()
:context) ; file can change
; Movement should only be allowed if no unknown functions
; and constrained by sync and file operations
:optimizer
(apply-literal-frag
(cl:let ((file (new-var 'file)))
`((((reader)) ((items t))
((items t) (done t (list nil)))
()
()
((if (eq (setq items (cl:funcall reader ,file nil done)) done)
(go end)))
()
((#'(lambda (code)
(list 'with-open-file
'(,file ,name :direction :input)
code)) :loop))
:context)
,reader))))
;; API
(defS scan-stream (name &optional (reader #'read))
"(scan-stream stream &optional (reader #'read))
Creates a series of the forms in the stream STREAM. Similar to
SCAN-FILE, except we read from an existing stream."
(fragl ((name) (reader)) ((items t))
((items t)
(lastcons cons (list nil))
(lst list))
()
((setq lst lastcons)
(cl:let ((done (list nil)))
(loop
(cl:let ((item (cl:funcall reader name nil done)))
(when (eq item done)
(return nil))
(setq lastcons (setf (cdr lastcons) (cons item nil))))))
(setq lst (cdr lst)))
((if (null lst) (go end))
(setq items (car lst))
(setq lst (cdr lst)))
()
()
:mutable ; stream can change - OK if scan-private stream
)
:optimizer
(apply-literal-frag
`((((reader)) ((items t))
((items t) (done t (list nil)))
()
()
((if (eq (setq items (cl:funcall reader ,name nil done)) done)
(go end)))
()
()
:mutable ; stream can change - OK if scan-private stream
)
,reader
)))
;; API
(defS scan-hash (table)
"(scan-hash table)
Scans the entries of teh hash table and returns two series containing
the keys and their associated values. The first element of key series
is the key of the first entry in the hash table, and the first element
of the values series is the value of the first entry, and so on. The
order of scanning the hash table is not specified."
#-CLISP
(fragl ((table))
((keys t) (values t))
((keys t) (values t)
(lst list nil))
()
((maphash #'(lambda (key val) (push (cons key val) lst)) table))
((if (null lst) (go end))
(setq keys (caar lst))
(setq values (cdar lst))
(setq lst (cdr lst)))
()
()
:mutable ; table can change - OK if scan-private table
)
#+CLISP
(fragl ((table))
((keys t) (values t))
((state t (sys::hash-table-iterator table))
(nextp t) (keys t) (values t))
()
()
((multiple-value-setq (nextp keys values) (sys::hash-table-iterate state))
(unless nextp (go end)))
()
()
:mutable ; table can change - OK if scan-private table
)
#+symbolics :optimizer #+symbolics
(apply-literal-frag
`((((table))
((keys t) (values t))
((state t nil) (keys t) (values t))
()
()
((if (not (multiple-value-setq (state keys values)
(si:send table :next-element state)))
(go end))) ()
((#'(lambda (c) `(si:inhibit-gc-flips ,c)) :loop))
:mutable ; table can change - OK if scan-private table
)
,table))
)
;; API
(defS previous (items &optional (default nil) (amount 1))
"(previous items &optional (default nil) (amount 1))
The series returned by PREVIOUS is the same as the input series ITEMS
except that it is shifted to the right by the positive integer AMOUNT. The
shifting is done by inserting AMOUNT copies of DEFAULT before ITEMS and
discarding AMOUNT elements from the end of ITEMS."
(cond ((eql amount 1)
(fragl ((items t) (default)) ((shifted-items t))
((shifted-items (series-element-type items))
(state (series-element-type items) default))
()
()
((setq shifted-items state) (setq state items))
()
()
nil ; series dataflow constraint takes care
))
(t (fragl ((items t) (default) (amount)) ((shifted-items t))
((shifted-items (series-element-type items))
(ring list (make-list (1+ amount) :initial-element default)))
()
((nconc ring ring))
((rplaca ring items)
(setq ring (cdr ring))
(setq shifted-items (car ring)))
()
()
nil ; series dataflow constraint takes care
))))
;; API
(defS latch (items &key (after nil) (before nil) (pre nil pre-p) (post nil post-p))
"(latch items &key after before pre post)
The series returned by LATCH is the same as the input series ITEMS except
that some of the elements are replaced by other values. LATCH acts like a
LATCH electronic circuit component. Each input element causes the creation
of a corresponding output element. After a specified number of non-null
input elements have been encountered, the latch is triggered and the output
mode is permanently changed.
The :AFTER and :BEFORE arguments specify the latch point. The latch point
is just after the :AFTER-th non-null element in ITEMS or just before the
:BEFORE-th non-null element. If neither :AFTER nor :BEFORE is specified,
an :AFTER of 1 is assumed. If both are specified, it is an error.
If a :PRE is specified, every element prior to the latch point is replaced
by this value. If a :POST is specified, every element after the latch
point is replaced by this value. If neither is specified, a :POST of NIL
is assumed."
(progn (when (and after before)
(ers 79 "~%:AFTER and :BEFORE both specified in a call on LATCH."))
(when (not (or before after))
(setq after 1))
(when (null pre-p)
(setq post-p t))
(cond (after
(fragl ((items t) (after) (pre) (pre-p) (post) (post-p))
((masked-items t))
((masked-items t)
(state fixnum after))
()
()
((cond ((plusp state) (if items (decf state))
(setq masked-items (if pre-p pre items)))
(t (setq masked-items (if post-p post items)))))()
()
nil ; series dataflow constraint takes care
))
(t (fragl ((items t) (before) (pre) (pre-p) (post) (post-p))
((masked-items t))
((masked-items t)
(state fixnum before))
()
()
((cond ((and (plusp state)
(or (null items)
(not (zerop (setq state (1- state))))))
(setq masked-items (if pre-p pre items)))
(t (setq masked-items
(if post-p post items)))))
()
()
nil ; series dataflow constraint takes care
)))))
(defS until1 (bools items)
"Returns ITEMS up to, but not including, the first non-null element of BOOLS."
(fragl ((bools t) (items t)) ((items t)) () ()
()
((if bools (go end)))
()
()
nil
))
;; API
(defS until (bools items-1 &rest items-i)
"(until bools items-1 &rest series-inputs)
Returns ITEMS-I up to, but not including, the first non-null element of BOOLS."
(if (null items-i)
(until1 bools items-1)
(apply #'cotruncate
(mapcar #'(lambda (i) (until1 bools i)) (cons items-1 items-i))))
:optimizer
(cl:let ((extra-ins (mapcar #'(lambda (x) (declare (ignore x))
(list (gensym "ITEMS") t))
items-i)))
(apply-literal-frag
(list* `(((bools t) (items t) ,@ extra-ins)
((items t) ,@(copy-tree extra-ins))
() ()
() ((if bools (go end))) () () nil)
bools items-1 items-i))))
(defS until-if1 (pred items other-items)
"Returns ITEMS up to, but not including, the first element which satisfies PRED."
(fragl ((pred) (items t) (other-items t)) ((other-items t)) () ()
() ((if (cl:funcall pred items) (go end))) () () nil))
;; API
(defS until-if (pred items-1 &rest items-i)
"(until-if pred items-1 &rest series-inputs)
Returns ITEMS-i up to, but not including, the first element which
satisfies PRED."
(if (null items-i)
(until-if1 pred items-1 items-1)
(apply #'cotruncate
(mapcar #'(lambda (i) (until-if1 pred items-1 i))
(cons items-1 items-i))))
:optimizer
(cl:let* ((params nil)
(frag (make-frag :impure nil))
(item-vars (n-gensyms (1+ (length items-i)) (symbol-name '#:items-)))
(*state* nil))
(multiple-value-setq (pred params) (handle-fn-arg frag pred params))
(setq params (mapcar #'retify (nconc params (cons items-1 items-i))))
(dolist (var item-vars)
(+arg (make-sym :var var :series-var-p t) frag)
(+ret (make-sym :var var :series-var-p t) frag))
(setf (body frag)
`((if ,(car (handle-fn-call frag nil pred (list (car item-vars)) t))
(go ,end))))
(apply-frag frag params)))
;; API
(defS positions (bools)
"(positions bools)
Returns a series of the positions of non-null elements in bools.
Positions are counted from 0."
(fragl ((bools t -X-)) ((index t)) ((index fixnum -1))
()
()
(L -X- (incf index) (if (not bools) (go L))) () () nil))
;; API
(defS mask (monotonic-indices)
"(mask monotonic-indices)
Creates a series containing T in the indicated positions and NIL
elsewhere. The positions must be a strictly increasing series of
non-negative integers."
(fragl ((monotonic-indices t -x- d)) ((bools t))
((bools boolean t) (index fixnum 0))
()
()
#-(and :allegro-version>= (version>= 5 0) (not (version>= 5 1)))
( (if (not bools) (go f))
-x- (go f) d (setq index -1)
f (setq bools (and (not (minusp index))
(= (prog1 index (incf index))
monotonic-indices))))
#+(and :allegro-version>= (version>= 5 0) (not (version>= 5 1)))
((if (not bools) (go f)) (go forward) d (go e) forward
-x- (go f) e (setq index -1)
f (setq bools (and (not (minusp index))
(= (prog1 index (incf index))
monotonic-indices))))
() () nil))
;; API
(defS choose (bools &optional (items nil items-p))
"(choose bools &optional (items bools))
Chooses the elements of ITEMS corresponding to non-null elements of
BOOLS. If ITEMS is not given, then the non-null elements of BOOLS is
returned"
(cond (items-p
(fragl ((bools t) (items t)) ((items t -X-)) () ()
() ((if (not bools) (go F)) -X- F) () () nil))
(t (fragl ((bools t -X-)) ((bools t)) () ()
() (L -X- (if (not bools) (go L))) () () nil))))
;; API
(defS choose-if (pred items)
"(choose-if pred items)
Chooses the elements of ITEMS for which PRED is non-null."
(cl:flet ((gen-unopt ()
(fragl ((pred) (items t -X-)) ((items t)) () ()
() (L -X- (if (not (cl:funcall pred items)) (go L))) () () nil)))
(eoptif-q
(funcase (fun pred)
((name anonymous)
(efragl ((items t -X-))
`(((items t)) () ()
()
(L -X- (if (not (,(if (symbolp fun) fun (process-fn fun)) items))
(go L)))
() () nil)))
(t
(gen-unopt)))
(gen-unopt))))
;; API
(defS expand (bools items &optional (default nil))
"(expand bools items &optional (default nil))
The output contains the elements of the input series ITEMS spread out
into the positions specified by the non-null elements in BOOLS---that
is, ITEMS[j] is in the position occupied by the jth non-null element
in BOOLS. The other positions in the output are occupied by DEFAULT.
The output stops as soon as BOOLS runs out of elements or a non-null
element in BOOLS is encountered for which there is no corresponding
element in ITEMS."
(fragl ((bools t) (items t -X-) (default)) ((expanded t))
((expanded (series-element-type items)))
()
()
((when (not bools) (setq expanded default) (go F))
-X- (setq expanded items)
F)
() () nil))
;; API
(defS spread (gaps items &optional (default nil))
"(spread gaps items &optional (default nil)
SPREAD is quite similar to EXPAND, except instead of giving booleans
on where to put the items, GAPS are specified which indicate how far
apart the items should be. A gap of 0 means the items will be
adjacent."
(fragl ((gaps t) (items t) (default)) ((expanded t -X-))
((expanded (series-element-type items)) (count fixnum))
()
()
((setq count gaps)
L (setq expanded (if (zerop count) items default))
-X-
(when (plusp count) (decf count) (go L)))
() () nil))
;; API
(defS subseries (items start &optional (below nil below-p))
"(subseries items start &optional below)
SUBSERIES returns a series containing the elements of the input series
ITEMS indexed by the non-negative integers from START up to, but not
including, BELOW. If BELOW is omitted or greater than the length of ITEMS,
the output goes all of the way to the end of ITEMS."
(cond (below-p
(fragl ((items t -X-) (start) (below)) ((items t))
((index (integer -1) -1))
()
()
(LP -X-
(incf index)
(locally
(declare (type nonnegative-integer index))
(if (>= index below) (go end))
(if (< index start) (go LP))))
() () nil))
(t (fragl ((items t -X-) (start)) ((items t))
((index integer (- -1 start)))
()
()
(LP -X-
(incf index)
(if (minusp index) (go LP)))
() () nil))))
;; API
(defS mingle (items1 items2 comparator)
"(mingle items1 items2 comparator)
Merges two series into one, with the same elements and order as ITEMS1
and ITEMS2.
The COMPARATOR must accept two arguments and return non-null if and only if
its first argument is strictly less than its second argument (in some
appropriate sense). At each step, the COMPARATOR is used to compare the
current elements in the two series. If the current element from ITEMS2 is
strictly less than the current element from ITEMS1, the current element is
removed from ITEMS2 and transferred to the output. Otherwise, the next
output element comes from ITEMS1. "
(fragl ((items1 t -X1- F1) (items2 t -X2- F2) (comparator)) ((items t))
((items (or (series-element-type items1)
(series-element-type items2)))
(need1 fixnum 1) (need2 fixnum 1))
()
()
((if (not (plusp need1)) (go F1))
(setq need1 -1)
-X1-
(setq need1 0)
F1 (if (not (plusp need2)) (go F2))
(setq need2 -1)
-X2-
(setq need2 0)
F2 (cond ((and (minusp need1) (minusp need2)) (go end))
((minusp need1) (setq items items2) (setq need2 1))
((minusp need2) (setq items items1) (setq need1 1))
((not (cl:funcall comparator items2 items1))
(setq items items1) (setq need1 1))
(t (setq items items2) (setq need2 1))))
() () nil))
;;; Concatenation
(defS catenate2 (items1 items2) ""
(fragl ((items1 t -X- F) (items2 t -Y-)) ((items t))
((items t) (flag boolean nil))
()
()
( (if flag (go B))
-X- (setq items items1) (go D)
F (setq flag t)
B -Y- (setq items items2) D)
() () nil))
;; API
(defS catenate (items1 items2 &rest more-items)
"(catenate items1 items2 &rest more-items)
Concatenates two or more series end to end."
(if more-items
(catenate2 items1 (apply #'catenate items2 more-items))
(catenate2 items1 items2))
:optimizer
(if more-items
`(catenate2 ,items1 (catenate ,items2 ,@ more-items))
`(catenate2 ,items1 ,items2)))
#|
(defS collect-union (&rest items)
"Collect the union of 0 or more series sets"
(cond ((cddr items)
(collect 'set (apply #'catenate items)))
(items
(collect 'list items))
(t
nil))
:optimizer
(cond ((cddr items)
`(collect 'set (catenate ,@items)))
(items
(basic-collect-list items))
(t
nil))
:trigger t)
|#
;;; Splitting
;; HELPER
(cl:defun image-of-with-datum (g datum)
(cl:let (item)
(loop (setq item (basic-do-next-in g))
(when (or (null (gen-state g))
(eql (car item) datum))
(return (cdr item))))))
;; OPTIMIZER
(cl:defun do-split (items stuff bools-p)
(cl:let ((frag (make-frag :impure nil))
(ivar (new-var 'splititems))
(D (new-var 'dne)))
(+arg (make-sym :var ivar :series-var-p t) frag)
(dotimes (i (length stuff) i)
(cl:let ((var (new-var 'h))
(-X- (new-var '-z-))
(S (new-var 'ss)))
(+arg (make-sym :var var :series-var-p bools-p) frag)
(+ret (make-sym :var ivar :series-var-p t :off-line-spot -X-) frag)
(setf (body frag)
`(,@(body frag)
(if (not ,(if bools-p var `(cl:funcall ,var ,ivar))) (go ,S))
,-X-
(go ,D)
,S ))))
(cl:let ((-X- (new-var '-Y-)))
(+ret (make-sym :var ivar :series-var-p t :off-line-spot -X-) frag)
(setf (body frag)
`(,@(body frag)
,-X- ,D)))
(apply-frag frag (cons items stuff))))
;; API
(defS split (items bools &rest more-bools)
"(split items bools &rest more-bools)
Partition the input series ITEMS between several outputs. If there
are N test inputs following ITEMS, then there are N+1 outputs. Each
input element is placed in exactly one output series, depending on the
outcome of a sequence of tests. If the element ITEMS[j] fails the
first K-1 tests and passes the kth test, it is put in the kth output.
If ITEMS[j] fails every test, it is placed in the last output. In
addition, all output stops as soon as any series input runs out of
elements."
(cl:let* ((pos-lists
(apply #'map-fn t
#'(lambda (item &rest bools)
(cons (apply #'pos bools) item))
(promote-series items)
(list* bools (copy-list more-bools)))))
(values-list
(mapcar #'(lambda (i)
(make-image-series :alter-fn (alter-fn items)
:image-fn #'image-of-with-datum
:image-datum i
:image-base pos-lists))
(n-integers (+ 2 (length more-bools))))))
:optimizer
(do-split items (cons bools (copy-list more-bools)) t))
;; API
(defS split-if (items pred &rest more-pred)
"(split-if items pred &rest more-pred)
Partition the input series ITEMS between several outputs. If there
are N test inputs following ITEMS, then there are N+1 outputs. Each
input element is placed in exactly one output series, depending on the
outcome of a sequence of tests. If the element ITEMS[j] fails the
first K-1 predicate tests and passes the kth test, it is put in the
kth output. If ITEMS[j] fails every test, it is placed in the last
output. In addition, all output stops as soon as any series input
runs out of elements."
(cl:let* ((preds (list* pred (copy-list more-pred))))
;; FIXME
;;
;; This is a really gross hack because I don't know how
;; this works. According to bug 516952, the following
;; doesn't work
;;
;; (split-if (scan '(1 2 1 2 3)) (lambda (item) (evenp item)))
;;
;; What happens is something like '(1 (1 2 1 2 3) ..)
;; gets passed to pos-if, which is not expecting a list.
;;
;; However the obvious fix of just taking the car then fails for
;;
;; (split-if #z(1 2 1 2 3) (lambda (item) (evenp item)))
;;
;; because pos-if would have been passed the individual items.
;;
;; So the hack is to see if there is to have promote-series return
;; a second value that tells whether we're returning the series as
;; is (NIL) or we copied the series (T). Then, if T, we take the
;; car of the item, otherwise just the item.
;;
;; If I (rtoy) were smarter I'd fix this better, but I'm
;; too stupid.
(multiple-value-bind (ps altered)
(promote-series items)
(let ((pos-lists
(map-fn t
#'(lambda (item)
(let ((it (if altered
(car item)
item)))
(cons (apply #'pos-if it preds) item)))
ps)))
(values-list
(mapcar #'(lambda (i)
(make-image-series :alter-fn (alter-fn items)
:image-fn #'image-of-with-datum
:image-datum i
:image-base pos-lists))
(n-integers (+ 2 (length more-pred))))))))
:optimizer
(do-split items (cons pred (copy-list more-pred)) nil))
;; API
(defS every-nth (m n items)
"Returns a series of every Nth element of ITEMS, after skipping M elements."
(fragl ((m) (n) (items t -X-)) ((items t))
((count fixnum (1- m)))
()
()
(L -X- (cond ((plusp count) (decf count) (go L))
(t (setq count (1- n))))) () () :args))
;; API
(defS chunk (m n &optional (items nil items-p))
"(chunk m n items)
Break up the input series ITEMS into (possibly overlapping) chunks of
length M. The starting positions of successive chunks differ by N.
The inputs M and N must both be positive integers.
CHUNK produces M output series. The ith chunk consists of the ith
elements of the M outputs. Suppose that the length of ITEMS is L.
The length of each output is the floor of 1+(L-M)/N. The ith element
of the kth output is the (i*n+k)th element of ITEMS (i and k counting
from zero)."
(progn
(when (not items-p) ;it is actually n that is optional
(setq items n)
(setq n 1))
(cond ((not (typep m 'positive-integer))
(ers 63 "~%M argument " m " to CHUNK fails to be a positive integer."))
((not (typep n 'positive-integer))
(ers 64 "~%N argument " n " to CHUNK fails to be a positive integer."))
(t (values-list
(mapcar #'(lambda (i)
(every-nth m n
(if (zerop i)
items
(previous items nil i))))
(nreverse (n-integers m)))))))
:optimizer
(progn
(when (not items-p) ;it is actually n that is optional
(setq items n)
(setq n 1))
(cond ((not (typep m 'positive-integer))
(rrs 3 "~%M argument " m " to CHUNK fails to be a positive integer."))
((not (typep n 'positive-integer))
(rrs 4 "~%N argument " n " to CHUNK fails to be a positive integer."))
(t (cl:let* ((vars (n-gensyms m (symbol-name '#:chunk-)))
(outs (mapcar #'(lambda (v) (list v t)) vars))
(auxes (mapcar #'(lambda (v)
`(,v ,(copy-list
'(series-element-type in))))
vars))
(setqs (mapcar #'(lambda (u v) (list 'setq u v))
vars (cdr vars))))
(apply-frag
(literal-frag
`(((in t -X-)) ,outs ((count fixnum) ,@ auxes) ()
((setq count ,(1- m)))
(L -X- ,@ setqs (setq ,(car (last vars)) in)
(cond ((plusp count) (decf count) (go L))
(t (setq count ,(1- n))))) () () :args))
(list items)))))))
;; API
(defS collect-append (seq-type &optional (items nil items-p))
"(collect-append [type] items)
Given a series of sequences, COLLECT-APPEND returns a new sequence by
concatenating these sequences together in order. The TYPE is a type
specifier indicating the type of sequence created and must be a proper
subtype of SEQUENCE. If TYPE is omitted, it defaults to LIST. For
example:
(COLLECT-APPEND #Z((A B) NIL (C D))) => (A B C D)"
(progn
(when (not items-p) ;it is actually seq-type that is optional
(setq items seq-type)
(setq seq-type (optq 'list)))
(cond ((equal seq-type (optq 'list))
(fragl ((items t)) ((lst))
((lst list nil) (list-end list nil))
()
()
((when items
(cl:multiple-value-bind (copy lastcons) (copy-list-last items)
(when list-end (rplacd list-end copy))
(setq list-end lastcons)
(when (null lst) (setq lst copy)))))
() () nil))
(t (fragl ((seq-type) (items t)) ((seq))
((seq t nil))
()
()
((setq seq (cons items seq)))
((setq seq (apply #'concatenate seq-type (nreverse seq))))
()
nil))))
:trigger t)
;; API
(defS collect-nconc (items)
"(collect-nconc items)
COLLECT-NCONC NCONCs the elements of the series LISTS together in
order and returns the result. This is the same as COLLECT-APPEND
except that the input must be a series of lists, the output is always
a list, the concatenation is done rapidly by destructively modifying
the input elements, and therefore the output shares all of its
structure with the input elements."
(fragl ((items t)) ((lst))
((lst list nil) (list-end list nil))
()
()
((when items
(when list-end (setf (cdr (last list-end)) items))
(setq list-end items)
(when (null lst) (setq lst items))))
() () nil)
:trigger t)
;; API
(defS collect-hash (keys values &rest option-plist)
"(collect-hash keys values :test :size :rehash-size :rehash-threshold)
Combines a series of keys and a series of values together into a hash
table. The keyword arguments specify the attributes of the hash table
to be produced. They are used as arguments to MAKE-HASH-TABLE"
(fragl ((keys t) (values t) (option-plist))
((table))
((table t (apply #'make-hash-table option-plist)))
()
()
((setf (gethash keys table) values)) () () nil)
:optimizer
(apply-literal-frag
(list '(((keys t) (values t) (table)) ((table)) () ()
() ((setf (gethash keys table) values)) () () nil)
keys values `(make-hash-table ,@ option-plist)))
:trigger t)
;; API
(defS collect-file (name items &optional (printer #'print))
"(collect-file name items &optional (printer #'print)
This creates a file named FILE-NAME and writes the elements of the
series ITEMS into it using the function PRINTER. PRINTER must accept
two inputs: an object and an output stream. (For instance, PRINTER
can be PRINT, PRIN1, PRINC, PPRINT, WRITE-CHAR, WRITE-STRING, or
WRITE-LINE.) If omitted, PRINTER defaults to PRINT. The value T is
returned. The file is correctly closed, even if an abort occurs."
(fragl ((name) (items t) (printer)) ((out))
((out boolean t)
(lastcons cons (list nil))
(lst list))
()
((setq lst lastcons))
((setq lastcons (setf (cdr lastcons) (cons items nil))))
((with-open-file (f name :direction :output)
(dolist (item (cdr lst))
(cl:funcall printer item f))))
()
:context
)
:optimizer
(apply-literal-frag
(cl:let ((file (new-var 'outfile)))
`((((items t) (printer)) ((out))
((out boolean t))
()
()
((cl:funcall printer items ,file))
()
((#'(lambda (c)
(list 'with-open-file '(,file ,name :direction :output) c)) :loop))
:context
)
,items ,printer)))
:trigger t)
;; API
(defS collect-stream (name items &optional (printer #'print))
"Prints the elements of ITEMS onto the stream NAME."
(fragl ((name) (items t) (printer)) (())
((lastcons cons (list nil))
(lst list))
()
((setq lst lastcons))
((setq lastcons (setf (cdr lastcons) (cons items nil))))
((dolist (item (cdr lst))
(cl:funcall printer item name)))
()
:context
)
:optimizer
(apply-literal-frag
`((((items t) (printer)) (()) () ()
() ((cl:funcall printer items ,name)) ()
((#'(lambda (c)
c) :loop))
:context
)
,items ,printer))
:trigger t)
;; API
(defS collect-alist (keys values)
"(collect-alist keys values)
Combines a series of keys and a series of values together into an alist."
(fragl ((keys t) (values t)) ((alist))
((alist list nil))
()
()
((setq alist (cons (cons keys values) alist)))
() () nil)
:trigger t)
;; API
(defS collect-plist (indicators values)
"(collect-plist indicators values)
Combines a series of indicators and a series of values together into a plist."
(fragl ((indicators t) (values t)) ((plist))
((plist list nil))
()
()
((setq plist (list* indicators values plist)))
() () nil)
:trigger t)
;; API
(defS collect-last (items &optional (default nil))
"(collect-last items &optional (default nil))
Returns the last element of the series ITEMS. If ITEMS has no
elements, DEFAULT is returned."
(fragl ((items t) (default)) ((item))
((item (null-or (series-element-type items)) default))
()
()
((setq item items))
() () nil)
:trigger t)
;; API
(defS collect-first (items &optional (default nil))
"(collect-first items &optional (default nil))
Returns the first element of the series ITEMS. If ITEMS has no
elements, DEFAULT is returned."
(fragl ((items t) (default)) ((item))
((item (null-or (series-element-type items)) default))
()
()
((setq item items) (go end))
() () nil)
:trigger t)
;; API
(defS collect-nth (n items &optional (default nil))
"(collect-nth n items &optional (default nil))
Returns the Nth element of the series ITEMS. If ITEMS has no Nth
element, DEFAULT is returned."
(fragl ((n) (items t) (default)) ((item))
((counter fixnum n)
(item (null-or (series-element-type items)) default))
()
()
((when (zerop counter) (setq item items) (go end))
(decf counter)) () () nil)
:trigger t)
;; API
(defS collect-and (bools)
"(collect-and bools)
Computes the AND of the elements of BOOLS."
(fragl ((bools t)) ((bool))
((bool t t))
()
()
((if (null (setq bool bools)) (go end))) () () nil)
:trigger t)
;; API
(defS collect-or (bools)
"(collect-or bools)
Computes the OR of the elements of BOOLS."
(fragl ((bools t)) ((bool))
((bool t nil))
()
()
((if (setq bool bools) (go end))) () () nil)
:trigger t)
;; API
(defS collect-length (items)
"(collect-length items)
Returns the number of elements in ITEMS."
(fragl ((items t)) ((number))
((number fixnum 0))
()
()
((incf number)) () () nil)
:trigger t)
;; API
(defS collect-sum (numbers &optional (type 'number))
"(collect-sum numbers &optional (type 'number))
Computes the sum of the elements in NUMBERS. TYPE specifies the
type of sum to be created."
(fragl ((numbers t) (type)) ((sum))
((sum t (coerce-maybe-fold 0 type)))
()
()
((setq sum (+ sum numbers)))
() () nil)
:optimizer
(apply-literal-frag
`((((numbers t)) ((sum))
((sum ,(must-be-quoted type) ,(coerce-maybe-fold 0 (must-be-quoted type)))) ()
()
((setq sum (+ sum numbers))) () () nil)
,numbers))
:trigger t)
;; API
(defS collect-product (numbers &optional (type 'number))
"(collect-product numbers &optional (type 'number))
Computes the product of the elements in NUMBERS. TYPE specifies the
type of product to be created."
(fragl ((numbers t)
(type)) ((mul))
((mul t (coerce-maybe-fold 1 type)))
()
()
((setq mul (* mul numbers)))
() () nil)
:optimizer
(apply-literal-frag
`((((numbers t)) ((mul))
((mul ,(must-be-quoted type) ,(coerce-maybe-fold 1 (must-be-quoted type)))) ()
()
((setq mul (* mul numbers))) () () nil)
,numbers))
:trigger t)
;; API
(defS collect-max (numbers &optional (items numbers items-p) (default nil))
"(collect-max numbers &optional (items numbers items-p) (default nil))
Returns the element of ITEMS that corresponds to the maximum element
of NUMBERS. If ITEMS is omitted, then the maximum of NUMBERS itself
is returned. The value DEFAULT is returned if either NUMBERS or ITEMS
has zero length."
(if items-p
(fragl ((numbers t) (items t) (default)) ((result))
((number t nil)
(result (null-or (series-element-type items))))
()
()
((if (or (null number) (< number numbers))
(setq number numbers result items)))
((if (null number) (setq result default)))
()
nil)
(fragl ((numbers t) (default)) ((number))
((number t nil))
()
()
((if (or (null number) (< number numbers)) (setq number numbers)))
((if (null number) (setq number default)))
()
nil))
:trigger t)
;; API
(defS collect-min (numbers &optional (items numbers items-p) (default nil))
"(collect-min numbers &optional (items numbers items-p) (default nil))
Returns the element of ITEMS that corresponds to the minimum element
of NUMBERS. If ITEMS is omitted, then the minimum of NUMBERS itself
is returned. The value DEFAULT is returned if either NUMBERS or ITEMS
has zero length."
(if items-p
(fragl ((numbers t) (items t) (default)) ((result))
((number t nil)
(result (null-or (series-element-type items))))
()
()
((if (or (null number) (> number numbers))
(setq number numbers result items)))
((if (null number) (setq result default)))
()
nil)
(fragl ((numbers t) (default)) ((number))
((number t nil))
()
()
((if (or (null number) (> number numbers)) (setq number numbers)))
((if (null number) (setq number default)))
()
nil))
:trigger t)
(pushnew :series *features*)
#+:cltl2-series
(pushnew :cltl2-series *features*)
;;#+:excl
;;(setf excl:*cltl1-in-package-compatibility-p* nil)
;;#+:excl
;;(setf comp:*cltl1-compile-file-toplevel-compatibility-p* nil)
;;; A note on types. Things are set up so that every aux variable
;;; (except the variable that is necessary when a non-series input is
;;; not a constant) is given a type declaration whereas inputs are
;;; never given types. This ensures that everything is given a type
;;; definition and only once. The only exception is that a user can
;;; use a type decl in a series::let which will then override the
;;; default type. You can also wrap a (THE TYPE ...) around any
;;; series function call to override the types of the output.
;;; Some types are given in the form (series-element-type var) where
;;; var is a series input. A final pass substitutes this type if it
;;; can be found. Note that this is a purely one-way propagation of
;;; information starting on the inputs. The final pass also discards
;;; any type declarations which are t.
(provide "SERIES")
;;; ------------------------------------------------------------
;;; some things added since the last documentation
;;; #nM for returning multiple values
;;; Note #M does odd stuff with the keywords for keyword arguments, but
;;; there is nothing we can do about this, because the documentation is very
;;; clear on what #M does. If your are using implicit mapping,
;;; #M is unnecessary anyway.
;;; *series-implicit-map*, note the detailed rules for when mapping
;;; happens, which are much like OSS was, but more conservative.
;;; We never map a function unless we MUST---i.e., only when one of
;;; its actual arguments is a series. We never map a special form except IF.
;;; The virtue of this is that it is applicable on a single function
;;; by single function basis, and gets the same results no matter what
;;; the input looks like syntactically. (Note you might not get portable
;;; resuls. if some standard macro expands into code with an IF in one
;;; implementation and without in another.) (Note the forced evaluation
;;; of non-series functions that are not last in a let etc. is already done.)
;;; ------------------------------------------------------------------------
;;; Copyright Massachusetts Institute of Technology, Cambridge, Massachusetts.
;;; Permission to use, copy, modify, and distribute this software and its
;;; documentation for any purpose and without fee is hereby granted,
;;; provided that this copyright and permission notice appear in all
;;; copies and supporting documentation, and that the name of M.I.T not
;;; be used in advertising or publicity pertaining to distribution of the
;;; software without specific, written prior permission. M.I.T. makes no
;;; representations about the suitability of this software for any
;;; purpose. It is provided "as is" without express or implied warranty.
;;; M.I.T. DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING
;;; ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL
;;; M.I.T. BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR
;;; ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
;;; WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
;;; ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
;;; SOFTWARE.
;;; -------------------------------------------------------------------------
| 371,115 | Common Lisp | .lisp | 9,029 | 34.672167 | 362 | 0.607846 | Bradford-Miller/CL-LIB | 1 | 0 | 1 | LGPL-3.0 | 9/19/2024, 11:28:28 AM (Europe/Amsterdam) | 79968debe748a440fb1b140537a2a34bbd2b6f67558aa7d944211cf3d657a46b | 25,896 | [
-1
] |
25,897 | s-install.lisp | Bradford-Miller_CL-LIB/packages/SERIES/s-install.lisp | ;; This is for loading and installing the SERIES package.
(eval-when (load)
(series::install))
| 101 | Common Lisp | .lisp | 3 | 30.666667 | 57 | 0.744681 | Bradford-Miller/CL-LIB | 1 | 0 | 1 | LGPL-3.0 | 9/19/2024, 11:28:28 AM (Europe/Amsterdam) | a8c412beef61de4d56c10680ae67f05e428a4df45655ff259214dec53a311ad2 | 25,897 | [
-1
] |
25,898 | old-defsystem.lisp | Bradford-Miller_CL-LIB/archive/old-defsystem.lisp | ;; Time-stamp: <2005-06-29 11:08:23 miller>
;;; OBSOLETE!
;;; Note new defsystem-lispworks.lisp which has references to the new file-refactoring.
;;;
;;; New versions for other platforms should be straightforward based on that file (essentially only needs ported for the
;;; native defsystem for that platform)
;;;
;;; BWM 6/2005
(DECLAIM (OPTIMIZE (SPEED 2) (SAFETY 1) (DEBUG 1)))
;; miller - Brad Miller ([email protected])
#+ccl (require "LISP-PACKAGE") ; for series
(defpackage series
(:use common-lisp)
#+excl (:import-from excl compiler-let #||special-form-p||#)
#+ccl (:import-from lisp compiler-let special-form-p provide)
(:shadow #:let #:let* #:multiple-value-bind #:funcall #:defun #:restart #:condition)
(:export ;74 total concepts in the interface
;;(2) readmacros (#M and #Z)
;;(5) declarations and types (note dual meaning of series)
#:optimizable-series-function #:off-line-port ;series
#:series-element-type #:propagate-alterability
;(10) special functions
#:alter #:to-alter #:encapsulated #:terminate-producing
#:next-in #:next-out #:generator #:gatherer #:result-of #:gathering
;(55) main line functions
#:make-series #:series #:scan #:scan-multiple #:scan-range #:scan-sublists #:scan-fn
#:scan-fn-inclusive #:scan-lists-of-lists #:scan-lists-of-lists-fringe #:scan-file
#:scan-hash #:scan-alist #:scan-plist #:scan-symbols #:collect-fn #:collect
#:collect-append #:collect-nconc #:collect-file #:collect-alist #:collect-plist
#:collect-hash #:collect-length #:collect-sum #:collect-max #:collect-min
#:collect-last #:collect-first #:collect-nth #:collect-and #:collect-or
#:previous #:map-fn #:iterate #:mapping #:collecting-fn #:cotruncate
#:latch #:until #:until-if #:positions #:choose #:choose-if
#:spread #:expand #:mask #:subseries #:mingle #:catenate #:split #:split-if
#:producing #:chunk
;(5) variables
#:*series-expression-cache*
#:*last-series-loop*
#:*last-series-error*
#:*suppress-series-warnings*))
(defpackage "QUERY-P" (:use #+:lucid "LISP" #-:lucid #:common-lisp)
(:shadow #:y-or-n-p #:yes-or-no-p)
(:export #:query #:y-or-n-p-wait #:yes-or-no-p-wait))
;;; For a History of recent changes, see the file cl-lib-news in this directory.
(defpackage cl-lib
(:use common-lisp series query-p)
#+symbolics (:import-from scl
#:read-delimited-string #:add-initialization #:initializations #:delete-initialization #:reset-initializations)
#+symbolics (:shadow #:defresource #:allocate-resource #:deallocate-resource #:clear-resource #:map-resource)
(:export #:command-line-arg #:force-list #:flatten #:*cl-lib-version*
;; cl-sets.lisp
#:list-without-nulls #:cartesian-product #:cross-product
#:permutations #:powerset #:circular-list
;;;;
;;;; #:occurs
;;;;
#:firstn #:in-order-union
#:seq-butlast #:seq-last #:dosequence
#:prefix?
;; number-handling.lisp
#:between #:ordinal-string
#:bit-length #:sum-of-powers-of-two-representation
#:difference-of-powers-of-two-representation
;; strings.lisp
#:string-search-car #:string-search-cdr #:parse-with-delimiter #:parse-with-delimiters
#:parallel-substitute #:parse-with-string-delimiter
#:parse-with-string-delimiter* #:split-string #:format-justified-string #:number-to-string #:null-string
#:time-string
#:force-string #:elapsed-time-in-seconds
#:factorial #:round-to
#:extract-keyword #:truncate-keywords #:remove-keyword-arg
#:update-alist #:msetq #:mlet #:while #:while-not #:let*-non-null
#:cond-binding-predicate-to
#:mapc-dotted-list #:mapcar-dotted-list #:mapcan-dotted-list #:maplist-dotted-list
#:some-dotted-list #:every-dotted-list
#:copy-hash-table
#:defclass-x #:defflag #:defflags #:let-maybe
#:eqmemb #-MCL #:neq #:car-eq #:dremove #:displace #:tailpush
#:explode #:implode #:crush
#:listify-string #:listify
#:and-list #:or-list
#:make-variable #:variablep
#:dofile #:copy-array
#-excl #:if*
#-excl #:*keyword-package*
#+excl #:raw-read-char
#+excl #:raw-peek-char
#+excl #:raw-read-char-no-hang
#:make-plist
#:make-keyword
#:internal-real-time-in-seconds #:read-char-wait
;; reexport from query-p
#:y-or-n-p-wait #:yes-or-no-p-wait #:query
#:flags #:add-initialization #:initializations #:delete-initialization #:reset-initializations
#:*cold-initialization-list* #:*warm-initialization-list* #:*once-initialization-list*
#:*gc-initialization-list* #:*before-cold-initialization-list* #:*after-gc-initialization-list*
#:*initialization-keywords*
#:reader #:compatiblep #:convert-re-to-dfa #:clear-dfa-cache #:read-delimited-string #:mapatoms
#:reverse-alist #:fast-union #:fast-intersection
#:true-list-p #:progfoo #:foo #:mv-progfoo #:mv-foo #:with-rhyme
#:get-compiled-function-name #:fast-read-char #:fast-read-file-char
;; scheme-streams.lisp
#:scheme-delay #:scheme-delay-p #:scheme-force #:scheme-stream
#:ss-head #:ss-tail #:cons-scheme-stream #:make-scheme-stream
#:list-scheme-stream #:rlist-to-scheme-stream #:fake-scheme-delay
#:scheme-stream-p
;; better-errors.lisp
#:warn-or-error #:*general-warning-list* #:*warn-or-error-cleanup-initializations*
#:check
#:parser-error
;; resources.lisp
#:defresource #:allocate-resource #:deallocate-resource #:clear-resource #:map-resource #:with-resource
#+excl #:edit-system
#:macro-indent-rule
#:alist #:comment
#:xor #:eqv #:nand #:nor
#:load-once #:clear-load-once
;; locatives.lisp
#:locf #:location-contents #:locative-p #:locative
;; nregex.lisp
#:regex #:regex-compile
;; triangular-matrices.lisp
#:tarray #:tarray-p #:make-tarray #:make-upper-tarray #:make-lower-tarray
#:taref #:tarray-element-type #:tarray-rank #:tarray-dimension #:tarray-dimensions #:copy-tarray
#:tarray-total-size #:tarray-in-bounds-p #:increment-tarray #:upper-tarray-p #:lower-tarray-p #:full-tarray-p
;; prompt-and-read
#+clim #:popup-read-form #+clim #:popup-error #:prompt-and-read #:prompt-for
#+clim #:convert-to-presentation-type #+clim #:convert-satisfies-to-presentation-type
#+clim #:*default-presentation-type* #+clim #:clim-prompt-for #+clim #:clim-prompt-for-with-default
#:*suppress-clim*
;; string-io-streams
#:stream-input-available-p
#:string-io-stream #:string-io-stream-p #:make-string-io-stream
#:string-io-stream-mw #:string-io-stream-mw-p #:make-string-io-stream-mw
#:stream-flush-buffer
;; clos-extensions
#:make-load-form-with-all-slots #:determine-slot-readers #:determine-slot-writers #:determine-slot-initializers
#:generate-legal-slot-initargs #:*load-form-quote-p-fn*
;; syntax
#:add-syntax #:with-syntax #:set-syntax
;; queues
#:make-queue #:queue-elements #:empty-queue-p #:queue-front #:dequeue #:enqueue #:safe-dequeue
))
#+excl
(defpackage process
(:import-from mp #:*current-process*)
(:export #:with-lock #:make-lock-argument #:lock #:lock-idle-p #:interrupt #:block-process #:process-wait #:runnable-p
#:without-preemption #:without-interrupts #:process-name #:unlock
#:block-and-poll-wait-function #:block-and-poll-with-timeout #:process-run-function #:process-abort
#:make-lock #:make-process #:make-process-priority #:reset #:kill #:wakeup #:wakeup-without-test
#:*default-process-priority* #:*current-process*))
#+excl
(excl:defsystem :cl-lib
(:default-pathname "/cyc/projects/dialog/agents/lib/cl-lib/"
:pretty-name "Common Lisp Library"
)
(:module version ("cl-lib-version"))
(:module fix-allegro ("allegro-patches"))
(:module init ("initializations")
(:uses-definitions-from fix-allegro))
(:module basic-extensions ("query" "cl-extensions" "number-handling" "cl-sets" "strings" "more-extensions" "series/s" "queues" "scheme-streams")
(:uses-definitions-from fix-allegro init))
(:module clos-extensions ("clos-extensions")
(:uses-definitions-from fix-allegro init basic-extensions))
(:module more-ui ("better-errors" "prompt-and-read")
(:uses-definitions-from fix-allegro init basic-extensions clos-extensions))
(:module more-libraries ("locatives" "triangular-matrices" "syntax")
(:uses-definitions-from fix-allegro init basic-extensions clos-extensions))
(:module more-allegro ("allegro-stuff" "more-allegro")
(:uses-definitions-from fix-allegro init basic-extensions clos-extensions more-libraries))
(:module advanced-tools ("re-to-dfa" "reader" "nregex" "init-extras")
(:uses-definitions-from fix-allegro init basic-extensions clos-extensions more-allegro))
(:module resources ("resources")
(:uses-definitions-from fix-allegro init basic-extensions clos-extensions more-allegro advanced-tools))
(:module processes ("process")
(:uses-definitions-from fix-allegro init basic-extensions clos-extensions more-allegro advanced-tools))
(:module charts ("chart")
(:uses-definitions-from fix-allegro basic-extensions clos-extensions))
(:module streams ("string-io-stream")
(:uses-definitions-from fix-allegro init basic-extensions clos-extensions
more-allegro advanced-tools processes))
(:module logs "transcripts"
(:uses-definitions-from fix-allegro basic-extensions)))
#+mk-defsystem
(defsystem :cl-lib
;; these are correct for my mac
:source-pathname "Pennyfarthing:Development:MCL 2.0.1:knowledge-tools:cl-lib:"
:binary-pathname "Pennyfarthing:Development:MCL 2.0.1:knowledge-tools:cl-lib:"
:components (
(:module version
:source-pathname ""
:components ("cl-lib-version"))
(:module init
:source-pathname ""
:components ("initializations"))
(:module basic-extensions
:source-pathname ""
:components ("query" "cl-extensions" "more-extensions" #-ccl "series/s" "clos-extensions")
:depends-on (init))
(:module more-ui
:source-pathname ""
:components ("better-errors" "prompt-and-read")
:depends-on (init basic-extensions))
(:module more-libraries
:source-pathname ""
:components ("locatives" "triangular-matrices" "syntax")
:depends-on (init basic-extensions))
(:module series
:source-pathname "series"
:components ("s"))
(:module queues
:source-pathname ""
:components ("scheme-streams" "queues"))
(:module advanced-tools
:source-pathname ""
:components ("re-to-dfa" "reader" "nregex" "init-extras")
:depends-on (init basic-extensions))
(:module charts
:source-pathname ""
:components ("chart")
:depends-on (basic-extensions))
(:module resources
:source-pathname ""
:components ("resources")
:depends-on (init basic-extensions advanced-tools))))
#-(or excl mk-defsystem)
(eval-when (compile load eval)
(error "Non-allegro / mk defsystems are not currently supported. Please port and send us a copy with your implementation *features*."))
#-cl-lib
(push :cl-lib *features*) ; for portably portable code (:-)
| 12,535 | Common Lisp | .lisp | 1 | 12,534 | 12,535 | 0.601915 | Bradford-Miller/CL-LIB | 1 | 0 | 1 | LGPL-3.0 | 9/19/2024, 11:28:28 AM (Europe/Amsterdam) | a9b8343b56f979abc78554e250ae45d895e04f8d776ccc5e3faae223b0b0d1b1 | 25,898 | [
-1
] |
25,899 | old-minimal-cl-lib.lisp | Bradford-Miller_CL-LIB/archive/old-minimal-cl-lib.lisp | ;; Time-stamp: <2012-01-05 17:41:04 millerb>
;;; OBSOLETE!
;;; Note new defsystem-lispworks.lisp which has references to the new file-refactoring.
;;;
;;; New versions for other platforms should be straightforward based on that file (essentially only needs ported for the
;;; native defsystem for that platform)
;;;
;;; BWM 6/2005
(DECLAIM (OPTIMIZE (SPEED 2) (SAFETY 1) (DEBUG 1)))
;; miller - Brad Miller ([email protected]) (now [email protected])
;; Miminal version of cl-lib (for ttrains application dumping), no series, query-p, prompt-and-read, triangular matrices
;; also no process patches, reader, re-dfa, string-io-stream, init-extras
;;; For a History of recent changes, see the file cl-lib-news in this directory.
(defpackage cl-lib
(:use common-lisp)
(:export #:command-line-arg #:force-list #:flatten #:*cl-lib-version*
;; clim-extensions.lisp
#+(AND CLIM (NOT LISPWORKS))
#:frame-pane
;; cl-sets.lisp
#:list-without-nulls #:cartesian-product #:cross-product
#:permutations #:powerset #:circular-list
#:seq-butlast #:seq-last #:dosequence
#:prefix?
#:force-string #:elapsed-time-in-seconds
#:factorial #:round-to
#:extract-keyword #:truncate-keywords #:remove-keyword-arg
#:update-alist #:msetq #:mlet #:while #:while-not #:let*-non-null
#:cond-binding-predicate-to
#:mapc-dotted-list #:mapcar-dotted-list #:mapcan-dotted-list #:maplist-dotted-list
#:some-dotted-list #:every-dotted-list
#:copy-hash-table
#:defclass-x #:defflag #:defflags #:let-maybe
#:eqmemb #-MCL #:neq #:car-eq #:dremove #:displace #:tailpush
#:explode #:implode #:crush
#:listify-string #:listify
#:and-list #:or-list
#:make-variable #:variablep
#:dofile #:copy-array
#-excl #:if*
#-(or excl lispworks) #:*keyword-package*
#+excl #:raw-read-char
#+excl #:raw-peek-char
#+excl #:raw-read-char-no-hang
#:make-plist
#:make-keyword
#:internal-real-time-in-seconds #:read-char-wait
#:flags #:add-initialization #:initializations #:delete-initialization #:reset-initializations
#:*cold-initialization-list* #:*warm-initialization-list* #:*once-initialization-list*
#:*gc-initialization-list* #:*before-cold-initialization-list* #:*after-gc-initialization-list*
#:*initialization-keywords*
#:read-delimited-string #:mapatoms
#:reverse-alist #:fast-union #:fast-intersection
#:true-list-p #:progfoo #:foo #:mv-progfoo #:mv-foo #:with-rhyme
#:get-compiled-function-name #:fast-read-char #:fast-read-file-char
;; better-errors.lisp
#:warn-or-error #:*general-warning-list* #:*warn-or-error-cleanup-initializations*
#:check
#:parser-error
;; resources.lisp
#-LispWorks #:defresource
#-LispWorks #:allocate-resource
#-LispWorks #:deallocate-resource
#-LispWorks #:clear-resource
#-LispWorks #:map-resource
#-LispWorks #:with-resource
#+excl #:edit-system
#:macro-indent-rule
#:alist #:comment
#:xor #:eqv #:nand #:nor
#:load-once #:clear-load-once
;; locatives.lisp
#:locf #:location-contents #:locative-p #:locative
;; nregex.lisp
#:regex #:regex-compile
;; prompt-and-read
#+clim #:popup-read-form #+clim #:popup-error #:prompt-and-read #:prompt-for
#+clim #:convert-to-presentation-type #+clim #:convert-satisfies-to-presentation-type
#+clim #:*default-presentation-type* #+clim #:clim-prompt-for #+clim #:clim-prompt-for-with-default
#:*suppress-clim*
;; clos-extensions
#:make-load-form-with-all-slots #:determine-slot-readers #:determine-slot-writers #:determine-slot-initializers
#:generate-legal-slot-initargs #:*load-form-quote-p-fn*
;; syntax
#:add-syntax #:with-syntax #:set-syntax
;; scheme-streams
#:scheme-delay #:scheme-delay-p #:scheme-force #:scheme-stream
#:ss-head #:ss-tail #:cons-scheme-stream #:make-scheme-stream
#:list-scheme-stream #:rlist-to-scheme-stream #:fake-scheme-delay
#:scheme-stream-p #:scheme-stream-head #:scheme-stream-tail
#:scheme-stream-tail-closure-p
;; queues
#:make-queue #:queue-elements #:empty-queue-p #:queue-front #:dequeue #:enqueue #:safe-dequeue
))
#+excl
(find-package 'defsystem) ; will force auto-load
#+excl
(excl:defsystem :cl-lib
(:default-pathname "/cyc/projects/dialog/agents/lib/cl-lib/"
:pretty-name "Common Lisp Library"
)
(:module version ("cl-lib-version"))
(:module fix-allegro ("allegro-patches"))
(:module init ("initializations")
(:load-before-compile fix-allegro))
(:module basic-extensions ("cl-extensions" "cl-sets" "more-extensions" "scheme-streams" "queues" #+clim "clim-extensions")
(:load-before-compile fix-allegro init))
(:module clos-extensions ("clos-extensions")
(:load-before-compile fix-allegro init basic-extensions))
(:module more-ui ("better-errors" "prompt-and-read")
(:load-before-compile fix-allegro init basic-extensions clos-extensions))
(:module more-libraries ("locatives" "syntax")
(:load-before-compile fix-allegro init basic-extensions clos-extensions))
(:module more-allegro ("allegro-stuff")
(:load-before-compile fix-allegro init basic-extensions clos-extensions more-libraries))
(:module advanced-tools ("nregex")
(:load-before-compile fix-allegro init basic-extensions clos-extensions more-allegro))
(:module resources ("resources")
(:load-before-compile fix-allegro init basic-extensions clos-extensions more-allegro))
(:module charts ("chart")
(:load-before-compile fix-allegro basic-extensions clos-extensions))
(:module logs "transcripts"
(:load-before-compile fix-allegro basic-extensions))
)
#+mk-defsystem
(defsystem :cl-lib
;; these are correct for my mac
:source-pathname "Slaymore:Lisp:TRAINS:cl-lib:"
:binary-pathname "Slaymore:Lisp:TRAINS:cl-lib:"
:components (
(:module version
:source-pathname ""
:components ("cl-lib-version"))
(:module init
:source-pathname ""
:components ("initializations"))
(:module basic-extensions
:source-pathname ""
:components ("cl-extensions" "cl-sets" "more-extensions" "clos-extensions" "scheme-streams" "queues" #+clim "clim-extensions")
:depends-on (init))
(:module more-ui
:source-pathname ""
:components ("better-errors" "prompt-and-read")
:depends-on (init basic-extensions))
(:module more-libraries
:source-pathname ""
:components ("syntax")
:depends-on (init basic-extensions))
(:module charts
:source-pathname ""
:components ("chart")
:depends-on (basic-extensions))
(:module resources
:source-pathname ""
:components ("resources")
:depends-on (init basic-extensions))))
#+(and defsystem (not lispworks))
(clim-defsys:defsystem :cl-lib
(:default-pathname (pathname "cl-lib:")
:default-binary-pathname (pathname "cl-lib:")
#||:pretty-name "Common Lisp Library"||#
)
( "cl-lib-version")
( "initializations")
( "scheme-streams")
( "queues")
( "cl-extensions" :load-before-compile ("initializations"))
( "cl-sets" :load-before-compile ("initializations" "cl-extensions"))
( "more-extensions" :load-before-compile ("initializations" "cl-extensions" "cl-sets"))
( "MCL-mop"
:load-before-compile ("initializations" "cl-extensions" "cl-sets"))
( "MCL-CLOS"
:load-before-compile ("MCL-mop" "initializations" "cl-extensions" "cl-sets"))
( "clos-extensions"
:load-before-compile ("MCL-CLOS" "MCL-mop" "initializations" "cl-extensions" "cl-sets"))
( "better-errors"
:load-before-compile ("initializations" "cl-extensions" "cl-sets"))
( "prompt-and-read"
:load-before-compile ("initializations" "cl-extensions" "cl-sets" "better-errors"))
( "locatives"
:load-before-compile ("initializations" "cl-extensions" "cl-sets"))
( "syntax"
:load-before-compile ("initializations" "cl-extensions" "cl-sets"))
( "nregex"
:load-before-compile ("initializations" "cl-extensions" "cl-sets"))
( "resources"
:load-before-compile ("initializations" "cl-extensions" "cl-sets"))
( "chart"
:load-before-compile ("initializations" "cl-extensions" "cl-sets"))
( "transcripts"
:load-before-compile ("initializations" "cl-extensions" "cl-sets"))
( "MCL-TimeStamp"
:load-before-compile ("cl-extensions"))
#+clim ( "clim-extensions" )
)
#+lispworks
(defsystem :cl-lib
(:default-pathname #-win32 "~/Documents/Lisp/CL-LIB/"
#+win32 "C:\\Documents and Settings\\millerbw\\My Documents\\Lisp\\CL-LIB\\"
:documentation "Common Lisp Library"
)
:members(
"cl-lib-version"
"initializations"
"cl-extensions" "cl-sets" "more-extensions" "scheme-streams" "queues"
"clos-extensions"
"better-errors" "prompt-and-read"
"locatives" "syntax"
"nregex"
"chart"
"transcripts"
#+clim
"clim-extensions")
:rules (
(:in-order-to :compile :all (:requires (:load :previous)))
)
)
#-(or defsystem excl mk-defsystem lispworks)
(eval-when (compile load eval)
(error "Non-allegro / mk / clim / lispworks defsystems are not currently supported. Please port and send us a copy with your implementation *features*."))
#-cl-lib
(push :cl-lib *features*) ; for portably portable code (:-)
| 10,386 | Common Lisp | .lisp | 1 | 10,385 | 10,386 | 0.601386 | Bradford-Miller/CL-LIB | 1 | 0 | 1 | LGPL-3.0 | 9/19/2024, 11:28:28 AM (Europe/Amsterdam) | 01ffde22c3aa9298bc62633eb667df15a298f7b13b27e56616c9d3739440eeb4 | 25,899 | [
-1
] |
25,900 | defsystem-lispworks.lisp | Bradford-Miller_CL-LIB/archive/defsystem-lispworks.lisp | (in-package cl-user)
;; Time-stamp: <2012-01-30 15:42:53 gorbag>
;; CVS: $Id: defsystem-lispworks.lisp,v 1.5 2012/01/30 20:44:12 gorbag Exp $
;; This portion of CL-LIB Copyright (C) 2000-2008 Bradford W. Miller
;;
;; This library is free software; you can redistribute it and/or modify it under the terms of the GNU
;; Lesser General Public License as published by the Free Software Foundation; either version 3.0 of
;; the License, or (at your option) any later version.
;; This library 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.
;; You should have received a copy of the GNU Lesser General Public License along with this library;
;; if not, see <http://www.gnu.org/licenses/>.
#-lispworks
(eval-when (compile load eval)
(error "improper specialized defsystem file loaded."))
;; miller - Brad Miller ([email protected]) (now [email protected])
;; new fractured cl-lib, with multiple defsystems for each package. So the "right ones" can be added as needed.
(eval-when (:load-toplevel :execute)
(unless (boundp '*CL-LIB-BASE*)
(defvar *CL-LIB-BASE* (or (getenv "CL_LIB_BASE") "~/Lisp/freedev/CL-LIB/")))
(setf (logical-pathname-translations "CL-LIB")
`(("NULL;*.*.*"
,(make-pathname :host (pathname-host *cl-lib-base*)
:device (pathname-device *cl-lib-base*)
:directory (pathname-directory *cl-lib-base*)))
("**;*.*.*"
,(make-pathname :host (pathname-host *cl-lib-base*)
:device (pathname-device *cl-lib-base*)
:directory (append (pathname-directory *cl-lib-base*)
(list :wild-inferiors))))
("NULL;*.*"
,(make-pathname :host (pathname-host *cl-lib-base*)
:device (pathname-device *cl-lib-base*)
:directory (pathname-directory *cl-lib-base*)))
("**;*.*"
,(make-pathname :host (pathname-host *cl-lib-base*)
:device (pathname-device *cl-lib-base*)
:directory (append (pathname-directory *cl-lib-base*)
(list :wild-inferiors)))))))
(defun reload-cl-lib-defsystem ()
#+lispworks
(load "cl-lib:defsystem-lispworks")
#-lispworks
:dont-know-filename)
;;; For a History of recent changes, see the file cl-lib-news in this directory.
(defsystem :cl-lib-essentials
(:default-pathname "CL-LIB:functions;"
:documentation "Administrative Features of CL-LIB")
:members ("cl-lib-defpackage"
"cl-lib:packages;initializations"
"cl-lib-essentials")
:rules ((:in-order-to :compile :all (:requires (:load :previous)))))
(defsystem :cl-lib-console
(:default-pathname "CL-LIB:packages;"
:documentation "Console package for CL-LIB")
:members ((:cl-lib-essentials :type :system)
"popup-console")
:rules ((:in-order-to :compile :all (:requires (:load :previous)))))
(defsystem :cl-lib
(:default-pathname "CL-LIB:functions;"
:documentation "Collected CL-LIB Functions")
:members ((:cl-lib-essentials :type :system)
"cl-extensions"
"keywords"
"cl-list-fns"
"cl-sets"
"cl-array-fns"
"cl-map-fns"
"cl-boolean"
"clos-extensions"
"strings"
"number-handling"
"files"
#+clim
"cl-lib:compatibility;clim-extensions"
"cl-lib:null;cl-lib-version")
:rules ((:in-order-to :compile :all (:requires (:load :previous)))))
(defsystem :cl-lib-scheme-streams
(:default-pathname "CL-LIB:packages;")
:members ((:cl-lib-essentials :type :system)
"scheme-streams")
:rules ((:in-order-to :compile :all (:requires (:load :previous)))))
(defsystem :cl-lib-queues
(:default-pathname "CL-LIB:packages;")
:members ((:cl-lib-essentials :type :system)
"queues")
:rules ((:in-order-to :compile :all (:requires (:load :previous)))))
(defsystem :cl-lib-locatives
(:default-pathname "CL-LIB:packages;")
:members ((:cl-lib-essentials :type :system)
"locatives")
:rules ((:in-order-to :compile :all (:requires (:load :previous)))))
(defsystem :cl-lib-resources
(:default-pathname "CL-LIB:packages;")
:members ((:cl-lib-essentials :type :system)
"resources")
:rules ((:in-order-to :compile :all (:requires (:load :previous)))))
(defsystem :cl-lib-chart
(:default-pathname "CL-LIB:packages;")
:members ((:cl-lib-essentials :type :system)
"chart")
:rules ((:in-order-to :compile :all (:requires (:load :previous)))))
(defsystem :cl-lib-transcripts
(:default-pathname "CL-LIB:packages;")
:members ((:cl-lib-essentials :type :system)
"transcripts")
:rules ((:in-order-to :compile :all (:requires (:load :previous)))))
(defsystem :cl-lib-prompt-and-read
(:default-pathname "CL-LIB:packages;")
:members ((:cl-lib-essentials :type :system)
"prompt-and-read")
:rules ((:in-order-to :compile :all (:requires (:load :previous)))))
(defsystem :cl-lib-better-errors
(:default-pathname "CL-LIB:packages;")
:members ((:cl-lib-essentials :type :system)
"better-errors")
:rules ((:in-order-to :compile :all (:requires (:load :previous)))))
(defsystem :cl-lib-syntax
(:default-pathname "CL-LIB:packages;")
:members ((:cl-lib-essentials :type :system)
"syntax")
:rules ((:in-order-to :compile :all (:requires (:load :previous)))))
(defsystem :cl-lib-nregex
(:default-pathname "CL-LIB:packages;")
:members ((:cl-lib-essentials :type :system)
"nregex")
:rules ((:in-order-to :compile :all (:requires (:load :previous)))))
(defsystem :cl-lib-reader
(:default-pathname "CL-LIB:packages;")
:members ((:cl-lib-essentials :type :system)
"reader")
:rules ((:in-order-to :compile :all (:requires (:load :previous)))))
(defsystem :cl-lib-clos-facets
(:default-pathname "CL-LIB:packages;")
:members ((:cl-lib-essentials :type :system)
"clos-facets"
"clos-facet-defs"
;; while debugging
"clos-facets-tests")
:rules ((:in-order-to :compile :all (:requires (:load :previous)))
(:in-order-to :compile ("clos-facet-defs" "clos-facets-tests")
(:caused-by (:compile "clos-facets"))
(:requires (:load "clos-facets")))))
(defsystem :cl-lib-logic-parser
(:default-pathname "CL-LIB:packages;")
:members ((:cl-lib-essentials :type :system)
"logic-parser")
:rules ((:in-order-to :compile :all (:requires (:load :previous)))))
(defsystem :lispdoc
(:default-pathname "CL-LIB:packages;")
:members ((:cl-lib-essentials :type :system)
"lispdoc")
:rules ((:in-order-to :compile :all (:requires (:load :previous)))))
(defsystem :cl-lib-all
(:default-pathname "CL-LIB:packages;"
:documentation "Common Lisp Library (was minimal CL-LIB)")
:members ((:cl-lib-essentials :type :system)
(:cl-lib :type :system)
(:cl-lib-console :type :system)
(:cl-lib-scheme-streams :type :system)
(:cl-lib-queues :type :system)
(:cl-lib-better-errors :type :system)
(:cl-lib-prompt-and-read :type :system)
(:cl-lib-locatives :type :system)
(:cl-lib-resources :type :system)
(:cl-lib-syntax :type :system)
(:cl-lib-nregex :type :system)
(:cl-lib-chart :type :system)
(:cl-lib-transcripts :type :system)
(:cl-lib-reader :type :system)
(:cl-lib-clos-facets :type :system)
(:cl-lib-logic-parser :type :system)
(:lispdoc :type :system)))
| 8,073 | Common Lisp | .lisp | 1 | 8,071 | 8,073 | 0.596309 | Bradford-Miller/CL-LIB | 1 | 0 | 1 | LGPL-3.0 | 9/19/2024, 11:28:28 AM (Europe/Amsterdam) | 31877cd166c551dcfabbd8b26db39a2af5c84da6809ef072127c32961093f1f7 | 25,900 | [
-1
] |
25,901 | MCL-mop.lisp | Bradford-Miller_CL-LIB/archive/MCL/MCL-mop.lisp | ; Some MCL MOP examples
; Saturday October 30,1999
; Provides a few more CLOS mop capabilities to MCL. This code is highly MCL-specific.
; No warranties--use at your own risk. Please send suggestions
; and changes to [email protected]
(defmethod finalize-inheritance ((class standard-class))
(ccl::initialize-class class))
#| Don't know if these are meaningful in MCL
(defmethod finalize-inheritance ((class funcallable-standard-class))
(ccl::initialize-class class))
(defmethod finalize-inheritance ((class forward-referenced-class))
(ccl::initialize-class class))
|#
; Fails if any class in precedence list is undefined. I think that's what
; AMOP expects to happen.
(defmethod compute-class-precedence-list ((class class))
(ccl::compute-cpl class))
#| I don't know how to do this in MCL
(defmethod class-finalized-p ((class class))
nil)
|#
(defmethod class-direct-slots ((class class))
(append (class-direct-class-slots class)
(class-direct-instance-slots class)))
(defmethod class-slots ((class class))
(append (class-class-slots class)
(class-instance-slots class)))
(defun get-accessors-defined-on (class)
"Returns a list of reader and writer methods for class.
Note that this is just those defined at the level of class, not
all the accessors for all its parent classes."
(ccl::%class-get class 'ccl::accessor-methods))
(defun slot-for-accessor (method)
(ccl::method-slot-name method))
(defun methods-for-slot (slot-descriptor methods &optional (kind 'STANDARD-READER-METHOD))
"Returns members of methods list which access the given slot as the given
kind of method."
(let* ((slotname (slot-definition-name slot-descriptor))
(mymethods (reverse (remove-if #'(lambda (method)
(not (eq slotname
(slot-for-accessor method))))
methods))))
(remove-if #'(lambda (method)
(not (typep method kind)))
mymethods)))
#|
Note that you can't really write the MOP functions #'slot-definition-allocation
#'slot-definition-readers, etc. in MCL because slot defs are just lists, and they don't
know which class they came from.
|#
; These are pretty inefficient, but they illustrate how to do the job. In a real application, you'd
; probably want to refactor this functionality somewhat for better efficiency.
(defmethod mcl-slot-definition-readers ((slot cons) (class standard-class) &optional all-accessors)
(unless all-accessors
(setf all-accessors (get-accessors-defined-on class)))
(mapcar #'method-name (methods-for-slot slot all-accessors 'STANDARD-READER-METHOD)))
(defmethod mcl-slot-definition-writers ((slot cons) (class standard-class) &optional all-accessors)
(unless all-accessors
(setf all-accessors (get-accessors-defined-on class)))
(mapcar #'method-name (methods-for-slot slot all-accessors 'STANDARD-WRITER-METHOD)))
(defmethod mcl-slot-definition-accessors ((slot cons) (class standard-class) &optional all-accessors)
(unless all-accessors
(setf all-accessors (get-accessors-defined-on class)))
(intersection
(mcl-slot-definition-readers slot class all-accessors)
(mcl-slot-definition-writers slot class all-accessors)
:key #'(lambda (thing) (if (atom thing) thing (second thing))) ; account for SETF methods
))
#| These are already defined in MCL 3 and above:
slot-definition-initform
slot-definition-initfunction
slot-definition-initargs
slot-definition-type
slot-definition-name
|#
#| ; TESTS
(defclass foo ()
((slot1 :initarg :slot1 :initform 'hello :type 'fixnum :accessor slot1)
(slot2 :initarg :slot2 :initform 5 :accessor slot2)
(slot3 :initarg :slot3 :initform nil :accessor slot3 :reader another-slot3-reader :allocation :class)))
(get-accessors-defined-on (find-class 'foo))
--> (#<STANDARD-READER-METHOD SLOT1 (FOO)>
#<STANDARD-WRITER-METHOD (SETF SLOT1) (T FOO)>
#<STANDARD-READER-METHOD SLOT2 (FOO)>
#<STANDARD-WRITER-METHOD (SETF SLOT2) (T FOO)>
#<STANDARD-READER-METHOD SLOT3 (FOO)>
#<STANDARD-WRITER-METHOD (SETF SLOT3) (T FOO)>
#<STANDARD-READER-METHOD ANOTHER-SLOT3-READER (FOO)>)
(mapcar #'ccl::slot-definition-type (class-slots (find-class 'foo)))
--> (T 'FIXNUM T)
(mapcar #'ccl::slot-definition-initargs (class-slots (find-class 'foo)))
--> ((:SLOT3) (:SLOT1) (:SLOT2))
(mapcar #'ccl::slot-definition-initform (class-slots (find-class 'foo)))
--> (NIL HELLO 5)
(mapcar #'ccl::slot-definition-initfunction (class-slots (find-class 'foo)))
--> (#²COMPILED-LEXICAL-CLOSURE #xA83D356³ #²COMPILED-LEXICAL-CLOSURE #xA83D376³ #²COMPILED-LEXICAL-CLOSURE #xA83D396³)
(mcl-slot-definition-readers (first (class-slots #1=(find-class 'foo))) #1#)
--> (ANOTHER-SLOT3-READER SLOT3)
(mcl-slot-definition-writers (first (class-slots #1=(find-class 'foo))) #1#)
--> ((SETF SLOT3))
(mcl-slot-definition-accessors (first (class-slots #1=(find-class 'foo))) #1#)
--> (SLOT3)
|#
;;; still undefined!! [BWM]
;; class-default-initargs
;; class-direct-default-initargs
;; generic-function-argument-precedence-order
;; generic-function-declarations
;; generic-function-initial-methods
;; generic-function-lambda-list
;; method-lambda-list
;; slot-boundp-using-class
;; slot-definition-class
;; slot-definition-allocation
;; slot-exists-p-using-class
;; slot-makunbound-using-class
;; slot-value-using-class
| 5,457 | Common Lisp | .lisp | 1 | 5,456 | 5,457 | 0.703317 | Bradford-Miller/CL-LIB | 1 | 0 | 1 | LGPL-3.0 | 9/19/2024, 11:28:28 AM (Europe/Amsterdam) | 6f1a8feed687c99d56528ef4fd85b8e208bc8ee2481b6635c99259a9da7631ec | 25,901 | [
-1
] |
25,902 | MCL-TimeStamp.lisp | Bradford-Miller_CL-LIB/archive/MCL/MCL-TimeStamp.lisp | ;; The timestamp functionality for FRED: patterned after a similar function in elisp.
;;
;; Author: Bradford W. Miller ([email protected])
;; made part of CL-LIB 3/2/01 by [email protected]
;;;
;;; Copyright (c) 2001 by Bradford W. Miller
;;; Right of use & redistribution is granted as per the terms of the
;;; GNU LIBRARY GENERAL PUBLIC LICENCE version 2 which is incorporated here by
;;; reference.
;;;
;;; Bug reports, improvements, and feature requests should be sent
;;; to [email protected]
;;;
;;; 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 Library General Public License for more details.
;;;
;;; You should have received a copy of the Gnu Library General Public License
;;; along with this program; if not, write to the Free Software
;;; Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
;;;
;; Time-stamp: <2001-12-03 16:43:41 [email protected]>
;;
(in-package cl-user)
(defparameter *timestamp-string* ";; Time-stamp: ")
(defparameter *update-timestamp-on-save* t)
(defparameter *timestamp-default-who* "[email protected]")
(export '(*timestamp-string* *update-timestamp-on-save* *timestamp-default-who*))
(defun default-mark ()
(fred-buffer (front-fred-item)))
(defun buffer-timestamp (&optional (mark (default-mark)) (who *timestamp-default-who*))
(unless who
(setq who ""))
(cl-lib:mlet (second minute hour day month year) (get-decoded-time)
(buffer-insert-substring mark
(format nil "~A<~d-~2,'0d-~2,'0d ~2,'0D:~2,'0D:~2,'0D ~A>" *timestamp-string* year month day hour minute second who))))
(defun find-timestamp (&optional (old-mark (default-mark)))
(buffer-string-pos (make-mark old-mark 0) *timestamp-string*))
(defun replace-timestamp (timestamp-posn &optional (old-mark (default-mark)))
(let* ((delete-mark (make-mark old-mark timestamp-posn))
(delete-end (1+ (buffer-string-pos delete-mark ">"))))
(buffer-delete delete-mark timestamp-posn delete-end)
(buffer-timestamp delete-mark)
old-mark))
(defun find-and-replace-timestamp (&optional (old-mark (default-mark)))
(cl-lib:let*-non-null ((timestamp-posn (find-timestamp old-mark))
)
(replace-timestamp timestamp-posn old-mark)))
;; link them up.
(defun buffer-timestamp-i (&rest ignore)
(declare (ignore ignore))
(buffer-timestamp))
(def-fred-command (:control #\T) buffer-timestamp-i "Put a timestamp into the buffer at point. See variables *timestamp-string* and *timestamp-default-who*")
(advise buffer-write-file (when *update-timestamp-on-save*
(find-and-replace-timestamp (car arglist)))
:when :before :name :Timestamp)
| 2,914 | Common Lisp | .lisp | 1 | 2,913 | 2,914 | 0.683253 | Bradford-Miller/CL-LIB | 1 | 0 | 1 | LGPL-3.0 | 9/19/2024, 11:28:28 AM (Europe/Amsterdam) | 8306d1bb23229c525f6d1930d84bc53b94502e5af64e609f161819746d3f532c | 25,902 | [
-1
] |
25,903 | MCL-CLOS.lisp | Bradford-Miller_CL-LIB/archive/MCL/MCL-CLOS.lisp | ;; Time-stamp: <2008-05-03 13:26:47 gorbag>
;; MCL doesn't have a CLOS package. Define some MOP definitions compatible with Allegro
;; This portion of CL-LIB Copyright (C) 2001-2008 Bradford W. Miller
;;
;; This library is free software; you can redistribute it and/or modify it under the terms of the GNU
;; Lesser General Public License as published by the Free Software Foundation; either version 3.0 of
;; the License, or (at your option) any later version.
;; This library 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.
;; You should have received a copy of the GNU Lesser General Public License along with this library;
;; if not, see <http://www.gnu.org/licenses/>.
(defpackage CLOS (:use common-lisp ccl)
(:shadowing-import-from cl-user #:class-slots #:class-direct-slots)
(:export #:slot-definition-initargs #:slot-definition-name #:class-precedence-list
#:class-slots #:class-direct-slots
#:finalize-inheritance #:compute-class-precedence-list #:class-finalized-p
#:slot-for-accessor #:methods-for-slot
#:slot-definition-readers #:slot-definition-writers #:slot-definiiton-accessors
#:slot-definition-initform #:slot-definition-initfunction
#:slot-definition-initargs #:slot-definition-type #:slot-definition-name
))
(in-package clos)
;;
(defmethod slot-definition-readers (slot class &optional all-accessors)
(cl-user::mcl-slot-definition-readers slot class all-accessors))
(defmethod slot-definition-writers (slot class &optional all-accessors)
(cl-user::mcl-slot-definition-writers slot class all-accessors))
(defmethod slot-definition-accessors (slot class &optional all-accessors)
(cl-user::mcl-slot-definition-accessors slot class all-accessors))
| 1,960 | Common Lisp | .lisp | 1 | 1,959 | 1,960 | 0.731633 | Bradford-Miller/CL-LIB | 1 | 0 | 1 | LGPL-3.0 | 9/19/2024, 11:28:28 AM (Europe/Amsterdam) | c4a966e31a4c4d58b9686835bf65ba33c947f72516a2fce8f4166f8b3dd6b1ac | 25,903 | [
-1
] |
25,904 | allegro-patches.lisp | Bradford-Miller_CL-LIB/archive/allegro/allegro-patches.lisp | (in-package excl)
;; Time-stamp: <96/01/12 15:57:58 miller>
;; [email protected] 5/19/93
;; Patch to allegro source (from 4-1). Distributed with permission. See spr8367.
(defun sharp-sharp (stream chr label)
(declare (ignore chr))
(when *read-suppress* (return-from sharp-sharp nil))
(if (integerp label)
(let ((ret (gethash label sharp-sharp-alist sharp-sharp-alist))
ret1)
(if (eq ret sharp-sharp-alist)
(internal-reader-error stream "No object labelled #~S=" label)
(if (eq (setq ret1 (gethash ret sharp-equal-alist sharp-equal-alist))
sharp-equal-alist)
ret
ret1)))
(internal-reader-error stream "Non-integer label #~S#" label)))
;; something we just seem to need in case a non-development image is dumped.
;; make it easier to add macros to the lep
(eval-when (compile load eval)
(if (member "LEP" *modules* :test #'equal)
(pushnew :lep *features*)))
#+sun
(defun set-multiply-type (type)
(ecase type
(:hardware (comp::.primcall 'sys::set-multiply-type 1))
(:software (comp::.primcall 'sys::set-multiply-type 0))))
;;From: Doug Cutting <[email protected]>
;;To: [email protected]
;;Cc: [email protected]
;;Subject: Re: I/O efficiency question
;;Date: Tue, 23 Feb 1993 13:38:19 PST
;;
;;
;;If you really want to make your program burn, try the following:
;(in-package cl-lib)
;
;(defmacro fast-read-char (stream)
; #+(and allegro (version>= 4)) `(stream:stream-read-char ,stream)
; #+lucid`(lcl:fast-read-char ,stream nil :eof)
; #-(or (and allegro (version>= 4)) lucid) `(read-char ,stream nil :eof))
;
;(defmacro fast-read-file-char (stream) `(fast-read-char ,stream))
;
;#+(and allegro (version>= 4))
;(define-compiler-macro fast-read-file-char (stream)
; `(macrolet ((stream-slots (stream)
; `(the simple-vector (svref ,stream 1)))
; (stream-buffer (slots)
; `(the simple-string (svref ,slots 11)))
; (stream-buffpos (slots)
; `(the fixnum (svref ,slots 12)))
; (stream-maxbuffpos (slots)
; `(the fixnum (svref ,slots 13))))
; (declare (optimize (speed 3) (safety 0)))
; (let* ((stream ,stream)
; (slots (stream-slots stream))
; (buffpos (stream-buffpos slots))
; (maxbuffpos (stream-maxbuffpos slots)))
; (declare (fixnum buffpos maxbuffpos))
; (if (>= buffpos maxbuffpos)
; (stream:stream-read-char stream)
; (prog1 (schar (stream-buffer slots) buffpos)
; (when (= (setf (stream-buffpos slots) (the fixnum (1+ buffpos)))
; maxbuffpos)
; (setf (stream-maxbuffpos slots) 0)))))))
| 2,617 | Common Lisp | .lisp | 1 | 2,615 | 2,617 | 0.64081 | Bradford-Miller/CL-LIB | 1 | 0 | 1 | LGPL-3.0 | 9/19/2024, 11:28:28 AM (Europe/Amsterdam) | 155e82d9d31515fe006273cd61e5533aa2f12eda89ff55e326c920aae7fa0f2f | 25,904 | [
-1
] |
25,905 | allegro-stuff.lisp | Bradford-Miller_CL-LIB/archive/allegro/allegro-stuff.lisp | (in-package defsys)
;; Time-stamp: <1999-11-22 17:39:44 brad>
;; [email protected]
;; some new modules
(eval-when (compile load eval)
(export '(lisp-example-module foreign-syntax-module foreign-syntax-example-module edit-system md-lisp-example-module)))
;; lisp example - lisp code you don't want to compile but probably want to load.
(defclass lisp-example-module (lisp-module) ())
(defmethod compile-module ((module lisp-example-module) &rest keys &key &allow-other-keys)
(declare (ignore keys))
t) ; don't compile it.
(defclass foreign-syntax-mixin ()
((syntax :initform :syntax :accessor foreign-syntax)))
(defclass foreign-syntax-module (foreign-syntax-mixin lisp-module) ())
(defclass foreign-syntax-example-module (foreign-syntax-mixin lisp-example-module) ())
(defmethod load-module ((module foreign-syntax-mixin) &rest keys &key &allow-other-keys)
(declare (ignore keys))
(cl-lib:with-syntax (foreign-syntax module)
(call-next-method)))
(defmethod compile-module ((module foreign-syntax-mixin) &rest keys &key &allow-other-keys)
(declare (ignore keys))
(cl-lib:with-syntax (foreign-syntax module)
(call-next-method)))
(defmethod intermediate-pathname ((module foreign-module))
(merge-pathnames (make-pathname :type "o")
(source-pathname module)))
(defmethod product-pathname ((module foreign-module))
(merge-pathnames (make-pathname :type #+svr4 "so" #-svr4 "o")
(source-pathname module)))
(defmethod compile-module ((module c-module) &key)
;; do something like: "cc -c -o foo.o foo.c"
#-svr4
(excl:shell (concatenate 'string
"cc -c -o "
(namestring (product-pathname module))
" "
(namestring (source-pathname module))))
#+svr4
(excl:shell (concatenate 'string
"cc -K pic -DSVR4 -c -o "
(namestring (intermediate-pathname module))
" "
(namestring (source-pathname module))
"; ld -G -o "
(namestring (product-pathname module))
" "
(namestring (intermediate-pathname module))
)))
(defmethod product-pathname ((module lisp-example-module))
(source-pathname module))
;; edit system
(defun edit-system (system &key silent (include-components t))
(let (seen)
(excl:map-system system #'(lambda (module)
(unless (member module seen) ; because we might see things >1ce.
(push module seen)
(let ((source (source-pathname module)))
(unless silent
(format t "Editing source for ~A~%" source))
(ed source))))
:silent t
:include-components include-components)))
(defun release-system (system &key silent (include-components t))
(unless (typep (find-system system) 'md-system)
(return-from release-system :not-md-system))
(let (seen)
(excl:map-system system #'(lambda (module)
(unless (member module seen) ; because we might see things >1ce.
(push module seen)
(let ((source (source-pathname module)))
(when (pathname-match-p source (format nil "~A*.*" (get-developer-directory module)))
(let ((command (format nil "mv ~A ~A" (truename source) (truename (get-master-directory module)))))
(unless silent
(format t "~A~%" command))
(excl:shell command))))))
:silent t
:include-components include-components)))
;; system initializations
(cl-lib:add-initialization "init random" '(progn (if (fboundp 'tpl:setq-default)
(tpl:setq-default *random-state* (make-random-state t))
(setq *random-state* (make-random-state t)))
(format t "Initing *random-state*"))
'(:warm))
#-(and allegro-version>= (version>= 5))
(defmethod describe-object ((ht hash-table) stream)
(format stream "~&~S is a Hash-Table. It contains the following elements (key / value):~%")
(maphash #'(lambda (k v)
(format stream ",5t~S~,30t ~S~%" k v))
ht))
;; directoy from the example in the doc (16-19--16-20). Typed by [email protected]
(defclass md-system (default-system)
((master-directory :initform nil :initarg :master-directory :accessor master-directory)
(developer-directory :initform nil :initarg :developer-directory :accessor developer-directory)
(syntax :initform nil :initarg :syntax :accessor syntax)))
(defclass md-module-group (default-module-group)
((master-directory :initform nil :initarg :master-directory :accessor master-directory)
(developer-directory :initform nil :initarg :developer-directory :accessor developer-directory)
(syntax :initform nil :initarg :syntax :accessor syntax)))
(defclass md-module (lisp-module)
((master-directory :initform nil :initarg :master-directory :accessor master-directory)
(developer-directory :initform nil :initarg :developer-directory :accessor developer-directory)
(syntax :initform nil :initarg :syntax :accessor syntax)))
(defclass md-c-module (c-module)
((master-directory :initform nil :initarg :master-directory :accessor master-directory)
(developer-directory :initform nil :initarg :developer-directory :accessor developer-directory)))
(defclass md-lisp-example-module (md-module) ())
(defmethod compile-module ((module md-lisp-example-module) &rest keys &key &allow-other-keys)
(declare (ignore keys))
t) ; don't compile it.
(defmethod product-pathname ((module md-lisp-example-module))
(source-pathname module))
(defmethod get-master-directory ((system md-system))
(master-directory system))
(defmethod get-master-directory ((module-group md-module-group))
(or (master-directory module-group)
(get-master-directory (ds:parent-object module-group))))
(defmethod get-master-directory ((module md-module))
(or (master-directory module)
(get-master-directory (ds:parent-object module))))
(defmethod get-master-directory ((module md-c-module))
(or (master-directory module)
(get-master-directory (ds:parent-object module))))
(defmethod get-developer-directory ((system md-system))
(developer-directory system))
(defmethod get-developer-directory ((module-group md-module-group))
(or (developer-directory module-group)
(get-developer-directory (ds:parent-object module-group))))
(defmethod get-developer-directory ((module md-module))
(or (developer-directory module)
(get-developer-directory (ds:parent-object module))))
(defmethod get-developer-directory ((module md-c-module))
(or (developer-directory module)
(get-developer-directory (ds:parent-object module))))
(defmethod source-pathname ((module md-module))
;; if file exists in developer directory then return that,
;; else return the master directory pathname
(let* ((developer-directory (get-developer-directory module))
(master-directory (get-master-directory module))
(file-name (module-file module))
(default-file-type (default-file-type module))
(file-types sys::*source-file-types*)
(dev-pathname )
(master-pathname ))
(if developer-directory
(if default-file-type
(if (and (setq dev-pathname (merge-pathnames (pathname developer-directory)
(merge-pathnames (pathname file-name)
(make-pathname :type default-file-type))))
(probe-file dev-pathname))
(return-from source-pathname dev-pathname))
(dolist (ftype file-types)
(if (and (setq dev-pathname (merge-pathnames (pathname developer-directory)
(merge-pathnames (pathname file-name)
(make-pathname :type ftype))))
(probe-file dev-pathname))
(return-from source-pathname dev-pathname)))))
(if master-directory
(if default-file-type
(if (and (setq master-pathname (merge-pathnames (pathname master-directory)
(merge-pathnames (pathname file-name)
(make-pathname :type default-file-type))))
(probe-file master-pathname))
(return-from source-pathname master-pathname))
(dolist (ftype file-types)
(if (and (setq master-pathname (merge-pathnames (pathname master-directory)
(merge-pathnames (pathname file-name)
(make-pathname :type ftype))))
(probe-file master-pathname))
(return-from source-pathname master-pathname)))))
(call-next-method)))
(defmethod source-pathname ((module md-c-module))
;; if file exists in developer directory then return that,
;; else return the master directory pathname
(let* ((developer-directory (get-developer-directory module))
(master-directory (get-master-directory module))
(file-name (module-file module))
(default-file-type (default-file-type module))
(file-types '("c"))
(dev-pathname )
(master-pathname ))
(if developer-directory
(if default-file-type
(if (and (setq dev-pathname (merge-pathnames (pathname developer-directory)
(merge-pathnames (pathname file-name)
(make-pathname :type default-file-type))))
(probe-file dev-pathname))
(return-from source-pathname dev-pathname))
(dolist (ftype file-types)
(if (and (setq dev-pathname (merge-pathnames (pathname developer-directory)
(merge-pathnames (pathname file-name)
(make-pathname :type ftype))))
(probe-file dev-pathname))
(return-from source-pathname dev-pathname)))))
(if master-directory
(if default-file-type
(if (and (setq master-pathname (merge-pathnames (pathname master-directory)
(merge-pathnames (pathname file-name)
(make-pathname :type default-file-type))))
(probe-file master-pathname))
(return-from source-pathname master-pathname))
(dolist (ftype file-types)
(if (and (setq master-pathname (merge-pathnames (pathname master-directory)
(merge-pathnames (pathname file-name)
(make-pathname :type ftype))))
(probe-file master-pathname))
(return-from source-pathname master-pathname)))))
(call-next-method)))
(defmethod product-pathname ((module md-module))
;; always return pathname in developer directory
(let ((developer-directory (get-developer-directory module)))
(if developer-directory
(merge-pathnames (pathname developer-directory)
(merge-pathnames (pathname (module-file module))
(make-pathname
:type (typecase module
(lisp-module
excl:*fasl-default-type*)
(foreign-module
#+svr4
"so"
#-svr4
"o")
(t
nil)))))
(call-next-method))))
(defmethod product-pathname ((module md-c-module))
;; always return pathname in developer directory
(let ((developer-directory (get-developer-directory module)))
(if developer-directory
(merge-pathnames (pathname developer-directory)
(merge-pathnames (pathname (module-file module))
(make-pathname
:type (typecase module
(lisp-module
excl:*fasl-default-type*)
(foreign-module
#+svr4
"so"
#-svr4
"o")
(t
nil)))))
(call-next-method))))
(defmethod intermediate-pathname ((module md-c-module))
;; always return pathname in developer directory
(let ((developer-directory (get-developer-directory module)))
(if developer-directory
(merge-pathnames (pathname developer-directory)
(merge-pathnames (pathname (module-file module))
(make-pathname
:type (typecase module
(lisp-module
nil)
(foreign-module
"o")
(t
nil)))))
(call-next-method))))
(defmethod get-syntax ((module md-module))
(or (syntax module)
(get-syntax (ds:parent-object module))))
(defmethod get-syntax ((module md-module-group))
(or (syntax module)
(get-syntax (ds:parent-object module))))
(defmethod get-syntax ((system md-system))
(syntax system))
(defmethod compile-module ((module md-module) &rest keys &key &allow-other-keys)
(declare (ignore keys))
(cl-lib:with-syntax (get-syntax module)
(call-next-method)))
(defmethod load-module ((module md-module) &rest keys &key &allow-other-keys)
(declare (ignore keys))
(cl-lib:with-syntax (get-syntax module)
(call-next-method)))
;; This macro binds the class variables to our new classes
(defmacro md-defsystem (system-name options &body modules)
`(let ((*default-system-class* 'md-system)
(*default-module-group-class* 'md-module-group)
(*default-module-class* 'md-module))
(excl:defsystem ,system-name ,options ,@modules)))
(eval-when (:compile-toplevel :load-toplevel :eval)
(export '(md-defsystem md-c-module) (find-package 'defsys))
(import '(md-defsystem) (find-package 'cl-user))
)
(cl-lib:macro-indent-rule md-defsystem (like defsystem))
;; here is an example of defining a system with our new system options
#||
(md-defsystem :sys1 (:master-directory #P"master/"
:developer-directory #p"devel/"
:default-file-type "cl")
(:parallel "filea" "fileb"))
||#
;; attempt to fix map-system
(defvar *mapped-components* nil)
(defmethod map-system :around ((system default-system) fun
&key)
(declare (ignore fun))
(let (*mapped-components*)
(call-next-method)))
(defmethod map-module :around ((module default-module) fun &key)
(declare (ignore fun))
(unless (member module *mapped-components*)
(push module *mapped-components*)
(call-next-method)))
| 16,758 | Common Lisp | .lisp | 1 | 16,756 | 16,758 | 0.53473 | Bradford-Miller/CL-LIB | 1 | 0 | 1 | LGPL-3.0 | 9/19/2024, 11:28:28 AM (Europe/Amsterdam) | 75c011b7400ca2eb871d91750e378c86dfc0e4b64e173051f738a22757f95342 | 25,905 | [
-1
] |
25,906 | string-io-stream.lisp | Bradford-Miller_CL-LIB/archive/allegro/string-io-stream.lisp | (in-package CL-LIB)
(cl-lib:version-reporter "CL-LIB-String-io-streams" 5 0 ";; Time-stamp: <2007-05-18 11:29:41 miller>"
"CVS: $Id: string-io-stream.lisp,v 1.1.1.1 2007/11/19 17:48:12 gorbag Exp $
restructured version")
;;; ****************************************************************
;;; String I/O Streams ********************************************
;;; ****************************************************************
;;;
;;; This is the string I/O Streams package written May 1994 by
;;; Bradford W. Miller
;;; [email protected]
;;; University of Rochester, Department of Computer Science
;;; 610 CS Building, Comp Sci Dept., U. Rochester, Rochester NY 14627-0226
;;; 716-275-1118
;;; I will be glad to respond to bug reports or feature requests.
;;; (please note I am no longer at that address)
;;;
;;; This version was NOT obtained from the directory
;;; /afs/cs.cmu.edu/user/mkant/Public/Lisp-Utilities/initializations.lisp
;;; via anonymous ftp from a.gp.cs.cmu.edu. (you got it in cl-lib).
;;;
;;; Copyright (C) 1994 by Bradford W. Miller, [email protected]
;;; and the Trustees of the University of Rochester
;;; All rights reserved.
;;; Right of use & redistribution is granted as per the terms of the
;;; GNU LIBRARY GENERAL PUBLIC LICENCE version 2 which is incorporated here by
;;; reference.
;;;
;;; This library 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 Library General Public License for more details.
;;;
;;; You should have received a copy of the GNU Library General Public License
;;; along with this program; if not, write to the Free Software
;;; Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
;;;
;; this depends on the allegro process and stream stuff, but should be simple to port.
;;; A common need for streams is to act as a delay, and for IPC. This package implements a simple single-writer
;;; multiple-reader stream for characters. The producer and each consumer is expected to be in their own process,
;;; that is, have a unique binding of mp:*current-process*.
(defclass-x string-io-stream (stream:fundamental-input-stream stream:fundamental-output-stream stream:fundamental-character-stream)
((buffer :initform (make-array '(200) :fill-pointer 0 :adjustable t :element-type 'character :initial-element #\space) :type vector :accessor sios-buffer)
(objects :initform nil :type list :accessor sios-objects)
(proc-pointer-alist :initform nil :type alist :accessor sios-proc-pointer-alist)
(writer-proc :initform mp:*current-process* :reader sios-writer-proc :initarg :writer-proc)
(eof-p :initform nil :type symbol :accessor sios-eof-p))
)
(defgeneric flush-stream-buffer (stream)
(:documentation "Flush the buffer in stream, usually after a commit has occured.
Allows us to gc the stream buffers, objects, etc.
Note that anyone who starts to read or rewind stream will only see things written after
the flush."))
(defgeneric get-posn (stream))
(defmethod get-posn ((stream string-io-stream))
(cond
((verify-writer stream nil)
(fill-pointer (sios-buffer stream)))
((cdr (assoc MP:*CURRENT-PROCESS* (sios-proc-pointer-alist stream))))
;; new reader
(t
(update-alist mp:*current-process* 0 (sios-proc-pointer-alist stream))
0)))
(defsetf get-posn (stream) (new-posn)
`(unless (and (string-io-stream-mw-p ,stream)
(assoc mp:*current-process* (sios-wbufs ,stream))) ; ignore writer posn
(setf (cdr (assoc MP:*CURRENT-PROCESS* (sios-proc-pointer-alist ,stream))) ,new-posn)))
(defgeneric verify-writer (stream error-p))
(defmethod verify-writer ((stream string-io-stream) error-p)
(cond
((equal mp:*current-process* (sios-writer-proc stream)))
(error-p
(error "Attempt to write to string-io-stream by a reader proc"))))
(defgeneric stream-input-available-p (stream))
(defmethod stream-input-available-p ((stream t))
(if (interactive-stream-p stream)
(stream:stream-listen stream)
t))
(defmethod stream-input-available-p ((stream string-io-stream))
(let ((posn (get-posn stream)))
(or (sios-eof-p stream)
(< posn (fill-pointer (sios-buffer stream))))))
(defmethod stream:stream-read-char ((stream string-io-stream))
(let ((posn (get-posn stream)))
(labels ((input-available (wait-fn)
(declare (ignore wait-fn))
(stream-input-available-p stream)))
(while-not (input-available nil)
(mp:wait-for-input-available
stream
:whostate "Stream Char Wait"
:wait-function #'input-available)))
(if (>= posn (fill-pointer (sios-buffer stream))) ; must have been at :eof, else we'd still be waiting.
:eof
(prog1 (aref (sios-buffer stream) posn)
(incf (get-posn stream))))))
(defmethod stream:stream-unread-char ((stream string-io-stream) char)
(let ((posn (1- (get-posn stream))))
(unless (eql (aref (sios-buffer stream) posn) char)
(error "Attempt to unread char ~C, but last character read was ~C." char (aref (sios-buffer stream) posn)))
(setf (get-posn stream) posn)))
(defmethod stream:stream-read-char-no-hang ((stream string-io-stream))
(if (or (sios-eof-p stream)
(stream:stream-listen stream))
(stream:stream-read-char stream)))
(defmethod stream:stream-listen ((stream string-io-stream))
(< (get-posn stream) (fill-pointer (sios-buffer stream))))
(defmethod stream:stream-write-char ((stream string-io-stream) character)
(verify-writer stream t)
(vector-push-extend character (sios-buffer stream)))
(defmethod stream:stream-terpri ((stream string-io-stream))
(stream:stream-write-char stream #\newline))
(defmethod stream:stream-line-column ((stream string-io-stream))
(let* ((posn (get-posn stream))
(rel-posn 0)
(rel-ptr (1- posn)))
(cond
((zerop posn)
0)
(t
(while-not (zerop rel-ptr)
(when (eql (aref (sios-buffer stream) rel-ptr) #\newline)
(return-from stream:stream-line-column rel-posn))
(incf rel-posn)
(decf rel-ptr))
rel-posn))))
(defmethod stream:stream-start-line-p ((stream string-io-stream))
(zerop (stream:stream-line-column stream)))
(defmethod stream:stream-write-string ((stream string-io-stream) string &optional start end)
(sios-sws-internal stream string start end))
(defun sios-sws-internal (stream string start end)
(let ((start (or start 0))
(end (or end (length string))))
(verify-writer stream t)
(let* ((posn (fill-pointer (sios-buffer stream)))
(new-fill (- (+ posn end) start))
(temp start)
(needed-increase (- new-fill (array-dimension (sios-buffer stream) 0))))
(when (plusp needed-increase)
(adjust-array (sios-buffer stream) (list new-fill)
:element-type 'character))
(while (< posn new-fill)
(setf (elt (sios-buffer stream) posn) (elt string temp))
(incf posn)
(incf temp))
(setf (fill-pointer (sios-buffer stream)) posn))
string))
(defmethod stream:stream-read-line ((stream string-io-stream))
(let* ((posn (get-posn stream))
next-newline)
(labels ((input-available (wait-fn)
(declare (ignore wait-fn))
(or (sios-eof-p stream)
(setq next-newline (position #\newline (sios-buffer stream) :start posn)))))
(while-not (input-available nil)
(mp:wait-for-input-available
stream
:whostate "Stream Line Wait"
:wait-function #'input-available)))
(cond
(next-newline
(incf next-newline)
(setf (get-posn stream) next-newline)
(values (subseq (sios-buffer stream) posn next-newline) nil))
(t
(setf (get-posn stream) (fill-pointer (sios-buffer stream)))
(values (subseq (sios-buffer stream) posn) t)))))
;; eventually want to specialize these to make protocol more efficient.
;;(defmethod stream:stream-read-sequence ((stream string-io-stream) sequence &optional start end)
;; )
;;(defmethod stream:stream-write-sequence ((stream string-io-stream) sequence &optional start end)
;; )
(defmethod close ((stream string-io-stream) &key abort)
(declare (ignore abort))
(when (verify-writer stream nil)
(setf (sios-eof-p stream) t))
(call-next-method))
;; a more complete version of the above, that allows multiple writers and readers. Note that this uses a locking protocol
;; to protect the writers from each other. Two processes simultaneously writing are not guarenteed a specific output order,
;; only that each write (a string terminated with a newline) will be atomic, i.e. they won't be garbled.
;; a single process may both read and write, but should avoid reading until closing out the current record (otherwise the results
;; may not be what is expected!) Reads will always be from the last read (0 start), and writes will always
;; be to the end.
;; Note that the close protocol is such that if there are no known writers (who have not closed the stream), then the stream
;; will have an EOF mark added to the end. It is important, then, if there are to be multiple writers that some writer
;; keep the stream open until you really want it closed. write1 write2 - close1 close2 - write3 will get an error, since
;; write3 is too late, but write1 write2 - close1 - write3 - close2 would have been ok, since we'd know process 3 would
;; be a writer so the close2 doesn't really close the stream.
;; by the same token, if you close the stream, you can still read and write to it if it isn't really closed. Writing to it
;; does prevent someone else from really closing it until you close it again. Obviously this is all moot unless you are
;; using these streams for some pathological cases :-)
(defclass-x string-io-stream-mw (string-io-stream)
;; have a separate buffer for each writer.
((write-buffers :initform nil :type alist :accessor sios-wbufs))
)
(defmethod verify-writer ((stream string-io-stream-mw) error-p)
(declare (ignore error-p))
t) ; any stream can write.
(defmethod get-posn ((stream string-io-stream-mw))
(let ((current-writer (assoc mp:*current-process* (sios-wbufs stream))))
(cond
((cdr current-writer)
(fill-pointer (cdr current-writer)))
((cdr (assoc MP:*CURRENT-PROCESS* (sios-proc-pointer-alist stream))))
;; new reader
(t
(update-alist mp:*current-process* 0 (sios-proc-pointer-alist stream))
0))))
(defmethod stream:stream-write-char ((stream string-io-stream-mw) character)
(let ((current-writer (assoc mp:*current-process* (sios-wbufs stream))))
(cond
((cdr current-writer)
(vector-push-extend character (cdr current-writer)))
((eql character #\newline)
(error "Bogus empty record to string-io-stream-mw"))
(t
(update-alist mp:*current-process* (make-array '(20) :fill-pointer 1 :adjustable t :element-type 'character :initial-element character) (sios-wbufs stream))
(setf current-writer (assoc mp:*current-process* (sios-wbufs stream)))))
;; handle copying to main buffer if record done.
(if (eql character #\newline)
(process:without-preemption
(sios-sws-internal stream (cdr current-writer) 0 (fill-pointer (cdr current-writer)))
(setf (cdr current-writer) nil)))))
(defmethod stream:stream-line-column ((stream string-io-stream-mw))
(let ((current-writer (assoc mp:*current-process* (sios-wbufs stream))))
(if (cdr current-writer)
(get-posn stream) ; position in the write buffer
(call-next-method))))
(defmethod stream:stream-write-string ((stream string-io-stream-mw) string &optional start end)
;; if there are any newline characters in the string, handle specially.
(let ((current-start (or start 0))
current-newline
(end (or end (length string))))
(while (setq current-newline (position #\newline string :start current-start :end end))
(sws-internal stream string current-start current-newline)
(stream:stream-terpri stream) ; will force copy to main buffer
(setq current-start (1+ current-newline))
(if (>= current-start end)
(return-from stream:stream-write-string string)))
(if (< current-start end)
(sws-internal stream string current-start end)
string)))
(defun sws-internal (stream string start end)
(let ((current-writer (assoc mp:*current-process* (sios-wbufs stream))))
(unless (cdr current-writer)
(update-alist mp:*current-process* (make-array '(100) :fill-pointer 0 :adjustable t :element-type 'character :initial-element #\space) (sios-wbufs stream))
(setq current-writer (assoc mp:*current-process* (sios-wbufs stream))))
(unless start
(setq start 0))
(unless end
(setq end (length string)))
(let* ((posn (fill-pointer (cdr current-writer)))
(new-fill (- (+ posn end) start))
(temp start)
(needed-increase (- new-fill (array-dimension (cdr current-writer) 0))))
(when (plusp needed-increase)
(adjust-array (cdr current-writer) (list new-fill)
:element-type 'character))
(while (< posn new-fill)
(setf (elt (cdr current-writer) posn) (elt string temp))
(incf posn)
(incf temp))
(setf (fill-pointer (cdr current-writer)) posn))
string))
(defmethod close ((stream string-io-stream-mw) &key abort)
(let ((current-writer (assoc mp:*current-process* (sios-wbufs stream))))
(setf (sios-proc-pointer-alist stream) (delete-if #'(lambda (entry)
(eq (car entry) mp:*current-process*))
(sios-proc-pointer-alist stream)))
(when (cdr current-writer)
(if (and (not abort)
(plusp (fill-pointer (cdr current-writer))))
(stream:stream-terpri stream))
(setf (sios-wbufs stream) (delete-if #'(lambda (entry)
(eq (car entry) mp:*current-process*))
(sios-wbufs stream))))
(when (null (sios-wbufs stream))
(call-next-method)))) ; everyone we know was writing has closed it.
(pushnew :cl-lib-string-io-stream *features*)
| 14,530 | Common Lisp | .lisp | 1 | 14,529 | 14,530 | 0.65265 | Bradford-Miller/CL-LIB | 1 | 0 | 1 | LGPL-3.0 | 9/19/2024, 11:28:28 AM (Europe/Amsterdam) | ebc1122c9aec8578cbea6f9e1ef8cdbcbc441e715314db5bf89acb9c18fdb4f4 | 25,906 | [
-1
] |
25,907 | more-allegro.lisp | Bradford-Miller_CL-LIB/archive/allegro/more-allegro.lisp | (in-package cl-lib)
;; Time-stamp: <96/01/12 15:58:07 miller>
;; raw io
(defun raw-read-char (&optional (stream *standard-input*) &rest args)
;; copied from the example on page 14-87 of the allegro 4.1 manual.
;; raw-reading is in response to our earlier enhancement request for the FI interface.
(excl:set-terminal-characteristics stream :input-processing :cbreak)
(sleep 1) ; a hack, the above call isn't synchronous.
(unwind-protect
(handler-case
(apply #'read-char stream args)
(error (c)
(format *terminal-io* "error doing read-char from ~s: ~a" stream c)))
(excl:set-terminal-characteristics stream :input-processing :cooked)))
(defun raw-read-char-no-hang (&optional (stream *standard-input*) &rest args)
;; copied from the example on page 14-87 of the allegro 4.1 manual.
;; raw-reading is in response to our earlier enhancement request for the FI interface.
(excl:set-terminal-characteristics stream :input-processing :cbreak)
(sleep 1) ; a hack, the above call isn't synchronous.
(unwind-protect
(handler-case
(apply #'read-char-no-hang stream args)
(error (c)
(format *terminal-io* "error doing read-char-no-hang from ~s: ~a" stream c)))
(excl:set-terminal-characteristics stream :input-processing :cooked)))
(defun raw-peek-char (&optional peek-type (stream *standard-input*) &rest args)
;; adapted from the example on page 14-87 of the allegro 4.1 manual.
;; raw-reading is in response to our earlier enhancement request for the FI interface.
(excl:set-terminal-characteristics stream :input-processing :cbreak)
(sleep 1) ; a hack, the above call isn't synchronous.
(unwind-protect
(handler-case
(apply #'peek-char peek-type stream args)
(error (c)
(format *terminal-io* "error doing peek-char from ~s: ~a" stream c)))
(excl:set-terminal-characteristics stream :input-processing :cooked)))
;; install the series stuff
(add-initialization "Install Waters Series"
'(let ((*package* (find-package 'cl-lib)))
(series::install))
'(:once :now))
| 2,224 | Common Lisp | .lisp | 1 | 2,222 | 2,224 | 0.651978 | Bradford-Miller/CL-LIB | 1 | 0 | 1 | LGPL-3.0 | 9/19/2024, 11:28:28 AM (Europe/Amsterdam) | ccda0e214540f426da86fa32de68ea27ed414a16efef8ebb754de61ce2e97de9 | 25,907 | [
-1
] |
25,908 | cl-lib-tests.asd | Bradford-Miller_CL-LIB/cl-lib-tests.asd | ;; Time-stamp: <2020-01-03 17:33:02 Bradford Miller(on Aragorn.local)>
;; This portion of CL-LIB Copyright (C) 2019, 2020 Bradford W. Miller
;;
;; This library is free software; you can redistribute it and/or modify it under the terms of the GNU
;; Lesser General Public License as published by the Free Software Foundation; either version 3.0 of
;; the License, or (at your option) any later version.
;; This library 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.
;; You should have received a copy of the GNU Lesser General Public License along with this library;
;; if not, see <http://www.gnu.org/licenses/>.
;; miller - Brad Miller ([email protected])
(in-package :asdf)
(defsystem :cl-lib-tests
:depends-on (:cl-lib-all :fiveam)
:components
((:file "cl-lib-tests")
(:module "functions"
:depends-on ("cl-lib-tests")
:serial t
:components
((:file "cl-lib-function-tests")))
(:module "packages"
:depends-on ("functions" "cl-lib-tests") ; macro definition
:serial t
:components
((:file "initializations-tests" )
(:file "clos-facets-tests")))))
| 1,404 | Common Lisp | .asd | 28 | 43.178571 | 102 | 0.66618 | Bradford-Miller/CL-LIB | 1 | 0 | 1 | LGPL-3.0 | 9/19/2024, 11:28:28 AM (Europe/Amsterdam) | cf7a3905639f40478f8f518d8588660d0f5ada3077a209268a354ae2375c8b72 | 25,908 | [
-1
] |
25,909 | cl-lib-prompt-and-read.asd | Bradford-Miller_CL-LIB/cl-lib-prompt-and-read.asd | ;; Time-stamp: <2019-01-27 16:53:34 Bradford Miller(on Aragorn.local)>
;; This portion of CL-LIB Copyright (C) 2019 Bradford W. Miller
;;
;; This library is free software; you can redistribute it and/or modify it under the terms of the GNU
;; Lesser General Public License as published by the Free Software Foundation; either version 3.0 of
;; the License, or (at your option) any later version.
;; This library 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.
;; You should have received a copy of the GNU Lesser General Public License along with this library;
;; if not, see <http://www.gnu.org/licenses/>.
;; miller - Brad Miller ([email protected])
;; new fractured cl-lib, with multiple defsystems for each package. So the "right ones" can be added as needed.
(in-package :asdf)
(defsystem :cl-lib-prompt-and-read
:depends-on (:cl-lib-essentials)
:components
((:module "packages" :serial t
:components
((:file "prompt-and-read")))))
| 1,159 | Common Lisp | .asd | 20 | 55.35 | 111 | 0.74735 | Bradford-Miller/CL-LIB | 1 | 0 | 1 | LGPL-3.0 | 9/19/2024, 11:28:28 AM (Europe/Amsterdam) | 899e6b020a0cbcbef65920d0546a5ad0d1c2e8eaf1257245fd1d61f671f96997 | 25,909 | [
-1
] |
25,910 | cl-lib-chart.asd | Bradford-Miller_CL-LIB/cl-lib-chart.asd | ;; Time-stamp: <2019-01-27 16:53:47 Bradford Miller(on Aragorn.local)>
;; This portion of CL-LIB Copyright (C) 2019 Bradford W. Miller
;;
;; This library is free software; you can redistribute it and/or modify it under the terms of the GNU
;; Lesser General Public License as published by the Free Software Foundation; either version 3.0 of
;; the License, or (at your option) any later version.
;; This library 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.
;; You should have received a copy of the GNU Lesser General Public License along with this library;
;; if not, see <http://www.gnu.org/licenses/>.
;; miller - Brad Miller ([email protected])
;; new fractured cl-lib, with multiple defsystems for each package. So the "right ones" can be added as needed.
(in-package :asdf)
(defsystem :cl-lib-chart
:depends-on (:cl-lib-essentials)
:components
((:module "packages" :serial t
:components
((:file "chart")))))
| 1,139 | Common Lisp | .asd | 20 | 54.35 | 111 | 0.746403 | Bradford-Miller/CL-LIB | 1 | 0 | 1 | LGPL-3.0 | 9/19/2024, 11:28:28 AM (Europe/Amsterdam) | 448d60df540f677c51f871279f1c10ee9396c43ed4d0a3027dcc55f4217be935 | 25,910 | [
-1
] |
25,911 | cl-lib-syntax.asd | Bradford-Miller_CL-LIB/cl-lib-syntax.asd | ;; Time-stamp: <2019-01-27 17:54:33 Bradford Miller(on Aragorn.local)>
;; This portion of CL-LIB Copyright (C) 2019 Bradford W. Miller
;;
;; This library is free software; you can redistribute it and/or modify it under the terms of the GNU
;; Lesser General Public License as published by the Free Software Foundation; either version 3.0 of
;; the License, or (at your option) any later version.
;; This library 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.
;; You should have received a copy of the GNU Lesser General Public License along with this library;
;; if not, see <http://www.gnu.org/licenses/>.
;; miller - Brad Miller ([email protected])
;; new fractured cl-lib, with multiple defsystems for each package. So the "right ones" can be added as needed.
(in-package :asdf)
(defsystem :cl-lib-syntax
:depends-on (:cl-lib-essentials)
:components
((:module "packages" :serial t
:components
((:file "syntax")))))
| 1,141 | Common Lisp | .asd | 20 | 54.45 | 111 | 0.746858 | Bradford-Miller/CL-LIB | 1 | 0 | 1 | LGPL-3.0 | 9/19/2024, 11:28:28 AM (Europe/Amsterdam) | d68992d507e08cf4a0c21cd4586f8346b2301952d6dad28344903c95b8ff933b | 25,911 | [
-1
] |
25,912 | cl-lib-queues.asd | Bradford-Miller_CL-LIB/cl-lib-queues.asd | ;; Time-stamp: <2019-01-27 16:36:35 Bradford Miller(on Aragorn.local)>
;; This portion of CL-LIB Copyright (C) 2019 Bradford W. Miller
;;
;; This library is free software; you can redistribute it and/or modify it under the terms of the GNU
;; Lesser General Public License as published by the Free Software Foundation; either version 3.0 of
;; the License, or (at your option) any later version.
;; This library 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.
;; You should have received a copy of the GNU Lesser General Public License along with this library;
;; if not, see <http://www.gnu.org/licenses/>.
;; miller - Brad Miller ([email protected])
;; new fractured cl-lib, with multiple defsystems for each package. So the "right ones" can be added as needed.
(in-package :asdf)
(defsystem :cl-lib-queues
:depends-on (:cl-lib-essentials)
:components
((:module "packages" :serial t
:components
((:file "queues")))))
| 1,141 | Common Lisp | .asd | 20 | 54.45 | 111 | 0.746858 | Bradford-Miller/CL-LIB | 1 | 0 | 1 | LGPL-3.0 | 9/19/2024, 11:28:28 AM (Europe/Amsterdam) | 51e6dccd4edee1068187c7ef65711e55a4e03a21443e7a7d04712ae1a68640c9 | 25,912 | [
-1
] |
25,913 | cl-lib-scheme-streams.asd | Bradford-Miller_CL-LIB/cl-lib-scheme-streams.asd | ;; Time-stamp: <2019-01-27 16:33:19 Bradford Miller(on Aragorn.local)>
;; This portion of CL-LIB Copyright (C) 2019 Bradford W. Miller
;;
;; This library is free software; you can redistribute it and/or modify it under the terms of the GNU
;; Lesser General Public License as published by the Free Software Foundation; either version 3.0 of
;; the License, or (at your option) any later version.
;; This library 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.
;; You should have received a copy of the GNU Lesser General Public License along with this library;
;; if not, see <http://www.gnu.org/licenses/>.
;; miller - Brad Miller ([email protected])
;; new fractured cl-lib, with multiple defsystems for each package. So the "right ones" can be added as needed.
(in-package :asdf)
(defsystem :cl-lib-scheme-streams
:depends-on (:cl-lib-essentials)
:components
((:module "packages" :serial t
:components
((:file "scheme-streams")))))
| 1,157 | Common Lisp | .asd | 20 | 55.25 | 111 | 0.748673 | Bradford-Miller/CL-LIB | 1 | 0 | 1 | LGPL-3.0 | 9/19/2024, 11:28:28 AM (Europe/Amsterdam) | 502df82c4c9bd74dc38f8d7196e83401dbd0a1595449ee5c584d0ffbe90d8762 | 25,913 | [
-1
] |
25,914 | cl-lib.asd | Bradford-Miller_CL-LIB/cl-lib.asd | ;; Time-stamp: <2017-04-14 13:31:25 Brad Miller(on ubuntu-vm-on-lobotomy)>
;; This portion of CL-LIB Copyright (C) 2000-2008 Bradford W. Miller
;;
;; This library is free software; you can redistribute it and/or modify it under the terms of the GNU
;; Lesser General Public License as published by the Free Software Foundation; either version 3.0 of
;; the License, or (at your option) any later version.
;; This library 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.
;; You should have received a copy of the GNU Lesser General Public License along with this library;
;; if not, see <http://www.gnu.org/licenses/>.
;; miller - Brad Miller ([email protected]) (now [email protected])
;; new fractured cl-lib, with multiple defsystems for each package. So the "right ones" can be added as needed.
(in-package :asdf)
(defsystem :cl-lib
:depends-on (:cl-lib-essentials)
:components
((:module "functions"
:serial t
:components
((:file "keywords" )
(:file "cl-list-fns")
(:file "cl-sets")
(:file "cl-array-fns")
(:file "cl-map-fns")
(:file "cl-boolean")
;(:file "clos-extensions")
(:file "strings")
(:file "number-handling")
(:file "files")))
(:file "cl-lib-version")))
| 1,573 | Common Lisp | .asd | 31 | 42.935484 | 111 | 0.645833 | Bradford-Miller/CL-LIB | 1 | 0 | 1 | LGPL-3.0 | 9/19/2024, 11:28:28 AM (Europe/Amsterdam) | 8bfad8ac2854612bf1c1779de30fbcec43439defb59909fcdb3c57418d4d0fc3 | 25,914 | [
-1
] |
25,915 | cl-lib-better-errors.asd | Bradford-Miller_CL-LIB/cl-lib-better-errors.asd | ;; Time-stamp: <2019-01-27 16:55:37 Bradford Miller(on Aragorn.local)>
;; This portion of CL-LIB Copyright (C) 2019 Bradford W. Miller
;;
;; This library is free software; you can redistribute it and/or modify it under the terms of the GNU
;; Lesser General Public License as published by the Free Software Foundation; either version 3.0 of
;; the License, or (at your option) any later version.
;; This library 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.
;; You should have received a copy of the GNU Lesser General Public License along with this library;
;; if not, see <http://www.gnu.org/licenses/>.
;; miller - Brad Miller ([email protected])
;; new fractured cl-lib, with multiple defsystems for each package. So the "right ones" can be added as needed.
(in-package :asdf)
(defsystem :cl-lib-better-errors
:depends-on (:cl-lib-essentials)
:components
((:module "packages" :serial t
:components
((:file "better-errors")))))
| 1,155 | Common Lisp | .asd | 20 | 55.15 | 111 | 0.748227 | Bradford-Miller/CL-LIB | 1 | 0 | 1 | LGPL-3.0 | 9/19/2024, 11:28:28 AM (Europe/Amsterdam) | 8581ce2bd592d1ca8878e22ebda142f83d15616898688e759e1fbfb9c6e39ffd | 25,915 | [
-1
] |
25,916 | cl-lib-nregex.asd | Bradford-Miller_CL-LIB/cl-lib-nregex.asd | ;; Time-stamp: <2019-01-27 17:54:58 Bradford Miller(on Aragorn.local)>
;; This portion of CL-LIB Copyright (C) 2019 Bradford W. Miller
;;
;; This library is free software; you can redistribute it and/or modify it under the terms of the GNU
;; Lesser General Public License as published by the Free Software Foundation; either version 3.0 of
;; the License, or (at your option) any later version.
;; This library 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.
;; You should have received a copy of the GNU Lesser General Public License along with this library;
;; if not, see <http://www.gnu.org/licenses/>.
;; miller - Brad Miller ([email protected])
;; new fractured cl-lib, with multiple defsystems for each package. So the "right ones" can be added as needed.
(in-package :asdf)
(defsystem :cl-lib-nregex
:depends-on (:cl-lib-essentials)
:components
((:module "packages" :serial t
:components
((:file "nregex")))))
| 1,141 | Common Lisp | .asd | 20 | 54.45 | 111 | 0.746858 | Bradford-Miller/CL-LIB | 1 | 0 | 1 | LGPL-3.0 | 9/19/2024, 11:28:28 AM (Europe/Amsterdam) | 364de1e3c3230d3307bfc64e22eace4c0400eeae8a67c82155d9bdbb5eaa5449 | 25,916 | [
-1
] |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.