_id
stringlengths
64
64
repository
stringlengths
6
84
name
stringlengths
4
110
content
stringlengths
0
248k
license
null
download_url
stringlengths
89
454
language
stringclasses
7 values
comments
stringlengths
0
74.6k
code
stringlengths
0
248k
7b10a052ab378fa25c724ab085e0c1ea22cfce605b7ae1e84708fe4ef26e0983
3b/3bgl-misc
bench.lisp
(in-package #:3bgl-bench) (defclass im-bench (basecode-glut perspective-projection basecode-clear ;;fps-graph basecode-draw-ground-plane basecode-exit-on-esc freelook-camera) ((count :accessor vertex-count :initform 1)) (:default-initargs :look-at-eye '(5 12 -20))) (defparameter *points* 0) (defparameter *frames* 0) (defparameter *start-time* 0) (defun update-points (c) (let ((now (get-internal-real-time))) (when (zerop *start-time*) (setf *start-time* now *frames* 0 *points* 0)) (incf *points* c) (incf *frames* 1) (when (> (- now *start-time*) (* 2 internal-time-units-per-second)) (let ((s (/ (float (- now *start-time*)) internal-time-units-per-second))) (format t "~s frames in ~s seconds = ~s fps~%" *frames* s (/ *frames* s)) (format t "~s points per frame, ~s points in ~s seconds = ~:d pps~%" c *points* s (floor (/ *points* s))) (setf *start-time* 0))))) ;;; cffi enums are slow :/ (%gl::defglfun ("glBegin" %gl::begini) :void (mode %gl::uint)) (defmethod basecode-draw ((w im-bench)) (declare (optimize speed)) (let* ((start (get-internal-real-time)) (c (vertex-count w)) (fc (float c 1.0)) (d 1.0)) (declare (single-float fc)) (update-points (* c c d)) (loop for z single-float from 0.0 below fc for z/c = (/ z fc) do (loop for y single-float from 0.0 below fc for y/c = (/ y fc) do (gl:color z/c y/c 1.0) (%gl::begini #.(cffi:foreign-enum-value '%gl:enum :points)) (loop for x single-float from 0.0 below d for x/c = (/ x d) #+do (gl:color z/c y/c x/c) do (gl:vertex x/c y/c z/c)) (%gl:end))) #++(gl:with-primitives :points (loop with c = (float (vertex-count w) 1.0) with w = (float (expt c 1/3) 1.0) with w^2 = (float (expt w 2) 1.0) for i below c for z = (/ i w^2) for xy of-type (single-float 0.0 1000000.0) = (float (mod i w^2) 1.0) for x = (/ xy w) for y = (mod xy w) do )) #++ (let* ((end (get-internal-real-time)) (dt (/ (float (- end start)) internal-time-units-per-second))) (cond ((< dt 0.1) (setf (vertex-count w) (min 100000000 (1+ (vertex-count w))))) ((> dt 0.13) (setf (vertex-count w) (max 1 (1- (vertex-count w))))))))) (defmethod mouse-down ((w im-bench) button x y) ) (defmethod key-down ((w im-bench) k) (case k ((#\z :z) (setf (vertex-count w) 1)) ((#\q :q) (setf (vertex-count w) 636)))) #++ (basecode-run (make-instance 'im-bench))
null
https://raw.githubusercontent.com/3b/3bgl-misc/e3bf2781d603feb6b44e5c4ec20f06225648ffd9/bench/bench.lisp
lisp
fps-graph basecode-draw-ground-plane cffi enums are slow :/
(in-package #:3bgl-bench) (defclass im-bench (basecode-glut perspective-projection basecode-clear basecode-exit-on-esc freelook-camera) ((count :accessor vertex-count :initform 1)) (:default-initargs :look-at-eye '(5 12 -20))) (defparameter *points* 0) (defparameter *frames* 0) (defparameter *start-time* 0) (defun update-points (c) (let ((now (get-internal-real-time))) (when (zerop *start-time*) (setf *start-time* now *frames* 0 *points* 0)) (incf *points* c) (incf *frames* 1) (when (> (- now *start-time*) (* 2 internal-time-units-per-second)) (let ((s (/ (float (- now *start-time*)) internal-time-units-per-second))) (format t "~s frames in ~s seconds = ~s fps~%" *frames* s (/ *frames* s)) (format t "~s points per frame, ~s points in ~s seconds = ~:d pps~%" c *points* s (floor (/ *points* s))) (setf *start-time* 0))))) (%gl::defglfun ("glBegin" %gl::begini) :void (mode %gl::uint)) (defmethod basecode-draw ((w im-bench)) (declare (optimize speed)) (let* ((start (get-internal-real-time)) (c (vertex-count w)) (fc (float c 1.0)) (d 1.0)) (declare (single-float fc)) (update-points (* c c d)) (loop for z single-float from 0.0 below fc for z/c = (/ z fc) do (loop for y single-float from 0.0 below fc for y/c = (/ y fc) do (gl:color z/c y/c 1.0) (%gl::begini #.(cffi:foreign-enum-value '%gl:enum :points)) (loop for x single-float from 0.0 below d for x/c = (/ x d) #+do (gl:color z/c y/c x/c) do (gl:vertex x/c y/c z/c)) (%gl:end))) #++(gl:with-primitives :points (loop with c = (float (vertex-count w) 1.0) with w = (float (expt c 1/3) 1.0) with w^2 = (float (expt w 2) 1.0) for i below c for z = (/ i w^2) for xy of-type (single-float 0.0 1000000.0) = (float (mod i w^2) 1.0) for x = (/ xy w) for y = (mod xy w) do )) #++ (let* ((end (get-internal-real-time)) (dt (/ (float (- end start)) internal-time-units-per-second))) (cond ((< dt 0.1) (setf (vertex-count w) (min 100000000 (1+ (vertex-count w))))) ((> dt 0.13) (setf (vertex-count w) (max 1 (1- (vertex-count w))))))))) (defmethod mouse-down ((w im-bench) button x y) ) (defmethod key-down ((w im-bench) k) (case k ((#\z :z) (setf (vertex-count w) 1)) ((#\q :q) (setf (vertex-count w) 636)))) #++ (basecode-run (make-instance 'im-bench))
e9aa9dc6e556d0e2f3c5be0cef9feb02792db327f11365df3ec82d0bac79241a
commonqt/commonqt
microbench.lisp
;;;; ;;;; Evaluate ;;;; (qt::microbench) ;;;; to run these benchmarks on an otherwise idle computer. Results are ;;;; written to the REPL, and in a machine readable format also dribbled ;;;; to files. Files names are, by default, of the form <lisp ;;;; implementation type>.txt. ;;;; Notes : 1 . These are microbenchmarks meant to aid understanding of the ;;;; implementation. They do not necessarily reflect overall or ;;;; real-world performance. 2 . Since each individual operation is too fast to benchmark , we ;;;; invoke them a large number of times and compute the average run ;;;; time afterwards. 3 . Before running benchmarks , we choose a repetition time depending on how fast ( or slow ) a simple test case is , so that slow ;;;; don't waste endless time running benchmarks. 4 . Benchmarks are run three times , and only the best run of those ;;;; three is reported, to account for issues with background activity ;;;; on the computer ruining the results. 5 . But you should _ still _ run the overall benchmarks several times ;;;; and see how reproducible the numbers are. ;;;; ;;;; There's no tool to parse the output files and drawn graphs yet, but ;;;; there should be. (READ-MICROBENCH-RESULTS already fetches the raw ;;;; sexps from each file though, just to check that they are READable). (in-package :qt) (named-readtables:in-readtable :qt) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; bench ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro measure-dotimes ((var repeat) &body body) `(%measure-dotimes (lambda (,var) (declare (ignorable ,var)) ,@body) ,repeat)) (defun %measure-dotimes (fun repeat) "Call fun repeatedly without GCing, as often as specified by REPEAT. Return the average run time per repetition in microseconds." (let ((run0 (get-internal-run-time))) (#+ccl ccl::without-gcing #+sbcl sb-sys:without-gcing #-(or ccl sbcl) progn (dotimes (i repeat) (funcall fun i))) (let* ((run1 (get-internal-run-time)) (q (float (* (- run1 run0) (/ 1000000000 internal-time-units-per-second) (/ repeat))))) (if (< q 10) q (round q))))) (defparameter *repeat* 50000) (defun bench-new-qobject (&optional (repeat *repeat*)) (let ((objects (make-array repeat))) (prog1 (measure-dotimes (x repeat) (setf (elt objects x) (#_new QObject))) (iter (for object in-vector objects) (#_delete object))))) (defun bench-new-qcolor (&optional (repeat *repeat*)) (let ((objects (make-array repeat))) (prog1 (measure-dotimes (x repeat) (setf (elt objects x) (#_new QColor))) (iter (for object in-vector objects) (#_delete object))))) (defun bench-new-qcolor/3 (&optional (repeat *repeat*)) (let ((objects (make-array repeat))) (prog1 (measure-dotimes (x repeat) (setf (elt objects x) (#_new QColor #xca #xfe #xba))) (iter (for object in-vector objects) (#_delete object))))) (defun bench-new-qcolor/4 (&optional (repeat *repeat*)) (let ((objects (make-array repeat))) (prog1 (measure-dotimes (x repeat) (setf (elt objects x) (#_new QColor #xca #xfe #xba #xbe))) (iter (for object in-vector objects) (#_delete object))))) (defun bench-delete-qobject (&optional (repeat *repeat*)) (let ((objects (make-array repeat))) (dotimes (i repeat) (setf (elt objects i) (#_new QObject))) (measure-dotimes (i repeat) (#_delete (elt objects i))))) (defun bench-delete-alternating (&optional (repeat *repeat*)) (let ((objects (make-array repeat))) (dotimes (i repeat) (setf (elt objects i) (if (evenp i) (#_new QObject) (#_new QColor)))) (measure-dotimes (i repeat) (#_delete (elt objects i))))) (defun measure-on-qobjects (fun repeat) (let ((objects (make-array repeat))) (dotimes (i repeat) (setf (elt objects i) (#_new QObject))) (prog1 (measure-dotimes (i repeat) (funcall fun objects i)) (iter (for object in-vector objects) (#_delete object))))) (defun bench-call-parent (&optional (repeat *repeat*)) (measure-on-qobjects (lambda (objects i) (#_parent (elt objects i))) repeat)) (defun bench-call-setparent0 (&optional (repeat *repeat*)) (let ((x (null-qobject (find-qclass "QObject")))) (measure-on-qobjects (lambda (objects i) (#_setParent (elt objects i) x)) repeat))) (defun bench-call-setparent (&optional (repeat *repeat*)) (let ((others (make-array repeat))) (dotimes (i repeat) (setf (elt others i) (#_new QObject))) (prog1 (measure-on-qobjects (lambda (objects i) (#_setParent (elt objects i) (elt others i))) repeat) (iter (for object in-vector others) (#_delete object))))) (defun bench-interpret-new-qobject (&optional (repeat *repeat*)) (let ((objects (make-array repeat))) (prog1 (measure-dotimes (x repeat) (setf (elt objects x) (interpret-new "QObject"))) (iter (for object in-vector objects) (#_delete object))))) (defun bench-interpret-new-qcolor (&optional (repeat *repeat*)) (let ((objects (make-array repeat))) (prog1 (measure-dotimes (x repeat) (setf (elt objects x) (interpret-new "QColor"))) (iter (for object in-vector objects) (#_delete object))))) (defun bench-interpret-new-qcolor/3 (&optional (repeat *repeat*)) (let ((objects (make-array repeat))) (prog1 (measure-dotimes (x repeat) (setf (elt objects x) (interpret-new "QColor" #xca #xfe #xba))) (iter (for object in-vector objects) (#_delete object))))) (defun bench-interpret-new-qcolor/4 (&optional (repeat *repeat*)) (let ((objects (make-array repeat))) (prog1 (measure-dotimes (x repeat) (setf (elt objects x) (interpret-new "QColor" #xca #xfe #xba #xbe))) (iter (for object in-vector objects) (#_delete object))))) (defun bench-interpret-delete-qobject (&optional (repeat *repeat*)) (let ((objects (make-array repeat))) (dotimes (i repeat) (setf (elt objects i) (#_new QObject))) (measure-dotimes (i repeat) (interpret-delete (elt objects i))))) (defun bench-interpret-call-parent (&optional (repeat *repeat*)) (measure-on-qobjects (lambda (objects i) (interpret-call (elt objects i) "parent")) repeat)) (defun bench-interpret-call-setparent0 (&optional (repeat *repeat*)) (let ((x (null-qobject (find-qclass "QObject")))) (measure-on-qobjects (lambda (objects i) (interpret-call (elt objects i) "setParent" x)) repeat))) (defun bench-interpret-call-setparent (&optional (repeat *repeat*)) (let ((others (make-array repeat))) (dotimes (i repeat) (setf (elt others i) (#_new QObject))) (prog1 (measure-on-qobjects (lambda (objects i) (interpret-call (elt objects i) "setParent" (elt others i))) repeat) (iter (for object in-vector others) (#_delete object))))) (defun bench/nop (&optional (repeat *repeat*)) (measure-on-qobjects (lambda (objects i) (declare (ignore objects i))) repeat)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; cffi ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defvar <binding>) (defvar <classfn-qobject>) (defvar <classfn-qcolor>) (defvar <marg-qobject>) (defvar <marg-qobject-dtor>) (defvar <marg-qcolor>) (defvar <marg-qcolor/3>) (defvar <marg-qcolor/4>) (defvar <marg-qobject-parent>) (defvar <marg-qobject-set-parent>) (defmacro %with-stack ((var accessor size) &body body) `(cffi:with-foreign-object (,var '(:union StackItem) ,size) (macrolet ((,accessor (i slot) `(cffi:foreign-slot-value (cffi:mem-aptr ,',var '(:union StackItem) ,i) '(:union StackItem) ',slot))) ,@body))) (defmacro %call-classfn (fun arg obj stack) `(cffi:foreign-funcall-pointer ,fun () :short ,arg :pointer ,obj :pointer ,stack :void)) (defun bench-new-qobject/cffi (&optional (repeat *repeat*)) (declare (optimize speed (safety 0) (debug 0))) (let ((objects (make-array repeat))) (prog1 (%with-stack (stack item 2) (measure-dotimes (x repeat) (setf (elt objects x) (progn (%call-classfn <classfn-qobject> <marg-qobject> (cffi:null-pointer) stack) (let ((object (item 0 ptr))) (setf (item 1 ptr) <binding>) (%call-classfn <classfn-qobject> 0 object stack) object))))) (let ((class (find-qclass "QObject"))) (iter (for object in-vector objects) (#_delete (%qobject class object))))))) (defun bench-new-qcolor/cffi (&optional (repeat *repeat*)) (declare (optimize speed (safety 0) (debug 0))) (let ((objects (make-array repeat))) (prog1 (%with-stack (stack item 2) (measure-dotimes (x repeat) (setf (elt objects x) (progn (%call-classfn <classfn-qcolor> <marg-qcolor> (cffi:null-pointer) stack) (let ((object (item 0 ptr))) (setf (item 1 ptr) <binding>) (%call-classfn <classfn-qcolor> 0 object stack) object))))) (let ((class (find-qclass "QColor"))) (iter (for object in-vector objects) (#_delete (%qobject class object))))))) (defun bench-new-qcolor3/cffi (&optional (repeat *repeat*)) (declare (optimize speed (safety 0) (debug 0))) (let ((objects (make-array repeat))) (prog1 (%with-stack (stack item 4) (measure-dotimes (x repeat) (setf (elt objects x) (progn (setf (item 1 int) 1) (setf (item 2 int) 2) (setf (item 3 int) 3) (%call-classfn <classfn-qcolor> <marg-qcolor/3> (cffi:null-pointer) stack) (let ((object (item 0 ptr))) (setf (item 1 ptr) <binding>) (%call-classfn <classfn-qcolor> 0 object stack) object))))) (let ((class (find-qclass "QColor"))) (iter (for object in-vector objects) (#_delete (%qobject class object))))))) (defun bench-new-qcolor4/cffi (&optional (repeat *repeat*)) (declare (optimize speed (safety 0) (debug 0))) (let ((objects (make-array repeat))) (prog1 (%with-stack (stack item 5) (measure-dotimes (x repeat) (setf (elt objects x) (progn (setf (item 1 int) 1) (setf (item 2 int) 2) (setf (item 3 int) 3) (setf (item 4 int) 4) (%call-classfn <classfn-qcolor> <marg-qcolor/4> (cffi:null-pointer) stack) (let ((object (item 0 ptr))) (setf (item 1 ptr) <binding>) (%call-classfn <classfn-qcolor> 0 object stack) object))))) (let ((class (find-qclass "QColor"))) (iter (for object in-vector objects) (#_delete (%qobject class object))))))) (defun bench-delete-qobject/cffi (&optional (repeat *repeat*)) (let ((objects (make-array repeat))) (dotimes (i repeat) (setf (elt objects i) (qobject-pointer (#_new QObject)))) (%with-stack (stack item 1) (measure-dotimes (i repeat) (%call-classfn <classfn-qcolor> <marg-qobject-dtor> (elt objects i) stack))))) (defun bench-call-parent/cffi (&optional (repeat *repeat*)) (let ((objects (make-array repeat))) (dotimes (i repeat) (setf (elt objects i) (qobject-pointer (#_new QObject)))) (prog1 (%with-stack (stack item 1) (measure-dotimes (i repeat) (%call-classfn <classfn-qcolor> <marg-qobject-parent> (elt objects i) stack) (item 0 ptr))) (let ((class (find-qclass "QObject"))) (iter (for object in-vector objects) (#_delete (%qobject class object))))))) (defun bench-call-setparent0/cffi (&optional (repeat *repeat*)) (let ((objects (make-array repeat))) (dotimes (i repeat) (setf (elt objects i) (qobject-pointer (#_new QObject)))) (prog1 (%with-stack (stack item 2) (measure-dotimes (i repeat) (setf (item 1 ptr) (cffi:null-pointer)) (%call-classfn <classfn-qobject> <marg-qobject-set-parent> (elt objects i) stack) (item 0 ptr))) (let ((class (find-qclass "QObject"))) (iter (for object in-vector objects) (#_delete (%qobject class object))))))) (defun bench-call-setparent/cffi (&optional (repeat *repeat*)) (let ((objects (make-array repeat)) (others (make-array repeat))) (dotimes (i repeat) (setf (elt objects i) (qobject-pointer (#_new QObject))) (setf (elt others i) (qobject-pointer (#_new QObject)))) (prog1 (%with-stack (stack item 2) (measure-dotimes (i repeat) (setf (item 1 ptr) (elt others i)) (%call-classfn <classfn-qobject> <marg-qobject-set-parent> (elt objects i) stack) (item 0 ptr))) (let ((class (find-qclass "QObject"))) (iter (for object in-vector objects) (#_delete (%qobject class object))) (iter (for object in-vector others) (#_delete (%qobject class object))))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; BENCH ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun init/cffi () (setf <classfn-qobject> (qclass-trampoline-fun (find-qclass "QObject"))) (setf <classfn-qcolor> (qclass-trampoline-fun (find-qclass "QColor"))) (setf <marg-qobject> (qmethod-classfn-index (find-applicable-method (find-qclass "QObject") "QObject" nil nil))) (setf <marg-qobject-dtor> (qmethod-classfn-index (find-applicable-method (find-qclass "QObject") "~QObject" nil nil))) (setf <marg-qobject-parent> (qmethod-classfn-index (find-applicable-method (find-qclass "QObject") "parent" nil nil))) (setf <marg-qobject-set-parent> (qmethod-classfn-index (find-applicable-method (find-qclass "QObject") "setParent" (list (%qobject (find-qclass "QObject") (cffi:null-pointer))) nil))) (setf <marg-qcolor> (qmethod-classfn-index (find-applicable-method (find-qclass "QColor") "QColor" nil nil))) (setf <marg-qcolor/3> (qmethod-classfn-index (find-applicable-method (find-qclass "QColor") "QColor" '(0 0 0) nil))) (setf <marg-qcolor/4> (qmethod-classfn-index (find-applicable-method (find-qclass "QColor") "QColor" '(0 0 0 0) nil))) (setf <binding> (data-binding (data-ref 0)))) (defun commonqt-directory () (asdf:component-pathname (asdf:find-system :qt))) (defun dribble-setup-info (s) (let ((now (get-universal-time))) (format s "(:test-run :date ~A " now) (multiple-value-bind (sec min h d month y) (decode-universal-time now) (format s ";; ======== ~4,'0D-~2,'0D-~2,'0D ~2,'0D:~2,'0D:~2,'0D~%" y month d h min sec))) (format s ":commonqt ~S~%" (let* ((dir (commonqt-directory)) (.git (merge-pathnames ".git/" dir)) (ref (with-open-file (s (merge-pathnames "HEAD" .git) :if-does-not-exist nil) (and s (subseq (read-line s) 5))))) (if ref (with-open-file (s (merge-pathnames ref .git)) (subseq (read-line s) 0 8)) "4.unknown"))) (format s ":implementation ~S~%" (format nil "~A ~A" (lisp-implementation-type) (lisp-implementation-version))) (format s ":machine: ~S~%" (format nil "~A ~A ~A" (machine-type) (machine-version) (machine-instance))) (format s ":software ~S~%" (format nil "~A ~A" (software-type) (software-version)))) (defun choose-repeat-count (&optional (fun 'bench-call-parent) (seconds-for-a-test 2)) run the call - parent microbench for at least a second to estimate ;; implementation speed, then choose a good iteration count based on that. (let* ((total-time 0) (niterations 0) (1s 1e9) (good-time-for-a-test (* seconds-for-a-test 1s))) (iter (until (> total-time 1s)) (incf total-time (measure-dotimes (dummy 1) (let ((arbitrary-number 1000)) (funcall fun arbitrary-number) (incf niterations arbitrary-number))))) (ceiling (* niterations (/ good-time-for-a-test total-time))))) (defun best-of-3-funcall (fun) "Call the function three times and return the best result." (min (funcall fun) (funcall fun) (funcall fun))) (defun microbench (&optional (name (lisp-implementation-type))) (ensure-smoke :qtcore) (ensure-smoke :qtgui) (with-open-file (s (make-pathname :name name :type "bench-txt" :defaults (commonqt-directory)) :direction :output :if-does-not-exist :create :if-exists :append) (dribble-setup-info s) (let ((*standard-output* (make-broadcast-stream *standard-output* s)) (*repeat* (choose-repeat-count))) (format s ":repeat-count ~D~%" *repeat*) (init/cffi) (format s ":results (~%") (dolist (fun '(bench/nop bench-new-qobject bench-delete-qobject bench-new-qcolor bench-new-qcolor/3 bench-new-qcolor/4 bench-call-parent bench-call-setparent0 bench-call-setparent)) (format t "(~A ~30T~7D)~%" fun (best-of-3-funcall fun))) ;; give the interpreted functions their own repeat count to avoid ;; long delays: (let ((*repeat* (choose-repeat-count 'bench-interpret-call-parent))) (dolist (fun '(bench-interpret-new-qobject bench-interpret-delete-qobject bench-interpret-new-qcolor bench-interpret-new-qcolor/3 bench-interpret-new-qcolor/4 bench-interpret-call-parent bench-interpret-call-setparent0 bench-interpret-call-setparent)) (format t "(~A ~30T~6D)~%" fun (best-of-3-funcall fun)))) ;; The /CFFI tests do not benchmark CommonQt as such ; they show ;; how fast we "would" be able to run if we had "optimal" performance while still using kdebindings . The use cffi to ;; call smoke as efficiently as possible, assuming perfect type ;; information, no runtime dispatch, etc. ;; (format t ";; the following numbers are for comparison only:~%") (let ((*repeat* (choose-repeat-count 'bench-new-qcolor/cffi ;; hmm, need to force a higher repeat count...: 5))) (dolist (fun '(bench-new-qobject/cffi bench-delete-qobject/cffi bench-new-qcolor/cffi bench-new-qcolor3/cffi bench-new-qcolor4/cffi bench-call-parent/cffi bench-call-setparent0/cffi bench-call-setparent/cffi)) (format t "(~A ~30T~6D)~%" fun (best-of-3-funcall fun))))) (format s "))~%"))) (defun read-microbench-results (&optional (name (lisp-implementation-type))) (with-open-file (s (make-pathname :name name :type "bench-txt" :defaults (commonqt-directory))) (iter (for form = (read s nil)) (while form) (collect form))))
null
https://raw.githubusercontent.com/commonqt/commonqt/dffff3ee3dbd0686c85c323f579b8bbf4881e60e/test/microbench.lisp
lisp
Evaluate (qt::microbench) to run these benchmarks on an otherwise idle computer. Results are written to the REPL, and in a machine readable format also dribbled to files. Files names are, by default, of the form <lisp implementation type>.txt. implementation. They do not necessarily reflect overall or real-world performance. invoke them a large number of times and compute the average run time afterwards. don't waste endless time running benchmarks. three is reported, to account for issues with background activity on the computer ruining the results. and see how reproducible the numbers are. There's no tool to parse the output files and drawn graphs yet, but there should be. (READ-MICROBENCH-RESULTS already fetches the raw sexps from each file though, just to check that they are READable). bench cffi implementation speed, then choose a good iteration count based on that. give the interpreted functions their own repeat count to avoid long delays: they show how fast we "would" be able to run if we had "optimal" call smoke as efficiently as possible, assuming perfect type information, no runtime dispatch, etc. hmm, need to force a higher repeat count...:
Notes : 1 . These are microbenchmarks meant to aid understanding of the 2 . Since each individual operation is too fast to benchmark , we 3 . Before running benchmarks , we choose a repetition time depending on how fast ( or slow ) a simple test case is , so that slow 4 . Benchmarks are run three times , and only the best run of those 5 . But you should _ still _ run the overall benchmarks several times (in-package :qt) (named-readtables:in-readtable :qt) (defmacro measure-dotimes ((var repeat) &body body) `(%measure-dotimes (lambda (,var) (declare (ignorable ,var)) ,@body) ,repeat)) (defun %measure-dotimes (fun repeat) "Call fun repeatedly without GCing, as often as specified by REPEAT. Return the average run time per repetition in microseconds." (let ((run0 (get-internal-run-time))) (#+ccl ccl::without-gcing #+sbcl sb-sys:without-gcing #-(or ccl sbcl) progn (dotimes (i repeat) (funcall fun i))) (let* ((run1 (get-internal-run-time)) (q (float (* (- run1 run0) (/ 1000000000 internal-time-units-per-second) (/ repeat))))) (if (< q 10) q (round q))))) (defparameter *repeat* 50000) (defun bench-new-qobject (&optional (repeat *repeat*)) (let ((objects (make-array repeat))) (prog1 (measure-dotimes (x repeat) (setf (elt objects x) (#_new QObject))) (iter (for object in-vector objects) (#_delete object))))) (defun bench-new-qcolor (&optional (repeat *repeat*)) (let ((objects (make-array repeat))) (prog1 (measure-dotimes (x repeat) (setf (elt objects x) (#_new QColor))) (iter (for object in-vector objects) (#_delete object))))) (defun bench-new-qcolor/3 (&optional (repeat *repeat*)) (let ((objects (make-array repeat))) (prog1 (measure-dotimes (x repeat) (setf (elt objects x) (#_new QColor #xca #xfe #xba))) (iter (for object in-vector objects) (#_delete object))))) (defun bench-new-qcolor/4 (&optional (repeat *repeat*)) (let ((objects (make-array repeat))) (prog1 (measure-dotimes (x repeat) (setf (elt objects x) (#_new QColor #xca #xfe #xba #xbe))) (iter (for object in-vector objects) (#_delete object))))) (defun bench-delete-qobject (&optional (repeat *repeat*)) (let ((objects (make-array repeat))) (dotimes (i repeat) (setf (elt objects i) (#_new QObject))) (measure-dotimes (i repeat) (#_delete (elt objects i))))) (defun bench-delete-alternating (&optional (repeat *repeat*)) (let ((objects (make-array repeat))) (dotimes (i repeat) (setf (elt objects i) (if (evenp i) (#_new QObject) (#_new QColor)))) (measure-dotimes (i repeat) (#_delete (elt objects i))))) (defun measure-on-qobjects (fun repeat) (let ((objects (make-array repeat))) (dotimes (i repeat) (setf (elt objects i) (#_new QObject))) (prog1 (measure-dotimes (i repeat) (funcall fun objects i)) (iter (for object in-vector objects) (#_delete object))))) (defun bench-call-parent (&optional (repeat *repeat*)) (measure-on-qobjects (lambda (objects i) (#_parent (elt objects i))) repeat)) (defun bench-call-setparent0 (&optional (repeat *repeat*)) (let ((x (null-qobject (find-qclass "QObject")))) (measure-on-qobjects (lambda (objects i) (#_setParent (elt objects i) x)) repeat))) (defun bench-call-setparent (&optional (repeat *repeat*)) (let ((others (make-array repeat))) (dotimes (i repeat) (setf (elt others i) (#_new QObject))) (prog1 (measure-on-qobjects (lambda (objects i) (#_setParent (elt objects i) (elt others i))) repeat) (iter (for object in-vector others) (#_delete object))))) (defun bench-interpret-new-qobject (&optional (repeat *repeat*)) (let ((objects (make-array repeat))) (prog1 (measure-dotimes (x repeat) (setf (elt objects x) (interpret-new "QObject"))) (iter (for object in-vector objects) (#_delete object))))) (defun bench-interpret-new-qcolor (&optional (repeat *repeat*)) (let ((objects (make-array repeat))) (prog1 (measure-dotimes (x repeat) (setf (elt objects x) (interpret-new "QColor"))) (iter (for object in-vector objects) (#_delete object))))) (defun bench-interpret-new-qcolor/3 (&optional (repeat *repeat*)) (let ((objects (make-array repeat))) (prog1 (measure-dotimes (x repeat) (setf (elt objects x) (interpret-new "QColor" #xca #xfe #xba))) (iter (for object in-vector objects) (#_delete object))))) (defun bench-interpret-new-qcolor/4 (&optional (repeat *repeat*)) (let ((objects (make-array repeat))) (prog1 (measure-dotimes (x repeat) (setf (elt objects x) (interpret-new "QColor" #xca #xfe #xba #xbe))) (iter (for object in-vector objects) (#_delete object))))) (defun bench-interpret-delete-qobject (&optional (repeat *repeat*)) (let ((objects (make-array repeat))) (dotimes (i repeat) (setf (elt objects i) (#_new QObject))) (measure-dotimes (i repeat) (interpret-delete (elt objects i))))) (defun bench-interpret-call-parent (&optional (repeat *repeat*)) (measure-on-qobjects (lambda (objects i) (interpret-call (elt objects i) "parent")) repeat)) (defun bench-interpret-call-setparent0 (&optional (repeat *repeat*)) (let ((x (null-qobject (find-qclass "QObject")))) (measure-on-qobjects (lambda (objects i) (interpret-call (elt objects i) "setParent" x)) repeat))) (defun bench-interpret-call-setparent (&optional (repeat *repeat*)) (let ((others (make-array repeat))) (dotimes (i repeat) (setf (elt others i) (#_new QObject))) (prog1 (measure-on-qobjects (lambda (objects i) (interpret-call (elt objects i) "setParent" (elt others i))) repeat) (iter (for object in-vector others) (#_delete object))))) (defun bench/nop (&optional (repeat *repeat*)) (measure-on-qobjects (lambda (objects i) (declare (ignore objects i))) repeat)) (defvar <binding>) (defvar <classfn-qobject>) (defvar <classfn-qcolor>) (defvar <marg-qobject>) (defvar <marg-qobject-dtor>) (defvar <marg-qcolor>) (defvar <marg-qcolor/3>) (defvar <marg-qcolor/4>) (defvar <marg-qobject-parent>) (defvar <marg-qobject-set-parent>) (defmacro %with-stack ((var accessor size) &body body) `(cffi:with-foreign-object (,var '(:union StackItem) ,size) (macrolet ((,accessor (i slot) `(cffi:foreign-slot-value (cffi:mem-aptr ,',var '(:union StackItem) ,i) '(:union StackItem) ',slot))) ,@body))) (defmacro %call-classfn (fun arg obj stack) `(cffi:foreign-funcall-pointer ,fun () :short ,arg :pointer ,obj :pointer ,stack :void)) (defun bench-new-qobject/cffi (&optional (repeat *repeat*)) (declare (optimize speed (safety 0) (debug 0))) (let ((objects (make-array repeat))) (prog1 (%with-stack (stack item 2) (measure-dotimes (x repeat) (setf (elt objects x) (progn (%call-classfn <classfn-qobject> <marg-qobject> (cffi:null-pointer) stack) (let ((object (item 0 ptr))) (setf (item 1 ptr) <binding>) (%call-classfn <classfn-qobject> 0 object stack) object))))) (let ((class (find-qclass "QObject"))) (iter (for object in-vector objects) (#_delete (%qobject class object))))))) (defun bench-new-qcolor/cffi (&optional (repeat *repeat*)) (declare (optimize speed (safety 0) (debug 0))) (let ((objects (make-array repeat))) (prog1 (%with-stack (stack item 2) (measure-dotimes (x repeat) (setf (elt objects x) (progn (%call-classfn <classfn-qcolor> <marg-qcolor> (cffi:null-pointer) stack) (let ((object (item 0 ptr))) (setf (item 1 ptr) <binding>) (%call-classfn <classfn-qcolor> 0 object stack) object))))) (let ((class (find-qclass "QColor"))) (iter (for object in-vector objects) (#_delete (%qobject class object))))))) (defun bench-new-qcolor3/cffi (&optional (repeat *repeat*)) (declare (optimize speed (safety 0) (debug 0))) (let ((objects (make-array repeat))) (prog1 (%with-stack (stack item 4) (measure-dotimes (x repeat) (setf (elt objects x) (progn (setf (item 1 int) 1) (setf (item 2 int) 2) (setf (item 3 int) 3) (%call-classfn <classfn-qcolor> <marg-qcolor/3> (cffi:null-pointer) stack) (let ((object (item 0 ptr))) (setf (item 1 ptr) <binding>) (%call-classfn <classfn-qcolor> 0 object stack) object))))) (let ((class (find-qclass "QColor"))) (iter (for object in-vector objects) (#_delete (%qobject class object))))))) (defun bench-new-qcolor4/cffi (&optional (repeat *repeat*)) (declare (optimize speed (safety 0) (debug 0))) (let ((objects (make-array repeat))) (prog1 (%with-stack (stack item 5) (measure-dotimes (x repeat) (setf (elt objects x) (progn (setf (item 1 int) 1) (setf (item 2 int) 2) (setf (item 3 int) 3) (setf (item 4 int) 4) (%call-classfn <classfn-qcolor> <marg-qcolor/4> (cffi:null-pointer) stack) (let ((object (item 0 ptr))) (setf (item 1 ptr) <binding>) (%call-classfn <classfn-qcolor> 0 object stack) object))))) (let ((class (find-qclass "QColor"))) (iter (for object in-vector objects) (#_delete (%qobject class object))))))) (defun bench-delete-qobject/cffi (&optional (repeat *repeat*)) (let ((objects (make-array repeat))) (dotimes (i repeat) (setf (elt objects i) (qobject-pointer (#_new QObject)))) (%with-stack (stack item 1) (measure-dotimes (i repeat) (%call-classfn <classfn-qcolor> <marg-qobject-dtor> (elt objects i) stack))))) (defun bench-call-parent/cffi (&optional (repeat *repeat*)) (let ((objects (make-array repeat))) (dotimes (i repeat) (setf (elt objects i) (qobject-pointer (#_new QObject)))) (prog1 (%with-stack (stack item 1) (measure-dotimes (i repeat) (%call-classfn <classfn-qcolor> <marg-qobject-parent> (elt objects i) stack) (item 0 ptr))) (let ((class (find-qclass "QObject"))) (iter (for object in-vector objects) (#_delete (%qobject class object))))))) (defun bench-call-setparent0/cffi (&optional (repeat *repeat*)) (let ((objects (make-array repeat))) (dotimes (i repeat) (setf (elt objects i) (qobject-pointer (#_new QObject)))) (prog1 (%with-stack (stack item 2) (measure-dotimes (i repeat) (setf (item 1 ptr) (cffi:null-pointer)) (%call-classfn <classfn-qobject> <marg-qobject-set-parent> (elt objects i) stack) (item 0 ptr))) (let ((class (find-qclass "QObject"))) (iter (for object in-vector objects) (#_delete (%qobject class object))))))) (defun bench-call-setparent/cffi (&optional (repeat *repeat*)) (let ((objects (make-array repeat)) (others (make-array repeat))) (dotimes (i repeat) (setf (elt objects i) (qobject-pointer (#_new QObject))) (setf (elt others i) (qobject-pointer (#_new QObject)))) (prog1 (%with-stack (stack item 2) (measure-dotimes (i repeat) (setf (item 1 ptr) (elt others i)) (%call-classfn <classfn-qobject> <marg-qobject-set-parent> (elt objects i) stack) (item 0 ptr))) (let ((class (find-qclass "QObject"))) (iter (for object in-vector objects) (#_delete (%qobject class object))) (iter (for object in-vector others) (#_delete (%qobject class object))))))) BENCH (defun init/cffi () (setf <classfn-qobject> (qclass-trampoline-fun (find-qclass "QObject"))) (setf <classfn-qcolor> (qclass-trampoline-fun (find-qclass "QColor"))) (setf <marg-qobject> (qmethod-classfn-index (find-applicable-method (find-qclass "QObject") "QObject" nil nil))) (setf <marg-qobject-dtor> (qmethod-classfn-index (find-applicable-method (find-qclass "QObject") "~QObject" nil nil))) (setf <marg-qobject-parent> (qmethod-classfn-index (find-applicable-method (find-qclass "QObject") "parent" nil nil))) (setf <marg-qobject-set-parent> (qmethod-classfn-index (find-applicable-method (find-qclass "QObject") "setParent" (list (%qobject (find-qclass "QObject") (cffi:null-pointer))) nil))) (setf <marg-qcolor> (qmethod-classfn-index (find-applicable-method (find-qclass "QColor") "QColor" nil nil))) (setf <marg-qcolor/3> (qmethod-classfn-index (find-applicable-method (find-qclass "QColor") "QColor" '(0 0 0) nil))) (setf <marg-qcolor/4> (qmethod-classfn-index (find-applicable-method (find-qclass "QColor") "QColor" '(0 0 0 0) nil))) (setf <binding> (data-binding (data-ref 0)))) (defun commonqt-directory () (asdf:component-pathname (asdf:find-system :qt))) (defun dribble-setup-info (s) (let ((now (get-universal-time))) (format s "(:test-run :date ~A " now) (multiple-value-bind (sec min h d month y) (decode-universal-time now) (format s ";; ======== ~4,'0D-~2,'0D-~2,'0D ~2,'0D:~2,'0D:~2,'0D~%" y month d h min sec))) (format s ":commonqt ~S~%" (let* ((dir (commonqt-directory)) (.git (merge-pathnames ".git/" dir)) (ref (with-open-file (s (merge-pathnames "HEAD" .git) :if-does-not-exist nil) (and s (subseq (read-line s) 5))))) (if ref (with-open-file (s (merge-pathnames ref .git)) (subseq (read-line s) 0 8)) "4.unknown"))) (format s ":implementation ~S~%" (format nil "~A ~A" (lisp-implementation-type) (lisp-implementation-version))) (format s ":machine: ~S~%" (format nil "~A ~A ~A" (machine-type) (machine-version) (machine-instance))) (format s ":software ~S~%" (format nil "~A ~A" (software-type) (software-version)))) (defun choose-repeat-count (&optional (fun 'bench-call-parent) (seconds-for-a-test 2)) run the call - parent microbench for at least a second to estimate (let* ((total-time 0) (niterations 0) (1s 1e9) (good-time-for-a-test (* seconds-for-a-test 1s))) (iter (until (> total-time 1s)) (incf total-time (measure-dotimes (dummy 1) (let ((arbitrary-number 1000)) (funcall fun arbitrary-number) (incf niterations arbitrary-number))))) (ceiling (* niterations (/ good-time-for-a-test total-time))))) (defun best-of-3-funcall (fun) "Call the function three times and return the best result." (min (funcall fun) (funcall fun) (funcall fun))) (defun microbench (&optional (name (lisp-implementation-type))) (ensure-smoke :qtcore) (ensure-smoke :qtgui) (with-open-file (s (make-pathname :name name :type "bench-txt" :defaults (commonqt-directory)) :direction :output :if-does-not-exist :create :if-exists :append) (dribble-setup-info s) (let ((*standard-output* (make-broadcast-stream *standard-output* s)) (*repeat* (choose-repeat-count))) (format s ":repeat-count ~D~%" *repeat*) (init/cffi) (format s ":results (~%") (dolist (fun '(bench/nop bench-new-qobject bench-delete-qobject bench-new-qcolor bench-new-qcolor/3 bench-new-qcolor/4 bench-call-parent bench-call-setparent0 bench-call-setparent)) (format t "(~A ~30T~7D)~%" fun (best-of-3-funcall fun))) (let ((*repeat* (choose-repeat-count 'bench-interpret-call-parent))) (dolist (fun '(bench-interpret-new-qobject bench-interpret-delete-qobject bench-interpret-new-qcolor bench-interpret-new-qcolor/3 bench-interpret-new-qcolor/4 bench-interpret-call-parent bench-interpret-call-setparent0 bench-interpret-call-setparent)) (format t "(~A ~30T~6D)~%" fun (best-of-3-funcall fun)))) performance while still using kdebindings . The use cffi to (format t ";; the following numbers are for comparison only:~%") (let ((*repeat* (choose-repeat-count 'bench-new-qcolor/cffi 5))) (dolist (fun '(bench-new-qobject/cffi bench-delete-qobject/cffi bench-new-qcolor/cffi bench-new-qcolor3/cffi bench-new-qcolor4/cffi bench-call-parent/cffi bench-call-setparent0/cffi bench-call-setparent/cffi)) (format t "(~A ~30T~6D)~%" fun (best-of-3-funcall fun))))) (format s "))~%"))) (defun read-microbench-results (&optional (name (lisp-implementation-type))) (with-open-file (s (make-pathname :name name :type "bench-txt" :defaults (commonqt-directory))) (iter (for form = (read s nil)) (while form) (collect form))))
5f370f4344dcc86cdfe8d16692670f8cd4ea2751b7466411fa3d12e27851f204
lowasser/TrieMap
OrdMap.hs
# LANGUAGE CPP # {-# OPTIONS -funbox-strict-fields #-} module Data.TrieMap.OrdMap () where import Data.TrieMap.TrieKey import Data.TrieMap.OrdMap.Base import Data.TrieMap.OrdMap.Alternatable () import Data.TrieMap.OrdMap.Searchable () import Data.TrieMap.OrdMap.Indexable () import Data.TrieMap.OrdMap.Traversable () import Data.TrieMap.OrdMap.Subset () import Data.TrieMap.OrdMap.SetOp () import Data.TrieMap.OrdMap.Projection () import Data.TrieMap.OrdMap.Splittable () import Data.TrieMap.OrdMap.Buildable () #define TIP SNode{node = Tip} #define BIN(args) SNode{node = (Bin args)} -- | @'TrieMap' ('Ordered' k) a@ is based on "Data.Map". instance Ord k => TrieKey (Ordered k) where getSimpleM (OrdMap m) = case m of TIP -> Null BIN(_ a TIP TIP) -> Singleton a _ -> NonSimple sizeM (OrdMap m) = sz m unifierM (Ord k') (Ord k) a = case compare k' k of EQ -> mzero LT -> return $ Hole $ Empty k' (LeftBin k a Root tip) GT -> return $ Hole $ Empty k' (RightBin k a tip Root) unifyM (Ord k1) a1 (Ord k2) a2 = case compare k1 k2 of EQ -> mzero LT -> return $ OrdMap $ bin k1 a1 tip (singleton k2 a2) GT -> return $ OrdMap $ bin k1 a1 (singleton k2 a2) tip
null
https://raw.githubusercontent.com/lowasser/TrieMap/1ab52b8d83469974a629f2aa577a85de3f9e867a/Data/TrieMap/OrdMap.hs
haskell
# OPTIONS -funbox-strict-fields # | @'TrieMap' ('Ordered' k) a@ is based on "Data.Map".
# LANGUAGE CPP # module Data.TrieMap.OrdMap () where import Data.TrieMap.TrieKey import Data.TrieMap.OrdMap.Base import Data.TrieMap.OrdMap.Alternatable () import Data.TrieMap.OrdMap.Searchable () import Data.TrieMap.OrdMap.Indexable () import Data.TrieMap.OrdMap.Traversable () import Data.TrieMap.OrdMap.Subset () import Data.TrieMap.OrdMap.SetOp () import Data.TrieMap.OrdMap.Projection () import Data.TrieMap.OrdMap.Splittable () import Data.TrieMap.OrdMap.Buildable () #define TIP SNode{node = Tip} #define BIN(args) SNode{node = (Bin args)} instance Ord k => TrieKey (Ordered k) where getSimpleM (OrdMap m) = case m of TIP -> Null BIN(_ a TIP TIP) -> Singleton a _ -> NonSimple sizeM (OrdMap m) = sz m unifierM (Ord k') (Ord k) a = case compare k' k of EQ -> mzero LT -> return $ Hole $ Empty k' (LeftBin k a Root tip) GT -> return $ Hole $ Empty k' (RightBin k a tip Root) unifyM (Ord k1) a1 (Ord k2) a2 = case compare k1 k2 of EQ -> mzero LT -> return $ OrdMap $ bin k1 a1 tip (singleton k2 a2) GT -> return $ OrdMap $ bin k1 a1 (singleton k2 a2) tip
5d084af4183e6efaeb786fee8f8567b0129342b353512732c8f736ea8db61012
WormBase/wormbase_rest
core.clj
(ns rest-api.classes.protein.core (:require [clojure.string :as str] [datomic.api :as d] [clojure.math.numeric-tower :as math] [rest-api.db.main :refer [datomic-homology-conn datomic-conn]] [rest-api.formatters.object :as obj :refer [pack-obj]])) (defn ** [x n] (reduce * (repeat n x))) (defn get-motif-details [p] (let [hdb (d/db datomic-homology-conn) db (d/db datomic-conn)] (some->> (d/q '[:find ?m ?l :in $ $hdb ?pid :where [$hdb ?hp :protein/id ?pid] [$hdb ?l :locatable/parent ?hp] [$hdb ?l :homology/motif ?hm] [$hdb ?hm :motif/id ?mid] [$ ?m :motif/id ?mid]] db hdb (:protein/id p)) (map (fn [ids] (let [motif (d/entity db (first ids)) locatable (d/entity hdb (second ids))] {:source {:id (let [mid (:motif/id motif)] (if (str/includes? mid ":") (second (str/split mid #":")) mid)) :db (or (some->> (:motif/database motif) (map :motif.database/database) (map :database/id) (first)) (->> locatable :locatable/method :method/id))} :start (when-let [lmin (:locatable/min locatable)] (+ 1 lmin)) :stop (:locatable/max locatable) :feat (let [motif-obj (pack-obj motif)] (conj motif-obj {:label (:id motif-obj)})) :desc (or (first (:motif/title motif)) (:motif/id motif)) :score (:locatable/score locatable)})))))) (defn get-best-blastp-matches [p] (let [db-homology (d/db datomic-homology-conn) db (d/db datomic-conn) plength (->> p :protein/peptide :protein.peptide/length)] (some->> (d/q '[:find [?h ...] :in $hdb ?pid :where [$hdb ?e :protein/id ?pid] [$hdb ?h :homology/protein ?e]] db-homology (:protein/id p)) (map (fn [id] (let [obj (d/entity db-homology id) homologous-protein-id (some->> (:locatable/parent obj) (:protein/id)) homologous-protein (some->> (d/q '[:find [?p ...] :in $db ?pid :where [$db ?p :protein/id ?pid]] db homologous-protein-id) (first) (d/entity db))] (when (not (str/starts-with? homologous-protein-id "MSP")) ; skip mass-spec results (when-let [score (:locatable/score obj)] {:id (str/join "-" [(->> homologous-protein :protein/species :species/id) homologous-protein-id (:locatable/max obj) (:locatable/min obj) (:homology/max obj) (:homology/min obj) (:locatable/score obj)]) :hit (when-let [obj (pack-obj homologous-protein)] (conj obj {:label (:id obj)})) :method (->> obj :locatable/method :method/id) :evalue (let [evalue-str (format "%7.0e" (/ 1 (math/expt 10 score)))] (if (= evalue-str " 0e+00") " 0" evalue-str)) :description (or (:protein/description homologous-protein) (first (:protein/gene-name homologous-protein))) :percent (if (and (:locatable/min obj) (:locatable/max obj)) (let [hlength (- (:homology/max obj) (:homology/min obj)) percentage (/ hlength plength)] (format "%.1f" (double (* 100 percentage))))) :taxonomy (if-let [species-id (->> homologous-protein :protein/species :species/id)] (let [[genus species] (str/split species-id #" ")] {:genus (first genus) :species species})) :score (:locatable/score obj) :species (->> homologous-protein :protein/species :species/id)}))))) (remove nil?) (group-by :id) (vals) (map first) (map (fn [obj] (dissoc obj :id))) (group-by :method) (map (fn [method-group] (let [max-hit (apply max-key :score (second method-group))] (dissoc max-hit :score :species :method))))))) (defn- homology-type-to-string [group] (cond (contains? group :homology-type/cog) "COG" (contains? group :homology-type/eunog) "euNOG" (contains? group :homology-type/fog) "FOG" (contains? group :homology-type/id) (:homology-type/id group) (contains? group :homology-type/kog) "KOG" (contains? group :homology-type/lse) "LSE" (contains? group :homology-type/menog) "meNOG" (contains? group :homology-type/nog) "NOG" (contains? group :homology-type/twog) "TWOG" :else "")) (defn get-homology-groups [p] (some->> (:homology-group/_protein p) (map (fn [g] {:title (first (:homology-group/title g)) :type (if (contains? g :homology-group/orthomcl-group) "OrthoMCL_group" (if (contains? g :homology-group/inparanoid_group) "InParanoid_group" (let [firstpart (if (contains? g :homology-group/eggnog-code) "eggNOG" (when (contains? g :homology-group/cog-code) "COG")) secondpart (homology-type-to-string (if (= firstpart "eggNOG") (:homology-group/eggnog-type g) (:homology-group/cog-type g)))] (str firstpart ":" secondpart)))) :id (pack-obj g)}))))
null
https://raw.githubusercontent.com/WormBase/wormbase_rest/e51026f35b87d96260b62ddb5458a81ee911bf3a/src/rest_api/classes/protein/core.clj
clojure
skip mass-spec results
(ns rest-api.classes.protein.core (:require [clojure.string :as str] [datomic.api :as d] [clojure.math.numeric-tower :as math] [rest-api.db.main :refer [datomic-homology-conn datomic-conn]] [rest-api.formatters.object :as obj :refer [pack-obj]])) (defn ** [x n] (reduce * (repeat n x))) (defn get-motif-details [p] (let [hdb (d/db datomic-homology-conn) db (d/db datomic-conn)] (some->> (d/q '[:find ?m ?l :in $ $hdb ?pid :where [$hdb ?hp :protein/id ?pid] [$hdb ?l :locatable/parent ?hp] [$hdb ?l :homology/motif ?hm] [$hdb ?hm :motif/id ?mid] [$ ?m :motif/id ?mid]] db hdb (:protein/id p)) (map (fn [ids] (let [motif (d/entity db (first ids)) locatable (d/entity hdb (second ids))] {:source {:id (let [mid (:motif/id motif)] (if (str/includes? mid ":") (second (str/split mid #":")) mid)) :db (or (some->> (:motif/database motif) (map :motif.database/database) (map :database/id) (first)) (->> locatable :locatable/method :method/id))} :start (when-let [lmin (:locatable/min locatable)] (+ 1 lmin)) :stop (:locatable/max locatable) :feat (let [motif-obj (pack-obj motif)] (conj motif-obj {:label (:id motif-obj)})) :desc (or (first (:motif/title motif)) (:motif/id motif)) :score (:locatable/score locatable)})))))) (defn get-best-blastp-matches [p] (let [db-homology (d/db datomic-homology-conn) db (d/db datomic-conn) plength (->> p :protein/peptide :protein.peptide/length)] (some->> (d/q '[:find [?h ...] :in $hdb ?pid :where [$hdb ?e :protein/id ?pid] [$hdb ?h :homology/protein ?e]] db-homology (:protein/id p)) (map (fn [id] (let [obj (d/entity db-homology id) homologous-protein-id (some->> (:locatable/parent obj) (:protein/id)) homologous-protein (some->> (d/q '[:find [?p ...] :in $db ?pid :where [$db ?p :protein/id ?pid]] db homologous-protein-id) (first) (d/entity db))] (when-let [score (:locatable/score obj)] {:id (str/join "-" [(->> homologous-protein :protein/species :species/id) homologous-protein-id (:locatable/max obj) (:locatable/min obj) (:homology/max obj) (:homology/min obj) (:locatable/score obj)]) :hit (when-let [obj (pack-obj homologous-protein)] (conj obj {:label (:id obj)})) :method (->> obj :locatable/method :method/id) :evalue (let [evalue-str (format "%7.0e" (/ 1 (math/expt 10 score)))] (if (= evalue-str " 0e+00") " 0" evalue-str)) :description (or (:protein/description homologous-protein) (first (:protein/gene-name homologous-protein))) :percent (if (and (:locatable/min obj) (:locatable/max obj)) (let [hlength (- (:homology/max obj) (:homology/min obj)) percentage (/ hlength plength)] (format "%.1f" (double (* 100 percentage))))) :taxonomy (if-let [species-id (->> homologous-protein :protein/species :species/id)] (let [[genus species] (str/split species-id #" ")] {:genus (first genus) :species species})) :score (:locatable/score obj) :species (->> homologous-protein :protein/species :species/id)}))))) (remove nil?) (group-by :id) (vals) (map first) (map (fn [obj] (dissoc obj :id))) (group-by :method) (map (fn [method-group] (let [max-hit (apply max-key :score (second method-group))] (dissoc max-hit :score :species :method))))))) (defn- homology-type-to-string [group] (cond (contains? group :homology-type/cog) "COG" (contains? group :homology-type/eunog) "euNOG" (contains? group :homology-type/fog) "FOG" (contains? group :homology-type/id) (:homology-type/id group) (contains? group :homology-type/kog) "KOG" (contains? group :homology-type/lse) "LSE" (contains? group :homology-type/menog) "meNOG" (contains? group :homology-type/nog) "NOG" (contains? group :homology-type/twog) "TWOG" :else "")) (defn get-homology-groups [p] (some->> (:homology-group/_protein p) (map (fn [g] {:title (first (:homology-group/title g)) :type (if (contains? g :homology-group/orthomcl-group) "OrthoMCL_group" (if (contains? g :homology-group/inparanoid_group) "InParanoid_group" (let [firstpart (if (contains? g :homology-group/eggnog-code) "eggNOG" (when (contains? g :homology-group/cog-code) "COG")) secondpart (homology-type-to-string (if (= firstpart "eggNOG") (:homology-group/eggnog-type g) (:homology-group/cog-type g)))] (str firstpart ":" secondpart)))) :id (pack-obj g)}))))
dc00bcee34b993a14c716ab582a3d3c6d6782142740d16bea6699cd60b687952
chaw/r7rs-libs
example-relief.sps
(import (scheme base) (srfi 42) (rebottled pstk)) (let ((tk (tk-start))) (tk/wm 'title tk "PS/Tk Example: Label relief") (tk 'configure 'borderwidth: 10) (do-ec (: relief '("raised" "sunken" "flat" "ridge" "groove" "solid")) (tk/pack (tk 'create-widget 'label 'text: relief 'relief: relief 'bd: 2 ; width of the relief 'padx: 10 ; inner padding, between label and its relief ' width : 10 ; hardcode desired size of label ' height : 5 ; 'anchor: "nw" ; indicate position for text of label ) 'side: 'left 'padx: 4)) (tk-event-loop tk))
null
https://raw.githubusercontent.com/chaw/r7rs-libs/b8b625c36b040ff3d4b723e4346629a8a0e8d6c2/rebottled-examples/pstk/example-relief.sps
scheme
width of the relief inner padding, between label and its relief hardcode desired size of label 'anchor: "nw" ; indicate position for text of label
(import (scheme base) (srfi 42) (rebottled pstk)) (let ((tk (tk-start))) (tk/wm 'title tk "PS/Tk Example: Label relief") (tk 'configure 'borderwidth: 10) (do-ec (: relief '("raised" "sunken" "flat" "ridge" "groove" "solid")) (tk/pack (tk 'create-widget 'label 'text: relief 'relief: relief ' height : 5 ) 'side: 'left 'padx: 4)) (tk-event-loop tk))
69792e275f6a9084c81de921b4949a25db02ffc79e4a623dd6de6eae05450dbb
digikar99/numericals
tests.lisp
(defpackage :sbcl-numericals.test (:use :sbcl-numericals :cl :fiveam :alexandria)) (in-package :sbcl-numericals.test) (def-suite :sbcl-numericals) (in-suite :sbcl-numericals) (defun map-array (function arr-a arr-b arr-c) (unless (and (equalp (array-dimensions arr-a) (array-dimensions arr-b)) (equalp (array-dimensions arr-a) (array-dimensions arr-c))) (error "ARR-A, ARR-B and ARR-C must have same dimensions!")) (let ((vec-a (sb-ext:array-storage-vector arr-a)) (vec-b (sb-ext:array-storage-vector arr-b)) (vec-c (sb-ext:array-storage-vector arr-c))) (loop for i below (array-total-size arr-a) do (setf (aref vec-c i) (funcall function (aref vec-a i) (aref vec-b i))) finally (return arr-c)))) (defun array-equal (arr-a arr-b) (let ((vec-a (if (numcl:numcl-array-p arr-a) (array-displacement arr-a) (sb-ext:array-storage-vector arr-a))) (vec-b (if (numcl:numcl-array-p arr-b) (array-displacement arr-b) (sb-ext:array-storage-vector arr-b)))) (not (when-let (diff (loop for i below (min (length vec-a) (length vec-b)) if (/= (aref vec-a i) (aref vec-b i)) collect i)) (let ((*print-pretty* nil)) (format t "ARR-A and ARR-B differ at position(s) ~D~%" diff)) t)))) (defmacro with-all-offsets (n element-type arr-a-initial-contents-generator arr-b-initial-contents-generator &body body) (let ((base-length 16) (axis-0 3)) `(let (,@(loop for i below n for arr-a-sym = (intern (concatenate 'string "ARR-A" (write-to-string i))) for arr-b-sym = (intern (concatenate 'string "ARR-B" (write-to-string i))) for arr-c-sym = (intern (concatenate 'string "ARR-C" (write-to-string i))) for arr-r-sym = (intern (concatenate 'string "ARR-R" (write-to-string i))) for len = (+ base-length i) collect `(,arr-a-sym (make-array '(,axis-0 ,len) :element-type ,element-type :initial-contents (loop for i below ,axis-0 collect (map 'vector ,arr-a-initial-contents-generator (iota ,len))))) collect `(,arr-b-sym (make-array '(,axis-0 ,len) :element-type ,element-type :initial-contents (loop for i below ,axis-0 collect (map 'vector ,arr-b-initial-contents-generator (iota ,len))))) collect `(,arr-c-sym (make-array '(,axis-0 ,len) :element-type ,element-type :initial-contents (loop for i below ,axis-0 collect (map 'vector (lambda (i) (declare (ignore i)) (coerce 0 ,element-type)) (iota ,len))))) collect `(,arr-r-sym (make-array '(,axis-0 ,len) :element-type ,element-type :initial-contents (loop for i below ,axis-0 collect (map 'vector (lambda (i) (declare (ignore i)) (coerce 0 ,element-type)) (iota ,len))))))) ,@body))) (defmacro define-sse-double-tests (&body op-double-op-pairs) `(progn ,@(loop for (op double-op) in op-double-op-pairs collect `(test ,double-op (with-all-offsets 2 'double-float (lambda (i) (+ 0.1d0 i)) (lambda (i) (+ 0.2d0 i)) (is (array-equal (,double-op arr-a0 arr-b0 arr-c0) (map-array ',op arr-a0 arr-b0 arr-r0))) (is (array-equal (,double-op arr-a1 arr-b1 arr-c1) (map-array ',op arr-a1 arr-b1 arr-r1)))))))) (defmacro define-sse-single-tests (&body op-single-op-pairs) `(progn ,@(loop for (op single-op) in op-single-op-pairs collect `(test ,single-op (with-all-offsets 4 'single-float (lambda (i) (+ 0.1 i)) (lambda (i) (+ 0.2 i)) (is (array-equal (,single-op arr-a0 arr-b0 arr-c0) (map-array ',op arr-a0 arr-b0 arr-r0))) (is (array-equal (,single-op arr-a1 arr-b1 arr-c1) (map-array ',op arr-a1 arr-b1 arr-r1))) (is (array-equal (,single-op arr-a2 arr-b2 arr-c2) (map-array ',op arr-a2 arr-b2 arr-r2))) (is (array-equal (,single-op arr-a3 arr-b3 arr-c3) (map-array ',op arr-a3 arr-b3 arr-r3)))))))) (define-sse-double-tests (+ d2+) (- d2-) (* d2*) (/ d2/)) (define-sse-single-tests (+ s2+) (- s2-) (* s2*) (/ s2/)) (defmacro define-avx2-double-tests (&body op-double-op-pairs) `(progn ,@(loop for (op double-op) in op-double-op-pairs collect `(test ,double-op (with-all-offsets 4 'double-float (lambda (i) (+ 0.1d0 i)) (lambda (i) (+ 0.2d0 i)) (is (array-equal (,double-op arr-a0 arr-b0 arr-c0) (map-array ',op arr-a0 arr-b0 arr-r0))) (is (array-equal (,double-op arr-a1 arr-b1 arr-c1) (map-array ',op arr-a1 arr-b1 arr-r1))) (is (array-equal (,double-op arr-a2 arr-b2 arr-c2) (map-array ',op arr-a2 arr-b2 arr-r2))) (is (array-equal (,double-op arr-a3 arr-b3 arr-c3) (map-array ',op arr-a3 arr-b3 arr-r3)))))))) (test broadcast-d+ (loop for size from 8 to 11 do (let ((arr-a (make-array (list 1 size) :initial-contents (list (loop for i below size collect (+ i 0.1d0))) :element-type 'double-float)) (arr-b (make-array (list size 1) :initial-contents (loop for i below size collect (list (+ i 0.2d0))) :element-type 'double-float)) (arr-c (make-array (list size size) :initial-element 0.0d0 :element-type 'double-float))) (is (array-equal (numcl:+ (numcl:asarray arr-a) (numcl:asarray arr-b)) (broadcast-d+ arr-a arr-b arr-c)))))) (define-avx2-double-tests (+ d+) (- d-) (* d*) (/ d/)) (defmacro define-avx2-single-tests (&body op-single-op-pairs) `(progn ,@(loop for (op single-op) in op-single-op-pairs collect `(test ,single-op (with-all-offsets 8 'single-float (lambda (i) (+ 0.1 i)) (lambda (i) (+ 0.2 i)) (is (array-equal (,single-op arr-a0 arr-b0 arr-c0) (map-array ',op arr-a0 arr-b0 arr-r0))) (is (array-equal (,single-op arr-a1 arr-b1 arr-c1) (map-array ',op arr-a1 arr-b1 arr-r1))) (is (array-equal (,single-op arr-a2 arr-b2 arr-c2) (map-array ',op arr-a2 arr-b2 arr-r2))) (is (array-equal (,single-op arr-a3 arr-b3 arr-c3) (map-array ',op arr-a3 arr-b3 arr-r3))) (is (array-equal (,single-op arr-a4 arr-b4 arr-c4) (map-array ',op arr-a4 arr-b4 arr-r4))) (is (array-equal (,single-op arr-a5 arr-b5 arr-c5) (map-array ',op arr-a5 arr-b5 arr-r5))) (is (array-equal (,single-op arr-a6 arr-b6 arr-c6) (map-array ',op arr-a6 arr-b6 arr-r6))) (is (array-equal (,single-op arr-a7 arr-b7 arr-c7) (map-array ',op arr-a7 arr-b7 arr-r7)))))))) (define-avx2-single-tests (+ s+) (- s-) (* s*) (/ s/)) (defun dot (array-a array-b) (let ((array-c (make-array (array-dimensions array-a) :initial-element 0))) (map-array '* array-a array-b array-c) (reduce '+ array-c :initial-value 0))) (defun almost-= (a b) (<= (abs (/ (- a b) (+ a b))) 1e-7)) (test sdot (loop for size from 32 to 35 do (let ((arr-a (make-array size :initial-contents (loop for i below size collect (+ i 1000.1)) :element-type 'single-float)) (arr-b (make-array size :initial-contents (loop for i below size collect (+ i 1000.2)) :element-type 'single-float))) (is (almost-= (dot arr-a arr-b) (sdot arr-a arr-b)))))) (test ddot (loop for size from 32 to 33 do (let ((arr-a (make-array size :initial-contents (loop for i below size collect (+ i 1000.1d0)) :element-type 'double-float)) (arr-b (make-array size :initial-contents (loop for i below size collect (+ i 1000.2d0)) :element-type 'double-float))) (is (almost-= (dot arr-a arr-b) (ddot arr-a arr-b))))))
null
https://raw.githubusercontent.com/digikar99/numericals/4f82b74e32b054f65110ee62ba080603c92ac103/sbcl-numericals/t/tests.lisp
lisp
(defpackage :sbcl-numericals.test (:use :sbcl-numericals :cl :fiveam :alexandria)) (in-package :sbcl-numericals.test) (def-suite :sbcl-numericals) (in-suite :sbcl-numericals) (defun map-array (function arr-a arr-b arr-c) (unless (and (equalp (array-dimensions arr-a) (array-dimensions arr-b)) (equalp (array-dimensions arr-a) (array-dimensions arr-c))) (error "ARR-A, ARR-B and ARR-C must have same dimensions!")) (let ((vec-a (sb-ext:array-storage-vector arr-a)) (vec-b (sb-ext:array-storage-vector arr-b)) (vec-c (sb-ext:array-storage-vector arr-c))) (loop for i below (array-total-size arr-a) do (setf (aref vec-c i) (funcall function (aref vec-a i) (aref vec-b i))) finally (return arr-c)))) (defun array-equal (arr-a arr-b) (let ((vec-a (if (numcl:numcl-array-p arr-a) (array-displacement arr-a) (sb-ext:array-storage-vector arr-a))) (vec-b (if (numcl:numcl-array-p arr-b) (array-displacement arr-b) (sb-ext:array-storage-vector arr-b)))) (not (when-let (diff (loop for i below (min (length vec-a) (length vec-b)) if (/= (aref vec-a i) (aref vec-b i)) collect i)) (let ((*print-pretty* nil)) (format t "ARR-A and ARR-B differ at position(s) ~D~%" diff)) t)))) (defmacro with-all-offsets (n element-type arr-a-initial-contents-generator arr-b-initial-contents-generator &body body) (let ((base-length 16) (axis-0 3)) `(let (,@(loop for i below n for arr-a-sym = (intern (concatenate 'string "ARR-A" (write-to-string i))) for arr-b-sym = (intern (concatenate 'string "ARR-B" (write-to-string i))) for arr-c-sym = (intern (concatenate 'string "ARR-C" (write-to-string i))) for arr-r-sym = (intern (concatenate 'string "ARR-R" (write-to-string i))) for len = (+ base-length i) collect `(,arr-a-sym (make-array '(,axis-0 ,len) :element-type ,element-type :initial-contents (loop for i below ,axis-0 collect (map 'vector ,arr-a-initial-contents-generator (iota ,len))))) collect `(,arr-b-sym (make-array '(,axis-0 ,len) :element-type ,element-type :initial-contents (loop for i below ,axis-0 collect (map 'vector ,arr-b-initial-contents-generator (iota ,len))))) collect `(,arr-c-sym (make-array '(,axis-0 ,len) :element-type ,element-type :initial-contents (loop for i below ,axis-0 collect (map 'vector (lambda (i) (declare (ignore i)) (coerce 0 ,element-type)) (iota ,len))))) collect `(,arr-r-sym (make-array '(,axis-0 ,len) :element-type ,element-type :initial-contents (loop for i below ,axis-0 collect (map 'vector (lambda (i) (declare (ignore i)) (coerce 0 ,element-type)) (iota ,len))))))) ,@body))) (defmacro define-sse-double-tests (&body op-double-op-pairs) `(progn ,@(loop for (op double-op) in op-double-op-pairs collect `(test ,double-op (with-all-offsets 2 'double-float (lambda (i) (+ 0.1d0 i)) (lambda (i) (+ 0.2d0 i)) (is (array-equal (,double-op arr-a0 arr-b0 arr-c0) (map-array ',op arr-a0 arr-b0 arr-r0))) (is (array-equal (,double-op arr-a1 arr-b1 arr-c1) (map-array ',op arr-a1 arr-b1 arr-r1)))))))) (defmacro define-sse-single-tests (&body op-single-op-pairs) `(progn ,@(loop for (op single-op) in op-single-op-pairs collect `(test ,single-op (with-all-offsets 4 'single-float (lambda (i) (+ 0.1 i)) (lambda (i) (+ 0.2 i)) (is (array-equal (,single-op arr-a0 arr-b0 arr-c0) (map-array ',op arr-a0 arr-b0 arr-r0))) (is (array-equal (,single-op arr-a1 arr-b1 arr-c1) (map-array ',op arr-a1 arr-b1 arr-r1))) (is (array-equal (,single-op arr-a2 arr-b2 arr-c2) (map-array ',op arr-a2 arr-b2 arr-r2))) (is (array-equal (,single-op arr-a3 arr-b3 arr-c3) (map-array ',op arr-a3 arr-b3 arr-r3)))))))) (define-sse-double-tests (+ d2+) (- d2-) (* d2*) (/ d2/)) (define-sse-single-tests (+ s2+) (- s2-) (* s2*) (/ s2/)) (defmacro define-avx2-double-tests (&body op-double-op-pairs) `(progn ,@(loop for (op double-op) in op-double-op-pairs collect `(test ,double-op (with-all-offsets 4 'double-float (lambda (i) (+ 0.1d0 i)) (lambda (i) (+ 0.2d0 i)) (is (array-equal (,double-op arr-a0 arr-b0 arr-c0) (map-array ',op arr-a0 arr-b0 arr-r0))) (is (array-equal (,double-op arr-a1 arr-b1 arr-c1) (map-array ',op arr-a1 arr-b1 arr-r1))) (is (array-equal (,double-op arr-a2 arr-b2 arr-c2) (map-array ',op arr-a2 arr-b2 arr-r2))) (is (array-equal (,double-op arr-a3 arr-b3 arr-c3) (map-array ',op arr-a3 arr-b3 arr-r3)))))))) (test broadcast-d+ (loop for size from 8 to 11 do (let ((arr-a (make-array (list 1 size) :initial-contents (list (loop for i below size collect (+ i 0.1d0))) :element-type 'double-float)) (arr-b (make-array (list size 1) :initial-contents (loop for i below size collect (list (+ i 0.2d0))) :element-type 'double-float)) (arr-c (make-array (list size size) :initial-element 0.0d0 :element-type 'double-float))) (is (array-equal (numcl:+ (numcl:asarray arr-a) (numcl:asarray arr-b)) (broadcast-d+ arr-a arr-b arr-c)))))) (define-avx2-double-tests (+ d+) (- d-) (* d*) (/ d/)) (defmacro define-avx2-single-tests (&body op-single-op-pairs) `(progn ,@(loop for (op single-op) in op-single-op-pairs collect `(test ,single-op (with-all-offsets 8 'single-float (lambda (i) (+ 0.1 i)) (lambda (i) (+ 0.2 i)) (is (array-equal (,single-op arr-a0 arr-b0 arr-c0) (map-array ',op arr-a0 arr-b0 arr-r0))) (is (array-equal (,single-op arr-a1 arr-b1 arr-c1) (map-array ',op arr-a1 arr-b1 arr-r1))) (is (array-equal (,single-op arr-a2 arr-b2 arr-c2) (map-array ',op arr-a2 arr-b2 arr-r2))) (is (array-equal (,single-op arr-a3 arr-b3 arr-c3) (map-array ',op arr-a3 arr-b3 arr-r3))) (is (array-equal (,single-op arr-a4 arr-b4 arr-c4) (map-array ',op arr-a4 arr-b4 arr-r4))) (is (array-equal (,single-op arr-a5 arr-b5 arr-c5) (map-array ',op arr-a5 arr-b5 arr-r5))) (is (array-equal (,single-op arr-a6 arr-b6 arr-c6) (map-array ',op arr-a6 arr-b6 arr-r6))) (is (array-equal (,single-op arr-a7 arr-b7 arr-c7) (map-array ',op arr-a7 arr-b7 arr-r7)))))))) (define-avx2-single-tests (+ s+) (- s-) (* s*) (/ s/)) (defun dot (array-a array-b) (let ((array-c (make-array (array-dimensions array-a) :initial-element 0))) (map-array '* array-a array-b array-c) (reduce '+ array-c :initial-value 0))) (defun almost-= (a b) (<= (abs (/ (- a b) (+ a b))) 1e-7)) (test sdot (loop for size from 32 to 35 do (let ((arr-a (make-array size :initial-contents (loop for i below size collect (+ i 1000.1)) :element-type 'single-float)) (arr-b (make-array size :initial-contents (loop for i below size collect (+ i 1000.2)) :element-type 'single-float))) (is (almost-= (dot arr-a arr-b) (sdot arr-a arr-b)))))) (test ddot (loop for size from 32 to 33 do (let ((arr-a (make-array size :initial-contents (loop for i below size collect (+ i 1000.1d0)) :element-type 'double-float)) (arr-b (make-array size :initial-contents (loop for i below size collect (+ i 1000.2d0)) :element-type 'double-float))) (is (almost-= (dot arr-a arr-b) (ddot arr-a arr-b))))))
c9b4eb07e20c065a4ad64ef0606819d486241edb76a1b5d571c9480194907764
polymeris/cljs-aws
codebuild.cljs
(ns cljs-aws.codebuild (:require [cljs-aws.base.requests]) (:require-macros [cljs-aws.base.service :refer [defservice]])) (defservice "CodeBuild" "codebuild-2016-10-06.min.json")
null
https://raw.githubusercontent.com/polymeris/cljs-aws/3326e7c4db4dfc36dcb80770610c14c8a7fd0d66/src/cljs_aws/codebuild.cljs
clojure
(ns cljs-aws.codebuild (:require [cljs-aws.base.requests]) (:require-macros [cljs-aws.base.service :refer [defservice]])) (defservice "CodeBuild" "codebuild-2016-10-06.min.json")
dadcb78090dfac4b230a9b5ea55ec337a7df0dad069bf9d0b5de042e9c0e4c95
gmr/privatepaste
privpaste_db.erl
%% ------------------------------------------------------------------ Database Abstraction %% ------------------------------------------------------------------ -module(privpaste_db). -export([create_paste/2, delete_paste/1, get_paste/2, increment_paste_views/2, update_paste/3]). -include("privpaste.hrl"). create_paste(Hostname, Paste) -> try ok = check_hostname(Hostname, Paste), ok = check_id_is_empty(Paste), ok = check_syntax(Paste), ok = check_ttl(Paste), NewPaste = Paste#paste{id=new_id()}, Write = fun() -> mnesia:write(pastes, NewPaste, write) end, case mnesia:activity(transaction, Write) of ok -> {ok, NewPaste}; Err -> {error, Err} end catch error:{badmatch, hostname_mistmatch} -> conflict; error:{badmatch, id_is_set} -> conflict; error:{badmatch, invalid_mode} -> conflict; error:{badmatch, invalid_ttl} -> conflict end. delete_paste(Id) -> Delete = fun() -> mnesia:delete(pastes, Id, write) end, mnesia:activity(transaction, Delete). get_paste(Hostname, Id) -> Pattern = #paste{hostname=Hostname, id=Id, _='_'}, Match = fun() -> case mnesia:match_object(pastes, Pattern, read) of [] -> not_found; Result -> Paste = hd(Result), try ok = check_expiration(Paste), {ok, Paste} catch error:{badmatch, expired_paste} -> expired_paste(Id) end end end, {atomic, Response} = mnesia:transaction(Match), Response. increment_paste_views(Hostname, Id) -> Pattern = #paste{hostname=Hostname, id=Id, _='_'}, Update = fun() -> case mnesia:match_object(pastes, Pattern, write) of [] -> not_found; Result -> Paste = hd(Result), Incremented = Paste#paste{views=Paste#paste.views + 1}, mnesia:write(pastes, Incremented, write) end end, mnesia:activity(transaction, Update). update_paste(Hostname, Id, Paste) -> Pattern = #paste{hostname=Hostname, id=Id, _='_'}, Update = fun() -> case mnesia:match_object(pastes, Pattern, write) of [] -> not_found; Result -> OldPaste = hd(Result), try ok = check_ids(Id, Paste), ok = check_expiration(OldPaste), ok = check_expiration(Paste), ok = check_hostname(Hostname, OldPaste), ok = check_hostname(Hostname, Paste), ok = check_syntax(Paste), ok = check_ttl(Paste), Updated = Paste#paste{id=Id, updated_at=calendar:universal_time(), revision=Paste#paste.revision + 1}, {mnesia:write(pastes, Updated, write), Updated} catch error:{badmatch, id_mistmatch} -> conflict; error:{badmatch, expired_paste} -> expired_paste(Id); error:{badmatch, hostname_mistmatch} -> conflict; error:{badmatch, invalid_mode} -> conflict; error:{badmatch, invalid_ttl} -> conflict end end end, mnesia:activity(transaction, Update). %% ------------------------------------------------------------------ %% Internal Methods %% ------------------------------------------------------------------ expired_paste(Id) -> lager:log(debug, self(), "Removing expired paste ~s", [Id]), delete_paste(Id), not_found. new_id() -> Base = uuid:uuid_to_string(uuid:get_v4()), list_to_binary(string:substr(Base, 1, 8)). %% ------------------------------------------------------------------ %% Validation Methods %% ------------------------------------------------------------------ check_expiration(#paste{} = Paste) -> ExpireDatetime = iso8601:add_time(Paste#paste.created_at, 0, 0, Paste#paste.ttl), ExpireAt = calendar:datetime_to_gregorian_seconds(ExpireDatetime), Now = calendar:datetime_to_gregorian_seconds(calendar:now_to_datetime(now())), case Now >= ExpireAt of true -> expired_paste; false -> ok end. check_hostname(Expectation, #paste{}=Paste) -> case Expectation == Paste#paste.hostname of true -> ok; false -> hostname_mismatch end. check_id_is_empty(#paste{} = Paste) -> case Paste#paste.id == null of true -> ok; false -> id_not_empty end. check_ids(Expectation, #paste{}=Paste) -> case Expectation == Paste#paste.id of true -> ok; false -> id_mismatch end. check_syntax(#paste{} = Paste) -> Modes = proplists:get_keys(?MODES), case lists:member(Paste#paste.syntax, Modes) of true -> ok; false -> invalid_mode end. check_ttl(#paste{} = Paste) -> case Paste#paste.ttl > ?TTL_MAX of true -> invalid_ttl; false -> ok end.
null
https://raw.githubusercontent.com/gmr/privatepaste/4cc53473eb7e3d4d237df4b18fce573e3588ec24/src/privpaste_db.erl
erlang
------------------------------------------------------------------ ------------------------------------------------------------------ ------------------------------------------------------------------ Internal Methods ------------------------------------------------------------------ ------------------------------------------------------------------ Validation Methods ------------------------------------------------------------------
Database Abstraction -module(privpaste_db). -export([create_paste/2, delete_paste/1, get_paste/2, increment_paste_views/2, update_paste/3]). -include("privpaste.hrl"). create_paste(Hostname, Paste) -> try ok = check_hostname(Hostname, Paste), ok = check_id_is_empty(Paste), ok = check_syntax(Paste), ok = check_ttl(Paste), NewPaste = Paste#paste{id=new_id()}, Write = fun() -> mnesia:write(pastes, NewPaste, write) end, case mnesia:activity(transaction, Write) of ok -> {ok, NewPaste}; Err -> {error, Err} end catch error:{badmatch, hostname_mistmatch} -> conflict; error:{badmatch, id_is_set} -> conflict; error:{badmatch, invalid_mode} -> conflict; error:{badmatch, invalid_ttl} -> conflict end. delete_paste(Id) -> Delete = fun() -> mnesia:delete(pastes, Id, write) end, mnesia:activity(transaction, Delete). get_paste(Hostname, Id) -> Pattern = #paste{hostname=Hostname, id=Id, _='_'}, Match = fun() -> case mnesia:match_object(pastes, Pattern, read) of [] -> not_found; Result -> Paste = hd(Result), try ok = check_expiration(Paste), {ok, Paste} catch error:{badmatch, expired_paste} -> expired_paste(Id) end end end, {atomic, Response} = mnesia:transaction(Match), Response. increment_paste_views(Hostname, Id) -> Pattern = #paste{hostname=Hostname, id=Id, _='_'}, Update = fun() -> case mnesia:match_object(pastes, Pattern, write) of [] -> not_found; Result -> Paste = hd(Result), Incremented = Paste#paste{views=Paste#paste.views + 1}, mnesia:write(pastes, Incremented, write) end end, mnesia:activity(transaction, Update). update_paste(Hostname, Id, Paste) -> Pattern = #paste{hostname=Hostname, id=Id, _='_'}, Update = fun() -> case mnesia:match_object(pastes, Pattern, write) of [] -> not_found; Result -> OldPaste = hd(Result), try ok = check_ids(Id, Paste), ok = check_expiration(OldPaste), ok = check_expiration(Paste), ok = check_hostname(Hostname, OldPaste), ok = check_hostname(Hostname, Paste), ok = check_syntax(Paste), ok = check_ttl(Paste), Updated = Paste#paste{id=Id, updated_at=calendar:universal_time(), revision=Paste#paste.revision + 1}, {mnesia:write(pastes, Updated, write), Updated} catch error:{badmatch, id_mistmatch} -> conflict; error:{badmatch, expired_paste} -> expired_paste(Id); error:{badmatch, hostname_mistmatch} -> conflict; error:{badmatch, invalid_mode} -> conflict; error:{badmatch, invalid_ttl} -> conflict end end end, mnesia:activity(transaction, Update). expired_paste(Id) -> lager:log(debug, self(), "Removing expired paste ~s", [Id]), delete_paste(Id), not_found. new_id() -> Base = uuid:uuid_to_string(uuid:get_v4()), list_to_binary(string:substr(Base, 1, 8)). check_expiration(#paste{} = Paste) -> ExpireDatetime = iso8601:add_time(Paste#paste.created_at, 0, 0, Paste#paste.ttl), ExpireAt = calendar:datetime_to_gregorian_seconds(ExpireDatetime), Now = calendar:datetime_to_gregorian_seconds(calendar:now_to_datetime(now())), case Now >= ExpireAt of true -> expired_paste; false -> ok end. check_hostname(Expectation, #paste{}=Paste) -> case Expectation == Paste#paste.hostname of true -> ok; false -> hostname_mismatch end. check_id_is_empty(#paste{} = Paste) -> case Paste#paste.id == null of true -> ok; false -> id_not_empty end. check_ids(Expectation, #paste{}=Paste) -> case Expectation == Paste#paste.id of true -> ok; false -> id_mismatch end. check_syntax(#paste{} = Paste) -> Modes = proplists:get_keys(?MODES), case lists:member(Paste#paste.syntax, Modes) of true -> ok; false -> invalid_mode end. check_ttl(#paste{} = Paste) -> case Paste#paste.ttl > ?TTL_MAX of true -> invalid_ttl; false -> ok end.
39df4bc70040885a60b36999e725773660a569ee986c7307530eb02efbb48b73
kunstmusik/pink
processes_test.clj
(ns pink.processes-test (:require [pink.processes :refer [process wait cue countdown-latch] :as p] [pink.config :refer :all] [clojure.test :refer :all])) (deftest test-process (let [counter (atom 0) p (process (reset! counter 1) (wait 1.0) (reset! counter 2)) num-wait (long (Math/round (+ 0.4999999 (/ *sr* *buffer-size*)))) ] (is (= @counter 0)) (p) (is (= @counter 1)) (loop [c 2] (if (p) (recur (inc c)) (is (= c num-wait)))) (is (= @counter 2)))) (deftest test-process-loop (let [counter (atom 0) p (process (loop [a 0] (wait 1.0) (reset! counter (inc a)) (recur (inc a)))) num-wait (Math/round (+ 0.4999999 (/ *sr* *buffer-size*))) num-wait2 (dec num-wait) ] (is (= @counter 0)) (loop [c 0] (if (= @counter 0) (do (p) (recur (inc c))) (do (is (= c num-wait)) (is (= @counter 1)) ))) ;; the last wait from previous loop starts the next wait, so counting from 1 here (loop [c 1] (if (= @counter 1) (do (p) (recur (inc c))) (do checking num - wait 2 , which is one buffer less ;; than num-wait, due to leftover samples from ;; previous wait time (is (= c num-wait2)) (is (= @counter 2)) ))))) (deftest test-cue (let [c (cue)] (is (not (p/has-cued? c))) (is (not (p/signal-done? c))) (p/signal-cue c) (is (p/has-cued? c)) (is (p/signal-done? c)) )) (deftest test-countdown-latch (let [l (countdown-latch 5)] (is (not (p/signal-done? l))) (is (not (p/latch-done? l))) (p/count-down l) (is (not (p/latch-done? l))) (is (not (p/signal-done? l))) (p/count-down l) (p/count-down l) (p/count-down l) (p/count-down l) (is (p/latch-done? l)) (is (p/signal-done? l)) ))
null
https://raw.githubusercontent.com/kunstmusik/pink/7d37764b6a036a68a4619c93546fa3887f9951a7/src/test/pink/processes_test.clj
clojure
the last wait from previous loop starts the next wait, than num-wait, due to leftover samples from previous wait time
(ns pink.processes-test (:require [pink.processes :refer [process wait cue countdown-latch] :as p] [pink.config :refer :all] [clojure.test :refer :all])) (deftest test-process (let [counter (atom 0) p (process (reset! counter 1) (wait 1.0) (reset! counter 2)) num-wait (long (Math/round (+ 0.4999999 (/ *sr* *buffer-size*)))) ] (is (= @counter 0)) (p) (is (= @counter 1)) (loop [c 2] (if (p) (recur (inc c)) (is (= c num-wait)))) (is (= @counter 2)))) (deftest test-process-loop (let [counter (atom 0) p (process (loop [a 0] (wait 1.0) (reset! counter (inc a)) (recur (inc a)))) num-wait (Math/round (+ 0.4999999 (/ *sr* *buffer-size*))) num-wait2 (dec num-wait) ] (is (= @counter 0)) (loop [c 0] (if (= @counter 0) (do (p) (recur (inc c))) (do (is (= c num-wait)) (is (= @counter 1)) ))) so counting from 1 here (loop [c 1] (if (= @counter 1) (do (p) (recur (inc c))) (do checking num - wait 2 , which is one buffer less (is (= c num-wait2)) (is (= @counter 2)) ))))) (deftest test-cue (let [c (cue)] (is (not (p/has-cued? c))) (is (not (p/signal-done? c))) (p/signal-cue c) (is (p/has-cued? c)) (is (p/signal-done? c)) )) (deftest test-countdown-latch (let [l (countdown-latch 5)] (is (not (p/signal-done? l))) (is (not (p/latch-done? l))) (p/count-down l) (is (not (p/latch-done? l))) (is (not (p/signal-done? l))) (p/count-down l) (p/count-down l) (p/count-down l) (p/count-down l) (is (p/latch-done? l)) (is (p/signal-done? l)) ))
651ed18550ca4688efb0051d2318e6acb5f1c64b8d4605e7d069fabc7dd6fd61
nkaretnikov/OOHaskell
Polymorph.hs
( C ) 2004 - 2005 , Oleg Kiselyov & 's overlooked object system module Polymorph where import Shape Weirich 's / 's test case main = do -- Handle the shapes polymorphically let scribble = [ Rectangle 10 20 5 6 , Circle 15 25 8 ] mapM_ (\x -> do draw x draw (rMoveTo 100 100 x)) scribble -- Handle rectangle-specific instance draw $ setWidth 30 (Rectangle 0 0 15 15)
null
https://raw.githubusercontent.com/nkaretnikov/OOHaskell/ddf42cfa62f8bd27643ff6db136dec6c14466232/repository/shapes/Haskell/Shapes1/Polymorph.hs
haskell
Handle the shapes polymorphically Handle rectangle-specific instance
( C ) 2004 - 2005 , Oleg Kiselyov & 's overlooked object system module Polymorph where import Shape Weirich 's / 's test case main = do let scribble = [ Rectangle 10 20 5 6 , Circle 15 25 8 ] mapM_ (\x -> do draw x draw (rMoveTo 100 100 x)) scribble draw $ setWidth 30 (Rectangle 0 0 15 15)
b1e54b3bbc4e1a55ff9ec298c810b007db697164a4f03213b8f6257715b8ba42
pirapira/coq2rust
universes.mli
(************************************************************************) v * The Coq Proof Assistant / The Coq Development Team < O _ _ _ , , * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999 - 2012 \VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * (* // * This file is distributed under the terms of the *) (* * GNU Lesser General Public License Version 2.1 *) (************************************************************************) open Util open Pp open Names open Term open Context open Environ open Locus open Univ (** Universes *) type universe_names = Univ.universe_level Idmap.t * Id.t Univ.LMap.t val global_universe_names : unit -> universe_names val set_global_universe_names : universe_names -> unit (** The global universe counter *) val set_remote_new_univ_level : universe_level RemoteCounter.installer (** Side-effecting functions creating new universe levels. *) val new_univ_level : Names.dir_path -> universe_level val new_univ : Names.dir_path -> universe val new_Type : Names.dir_path -> types val new_Type_sort : Names.dir_path -> sorts val new_global_univ : unit -> universe in_universe_context_set val new_sort_in_family : sorts_family -> sorts * { 6 Constraints for type inference } When doing conversion of universes , not only do we have = /<= constraints but also Lub constraints which correspond to unification of two levels which might not be necessary if unfolding is performed . When doing conversion of universes, not only do we have =/<= constraints but also Lub constraints which correspond to unification of two levels which might not be necessary if unfolding is performed. *) type universe_constraint_type = ULe | UEq | ULub type universe_constraint = universe * universe_constraint_type * universe module Constraints : sig include Set.S with type elt = universe_constraint val pr : t -> Pp.std_ppcmds end type universe_constraints = Constraints.t type 'a universe_constrained = 'a * universe_constraints type 'a universe_constraint_function = 'a -> 'a -> universe_constraints -> universe_constraints val subst_univs_universe_constraints : universe_subst_fn -> universe_constraints -> universe_constraints val enforce_eq_instances_univs : bool -> universe_instance universe_constraint_function val to_constraints : universes -> universe_constraints -> constraints (** [eq_constr_univs_infer u a b] is [true, c] if [a] equals [b] modulo alpha, casts, application grouping, the universe constraints in [u] and additional constraints [c]. *) val eq_constr_univs_infer : Univ.universes -> constr -> constr -> bool universe_constrained (** [leq_constr_univs u a b] is [true, c] if [a] is convertible to [b] modulo alpha, casts, application grouping, the universe constraints in [u] and additional constraints [c]. *) val leq_constr_univs_infer : Univ.universes -> constr -> constr -> bool universe_constrained (** [eq_constr_universes a b] [true, c] if [a] equals [b] modulo alpha, casts, application grouping and the universe constraints in [c]. *) val eq_constr_universes : constr -> constr -> bool universe_constrained (** [leq_constr_universes a b] [true, c] if [a] is convertible to [b] modulo alpha, casts, application grouping and the universe constraints in [c]. *) val leq_constr_universes : constr -> constr -> bool universe_constrained (** [eq_constr_universes a b] [true, c] if [a] equals [b] modulo alpha, casts, application grouping and the universe constraints in [c]. *) val eq_constr_universes_proj : env -> constr -> constr -> bool universe_constrained (** Build a fresh instance for a given context, its associated substitution and the instantiated constraints. *) val fresh_instance_from_context : universe_context -> universe_instance constrained val fresh_instance_from : universe_context -> universe_instance option -> universe_instance in_universe_context_set val fresh_sort_in_family : env -> sorts_family -> sorts in_universe_context_set val fresh_constant_instance : env -> constant -> pconstant in_universe_context_set val fresh_inductive_instance : env -> inductive -> pinductive in_universe_context_set val fresh_constructor_instance : env -> constructor -> pconstructor in_universe_context_set val fresh_global_instance : ?names:Univ.Instance.t -> env -> Globnames.global_reference -> constr in_universe_context_set val fresh_global_or_constr_instance : env -> Globnames.global_reference_or_constr -> constr in_universe_context_set * Get fresh variables for the universe context . Useful to make tactics that manipulate in universe contexts polymorphic . Useful to make tactics that manipulate constrs in universe contexts polymorphic. *) val fresh_universe_context_set_instance : universe_context_set -> universe_level_subst * universe_context_set (** Raises [Not_found] if not a global reference. *) val global_of_constr : constr -> Globnames.global_reference puniverses val global_app_of_constr : constr -> Globnames.global_reference puniverses * constr option val constr_of_global_univ : Globnames.global_reference puniverses -> constr val extend_context : 'a in_universe_context_set -> universe_context_set -> 'a in_universe_context_set (** Simplification and pruning of constraints: [normalize_context_set ctx us] - Instantiate the variables in [us] with their most precise universe levels respecting the constraints. - Normalizes the context [ctx] w.r.t. equality constraints, choosing a canonical universe in each equivalence class (a global one if there is one) and transitively saturate the constraints w.r.t to the equalities. *) module UF : Unionfind.PartitionSig with type elt = universe_level type universe_opt_subst = universe option universe_map val make_opt_subst : universe_opt_subst -> universe_subst_fn val subst_opt_univs_constr : universe_opt_subst -> constr -> constr val normalize_context_set : universe_context_set -> universe_opt_subst (* The defined and undefined variables *) -> universe_set (* univ variables that can be substituted by algebraics *) -> (universe_opt_subst * universe_set) in_universe_context_set val normalize_univ_variables : universe_opt_subst -> universe_opt_subst * universe_set * universe_set * universe_subst val normalize_univ_variable : find:(universe_level -> universe) -> update:(universe_level -> universe -> universe) -> universe_level -> universe val normalize_univ_variable_opt_subst : universe_opt_subst ref -> (universe_level -> universe) val normalize_univ_variable_subst : universe_subst ref -> (universe_level -> universe) val normalize_universe_opt_subst : universe_opt_subst ref -> (universe -> universe) val normalize_universe_subst : universe_subst ref -> (universe -> universe) (** Create a fresh global in the global environment, without side effects. BEWARE: this raises an ANOMALY on polymorphic constants/inductives: the constraints should be properly added to an evd. See Evd.fresh_global, Evarutil.new_global, and pf_constr_of_global for the proper way to get a fresh copy of a global reference. *) val constr_of_global : Globnames.global_reference -> constr (** ** DEPRECATED ** synonym of [constr_of_global] *) val constr_of_reference : Globnames.global_reference -> constr * [ unsafe_constr_of_global gr ] turns [ gr ] into a constr , works on polymorphic references by taking the original universe instance that is not recorded anywhere . The constraints are forgotten as well . DO NOT USE in new code . references by taking the original universe instance that is not recorded anywhere. The constraints are forgotten as well. DO NOT USE in new code. *) val unsafe_constr_of_global : Globnames.global_reference -> constr in_universe_context (** Returns the type of the global reference, by creating a fresh instance of polymorphic references and computing their instantiated universe context. (side-effect on the universe counter, use with care). *) val type_of_global : Globnames.global_reference -> types in_universe_context_set (** [unsafe_type_of_global gr] returns [gr]'s type, works on polymorphic references by taking the original universe instance that is not recorded anywhere. The constraints are forgotten as well. USE with care. *) val unsafe_type_of_global : Globnames.global_reference -> types (** Full universes substitutions into terms *) val nf_evars_and_universes_opt_subst : (existential -> constr option) -> universe_opt_subst -> constr -> constr (** Shrink a universe context to a restricted set of variables *) val universes_of_constr : constr -> universe_set val restrict_universe_context : universe_context_set -> universe_set -> universe_context_set val simplify_universe_context : universe_context_set -> universe_context_set * universe_level_subst val refresh_constraints : universes -> universe_context_set -> universe_context_set * universes (** Pretty-printing *) val pr_universe_opt_subst : universe_opt_subst -> Pp.std_ppcmds (* For tracing *) type constraints_map = (Univ.constraint_type * Univ.LMap.key) list Univ.LMap.t val pr_constraints_map : constraints_map -> Pp.std_ppcmds val choose_canonical : universe_set -> (Level.t -> bool) (* flexibles *) -> universe_set -> universe_set -> universe_level * (universe_set * universe_set * universe_set) val compute_lbound : (constraint_type * Univ.universe) list -> universe option val instantiate_with_lbound : Univ.LMap.key -> Univ.universe -> bool -> bool -> Univ.LSet.t * Univ.universe option Univ.LMap.t * Univ.LSet.t * (bool * bool * Univ.universe) Univ.LMap.t * Univ.constraints -> (Univ.LSet.t * Univ.universe option Univ.LMap.t * Univ.LSet.t * (bool * bool * Univ.universe) Univ.LMap.t * Univ.constraints) * (bool * bool * Univ.universe) val minimize_univ_variables : Univ.LSet.t -> Univ.universe option Univ.LMap.t -> Univ.LSet.t -> constraints_map -> constraints_map -> Univ.constraints -> Univ.LSet.t * Univ.universe option Univ.LMap.t * Univ.LSet.t * (bool * bool * Univ.universe) Univ.LMap.t * Univ.constraints * { 6 Support for old - style sort - polymorphism } val solve_constraints_system : universe option array -> universe array -> universe array -> universe array
null
https://raw.githubusercontent.com/pirapira/coq2rust/22e8aaefc723bfb324ca2001b2b8e51fcc923543/library/universes.mli
ocaml
********************************************************************** // * This file is distributed under the terms of the * GNU Lesser General Public License Version 2.1 ********************************************************************** * Universes * The global universe counter * Side-effecting functions creating new universe levels. * [eq_constr_univs_infer u a b] is [true, c] if [a] equals [b] modulo alpha, casts, application grouping, the universe constraints in [u] and additional constraints [c]. * [leq_constr_univs u a b] is [true, c] if [a] is convertible to [b] modulo alpha, casts, application grouping, the universe constraints in [u] and additional constraints [c]. * [eq_constr_universes a b] [true, c] if [a] equals [b] modulo alpha, casts, application grouping and the universe constraints in [c]. * [leq_constr_universes a b] [true, c] if [a] is convertible to [b] modulo alpha, casts, application grouping and the universe constraints in [c]. * [eq_constr_universes a b] [true, c] if [a] equals [b] modulo alpha, casts, application grouping and the universe constraints in [c]. * Build a fresh instance for a given context, its associated substitution and the instantiated constraints. * Raises [Not_found] if not a global reference. * Simplification and pruning of constraints: [normalize_context_set ctx us] - Instantiate the variables in [us] with their most precise universe levels respecting the constraints. - Normalizes the context [ctx] w.r.t. equality constraints, choosing a canonical universe in each equivalence class (a global one if there is one) and transitively saturate the constraints w.r.t to the equalities. The defined and undefined variables univ variables that can be substituted by algebraics * Create a fresh global in the global environment, without side effects. BEWARE: this raises an ANOMALY on polymorphic constants/inductives: the constraints should be properly added to an evd. See Evd.fresh_global, Evarutil.new_global, and pf_constr_of_global for the proper way to get a fresh copy of a global reference. * ** DEPRECATED ** synonym of [constr_of_global] * Returns the type of the global reference, by creating a fresh instance of polymorphic references and computing their instantiated universe context. (side-effect on the universe counter, use with care). * [unsafe_type_of_global gr] returns [gr]'s type, works on polymorphic references by taking the original universe instance that is not recorded anywhere. The constraints are forgotten as well. USE with care. * Full universes substitutions into terms * Shrink a universe context to a restricted set of variables * Pretty-printing For tracing flexibles
v * The Coq Proof Assistant / The Coq Development Team < O _ _ _ , , * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999 - 2012 \VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * open Util open Pp open Names open Term open Context open Environ open Locus open Univ type universe_names = Univ.universe_level Idmap.t * Id.t Univ.LMap.t val global_universe_names : unit -> universe_names val set_global_universe_names : universe_names -> unit val set_remote_new_univ_level : universe_level RemoteCounter.installer val new_univ_level : Names.dir_path -> universe_level val new_univ : Names.dir_path -> universe val new_Type : Names.dir_path -> types val new_Type_sort : Names.dir_path -> sorts val new_global_univ : unit -> universe in_universe_context_set val new_sort_in_family : sorts_family -> sorts * { 6 Constraints for type inference } When doing conversion of universes , not only do we have = /<= constraints but also Lub constraints which correspond to unification of two levels which might not be necessary if unfolding is performed . When doing conversion of universes, not only do we have =/<= constraints but also Lub constraints which correspond to unification of two levels which might not be necessary if unfolding is performed. *) type universe_constraint_type = ULe | UEq | ULub type universe_constraint = universe * universe_constraint_type * universe module Constraints : sig include Set.S with type elt = universe_constraint val pr : t -> Pp.std_ppcmds end type universe_constraints = Constraints.t type 'a universe_constrained = 'a * universe_constraints type 'a universe_constraint_function = 'a -> 'a -> universe_constraints -> universe_constraints val subst_univs_universe_constraints : universe_subst_fn -> universe_constraints -> universe_constraints val enforce_eq_instances_univs : bool -> universe_instance universe_constraint_function val to_constraints : universes -> universe_constraints -> constraints val eq_constr_univs_infer : Univ.universes -> constr -> constr -> bool universe_constrained val leq_constr_univs_infer : Univ.universes -> constr -> constr -> bool universe_constrained val eq_constr_universes : constr -> constr -> bool universe_constrained val leq_constr_universes : constr -> constr -> bool universe_constrained val eq_constr_universes_proj : env -> constr -> constr -> bool universe_constrained val fresh_instance_from_context : universe_context -> universe_instance constrained val fresh_instance_from : universe_context -> universe_instance option -> universe_instance in_universe_context_set val fresh_sort_in_family : env -> sorts_family -> sorts in_universe_context_set val fresh_constant_instance : env -> constant -> pconstant in_universe_context_set val fresh_inductive_instance : env -> inductive -> pinductive in_universe_context_set val fresh_constructor_instance : env -> constructor -> pconstructor in_universe_context_set val fresh_global_instance : ?names:Univ.Instance.t -> env -> Globnames.global_reference -> constr in_universe_context_set val fresh_global_or_constr_instance : env -> Globnames.global_reference_or_constr -> constr in_universe_context_set * Get fresh variables for the universe context . Useful to make tactics that manipulate in universe contexts polymorphic . Useful to make tactics that manipulate constrs in universe contexts polymorphic. *) val fresh_universe_context_set_instance : universe_context_set -> universe_level_subst * universe_context_set val global_of_constr : constr -> Globnames.global_reference puniverses val global_app_of_constr : constr -> Globnames.global_reference puniverses * constr option val constr_of_global_univ : Globnames.global_reference puniverses -> constr val extend_context : 'a in_universe_context_set -> universe_context_set -> 'a in_universe_context_set module UF : Unionfind.PartitionSig with type elt = universe_level type universe_opt_subst = universe option universe_map val make_opt_subst : universe_opt_subst -> universe_subst_fn val subst_opt_univs_constr : universe_opt_subst -> constr -> constr val normalize_context_set : universe_context_set -> (universe_opt_subst * universe_set) in_universe_context_set val normalize_univ_variables : universe_opt_subst -> universe_opt_subst * universe_set * universe_set * universe_subst val normalize_univ_variable : find:(universe_level -> universe) -> update:(universe_level -> universe -> universe) -> universe_level -> universe val normalize_univ_variable_opt_subst : universe_opt_subst ref -> (universe_level -> universe) val normalize_univ_variable_subst : universe_subst ref -> (universe_level -> universe) val normalize_universe_opt_subst : universe_opt_subst ref -> (universe -> universe) val normalize_universe_subst : universe_subst ref -> (universe -> universe) val constr_of_global : Globnames.global_reference -> constr val constr_of_reference : Globnames.global_reference -> constr * [ unsafe_constr_of_global gr ] turns [ gr ] into a constr , works on polymorphic references by taking the original universe instance that is not recorded anywhere . The constraints are forgotten as well . DO NOT USE in new code . references by taking the original universe instance that is not recorded anywhere. The constraints are forgotten as well. DO NOT USE in new code. *) val unsafe_constr_of_global : Globnames.global_reference -> constr in_universe_context val type_of_global : Globnames.global_reference -> types in_universe_context_set val unsafe_type_of_global : Globnames.global_reference -> types val nf_evars_and_universes_opt_subst : (existential -> constr option) -> universe_opt_subst -> constr -> constr val universes_of_constr : constr -> universe_set val restrict_universe_context : universe_context_set -> universe_set -> universe_context_set val simplify_universe_context : universe_context_set -> universe_context_set * universe_level_subst val refresh_constraints : universes -> universe_context_set -> universe_context_set * universes val pr_universe_opt_subst : universe_opt_subst -> Pp.std_ppcmds type constraints_map = (Univ.constraint_type * Univ.LMap.key) list Univ.LMap.t val pr_constraints_map : constraints_map -> Pp.std_ppcmds universe_level * (universe_set * universe_set * universe_set) val compute_lbound : (constraint_type * Univ.universe) list -> universe option val instantiate_with_lbound : Univ.LMap.key -> Univ.universe -> bool -> bool -> Univ.LSet.t * Univ.universe option Univ.LMap.t * Univ.LSet.t * (bool * bool * Univ.universe) Univ.LMap.t * Univ.constraints -> (Univ.LSet.t * Univ.universe option Univ.LMap.t * Univ.LSet.t * (bool * bool * Univ.universe) Univ.LMap.t * Univ.constraints) * (bool * bool * Univ.universe) val minimize_univ_variables : Univ.LSet.t -> Univ.universe option Univ.LMap.t -> Univ.LSet.t -> constraints_map -> constraints_map -> Univ.constraints -> Univ.LSet.t * Univ.universe option Univ.LMap.t * Univ.LSet.t * (bool * bool * Univ.universe) Univ.LMap.t * Univ.constraints * { 6 Support for old - style sort - polymorphism } val solve_constraints_system : universe option array -> universe array -> universe array -> universe array
4ab7c16f1f51b73eb1371962aa48849c2d0a583b2fb4fdb4bd85fa27e4341b20
spurious/chibi-scheme-mirror
procedural.scm
(define (make-rtd name fields . o) (let ((parent (and (pair? o) (car o)))) (register-simple-type name parent (vector->list fields)))) (define (rtd? x) (type? x)) (define (rtd-constructor rtd . o) (let ((fields (vector->list (if (pair? o) (car o) (rtd-all-field-names rtd)))) (make (make-constructor (type-name rtd) rtd))) (lambda args (let ((res (make))) (let lp ((a args) (p fields)) (cond ((null? a) (if (null? p) res (error "not enough args" p))) ((null? p) (error "too many args" a)) (else (slot-set! rtd res (rtd-field-offset rtd (car p)) (car a)) (lp (cdr a) (cdr p))))))))) (define (rtd-predicate rtd) (make-type-predicate (type-name rtd) rtd)) (define (field-index-of ls field) (let lp ((i 0) (ls ls)) (cond ((null? ls ) #f) ((if (pair? (car ls)) (eq? field (car (cdar ls))) (eq? field (car ls))) i) (else (lp (+ i 1) (cdr ls)))))) (define (rtd-field-offset rtd field) (let ((p (type-parent rtd))) (or (and (type? p) (rtd-field-offset p field)) (let ((i (field-index-of (type-slots rtd) field))) (and i (if (type? p) (+ i (vector-length (rtd-all-field-names p))) i)))))) (define (rtd-accessor rtd field) (make-getter (type-name rtd) rtd (rtd-field-offset rtd field))) (define (rtd-mutator rtd field) (if (rtd-field-mutable? rtd field) (make-setter (type-name rtd) rtd (rtd-field-offset rtd field)) (error "can't make mutator for immutable field" rtd field)))
null
https://raw.githubusercontent.com/spurious/chibi-scheme-mirror/49168ab073f64a95c834b5f584a9aaea3469594d/lib/srfi/99/records/procedural.scm
scheme
(define (make-rtd name fields . o) (let ((parent (and (pair? o) (car o)))) (register-simple-type name parent (vector->list fields)))) (define (rtd? x) (type? x)) (define (rtd-constructor rtd . o) (let ((fields (vector->list (if (pair? o) (car o) (rtd-all-field-names rtd)))) (make (make-constructor (type-name rtd) rtd))) (lambda args (let ((res (make))) (let lp ((a args) (p fields)) (cond ((null? a) (if (null? p) res (error "not enough args" p))) ((null? p) (error "too many args" a)) (else (slot-set! rtd res (rtd-field-offset rtd (car p)) (car a)) (lp (cdr a) (cdr p))))))))) (define (rtd-predicate rtd) (make-type-predicate (type-name rtd) rtd)) (define (field-index-of ls field) (let lp ((i 0) (ls ls)) (cond ((null? ls ) #f) ((if (pair? (car ls)) (eq? field (car (cdar ls))) (eq? field (car ls))) i) (else (lp (+ i 1) (cdr ls)))))) (define (rtd-field-offset rtd field) (let ((p (type-parent rtd))) (or (and (type? p) (rtd-field-offset p field)) (let ((i (field-index-of (type-slots rtd) field))) (and i (if (type? p) (+ i (vector-length (rtd-all-field-names p))) i)))))) (define (rtd-accessor rtd field) (make-getter (type-name rtd) rtd (rtd-field-offset rtd field))) (define (rtd-mutator rtd field) (if (rtd-field-mutable? rtd field) (make-setter (type-name rtd) rtd (rtd-field-offset rtd field)) (error "can't make mutator for immutable field" rtd field)))
1962399238f9cc3f38553f6ea144200c07aab784ce1fd76fc2fda5b129b190e0
camsaul/toucan2
query_test.clj
(ns toucan2.query-test (:require [clojure.test :refer :all] [methodical.core :as m] [toucan2.model :as model] [toucan2.pipeline :as pipeline] [toucan2.query :as query] [toucan2.test :as test])) (deftest ^:parallel default-parse-args-test (are [args expected] (= expected (query/parse-args :default args)) [:model] {:modelable :model, :queryable {}} [:model {}] {:modelable :model, :queryable {}} [:model nil] {:modelable :model, :queryable nil} [[:model] {}] {:modelable :model, :queryable {}} [[:model :a :b :c] {}] {:modelable :model, :columns [:a :b :c], :queryable {}} [:model :k :v] {:modelable :model, :kv-args {:k :v}, :queryable {}} [:model :k :v {}] {:modelable :model, :kv-args {:k :v}, :queryable {}} [:conn :db :model] {:connectable :db, :modelable :model, :queryable {}} [:conn :db :model :query] {:connectable :db, :modelable :model, :queryable :query} [:conn :db [:model]] {:connectable :db, :modelable :model, :queryable {}} [:conn :db [:model :a] :query] {:connectable :db, :modelable :model, :columns [:a], :queryable :query} [:conn :db :model :id 1] {:connectable :db, :modelable :model, :kv-args {:id 1}, :queryable {}})) (derive ::venues.compound-pk ::test/venues) (m/defmethod model/primary-keys ::venues.compound-pk [_model] [:id :name]) (deftest ^:parallel toucan-pk-vector-forms-test (testing ":toucan/pk should work with vector forms like `:in`" (are [model arg expected] (= {:select [:*] :from [[:venues]] :where expected} (pipeline/build :toucan.query-type/select.instances model {:kv-args {:toucan/pk arg}} {})) ::test/venues 4 [:= :id 4] ::test/venues [4] [:= :id 4] ::test/venues [:> 4] [:> :id 4] ::test/venues [:in [4]] [:in :id [4]] ::test/venues [:in [4 5]] [:in :id [4 5]] ::test/venues [:between 4 5] [:between :id 4 5] ::venues.compound-pk [4 "BevMo"] [:and [:= :id 4] [:= :name "BevMo"]] ::venues.compound-pk [:> [4 "BevMo"]] [:and [:> :id 4] [:> :name "BevMo"]] ::venues.compound-pk [:in [[4 "BevMo"]]] [:and [:in :id [4]] [:in :name ["BevMo"]]] ::venues.compound-pk [:in [[4 "BevMo"] [5 "BevLess"]]] [:and [:in :id [4 5]] [:in :name ["BevMo" "BevLess"]]] ::venues.compound-pk [:between [4 "BevMo"] [5 "BevLess"]] [:and [:between :id 4 5] [:between :name "BevMo" "BevLess"]]))) (derive ::venues.namespaced ::test/venues) (m/defmethod model/model->namespace ::venues.namespaced [_model] {::test/venues :venue}) (deftest ^:parallel namespaced-toucan-pk-test (is (= {:select [:*] :from [[:venues :venue]] :where [:= :venue/id 1]} (pipeline/build :toucan.query-type/select.instances ::venues.namespaced {:kv-args {:toucan/pk 1}} {}))))
null
https://raw.githubusercontent.com/camsaul/toucan2/6d1e0df579c51a0bb128ca5586028d8b374c59be/test/toucan2/query_test.clj
clojure
(ns toucan2.query-test (:require [clojure.test :refer :all] [methodical.core :as m] [toucan2.model :as model] [toucan2.pipeline :as pipeline] [toucan2.query :as query] [toucan2.test :as test])) (deftest ^:parallel default-parse-args-test (are [args expected] (= expected (query/parse-args :default args)) [:model] {:modelable :model, :queryable {}} [:model {}] {:modelable :model, :queryable {}} [:model nil] {:modelable :model, :queryable nil} [[:model] {}] {:modelable :model, :queryable {}} [[:model :a :b :c] {}] {:modelable :model, :columns [:a :b :c], :queryable {}} [:model :k :v] {:modelable :model, :kv-args {:k :v}, :queryable {}} [:model :k :v {}] {:modelable :model, :kv-args {:k :v}, :queryable {}} [:conn :db :model] {:connectable :db, :modelable :model, :queryable {}} [:conn :db :model :query] {:connectable :db, :modelable :model, :queryable :query} [:conn :db [:model]] {:connectable :db, :modelable :model, :queryable {}} [:conn :db [:model :a] :query] {:connectable :db, :modelable :model, :columns [:a], :queryable :query} [:conn :db :model :id 1] {:connectable :db, :modelable :model, :kv-args {:id 1}, :queryable {}})) (derive ::venues.compound-pk ::test/venues) (m/defmethod model/primary-keys ::venues.compound-pk [_model] [:id :name]) (deftest ^:parallel toucan-pk-vector-forms-test (testing ":toucan/pk should work with vector forms like `:in`" (are [model arg expected] (= {:select [:*] :from [[:venues]] :where expected} (pipeline/build :toucan.query-type/select.instances model {:kv-args {:toucan/pk arg}} {})) ::test/venues 4 [:= :id 4] ::test/venues [4] [:= :id 4] ::test/venues [:> 4] [:> :id 4] ::test/venues [:in [4]] [:in :id [4]] ::test/venues [:in [4 5]] [:in :id [4 5]] ::test/venues [:between 4 5] [:between :id 4 5] ::venues.compound-pk [4 "BevMo"] [:and [:= :id 4] [:= :name "BevMo"]] ::venues.compound-pk [:> [4 "BevMo"]] [:and [:> :id 4] [:> :name "BevMo"]] ::venues.compound-pk [:in [[4 "BevMo"]]] [:and [:in :id [4]] [:in :name ["BevMo"]]] ::venues.compound-pk [:in [[4 "BevMo"] [5 "BevLess"]]] [:and [:in :id [4 5]] [:in :name ["BevMo" "BevLess"]]] ::venues.compound-pk [:between [4 "BevMo"] [5 "BevLess"]] [:and [:between :id 4 5] [:between :name "BevMo" "BevLess"]]))) (derive ::venues.namespaced ::test/venues) (m/defmethod model/model->namespace ::venues.namespaced [_model] {::test/venues :venue}) (deftest ^:parallel namespaced-toucan-pk-test (is (= {:select [:*] :from [[:venues :venue]] :where [:= :venue/id 1]} (pipeline/build :toucan.query-type/select.instances ::venues.namespaced {:kv-args {:toucan/pk 1}} {}))))
a2e87d34cf26db35f5a0fef86382fccd0eafd80944b3b42348dc988c64029313
na4zagin3/satyrographos
lint_prim.ml
open Core include Lint_problem module Location = Satyrographos.Location type location = | SatyristesModLoc of (string * string * (int * int) option) | FileLoc of Location.t | OpamLoc of string type level = [`Error | `Warning] [@@deriving equal] type diagnosis = { locs : location list; level : level; problem : problem; } let show_location ~outf ~basedir = let concat_with_basedir = FilePath.make_absolute basedir in function | SatyristesModLoc (buildscript_path, module_name, None) -> Format.fprintf outf "%s: (module %s):@." (concat_with_basedir buildscript_path) module_name | SatyristesModLoc (buildscript_path, module_name, Some (line, col)) -> Format.fprintf outf "%s:%d:%d: (module %s):@." (concat_with_basedir buildscript_path) line col module_name | FileLoc loc -> Format.fprintf outf "%s:@." (Location.display loc) | OpamLoc (opam_path) -> Format.fprintf outf "%s:@." (concat_with_basedir opam_path) let show_locations ~outf ~basedir locs = List.rev locs |> List.iter ~f:(show_location ~outf ~basedir) let show_problem ~outf ~basedir {locs; level; problem;} = show_locations ~outf ~basedir locs; Format.fprintf outf "@[<2>"; begin match level with | `Error-> Format.fprintf outf "Error: " | `Warning -> Format.fprintf outf "Warning: " end; Format.fprintf outf "%s@\n" (problem_class problem); show_problem ~outf problem; Format.fprintf outf "@]@.@." let show_problems ~outf ~basedir = List.iter ~f:(show_problem ~outf ~basedir) let get_opam_name ~opam ~opam_path = OpamFile.OPAM.name_opt opam |> Option.map ~f:OpamPackage.Name.to_string |> Option.value ~default:(FilePath.basename opam_path |> FilePath.chop_extension)
null
https://raw.githubusercontent.com/na4zagin3/satyrographos/9dbccf05138510c977a67c859bbbb48755470c7f/src/command/lint_prim.ml
ocaml
open Core include Lint_problem module Location = Satyrographos.Location type location = | SatyristesModLoc of (string * string * (int * int) option) | FileLoc of Location.t | OpamLoc of string type level = [`Error | `Warning] [@@deriving equal] type diagnosis = { locs : location list; level : level; problem : problem; } let show_location ~outf ~basedir = let concat_with_basedir = FilePath.make_absolute basedir in function | SatyristesModLoc (buildscript_path, module_name, None) -> Format.fprintf outf "%s: (module %s):@." (concat_with_basedir buildscript_path) module_name | SatyristesModLoc (buildscript_path, module_name, Some (line, col)) -> Format.fprintf outf "%s:%d:%d: (module %s):@." (concat_with_basedir buildscript_path) line col module_name | FileLoc loc -> Format.fprintf outf "%s:@." (Location.display loc) | OpamLoc (opam_path) -> Format.fprintf outf "%s:@." (concat_with_basedir opam_path) let show_locations ~outf ~basedir locs = List.rev locs |> List.iter ~f:(show_location ~outf ~basedir) let show_problem ~outf ~basedir {locs; level; problem;} = show_locations ~outf ~basedir locs; Format.fprintf outf "@[<2>"; begin match level with | `Error-> Format.fprintf outf "Error: " | `Warning -> Format.fprintf outf "Warning: " end; Format.fprintf outf "%s@\n" (problem_class problem); show_problem ~outf problem; Format.fprintf outf "@]@.@." let show_problems ~outf ~basedir = List.iter ~f:(show_problem ~outf ~basedir) let get_opam_name ~opam ~opam_path = OpamFile.OPAM.name_opt opam |> Option.map ~f:OpamPackage.Name.to_string |> Option.value ~default:(FilePath.basename opam_path |> FilePath.chop_extension)
ed2b1f52fcdf3b2a39f91aafe7d83d5e94a412554bd4967227a8c7bd96ff8364
maranget/hevea
version.mli
(***********************************************************************) (* *) (* HEVEA *) (* *) , projet PARA , INRIA Rocquencourt (* *) Copyright 1998 Institut National de Recherche en Informatique et Automatique . Distributed only by permission . (* *) (***********************************************************************) val version : string
null
https://raw.githubusercontent.com/maranget/hevea/226eac8c506f82a600d453492fbc1b9784dd865f/version.mli
ocaml
********************************************************************* HEVEA *********************************************************************
, projet PARA , INRIA Rocquencourt Copyright 1998 Institut National de Recherche en Informatique et Automatique . Distributed only by permission . val version : string
80801f9a2db2d154c4910346c8c0471d946f09ac59a12a5b72810559962ad63d
sile/logi
logi_sink_set_sup.erl
2014 - 2016 < > %% @doc Supervisor for logi_sink_sup processes @private %% @end -module(logi_sink_set_sup). -behaviour(supervisor). %%---------------------------------------------------------------------------------------------------------------------- %% Exported API %%---------------------------------------------------------------------------------------------------------------------- -export([start_link/0]). -export([start_child/3]). -export([stop_child/2]). %%---------------------------------------------------------------------------------------------------------------------- %% 'supervisor' Callback API %%---------------------------------------------------------------------------------------------------------------------- -export([init/1]). %%---------------------------------------------------------------------------------------------------------------------- %% Exported Functions %%---------------------------------------------------------------------------------------------------------------------- %% @doc Starts a supervisor -spec start_link() -> {ok, pid()} | {error, Reason::term()}. start_link() -> supervisor:start_link(?MODULE, [self()]). %% @doc Starts a new child (i.e., logi_sink_sup process) -spec start_child(pid(), logi_sink:id(), supervisor:sup_flags()) -> {ok, logi_sink_proc:sink_sup()} | {error, Reason::term()}. start_child(Sup, SinkId, Flags) -> supervisor:start_child(Sup, [SinkId, Flags]). %% @doc Stops the child -spec stop_child(pid(), logi_sink_proc:sink_sup()) -> ok. stop_child(Sup, SinkSup) -> _ = supervisor:terminate_child(Sup, SinkSup), ok. %%---------------------------------------------------------------------------------------------------------------------- %% 'supervisor' Callback Functions %%---------------------------------------------------------------------------------------------------------------------- @private init([ParentSup]) -> ok = logi_sink_proc:register_grandchildren_sup(ParentSup, self()), Child = #{id => sink_sup, start => {logi_sink_sup, start_link, []}, restart => temporary, type => supervisor}, {ok, {#{strategy => simple_one_for_one}, [Child]}}.
null
https://raw.githubusercontent.com/sile/logi/1022fbc238a7d18765fe864a7174958142160ee8/src/logi_sink_set_sup.erl
erlang
@end ---------------------------------------------------------------------------------------------------------------------- Exported API ---------------------------------------------------------------------------------------------------------------------- ---------------------------------------------------------------------------------------------------------------------- 'supervisor' Callback API ---------------------------------------------------------------------------------------------------------------------- ---------------------------------------------------------------------------------------------------------------------- Exported Functions ---------------------------------------------------------------------------------------------------------------------- @doc Starts a supervisor @doc Starts a new child (i.e., logi_sink_sup process) @doc Stops the child ---------------------------------------------------------------------------------------------------------------------- 'supervisor' Callback Functions ----------------------------------------------------------------------------------------------------------------------
2014 - 2016 < > @doc Supervisor for logi_sink_sup processes @private -module(logi_sink_set_sup). -behaviour(supervisor). -export([start_link/0]). -export([start_child/3]). -export([stop_child/2]). -export([init/1]). -spec start_link() -> {ok, pid()} | {error, Reason::term()}. start_link() -> supervisor:start_link(?MODULE, [self()]). -spec start_child(pid(), logi_sink:id(), supervisor:sup_flags()) -> {ok, logi_sink_proc:sink_sup()} | {error, Reason::term()}. start_child(Sup, SinkId, Flags) -> supervisor:start_child(Sup, [SinkId, Flags]). -spec stop_child(pid(), logi_sink_proc:sink_sup()) -> ok. stop_child(Sup, SinkSup) -> _ = supervisor:terminate_child(Sup, SinkSup), ok. @private init([ParentSup]) -> ok = logi_sink_proc:register_grandchildren_sup(ParentSup, self()), Child = #{id => sink_sup, start => {logi_sink_sup, start_link, []}, restart => temporary, type => supervisor}, {ok, {#{strategy => simple_one_for_one}, [Child]}}.
4a5ba20277d72ef58e3f81149af77fc1ca3de88a6b08a263aef4fb5aa4cbf544
NorfairKing/sydtest
AroundCombinationSpec.hs
# LANGUAGE DataKinds # # LANGUAGE ScopedTypeVariables # # LANGUAGE TypeFamilies # module Test.Syd.AroundCombinationSpec (spec) where import Control.Concurrent.STM import Control.Monad.IO.Class import Test.Syd spec :: Spec spec = sequential $ doNotRandomiseExecutionOrder $ do describe "aroundAll + aroundAllWith + around + aroundWith'" $ do var <- liftIO $ newTVarIO (0 :: Int) let readAndIncrement :: IO Int readAndIncrement = atomically $ stateTVar var $ \i -> (i + 1, i + 1) let increment :: IO () increment = atomically $ modifyTVar var (+ 1) let incrementAround :: (Int -> IO ()) -> IO () incrementAround func = do i <- readAndIncrement func i increment let incrementAroundWith :: (Int -> IO ()) -> Int -> IO () incrementAroundWith func j = do i <- readAndIncrement func (i + j) increment let incrementAroundWith2 :: (Int -> Int -> IO ()) -> Int -> Int -> IO () incrementAroundWith2 func j k = do i <- readAndIncrement func (i + j) k increment aroundAll incrementAround $ aroundAllWith incrementAroundWith $ around incrementAround $ aroundWith' incrementAroundWith2 $ do itWithBoth "reads correctly" $ \i k -> (i, k) `shouldBe` (3, 3) itWithBoth "reads correctly" $ \i k -> (i, k) `shouldBe` (3, 7)
null
https://raw.githubusercontent.com/NorfairKing/sydtest/0fad471cee677a4018acbe1983385dfc9a1b49d2/sydtest/test/Test/Syd/AroundCombinationSpec.hs
haskell
# LANGUAGE DataKinds # # LANGUAGE ScopedTypeVariables # # LANGUAGE TypeFamilies # module Test.Syd.AroundCombinationSpec (spec) where import Control.Concurrent.STM import Control.Monad.IO.Class import Test.Syd spec :: Spec spec = sequential $ doNotRandomiseExecutionOrder $ do describe "aroundAll + aroundAllWith + around + aroundWith'" $ do var <- liftIO $ newTVarIO (0 :: Int) let readAndIncrement :: IO Int readAndIncrement = atomically $ stateTVar var $ \i -> (i + 1, i + 1) let increment :: IO () increment = atomically $ modifyTVar var (+ 1) let incrementAround :: (Int -> IO ()) -> IO () incrementAround func = do i <- readAndIncrement func i increment let incrementAroundWith :: (Int -> IO ()) -> Int -> IO () incrementAroundWith func j = do i <- readAndIncrement func (i + j) increment let incrementAroundWith2 :: (Int -> Int -> IO ()) -> Int -> Int -> IO () incrementAroundWith2 func j k = do i <- readAndIncrement func (i + j) k increment aroundAll incrementAround $ aroundAllWith incrementAroundWith $ around incrementAround $ aroundWith' incrementAroundWith2 $ do itWithBoth "reads correctly" $ \i k -> (i, k) `shouldBe` (3, 3) itWithBoth "reads correctly" $ \i k -> (i, k) `shouldBe` (3, 7)
4b718162bca9dfae9362d688eb0b7e21ba4f5eaacba14c30110d987a9d1c3394
Helium4Haskell/helium
Guards7.hs
main :: [Int] -> () main [] = () main (1:xs) | False = ()
null
https://raw.githubusercontent.com/Helium4Haskell/helium/5928bff479e6f151b4ceb6c69bbc15d71e29eb47/test/staticwarnings/Guards7.hs
haskell
main :: [Int] -> () main [] = () main (1:xs) | False = ()
cdbbc049dbef397a07247c8090cfcaa24891666f44a2650817b6dcc9ba55e9c5
ScottBrooks/Erlcraft
mc_util.erl
-module(mc_util). -compile(export_all). write_packet(PacketID, Contents) -> BinaryData = encode_list(Contents), <<PacketID:8, BinaryData/binary>>. or_binaries(BinA, BinB) when size(BinA) =:= size(BinB) -> or_binaries(BinA, BinB, <<>>). or_binaries(<<>>, <<>>, Buffer) -> Buffer; or_binaries(BinA, BinB, Buffer) -> <<A:8/integer, RestA/binary>> = BinA, <<B:8/integer, RestB/binary>> = BinB, C = A bor B, NewBuffer = <<Buffer/binary, C:8/integer>>, or_binaries(RestA, RestB, NewBuffer). expand_4_to_8(Bytes) -> expand_4_to_8(Bytes, <<>>). expand_4_to_8(<<>>, Buffer) -> Buffer; expand_4_to_8(Bytes, Buffer) -> <<Chunk:4/bits, Rest/bits>> = Bytes, ByteChunk = << <<0:4>>/bits, Chunk/bits>>, NewBuff = <<Buffer/bits, ByteChunk/bits>>, expand_4_to_8(Rest, NewBuff). encode_list([], Acc) -> Acc; encode_list([H|T], Acc) -> Value = encode_value(H), encode_list(T, <<Acc/binary, Value/bits>>). encode_list(List) -> encode_list(List, <<>>). encode_value({int, Int}) when is_integer(Int)-> <<Int:32/integer-signed-big>>; encode_value({bool, Bool}) when is_integer(Bool) -> <<Bool:8>>; encode_value({long, Long}) when is_integer(Long) -> <<Long:64/integer-signed-big>>; encode_value({short, Short}) when is_integer(Short) -> <<Short:16/integer-signed-big>>; encode_value({byte, Byte}) when is_integer(Byte) -> <<Byte:8>>; encode_value({nibble, Nibble}) when is_integer(Nibble) -> <<Nibble:4>>; encode_value({double, Double}) when is_float(Double)-> <<Double:64/float>>; encode_value({double, Double}) when is_integer(Double) -> encode_value({double, float(Double)}); encode_value({float, Float}) when is_float(Float) -> <<Float:32/float>>; encode_value({float, Float}) when is_integer(Float) -> encode_value({float, float(Float)}); encode_value({binary, Binary}) when is_binary(Binary) -> Binary; encode_value({string, String}) when is_list(String) -> Len = length(String), BinVal = list_to_binary(String), <<Len:16/integer-signed-big, BinVal/binary>>. block_chunk()-> [{byte,1}, {byte,1},{nibble,5}]. chunk_size(X,Y,Z)-> Size = round(X * Y * Z * 2.5), io:format("Chunk Size: ~p~n", [Size]), Size. chunk_data(Blocks) -> Array = array:map(fun(Idx,_Value) -> Z = trunc(Idx/2048), X = trunc((Idx-Z*2048)/128), Y = Idx - Z*2048 - X*128, Light = case 128-Y of Dark when Dark >= 0, Dark =< 63 -> 0; _ -> 255 end, case 128-Y of 0 -> %io:format("Bedrock: [~p, ~p, ~p]~n", [X, Y, Z]), {block, 7, 0, Light}; Ground when Ground >=0, Ground =< 63 -> io : format("Dirt : [ ~p , ~p , ~p]~n " , [ X , Y , Z ] ) , {block, 3,0,Light}; Ground when Ground == 64 -> %io:format("Grass: [~p, ~p, ~p]~n", [X, Y, Z]), {block, 2,0,Light}; _ -> %io:format("Air: [~p, ~p, ~p]~n", [X, Y, Z]), {block, 0,0,Light} end end, array:new(Blocks)), lists:flatten(array:foldl( fun(_Idx, Value, [Type,Meta,Light]) -> {block, BType, BMeta, BLight} = Value, [[{byte, BType}|Type], [{byte, BMeta}|Meta], [{nibble,BLight}|Light]] end, [[],[],[]], Array)).
null
https://raw.githubusercontent.com/ScottBrooks/Erlcraft/ed336eb8da4d83e937687ce34feecb76b4128288/src/mc_util.erl
erlang
io:format("Bedrock: [~p, ~p, ~p]~n", [X, Y, Z]), io:format("Grass: [~p, ~p, ~p]~n", [X, Y, Z]), io:format("Air: [~p, ~p, ~p]~n", [X, Y, Z]),
-module(mc_util). -compile(export_all). write_packet(PacketID, Contents) -> BinaryData = encode_list(Contents), <<PacketID:8, BinaryData/binary>>. or_binaries(BinA, BinB) when size(BinA) =:= size(BinB) -> or_binaries(BinA, BinB, <<>>). or_binaries(<<>>, <<>>, Buffer) -> Buffer; or_binaries(BinA, BinB, Buffer) -> <<A:8/integer, RestA/binary>> = BinA, <<B:8/integer, RestB/binary>> = BinB, C = A bor B, NewBuffer = <<Buffer/binary, C:8/integer>>, or_binaries(RestA, RestB, NewBuffer). expand_4_to_8(Bytes) -> expand_4_to_8(Bytes, <<>>). expand_4_to_8(<<>>, Buffer) -> Buffer; expand_4_to_8(Bytes, Buffer) -> <<Chunk:4/bits, Rest/bits>> = Bytes, ByteChunk = << <<0:4>>/bits, Chunk/bits>>, NewBuff = <<Buffer/bits, ByteChunk/bits>>, expand_4_to_8(Rest, NewBuff). encode_list([], Acc) -> Acc; encode_list([H|T], Acc) -> Value = encode_value(H), encode_list(T, <<Acc/binary, Value/bits>>). encode_list(List) -> encode_list(List, <<>>). encode_value({int, Int}) when is_integer(Int)-> <<Int:32/integer-signed-big>>; encode_value({bool, Bool}) when is_integer(Bool) -> <<Bool:8>>; encode_value({long, Long}) when is_integer(Long) -> <<Long:64/integer-signed-big>>; encode_value({short, Short}) when is_integer(Short) -> <<Short:16/integer-signed-big>>; encode_value({byte, Byte}) when is_integer(Byte) -> <<Byte:8>>; encode_value({nibble, Nibble}) when is_integer(Nibble) -> <<Nibble:4>>; encode_value({double, Double}) when is_float(Double)-> <<Double:64/float>>; encode_value({double, Double}) when is_integer(Double) -> encode_value({double, float(Double)}); encode_value({float, Float}) when is_float(Float) -> <<Float:32/float>>; encode_value({float, Float}) when is_integer(Float) -> encode_value({float, float(Float)}); encode_value({binary, Binary}) when is_binary(Binary) -> Binary; encode_value({string, String}) when is_list(String) -> Len = length(String), BinVal = list_to_binary(String), <<Len:16/integer-signed-big, BinVal/binary>>. block_chunk()-> [{byte,1}, {byte,1},{nibble,5}]. chunk_size(X,Y,Z)-> Size = round(X * Y * Z * 2.5), io:format("Chunk Size: ~p~n", [Size]), Size. chunk_data(Blocks) -> Array = array:map(fun(Idx,_Value) -> Z = trunc(Idx/2048), X = trunc((Idx-Z*2048)/128), Y = Idx - Z*2048 - X*128, Light = case 128-Y of Dark when Dark >= 0, Dark =< 63 -> 0; _ -> 255 end, case 128-Y of 0 -> {block, 7, 0, Light}; Ground when Ground >=0, Ground =< 63 -> io : format("Dirt : [ ~p , ~p , ~p]~n " , [ X , Y , Z ] ) , {block, 3,0,Light}; Ground when Ground == 64 -> {block, 2,0,Light}; _ -> {block, 0,0,Light} end end, array:new(Blocks)), lists:flatten(array:foldl( fun(_Idx, Value, [Type,Meta,Light]) -> {block, BType, BMeta, BLight} = Value, [[{byte, BType}|Type], [{byte, BMeta}|Meta], [{nibble,BLight}|Light]] end, [[],[],[]], Array)).
8a944d29dba74461f8c4bf11a0a3debc602a61cadbcff2c1ce0edd4a08d3129f
AbstractMachinesLab/caramel
builtin_attributes.ml
open Asttypes open Parsetree let string_of_cst = function | Pconst_string(s, _) -> Some s | _ -> None let string_of_payload = function | PStr[{pstr_desc=Pstr_eval({pexp_desc=Pexp_constant c},_)}] -> string_of_cst c | _ -> None let warning_scope = ref [] let warning_enter_scope () = warning_scope := (Warnings.backup ()) :: !warning_scope let warning_leave_scope () = match !warning_scope with | [] -> assert false | hd :: tl -> Warnings.restore hd; warning_scope := tl let warning_attribute attrs = let process loc txt errflag payload = match string_of_payload payload with | Some s -> begin try Warnings.parse_options errflag s with Arg.Bad _ -> Location.prerr_warning loc (Warnings.Attribute_payload (txt, "Ill-formed list of warnings")) end | None -> Location.prerr_warning loc (Warnings.Attribute_payload (txt, "A single string literal is expected")) in List.iter (function | ({txt = ("ocaml.warning"|"warning") as txt; loc}, payload) -> process loc txt false payload | ({txt = ("ocaml.warnerror"|"warnerror") as txt; loc}, payload) -> process loc txt true payload | _ -> () ) attrs let with_warning_attribute attrs f = warning_enter_scope (); warning_attribute attrs; match f () with | result -> warning_leave_scope (); result | exception exn -> warning_leave_scope (); Std.reraise exn let warning_scope ?ppwarning:_ attrs f = let prev = Warnings.backup () in try warning_attribute attrs; let ret = f () in Warnings.restore prev; ret with exn -> Warnings.restore prev; raise exn
null
https://raw.githubusercontent.com/AbstractMachinesLab/caramel/7d4e505d6032e22a630d2e3bd7085b77d0efbb0c/vendor/ocaml-lsp-1.4.0/ocaml-lsp-server/vendor/merlin/src/ocaml/parsing/402/builtin_attributes.ml
ocaml
open Asttypes open Parsetree let string_of_cst = function | Pconst_string(s, _) -> Some s | _ -> None let string_of_payload = function | PStr[{pstr_desc=Pstr_eval({pexp_desc=Pexp_constant c},_)}] -> string_of_cst c | _ -> None let warning_scope = ref [] let warning_enter_scope () = warning_scope := (Warnings.backup ()) :: !warning_scope let warning_leave_scope () = match !warning_scope with | [] -> assert false | hd :: tl -> Warnings.restore hd; warning_scope := tl let warning_attribute attrs = let process loc txt errflag payload = match string_of_payload payload with | Some s -> begin try Warnings.parse_options errflag s with Arg.Bad _ -> Location.prerr_warning loc (Warnings.Attribute_payload (txt, "Ill-formed list of warnings")) end | None -> Location.prerr_warning loc (Warnings.Attribute_payload (txt, "A single string literal is expected")) in List.iter (function | ({txt = ("ocaml.warning"|"warning") as txt; loc}, payload) -> process loc txt false payload | ({txt = ("ocaml.warnerror"|"warnerror") as txt; loc}, payload) -> process loc txt true payload | _ -> () ) attrs let with_warning_attribute attrs f = warning_enter_scope (); warning_attribute attrs; match f () with | result -> warning_leave_scope (); result | exception exn -> warning_leave_scope (); Std.reraise exn let warning_scope ?ppwarning:_ attrs f = let prev = Warnings.backup () in try warning_attribute attrs; let ret = f () in Warnings.restore prev; ret with exn -> Warnings.restore prev; raise exn
fcd672a7d0cd4e8ad438857ce189b732e24c8c7aa1ecda181c15bbf7343e99d2
Quid2/zm
String.hs
{-# LANGUAGE DeriveAnyClass #-} {-# LANGUAGE DeriveGeneric #-} module ZM.Type.String ( String(..) ) where import Control.DeepSeq import Flat import Data.Model import Prelude hiding ( String ) import ZM.Model ( ) data String = String [Char] deriving (Eq, Ord, Show, Generic, Flat, Model, NFData)
null
https://raw.githubusercontent.com/Quid2/zm/02c0514777a75ac054bfd6251edd884372faddea/src/ZM/Type/String.hs
haskell
# LANGUAGE DeriveAnyClass # # LANGUAGE DeriveGeneric #
module ZM.Type.String ( String(..) ) where import Control.DeepSeq import Flat import Data.Model import Prelude hiding ( String ) import ZM.Model ( ) data String = String [Char] deriving (Eq, Ord, Show, Generic, Flat, Model, NFData)
19e7e3febef6020103c02eb1e5c62298f2e83ee06226d9d3dfb77f6722dd2104
haskell-tls/hs-certificate
Unix.hs
-- | -- Module : System.X509 -- License : BSD-style Maintainer : < > -- Stability : experimental -- Portability : unix only -- -- this module is portable to unix system where there is usually -- a /etc/ssl/certs with system X509 certificates. -- -- the path can be dynamically override using the environment variable -- defined by envPathOverride in the module, which by -- default is SYSTEM_CERTIFICATE_PATH -- module System.X509.Unix ( getSystemCertificateStore ) where import System.Environment (getEnv) import Data.X509.CertificateStore import Control.Applicative ((<$>)) import qualified Control.Exception as E import Data.Maybe (catMaybes) import Data.Monoid (mconcat) defaultSystemPaths :: [FilePath] defaultSystemPaths = [ "/etc/ssl/certs/" -- linux android , "/etc/ssl/cert.pem" -- openbsd ] envPathOverride :: String envPathOverride = "SYSTEM_CERTIFICATE_PATH" getSystemCertificateStore :: IO CertificateStore getSystemCertificateStore = mconcat . catMaybes <$> (getSystemPaths >>= mapM readCertificateStore) getSystemPaths :: IO [FilePath] getSystemPaths = E.catch ((:[]) <$> getEnv envPathOverride) inDefault where inDefault :: E.IOException -> IO [FilePath] inDefault _ = return defaultSystemPaths
null
https://raw.githubusercontent.com/haskell-tls/hs-certificate/4a0a2ce292ea46c0c5f72e1d31eca2001079cdd2/x509-system/System/X509/Unix.hs
haskell
| Module : System.X509 License : BSD-style Stability : experimental Portability : unix only this module is portable to unix system where there is usually a /etc/ssl/certs with system X509 certificates. the path can be dynamically override using the environment variable defined by envPathOverride in the module, which by default is SYSTEM_CERTIFICATE_PATH linux openbsd
Maintainer : < > module System.X509.Unix ( getSystemCertificateStore ) where import System.Environment (getEnv) import Data.X509.CertificateStore import Control.Applicative ((<$>)) import qualified Control.Exception as E import Data.Maybe (catMaybes) import Data.Monoid (mconcat) defaultSystemPaths :: [FilePath] defaultSystemPaths = android ] envPathOverride :: String envPathOverride = "SYSTEM_CERTIFICATE_PATH" getSystemCertificateStore :: IO CertificateStore getSystemCertificateStore = mconcat . catMaybes <$> (getSystemPaths >>= mapM readCertificateStore) getSystemPaths :: IO [FilePath] getSystemPaths = E.catch ((:[]) <$> getEnv envPathOverride) inDefault where inDefault :: E.IOException -> IO [FilePath] inDefault _ = return defaultSystemPaths
b9afa242c60e83f9d19a224d21dd0fb9cd6a8efb922d6a85a312e69794dc9bc5
AccelerateHS/accelerate-examples
Config.hs
# LANGUAGE TemplateHaskell # module Config where import Data.Label import System.Console.GetOpt -- Configuration options -- data Config = Config deriving Show $(mkLabels [''Config]) defaults :: Config defaults = Config -- The set of available command line options -- options :: [OptDescr (Config -> Config)] options = [] -- Command line decoration -- header :: [String] header = [ "accelerate-kmeans (c) [2014..2020] The Accelerate Team" , "" , "Usage: accelerate-kmeans [OPTIONS]" , "" , "Be sure to first build and run the GenSamples program, in order to" , "generate some random data points." , "" ] footer :: [String] footer = [ "" ]
null
https://raw.githubusercontent.com/AccelerateHS/accelerate-examples/a973ee423b5eadda6ef2e2504d2383f625e49821/examples/kmeans/Config.hs
haskell
Configuration options The set of available command line options Command line decoration
# LANGUAGE TemplateHaskell # module Config where import Data.Label import System.Console.GetOpt data Config = Config deriving Show $(mkLabels [''Config]) defaults :: Config defaults = Config options :: [OptDescr (Config -> Config)] options = [] header :: [String] header = [ "accelerate-kmeans (c) [2014..2020] The Accelerate Team" , "" , "Usage: accelerate-kmeans [OPTIONS]" , "" , "Be sure to first build and run the GenSamples program, in order to" , "generate some random data points." , "" ] footer :: [String] footer = [ "" ]
333d7ad658ed643f70ee1208e0812b3607924fb6252b741378a1812113650f9b
facebook/infer
cField_decl.ml
* Copyright ( c ) Facebook , Inc. and its affiliates . * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree . * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. *) open! IStd (** Utility module to retrieve fields of structs of classes *) module L = Logging type field_type = Fieldname.t * Typ.t * Annot.Item.t let rec get_fields_super_classes tenv super_class = L.(debug Capture Verbose) " ... Getting fields of superclass '%s'@\n" (Typ.Name.to_string super_class) ; match Tenv.lookup tenv super_class with | None -> [] | Some {fields; supers= super_class :: _} -> let sc_fields = get_fields_super_classes tenv super_class in CGeneral_utils.append_no_duplicates_fields fields sc_fields | Some {fields} -> fields let fields_superclass tenv otdi_super = match otdi_super with | Some dr -> ( match dr.Clang_ast_t.dr_name with | Some sc -> let classname = Typ.Name.Objc.from_qual_name (CAst_utils.get_qualified_name sc) in get_fields_super_classes tenv classname | _ -> [] ) | _ -> [] let build_sil_field qual_type_to_sil_type tenv class_tname ni_name qual_type prop_attributes = let prop_atts = List.map ~f:(fun att -> Annot.{name= None; value= Str (Clang_ast_j.string_of_property_attribute att)}) prop_attributes in let annotation_from_type t = match t.Typ.desc with | Typ.Tptr (_, Typ.Pk_objc_weak) -> [Annot.{name= None; value= Str Config.weak}] | Typ.Tptr (_, Typ.Pk_objc_unsafe_unretained) -> [Annot.{name= None; value= Str Config.unsafe_unret}] | _ -> [] in let fname = CGeneral_utils.mk_class_field_name class_tname ni_name in let typ = qual_type_to_sil_type tenv qual_type in let item_annotations = match prop_atts with | [] -> {Annot.class_name= Config.ivar_attributes; parameters= annotation_from_type typ} | _ -> {Annot.class_name= Config.property_attributes; parameters= prop_atts} in let item_annotations = item_annotations :: CAst_utils.sil_annot_of_type qual_type in (fname, typ, item_annotations) (* Given a list of declarations in an interface returns a list of fields *) let get_fields ~implements_remodel_class qual_type_to_sil_type tenv class_tname decl_list = let open Clang_ast_t in let get_sil_field ni_name (qt : qual_type) property_attributes = build_sil_field qual_type_to_sil_type tenv class_tname ni_name qt property_attributes in let rec get_field fields decl = match decl with | ObjCPropertyDecl (_, {ni_name}, {opdi_qual_type; opdi_ivar_decl; opdi_property_attributes}) -> let ni_name, qual_type = match CAst_utils.get_decl_opt_with_decl_ref_opt opdi_ivar_decl with | Some (ObjCIvarDecl (_, {ni_name}, qual_type, _, _)) -> (ni_name, qual_type) | _ -> let ni_name = if implements_remodel_class then "_" ^ ni_name else ni_name in (ni_name, opdi_qual_type) in let field = get_sil_field ni_name qual_type opdi_property_attributes in CGeneral_utils.add_no_duplicates_fields field fields | ObjCPropertyImplDecl (_, obj_c_property_impl_decl_info) -> ( let property_decl_opt = obj_c_property_impl_decl_info.Clang_ast_t.opidi_property_decl in match CAst_utils.get_decl_opt_with_decl_ref_opt property_decl_opt with | Some decl -> get_field fields decl | None -> fields ) | ObjCIvarDecl (_, {ni_name}, qual_type, _, _) -> let field = get_sil_field ni_name qual_type [] in CGeneral_utils.add_no_duplicates_fields field fields | _ -> fields in List.fold ~f:get_field ~init:[] decl_list let modelled_fields_in_classes = [("NSArray", "elementData", Typ.mk (Tint Typ.IInt))] let modelled_field class_name_info = let modelled_field_in_class res (class_name, field_name, typ) = if String.equal class_name class_name_info.Clang_ast_t.ni_name then let class_tname = Typ.Name.Objc.from_string class_name in let name = Fieldname.make class_tname field_name in (name, typ, Annot.Item.empty) :: res else res in List.fold ~f:modelled_field_in_class ~init:[] modelled_fields_in_classes
null
https://raw.githubusercontent.com/facebook/infer/432243b21f4990c3071ba0b3ee2a472a215be1c6/infer/src/clang/cField_decl.ml
ocaml
* Utility module to retrieve fields of structs of classes Given a list of declarations in an interface returns a list of fields
* Copyright ( c ) Facebook , Inc. and its affiliates . * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree . * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. *) open! IStd module L = Logging type field_type = Fieldname.t * Typ.t * Annot.Item.t let rec get_fields_super_classes tenv super_class = L.(debug Capture Verbose) " ... Getting fields of superclass '%s'@\n" (Typ.Name.to_string super_class) ; match Tenv.lookup tenv super_class with | None -> [] | Some {fields; supers= super_class :: _} -> let sc_fields = get_fields_super_classes tenv super_class in CGeneral_utils.append_no_duplicates_fields fields sc_fields | Some {fields} -> fields let fields_superclass tenv otdi_super = match otdi_super with | Some dr -> ( match dr.Clang_ast_t.dr_name with | Some sc -> let classname = Typ.Name.Objc.from_qual_name (CAst_utils.get_qualified_name sc) in get_fields_super_classes tenv classname | _ -> [] ) | _ -> [] let build_sil_field qual_type_to_sil_type tenv class_tname ni_name qual_type prop_attributes = let prop_atts = List.map ~f:(fun att -> Annot.{name= None; value= Str (Clang_ast_j.string_of_property_attribute att)}) prop_attributes in let annotation_from_type t = match t.Typ.desc with | Typ.Tptr (_, Typ.Pk_objc_weak) -> [Annot.{name= None; value= Str Config.weak}] | Typ.Tptr (_, Typ.Pk_objc_unsafe_unretained) -> [Annot.{name= None; value= Str Config.unsafe_unret}] | _ -> [] in let fname = CGeneral_utils.mk_class_field_name class_tname ni_name in let typ = qual_type_to_sil_type tenv qual_type in let item_annotations = match prop_atts with | [] -> {Annot.class_name= Config.ivar_attributes; parameters= annotation_from_type typ} | _ -> {Annot.class_name= Config.property_attributes; parameters= prop_atts} in let item_annotations = item_annotations :: CAst_utils.sil_annot_of_type qual_type in (fname, typ, item_annotations) let get_fields ~implements_remodel_class qual_type_to_sil_type tenv class_tname decl_list = let open Clang_ast_t in let get_sil_field ni_name (qt : qual_type) property_attributes = build_sil_field qual_type_to_sil_type tenv class_tname ni_name qt property_attributes in let rec get_field fields decl = match decl with | ObjCPropertyDecl (_, {ni_name}, {opdi_qual_type; opdi_ivar_decl; opdi_property_attributes}) -> let ni_name, qual_type = match CAst_utils.get_decl_opt_with_decl_ref_opt opdi_ivar_decl with | Some (ObjCIvarDecl (_, {ni_name}, qual_type, _, _)) -> (ni_name, qual_type) | _ -> let ni_name = if implements_remodel_class then "_" ^ ni_name else ni_name in (ni_name, opdi_qual_type) in let field = get_sil_field ni_name qual_type opdi_property_attributes in CGeneral_utils.add_no_duplicates_fields field fields | ObjCPropertyImplDecl (_, obj_c_property_impl_decl_info) -> ( let property_decl_opt = obj_c_property_impl_decl_info.Clang_ast_t.opidi_property_decl in match CAst_utils.get_decl_opt_with_decl_ref_opt property_decl_opt with | Some decl -> get_field fields decl | None -> fields ) | ObjCIvarDecl (_, {ni_name}, qual_type, _, _) -> let field = get_sil_field ni_name qual_type [] in CGeneral_utils.add_no_duplicates_fields field fields | _ -> fields in List.fold ~f:get_field ~init:[] decl_list let modelled_fields_in_classes = [("NSArray", "elementData", Typ.mk (Tint Typ.IInt))] let modelled_field class_name_info = let modelled_field_in_class res (class_name, field_name, typ) = if String.equal class_name class_name_info.Clang_ast_t.ni_name then let class_tname = Typ.Name.Objc.from_string class_name in let name = Fieldname.make class_tname field_name in (name, typ, Annot.Item.empty) :: res else res in List.fold ~f:modelled_field_in_class ~init:[] modelled_fields_in_classes
43d5238888d1394c7a958cb73c2ceb33b96e76d5123c35e61b0774e5fb9f5cc3
rd--/hsc3
oscN.help.hs
-- c.f . osc
null
https://raw.githubusercontent.com/rd--/hsc3/60cb422f0e2049f00b7e15076b2667b85ad8f638/Help/Ugen/oscN.help.hs
haskell
c.f . osc
1f39fe5297be4e7c3256290eb9d37ca2c3e3015598445303238140e6fc25d1b5
hercules-ci/hercules-ci-agent
AttributeEffectEventSpec.hs
module Hercules.API.Agent.Evaluate.EvaluateEvent.AttributeEffectEventSpec where import Data.Aeson (Value, eitherDecode, encode) import qualified Data.ByteString.Lazy as BL import qualified Data.Map as M import Hercules.API.Agent.Evaluate.EvaluateEvent.AttributeEffectEvent (AttributeEffectEvent (AttributeEffectEvent), GitToken (MkGitToken), SecretRef (..), SimpleSecret (MkSimpleSecret)) import qualified Hercules.API.Agent.Evaluate.EvaluateEvent.AttributeEffectEvent import Test.Hspec import Prelude objectV1 :: AttributeEffectEvent objectV1 = AttributeEffectEvent { expressionPath = ["effects", "doIt"], derivationPath = "/nix/store/bar.drv", secretsToUse = M.fromList [ ("foo", (SimpleSecret MkSimpleSecret {name = "default-foo"})), ("bar", (GitToken MkGitToken {})) ] } jsonV1 :: BL.ByteString jsonV1 = "{\"derivationPath\":\"/nix/store/bar.drv\",\"expressionPath\":[\"effects\",\"doIt\"],\"secretsToUse\":{\"bar\":{\"contents\":[],\"tag\":\"GitToken\"},\"foo\":{\"contents\":{\"name\":\"default-foo\"},\"tag\":\"SimpleSecret\"}}}" spec :: Spec spec = do describe "AttributeEventSpec" $ do describe "FromJSON" $ do it "parses v1 correctly" $ do eitherDecode jsonV1 `shouldBe` Right objectV1 describe "ToJSON" $ do it "encodes correctly" $ do json (encode objectV1) `shouldBe` json jsonV1 json :: BL.ByteString -> Value json lbs = case eitherDecode lbs of Left e -> error e Right r -> r
null
https://raw.githubusercontent.com/hercules-ci/hercules-ci-agent/be8142e7f38eba5e3805f21d5b6423ce7239e0f0/hercules-ci-api-agent/test/Hercules/API/Agent/Evaluate/EvaluateEvent/AttributeEffectEventSpec.hs
haskell
module Hercules.API.Agent.Evaluate.EvaluateEvent.AttributeEffectEventSpec where import Data.Aeson (Value, eitherDecode, encode) import qualified Data.ByteString.Lazy as BL import qualified Data.Map as M import Hercules.API.Agent.Evaluate.EvaluateEvent.AttributeEffectEvent (AttributeEffectEvent (AttributeEffectEvent), GitToken (MkGitToken), SecretRef (..), SimpleSecret (MkSimpleSecret)) import qualified Hercules.API.Agent.Evaluate.EvaluateEvent.AttributeEffectEvent import Test.Hspec import Prelude objectV1 :: AttributeEffectEvent objectV1 = AttributeEffectEvent { expressionPath = ["effects", "doIt"], derivationPath = "/nix/store/bar.drv", secretsToUse = M.fromList [ ("foo", (SimpleSecret MkSimpleSecret {name = "default-foo"})), ("bar", (GitToken MkGitToken {})) ] } jsonV1 :: BL.ByteString jsonV1 = "{\"derivationPath\":\"/nix/store/bar.drv\",\"expressionPath\":[\"effects\",\"doIt\"],\"secretsToUse\":{\"bar\":{\"contents\":[],\"tag\":\"GitToken\"},\"foo\":{\"contents\":{\"name\":\"default-foo\"},\"tag\":\"SimpleSecret\"}}}" spec :: Spec spec = do describe "AttributeEventSpec" $ do describe "FromJSON" $ do it "parses v1 correctly" $ do eitherDecode jsonV1 `shouldBe` Right objectV1 describe "ToJSON" $ do it "encodes correctly" $ do json (encode objectV1) `shouldBe` json jsonV1 json :: BL.ByteString -> Value json lbs = case eitherDecode lbs of Left e -> error e Right r -> r
549eb46ac38d9d0e7eb0434a255e36e82406a535ed666223e435943a9fd18034
wrengr/bytestring-trie
MatchOne.hs
{-# OPTIONS_GHC -Wall -fwarn-tabs #-} # LANGUAGE CPP , BangPatterns # ---------------------------------------------------------------- ~ 2022.02.12 -- | -- Module : Bench.MatchOne Copyright : 2008 - -2022 wren romano -- License : BSD-3-Clause -- Maintainer : -- Stability : provisional -- Portability : portable -- -- Benchmarking definitions for 'TI.match_' ---------------------------------------------------------------- module Main (main) where import qualified Data.Trie as T import qualified Data.Trie.Internal as TI import qualified Data.ByteString as S import Control.Applicative (liftA2) import Control.DeepSeq (NFData) import qualified Test.QuickCheck as QC import qualified Criterion.Main as C -- TODO: consider trying <-bench>. Especially so we can add tests to ensure that all these implementations are correct; but also for the comparisons across versions (since @bench-show@ and @benchgraph@ are both too heavy-weight for our needs). ---------------------------------------------------------------- Using NOINLINE to improve the reliability\/quality of the benchmarks . match_v027, match_foldl, match_foldr, match_foldr_alt :: T.Trie a -> S.ByteString -> Maybe (Int, a) -- The manual implementation. # NOINLINE match_v027 # match_v027 = TI.match_ -- This implementation is based on @base-4.16.0.0@:'GHC.List.last'. -- N.B., the implementation uses 'foldl' in order to be a good -- consumer, contrary to the 'foldr' we would have expected; see: -- </-/issues/9339> -- Also, the actual definition of 'GHC.List.last' must be eta-expanded -- in order to actually have 'foldl' make it a good consumer; see: -- </-/issues/10260> -- (Not that that's relevant for us, since we're inlining the -- definition anyways, and the call-site is indeed saturated.) -- TODO : since when does ' foldl ' make good consumers ? Did GHC -- switch from build\/foldr to unfold\/destroy? -- -- Per the benchmarks below, this one is by far the slowest; thereby -- suggesting that 'foldl' is not in fact a good consumer! # NOINLINE match_foldl # match_foldl t q = foldl (\_ x -> Just x) Nothing (TI.matches_ t q) This uses the definition of ' GHC.List.last ' prior to # 9339 . Note -- how @step@ returns the @Just@ immediately, and only lazily does -- the case analysis. -- -- Per the benchmarks below, this is better than 'match_foldl' but -- not as good as 'match_foldr_alt' # NOINLINE match_foldr # match_foldr t q = foldr step Nothing (TI.matches_ t q) where step x m = Just (case m of { Nothing -> x; Just y -> y }) -- And here's a version that doesn't do that @Just@-before-case... -- -- Per the benchmarks below, this is better than 'match_foldr' but -- still not as good as 'match_v027'. # NOINLINE match_foldr_alt # match_foldr_alt t q = foldr step Nothing (TI.matches_ t q) where step x Nothing = Just x step _ y = y TODO : maybe try a Codensity version of the above two , to avoid -- redundant case analysis on the intermediate 'Maybe' ---------------------------------------------------------------- -- TODO: move this stuff off to the shared file. -- TODO: should have argument to bound the 'Word8' arbitraryBS :: Int -> QC.Gen S.ByteString arbitraryBS maxL = do l <- QC.chooseInt (0, maxL) xs <- QC.vector l return $! S.pack xs arbitraryTrie :: Int -> Int -> QC.Gen (T.Trie Int) arbitraryTrie maxK maxL = do k <- QC.chooseInt (0, maxK) keys <- QC.vectorOf k $ arbitraryBS maxL return $! T.fromList (zip keys [0..]) -- TODO: really need a better environment to work on than this... generateEnv :: IO ([T.Trie Int], [S.ByteString]) generateEnv = QC.generate $ do ts <- QC.vectorOf 10 $ arbitraryTrie 30 10 qs <- QC.vectorOf 10 $ arbitraryBS 12 return (ts, qs) cartesianNF :: NFData c => (a -> b -> c) -> [a] -> [b] -> C.Benchmarkable cartesianNF f xs ys = C.nf (liftA2 f xs) ys ---------------------------------------------------------------- -- TODO: <-tests/benchmarks/IntMap.hs> uses ' Control.Exception.evaluate ' instead of ' C.env ' . Is that -- because of using the @gauge@ library instead of @criterion@, or -- is there some other reason? main :: IO () main = C.defaultMain [ C.env generateEnv $ \ ~(ts, qs) -> C.bgroup "MatchOne" [ C.bench "match_v027" $ cartesianNF match_v027 ts qs , C.bench "match_foldl" $ cartesianNF match_foldl ts qs , C.bench "match_foldr" $ cartesianNF match_foldr ts qs , C.bench "match_foldr_alt" $ cartesianNF match_foldr_alt ts qs ] ] ---------------------------------------------------------------- ----------------------------------------------------------- fin.
null
https://raw.githubusercontent.com/wrengr/bytestring-trie/53e3b0e0eca0ef8980b155b4ad110835a78716e6/dev/Bench/MatchOne.hs
haskell
# OPTIONS_GHC -Wall -fwarn-tabs # -------------------------------------------------------------- | Module : Bench.MatchOne License : BSD-3-Clause Maintainer : Stability : provisional Portability : portable Benchmarking definitions for 'TI.match_' -------------------------------------------------------------- TODO: consider trying <-bench>. Especially so we can add tests to ensure that all these implementations are correct; but also for the comparisons across versions (since @bench-show@ and @benchgraph@ are both too heavy-weight for our needs). -------------------------------------------------------------- The manual implementation. This implementation is based on @base-4.16.0.0@:'GHC.List.last'. N.B., the implementation uses 'foldl' in order to be a good consumer, contrary to the 'foldr' we would have expected; see: </-/issues/9339> Also, the actual definition of 'GHC.List.last' must be eta-expanded in order to actually have 'foldl' make it a good consumer; see: </-/issues/10260> (Not that that's relevant for us, since we're inlining the definition anyways, and the call-site is indeed saturated.) switch from build\/foldr to unfold\/destroy? Per the benchmarks below, this one is by far the slowest; thereby suggesting that 'foldl' is not in fact a good consumer! how @step@ returns the @Just@ immediately, and only lazily does the case analysis. Per the benchmarks below, this is better than 'match_foldl' but not as good as 'match_foldr_alt' And here's a version that doesn't do that @Just@-before-case... Per the benchmarks below, this is better than 'match_foldr' but still not as good as 'match_v027'. redundant case analysis on the intermediate 'Maybe' -------------------------------------------------------------- TODO: move this stuff off to the shared file. TODO: should have argument to bound the 'Word8' TODO: really need a better environment to work on than this... -------------------------------------------------------------- TODO: <-tests/benchmarks/IntMap.hs> because of using the @gauge@ library instead of @criterion@, or is there some other reason? -------------------------------------------------------------- --------------------------------------------------------- fin.
# LANGUAGE CPP , BangPatterns # ~ 2022.02.12 Copyright : 2008 - -2022 wren romano module Main (main) where import qualified Data.Trie as T import qualified Data.Trie.Internal as TI import qualified Data.ByteString as S import Control.Applicative (liftA2) import Control.DeepSeq (NFData) import qualified Test.QuickCheck as QC import qualified Criterion.Main as C Using NOINLINE to improve the reliability\/quality of the benchmarks . match_v027, match_foldl, match_foldr, match_foldr_alt :: T.Trie a -> S.ByteString -> Maybe (Int, a) # NOINLINE match_v027 # match_v027 = TI.match_ TODO : since when does ' foldl ' make good consumers ? Did GHC # NOINLINE match_foldl # match_foldl t q = foldl (\_ x -> Just x) Nothing (TI.matches_ t q) This uses the definition of ' GHC.List.last ' prior to # 9339 . Note # NOINLINE match_foldr # match_foldr t q = foldr step Nothing (TI.matches_ t q) where step x m = Just (case m of { Nothing -> x; Just y -> y }) # NOINLINE match_foldr_alt # match_foldr_alt t q = foldr step Nothing (TI.matches_ t q) where step x Nothing = Just x step _ y = y TODO : maybe try a Codensity version of the above two , to avoid arbitraryBS :: Int -> QC.Gen S.ByteString arbitraryBS maxL = do l <- QC.chooseInt (0, maxL) xs <- QC.vector l return $! S.pack xs arbitraryTrie :: Int -> Int -> QC.Gen (T.Trie Int) arbitraryTrie maxK maxL = do k <- QC.chooseInt (0, maxK) keys <- QC.vectorOf k $ arbitraryBS maxL return $! T.fromList (zip keys [0..]) generateEnv :: IO ([T.Trie Int], [S.ByteString]) generateEnv = QC.generate $ do ts <- QC.vectorOf 10 $ arbitraryTrie 30 10 qs <- QC.vectorOf 10 $ arbitraryBS 12 return (ts, qs) cartesianNF :: NFData c => (a -> b -> c) -> [a] -> [b] -> C.Benchmarkable cartesianNF f xs ys = C.nf (liftA2 f xs) ys uses ' Control.Exception.evaluate ' instead of ' C.env ' . Is that main :: IO () main = C.defaultMain [ C.env generateEnv $ \ ~(ts, qs) -> C.bgroup "MatchOne" [ C.bench "match_v027" $ cartesianNF match_v027 ts qs , C.bench "match_foldl" $ cartesianNF match_foldl ts qs , C.bench "match_foldr" $ cartesianNF match_foldr ts qs , C.bench "match_foldr_alt" $ cartesianNF match_foldr_alt ts qs ] ]
a2743bfafd6734a9da9204e0994aa202c956d19c65ef123cb031590a1f1aba9e
Soostone/hs-d3
Scope.hs
------------------------------------------------------------------------------ | The ` Cursor ` is an abstraction used to track how D3.hs should render -- D3 parameters that are data dependent. It accomplishes this through left -- and right composition. ------------------------------------------------------------------------------ # LANGUAGE ExistentialQuantification # # LANGUAGE FlexibleInstances # # LANGUAGE MultiParamTypeClasses # {-# LANGUAGE QuasiQuotes #-} module Graphics.HSD3.D3.Scope where import Control.Lens import Data.Monoid import Language.Javascript.JMacro import Graphics.HSD3.D3.Cursor import Graphics.HSD3.D3.Graph import Graphics.HSD3.D3.JMacro ------------------------------------------------------------------------------ -- | Changes the definition of __target__ for the scope of `gr`. Since -- the new target is data dependent, it relies on the cursor package. withTarget :: JExpr -> GraphT s a JExpr withTarget st = do st' <- toCursor st var <- newVar insertCont $ \cont -> [jmacro| var x = `(st')`; `(replace var x cont)`; |] return $ jsv var with :: GraphT s a JExpr -> GraphT s a b -> GraphT s a JExpr with node ext = do expr <- node joined <- use jJoined (_, inner) <- extract ext let f = if joined then replace "__datum__" xx else id insert [jmacro| `(replace "__target__" expr $ f $ inner mempty)`; |] return expr where xx = [jmacroE| `(target)`.datum() |] infixr 0 `with` withT :: JMacro b => GraphT s a JExpr -> GraphT s a b -> GraphT s a b withT node ext = do expr <- node (ex, inner) <- extract ext x <- newVar insertCont $ replace x (jsv "__target__") . replace "__target__" expr . inner . replace "__target__" (jsv x) return $ replace "__target__" expr ex infixr 0 `withT` withCursor :: JExpr -> GraphT s a c -> GraphT s a c withCursor r graph = do oldCursor <- use jCursor jCursor %= (. (replace "__cursor__" r)) b <- graph jCursor .= oldCursor return b | Scopes the ` jCursor ` property of the ` GraphState ` in a ` Graph ` . scopeCursor :: GraphT s a b -> GraphT s a b scopeCursor graph = do oldCursor <- use jCursor joined <- use jJoined jJoined .= True b <- graph jCursor .= oldCursor jJoined .= joined return b ------------------------------------------------------------------------------
null
https://raw.githubusercontent.com/Soostone/hs-d3/fb319ba444e263d7bc9655436db2723115a01c46/src/Graphics/HSD3/D3/Scope.hs
haskell
---------------------------------------------------------------------------- D3 parameters that are data dependent. It accomplishes this through left and right composition. ---------------------------------------------------------------------------- # LANGUAGE QuasiQuotes # ---------------------------------------------------------------------------- | Changes the definition of __target__ for the scope of `gr`. Since the new target is data dependent, it relies on the cursor package. ----------------------------------------------------------------------------
| The ` Cursor ` is an abstraction used to track how D3.hs should render # LANGUAGE ExistentialQuantification # # LANGUAGE FlexibleInstances # # LANGUAGE MultiParamTypeClasses # module Graphics.HSD3.D3.Scope where import Control.Lens import Data.Monoid import Language.Javascript.JMacro import Graphics.HSD3.D3.Cursor import Graphics.HSD3.D3.Graph import Graphics.HSD3.D3.JMacro withTarget :: JExpr -> GraphT s a JExpr withTarget st = do st' <- toCursor st var <- newVar insertCont $ \cont -> [jmacro| var x = `(st')`; `(replace var x cont)`; |] return $ jsv var with :: GraphT s a JExpr -> GraphT s a b -> GraphT s a JExpr with node ext = do expr <- node joined <- use jJoined (_, inner) <- extract ext let f = if joined then replace "__datum__" xx else id insert [jmacro| `(replace "__target__" expr $ f $ inner mempty)`; |] return expr where xx = [jmacroE| `(target)`.datum() |] infixr 0 `with` withT :: JMacro b => GraphT s a JExpr -> GraphT s a b -> GraphT s a b withT node ext = do expr <- node (ex, inner) <- extract ext x <- newVar insertCont $ replace x (jsv "__target__") . replace "__target__" expr . inner . replace "__target__" (jsv x) return $ replace "__target__" expr ex infixr 0 `withT` withCursor :: JExpr -> GraphT s a c -> GraphT s a c withCursor r graph = do oldCursor <- use jCursor jCursor %= (. (replace "__cursor__" r)) b <- graph jCursor .= oldCursor return b | Scopes the ` jCursor ` property of the ` GraphState ` in a ` Graph ` . scopeCursor :: GraphT s a b -> GraphT s a b scopeCursor graph = do oldCursor <- use jCursor joined <- use jJoined jJoined .= True b <- graph jCursor .= oldCursor jJoined .= joined return b
34a0a62630fce058eb593b73771cf5a615a966ab5af1ee0d275014d8dc7c0e49
hiratara/Haskell-Nyumon-Sample
chap07-samples-7-6-2.hs
{-# LANGUAGE OverloadedStrings, OverloadedLists #-} module Main(main) where import Data.Aeson import qualified Data.ByteString.Lazy.Char8 as B nameListValue :: Value nameListValue = Array [ object [ "coworkers" .= Array [ object [ "age" .= Number 20 , "name" .= String "Satoshi" ] , object [ "age" .= Number 23 , "name" .= String "Takeshi" ] ] , "departmentName" .= String "Planning" ] ] main :: IO () main = do B.putStrLn $ encode $ nameListValue
null
https://raw.githubusercontent.com/hiratara/Haskell-Nyumon-Sample/ac52b741e3b96722f6fc104cfa84078e39f7a241/chap07-samples/chap07-samples-7-6-2.hs
haskell
# LANGUAGE OverloadedStrings, OverloadedLists #
module Main(main) where import Data.Aeson import qualified Data.ByteString.Lazy.Char8 as B nameListValue :: Value nameListValue = Array [ object [ "coworkers" .= Array [ object [ "age" .= Number 20 , "name" .= String "Satoshi" ] , object [ "age" .= Number 23 , "name" .= String "Takeshi" ] ] , "departmentName" .= String "Planning" ] ] main :: IO () main = do B.putStrLn $ encode $ nameListValue
924b97aa0efc83cfade4600c7cd07bf18fefa341675037e34c0dd2d0dc0a55dc
aryx/fork-efuns
buffer_menu.mli
val menu: Efuns.action
null
https://raw.githubusercontent.com/aryx/fork-efuns/8f2f8f66879d45e26ecdca0033f9c92aec2b783d/major_modes/buffer_menu.mli
ocaml
val menu: Efuns.action
e1c968612a6ff446c276d10e8ff1f6af269ec3215dc5ba9113027dd8784c1464
typelead/intellij-eta
Project.hs
module FFI.Com.IntelliJ.OpenApi.Project ( Project ) where import FFI.Com.IntelliJ.OpenApi.Project.Project
null
https://raw.githubusercontent.com/typelead/intellij-eta/ee66d621aa0bfdf56d7d287279a9a54e89802cf9/plugin/src/main/eta/FFI/Com/IntelliJ/OpenApi/Project.hs
haskell
module FFI.Com.IntelliJ.OpenApi.Project ( Project ) where import FFI.Com.IntelliJ.OpenApi.Project.Project
954bf434a7aa3784fd0fbbb21921aba7ada0be63de347b142d18357c1899ac38
metabase/hawk
junit.clj
(ns mb.hawk.junit (:require [clojure.test :as t] [mb.hawk.junit.write :as write])) (defmulti ^:private handle-event!* {:arglists '([event])} :type) (defn handle-event! "Write JUnit output for a `clojure.test` event such as success or failure." [{test-var :var, :as event}] (let [test-var (or test-var (when (seq t/*testing-vars*) (last t/*testing-vars*))) event (merge {:var test-var} event (when test-var {:ns (:ns (meta test-var))}))] (try (handle-event!* event) (catch Throwable e (throw (ex-info (str "Error handling event: " (ex-message e)) {:event event} e)))))) ;; for unknown event types (e.g. `:clojure.test.check.clojure-test/trial`) just ignore them. (defmethod handle-event!* :default [_]) (defmethod handle-event!* :begin-test-run [_] (write/clean-output-dir!) (write/create-thread-pool!)) (defmethod handle-event!* :summary [_] (write/wait-for-writes-to-finish)) (defmethod handle-event!* :begin-test-ns [{test-ns :ns}] (alter-meta! test-ns assoc ::context {:start-time-ms (System/currentTimeMillis) :timestamp (java.time.OffsetDateTime/now) :test-count 0 :error-count 0 :failure-count 0 :results []})) (defmethod handle-event!* :end-test-ns [{test-ns :ns, :as event}] (let [context (::context (meta test-ns)) result (merge event context {:duration-ms (- (System/currentTimeMillis) (:start-time-ms context))})] (write/write-ns-result! result))) (defmethod handle-event!* :begin-test-var [{test-var :var}] (alter-meta! test-var assoc ::context {:start-time-ms (System/currentTimeMillis) :assertion-count 0 :results []})) (defmethod handle-event!* :end-test-var [{test-ns :ns, test-var :var, :as event}] (let [context (::context (meta test-var)) result (merge event context {:duration-ms (- (System/currentTimeMillis) (:start-time-ms context))})] (alter-meta! test-ns update-in [::context :results] conj result))) (defn- inc-ns-test-counts! [{test-ns :ns, :as _event} & ks] (alter-meta! test-ns update ::context (fn [context] (reduce (fn [context k] (update context k inc)) context ks)))) (defn- record-assertion-result! [{test-var :var, :as event}] (let [event (assoc event :testing-contexts (vec t/*testing-contexts*))] (alter-meta! test-var update ::context (fn [context] (-> context (update :assertion-count inc) (update :results conj event)))))) (defmethod handle-event!* :pass [event] (inc-ns-test-counts! event :test-count) (record-assertion-result! event)) (defmethod handle-event!* :fail [event] (inc-ns-test-counts! event :test-count :failure-count) (record-assertion-result! event)) (defmethod handle-event!* :error [{test-var :var, :as event}] ;; some `:error` events happen because of errors in fixture initialization and don't have associated vars/namespaces (when test-var (inc-ns-test-counts! event :test-count :error-count) (record-assertion-result! event)))
null
https://raw.githubusercontent.com/metabase/hawk/47e3abf80d04d12f229aabffcf496f02cd9fffd5/src/mb/hawk/junit.clj
clojure
for unknown event types (e.g. `:clojure.test.check.clojure-test/trial`) just ignore them. some `:error` events happen because of errors in fixture initialization and don't have associated vars/namespaces
(ns mb.hawk.junit (:require [clojure.test :as t] [mb.hawk.junit.write :as write])) (defmulti ^:private handle-event!* {:arglists '([event])} :type) (defn handle-event! "Write JUnit output for a `clojure.test` event such as success or failure." [{test-var :var, :as event}] (let [test-var (or test-var (when (seq t/*testing-vars*) (last t/*testing-vars*))) event (merge {:var test-var} event (when test-var {:ns (:ns (meta test-var))}))] (try (handle-event!* event) (catch Throwable e (throw (ex-info (str "Error handling event: " (ex-message e)) {:event event} e)))))) (defmethod handle-event!* :default [_]) (defmethod handle-event!* :begin-test-run [_] (write/clean-output-dir!) (write/create-thread-pool!)) (defmethod handle-event!* :summary [_] (write/wait-for-writes-to-finish)) (defmethod handle-event!* :begin-test-ns [{test-ns :ns}] (alter-meta! test-ns assoc ::context {:start-time-ms (System/currentTimeMillis) :timestamp (java.time.OffsetDateTime/now) :test-count 0 :error-count 0 :failure-count 0 :results []})) (defmethod handle-event!* :end-test-ns [{test-ns :ns, :as event}] (let [context (::context (meta test-ns)) result (merge event context {:duration-ms (- (System/currentTimeMillis) (:start-time-ms context))})] (write/write-ns-result! result))) (defmethod handle-event!* :begin-test-var [{test-var :var}] (alter-meta! test-var assoc ::context {:start-time-ms (System/currentTimeMillis) :assertion-count 0 :results []})) (defmethod handle-event!* :end-test-var [{test-ns :ns, test-var :var, :as event}] (let [context (::context (meta test-var)) result (merge event context {:duration-ms (- (System/currentTimeMillis) (:start-time-ms context))})] (alter-meta! test-ns update-in [::context :results] conj result))) (defn- inc-ns-test-counts! [{test-ns :ns, :as _event} & ks] (alter-meta! test-ns update ::context (fn [context] (reduce (fn [context k] (update context k inc)) context ks)))) (defn- record-assertion-result! [{test-var :var, :as event}] (let [event (assoc event :testing-contexts (vec t/*testing-contexts*))] (alter-meta! test-var update ::context (fn [context] (-> context (update :assertion-count inc) (update :results conj event)))))) (defmethod handle-event!* :pass [event] (inc-ns-test-counts! event :test-count) (record-assertion-result! event)) (defmethod handle-event!* :fail [event] (inc-ns-test-counts! event :test-count :failure-count) (record-assertion-result! event)) (defmethod handle-event!* :error [{test-var :var, :as event}] (when test-var (inc-ns-test-counts! event :test-count :error-count) (record-assertion-result! event)))
4ea5ba30377fea20593b823472aa967eee923e384caa2603270e1a46c0920439
craigfe/ppx_irmin
unsupported_type_open.ml
type t = .. [@@deriving irmin]
null
https://raw.githubusercontent.com/craigfe/ppx_irmin/06d764c6f1049131f1c4c7a3fbc59ff516c9d679/test/deriver/errors/unsupported_type_open.ml
ocaml
type t = .. [@@deriving irmin]
a7af1652b54493117a50ee08aba1a906e139de2713c251a15687bcc49f844dee
lmj/lparallel
defun.lisp
Copyright ( c ) 2011 - 2012 , . All rights reserved . ;;; ;;; Redistribution and use in source and binary forms, with or without ;;; modification, are permitted provided that the following conditions ;;; are met: ;;; ;;; * Redistributions of source code must retain the above copyright ;;; notice, this list of conditions and the following disclaimer. ;;; ;;; * Redistributions in binary form must reproduce the above ;;; copyright notice, this list of conditions and the following ;;; disclaimer in the documentation and/or other materials provided ;;; with the distribution. ;;; ;;; * Neither the name of the project nor the names of its ;;; contributors may be used to endorse or promote products derived ;;; from this software without specific prior written permission. ;;; ;;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS " AS IS " AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT ;;; LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ;;; A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR FOR ANY DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT LIMITED TO , PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES ; LOSS OF USE , ;;; DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT ;;; (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ;;; OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. (in-package #:lparallel.util) (defun constrain-return-type (return-type) (if (and (consp return-type) (eq 'values (first return-type))) (if (intersection return-type lambda-list-keywords) return-type (append return-type '(&optional))) `(values ,return-type &optional))) #-lparallel.with-debug (progn (defmacro defun/inline (name lambda-list &body body) "Shortcut for (declaim (inline foo)) (defun foo ...)." `(progn (declaim (inline ,name)) (defun ,name ,lambda-list ,@body))) (defmacro defun/type (name lambda-list arg-types return-type &body body) "Shortcut for (declaim (ftype (function arg-types return-type) foo) (defun foo ...). Additionally constrains return-type to the number of values provided." (setf return-type (constrain-return-type return-type)) (with-parsed-body (body declares docstring) `(progn (declaim (ftype (function ,arg-types ,return-type) ,name)) (defun ,name ,lambda-list ,@(unsplice docstring) ,@declares ;; for a simple arg list, also declare types ,@(when (not (intersection lambda-list lambda-list-keywords)) (loop for type in arg-types for param in lambda-list collect `(declare (type ,type ,param)))) (the ,return-type (progn ,@body)))))) (defmacro defun/type/inline (name lambda-list arg-types return-type &body body) `(progn (declaim (inline ,name)) (defun/type ,name ,lambda-list ,arg-types ,return-type ,@body)))) ;;; Since return types are not always checked, check manually. #+lparallel.with-debug (progn (defmacro defun/type (name lambda-list arg-types return-type &body body) (setf return-type (constrain-return-type return-type)) (with-parsed-body (body declares docstring) `(progn (declaim (ftype (function ,arg-types ,return-type) ,name)) (defun ,name ,lambda-list ,@(unsplice docstring) ,@declares ;; for a simple arg list, check types ,@(when (not (intersection lambda-list lambda-list-keywords)) (loop for type in arg-types for param in lambda-list collect `(check-type ,param ,type))) ;; for a simple values list, check types ,(if (intersection (ensure-list return-type) lambda-list-keywords) `(progn ,@body) (let* ((return-types (if (and (consp return-type) (eq 'values (car return-type))) (cdr return-type) (list return-type))) (return-vars (mapcar (lambda (x) (if (symbolp x) (gensym (symbol-name x)) (gensym))) return-types))) `(multiple-value-bind ,return-vars (progn ,@body) ,@(loop for type in return-types for var in return-vars collect `(check-type ,var ,type)) (values ,@return-vars)))))))) (alias-macro defun/inline defun) (alias-macro defun/type/inline defun/type))
null
https://raw.githubusercontent.com/lmj/lparallel/9c11f40018155a472c540b63684049acc9b36e15/src/util/defun.lisp
lisp
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the project nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT LOSS OF USE , DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. for a simple arg list, also declare types Since return types are not always checked, check manually. for a simple arg list, check types for a simple values list, check types
Copyright ( c ) 2011 - 2012 , . All rights reserved . " AS IS " AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT HOLDER OR FOR ANY DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT (in-package #:lparallel.util) (defun constrain-return-type (return-type) (if (and (consp return-type) (eq 'values (first return-type))) (if (intersection return-type lambda-list-keywords) return-type (append return-type '(&optional))) `(values ,return-type &optional))) #-lparallel.with-debug (progn (defmacro defun/inline (name lambda-list &body body) "Shortcut for (declaim (inline foo)) (defun foo ...)." `(progn (declaim (inline ,name)) (defun ,name ,lambda-list ,@body))) (defmacro defun/type (name lambda-list arg-types return-type &body body) "Shortcut for (declaim (ftype (function arg-types return-type) foo) (defun foo ...). Additionally constrains return-type to the number of values provided." (setf return-type (constrain-return-type return-type)) (with-parsed-body (body declares docstring) `(progn (declaim (ftype (function ,arg-types ,return-type) ,name)) (defun ,name ,lambda-list ,@(unsplice docstring) ,@declares ,@(when (not (intersection lambda-list lambda-list-keywords)) (loop for type in arg-types for param in lambda-list collect `(declare (type ,type ,param)))) (the ,return-type (progn ,@body)))))) (defmacro defun/type/inline (name lambda-list arg-types return-type &body body) `(progn (declaim (inline ,name)) (defun/type ,name ,lambda-list ,arg-types ,return-type ,@body)))) #+lparallel.with-debug (progn (defmacro defun/type (name lambda-list arg-types return-type &body body) (setf return-type (constrain-return-type return-type)) (with-parsed-body (body declares docstring) `(progn (declaim (ftype (function ,arg-types ,return-type) ,name)) (defun ,name ,lambda-list ,@(unsplice docstring) ,@declares ,@(when (not (intersection lambda-list lambda-list-keywords)) (loop for type in arg-types for param in lambda-list collect `(check-type ,param ,type))) ,(if (intersection (ensure-list return-type) lambda-list-keywords) `(progn ,@body) (let* ((return-types (if (and (consp return-type) (eq 'values (car return-type))) (cdr return-type) (list return-type))) (return-vars (mapcar (lambda (x) (if (symbolp x) (gensym (symbol-name x)) (gensym))) return-types))) `(multiple-value-bind ,return-vars (progn ,@body) ,@(loop for type in return-types for var in return-vars collect `(check-type ,var ,type)) (values ,@return-vars)))))))) (alias-macro defun/inline defun) (alias-macro defun/type/inline defun/type))
7d5e620bcc9c80a561e18f291e25a2e0dd0b8295aaeae915506b8fca73bf3271
ghcjs/ghcjs-boot
hSetBuffering002.hs
import System.IO main = hSetBuffering stdin NoBuffering >> hSetBuffering stdout NoBuffering >> interact id
null
https://raw.githubusercontent.com/ghcjs/ghcjs-boot/8c549931da27ba9e607f77195208ec156c840c8a/boot/base/tests/IO/hSetBuffering002.hs
haskell
import System.IO main = hSetBuffering stdin NoBuffering >> hSetBuffering stdout NoBuffering >> interact id
ab69c67e879b78ac06824f0852b5f60eba2f42857b1f1a0b13d73857cf05ed87
yminer/libml
initVisitor.mli
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * [ LibML - Machine Learning Library ] Copyright ( C ) 2002 - 2003 LAGACHERIE This program is free software ; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation ; either version 2 of the License , or ( at your option ) any later version . This program is distributed in the hope that it will be useful , but WITHOUT ANY WARRANTY ; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the GNU General Public License for more details . You should have received a copy of the GNU General Public License along with this program ; if not , write to the Free Software Foundation , Inc. , 59 Temple Place - Suite 330 , Boston , MA 02111 - 1307 , USA . SPECIAL NOTE ( the beerware clause ): This software is free software . However , it also falls under the beerware special category . That is , if you find this software useful , or use it every day , or want to grant us for our modest contribution to the free software community , feel free to send us a beer from one of your local brewery . Our preference goes to Belgium abbey beers and irish stout ( Guiness for strength ! ) , but we like to try new stuffs . Authors : E - mail : RICORDEAU E - mail : * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * [LibML - Machine Learning Library] Copyright (C) 2002 - 2003 LAGACHERIE Matthieu RICORDEAU Olivier This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. SPECIAL NOTE (the beerware clause): This software is free software. However, it also falls under the beerware special category. That is, if you find this software useful, or use it every day, or want to grant us for our modest contribution to the free software community, feel free to send us a beer from one of your local brewery. Our preference goes to Belgium abbey beers and irish stout (Guiness for strength!), but we like to try new stuffs. Authors: Matthieu LAGACHERIE E-mail : Olivier RICORDEAU E-mail : ****************************************************************) * The InitVisitor module @author @author @since 09/02/2003 The InitVisitor module @author Matthieu Lagacherie @author Olivier Ricordeau @since 09/02/2003 *) open DefaultVisitor class virtual ['a] initVisitor : object inherit ['a] defaultVisitor (** The generic visit method. *) method visit : 'a -> unit end
null
https://raw.githubusercontent.com/yminer/libml/1475dd87c2c16983366fab62124e8bbfbbf2161b/src/nn/init/initVisitor.mli
ocaml
* The generic visit method.
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * [ LibML - Machine Learning Library ] Copyright ( C ) 2002 - 2003 LAGACHERIE This program is free software ; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation ; either version 2 of the License , or ( at your option ) any later version . This program is distributed in the hope that it will be useful , but WITHOUT ANY WARRANTY ; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the GNU General Public License for more details . You should have received a copy of the GNU General Public License along with this program ; if not , write to the Free Software Foundation , Inc. , 59 Temple Place - Suite 330 , Boston , MA 02111 - 1307 , USA . SPECIAL NOTE ( the beerware clause ): This software is free software . However , it also falls under the beerware special category . That is , if you find this software useful , or use it every day , or want to grant us for our modest contribution to the free software community , feel free to send us a beer from one of your local brewery . Our preference goes to Belgium abbey beers and irish stout ( Guiness for strength ! ) , but we like to try new stuffs . Authors : E - mail : RICORDEAU E - mail : * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * [LibML - Machine Learning Library] Copyright (C) 2002 - 2003 LAGACHERIE Matthieu RICORDEAU Olivier This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. SPECIAL NOTE (the beerware clause): This software is free software. However, it also falls under the beerware special category. That is, if you find this software useful, or use it every day, or want to grant us for our modest contribution to the free software community, feel free to send us a beer from one of your local brewery. Our preference goes to Belgium abbey beers and irish stout (Guiness for strength!), but we like to try new stuffs. Authors: Matthieu LAGACHERIE E-mail : Olivier RICORDEAU E-mail : ****************************************************************) * The InitVisitor module @author @author @since 09/02/2003 The InitVisitor module @author Matthieu Lagacherie @author Olivier Ricordeau @since 09/02/2003 *) open DefaultVisitor class virtual ['a] initVisitor : object inherit ['a] defaultVisitor method visit : 'a -> unit end
f2d8ac0713c93e7253896d2ddbcd8e662d23147b5c3d683d06bcfdc5650dda70
Ericson2314/lighthouse
Class.hs
----------------------------------------------------------------------------- -- | Module : Control . Monad . State . Class Copyright : ( c ) 2001 , ( c ) Oregon Graduate Institute of Science and Technology , 2001 -- License : BSD-style (see the file libraries/base/LICENSE) -- -- Maintainer : -- Stability : experimental -- Portability : non-portable (multi-param classes, functional dependencies) -- MonadState class . -- -- This module is inspired by the paper -- /Functional Programming with Overloading and -- Higher-Order Polymorphism/, ( < /~mpj/ > ) Advanced School of Functional Programming , 1995 . ----------------------------------------------------------------------------- module Control.Monad.State.Class ( -- * MonadState class MonadState(..), modify, gets, ) where -- --------------------------------------------------------------------------- -- | /get/ returns the state from the internals of the monad. -- -- /put/ replaces the state inside the monad. class (Monad m) => MonadState s m | m -> s where get :: m s put :: s -> m () | Monadic state transformer . -- -- Maps an old state to a new state inside a state monad. -- The old state is thrown away. -- -- > Main> :t modify ((+1) :: Int -> Int) -- > modify (...) :: (MonadState Int a) => a () -- This says that ( +1)@ acts over any that is a member of the @MonadState@ class , with an @Int@ state . modify :: (MonadState s m) => (s -> s) -> m () modify f = do s <- get put (f s) -- | Gets specific component of the state, using a projection function -- supplied. gets :: (MonadState s m) => (s -> a) -> m a gets f = do s <- get return (f s)
null
https://raw.githubusercontent.com/Ericson2314/lighthouse/210078b846ebd6c43b89b5f0f735362a01a9af02/ghc-6.8.2/libraries/mtl/Control/Monad/State/Class.hs
haskell
--------------------------------------------------------------------------- | License : BSD-style (see the file libraries/base/LICENSE) Maintainer : Stability : experimental Portability : non-portable (multi-param classes, functional dependencies) This module is inspired by the paper /Functional Programming with Overloading and Higher-Order Polymorphism/, --------------------------------------------------------------------------- * MonadState class --------------------------------------------------------------------------- | /get/ returns the state from the internals of the monad. /put/ replaces the state inside the monad. Maps an old state to a new state inside a state monad. The old state is thrown away. > Main> :t modify ((+1) :: Int -> Int) > modify (...) :: (MonadState Int a) => a () | Gets specific component of the state, using a projection function supplied.
Module : Control . Monad . State . Class Copyright : ( c ) 2001 , ( c ) Oregon Graduate Institute of Science and Technology , 2001 MonadState class . ( < /~mpj/ > ) Advanced School of Functional Programming , 1995 . module Control.Monad.State.Class ( MonadState(..), modify, gets, ) where class (Monad m) => MonadState s m | m -> s where get :: m s put :: s -> m () | Monadic state transformer . This says that ( +1)@ acts over any that is a member of the @MonadState@ class , with an @Int@ state . modify :: (MonadState s m) => (s -> s) -> m () modify f = do s <- get put (f s) gets :: (MonadState s m) => (s -> a) -> m a gets f = do s <- get return (f s)
3e66b018d4a5be15144840694e213c9d2ba008901eceaeabb84587e3833569a5
metaocaml/ber-metaocaml
unused_types.ml
(* TEST flags = " -w A -strict-sequence " * expect *) module Unused : sig end = struct type unused = int end ;; [%%expect {| Line 3, characters 2-19: 3 | type unused = int ^^^^^^^^^^^^^^^^^ Warning 34: unused type unused. module Unused : sig end |}] module Unused_nonrec : sig end = struct type nonrec used = int type nonrec unused = used end ;; [%%expect {| Line 4, characters 2-27: 4 | type nonrec unused = used ^^^^^^^^^^^^^^^^^^^^^^^^^ Warning 34: unused type unused. module Unused_nonrec : sig end |}] module Unused_rec : sig end = struct type unused = A of unused end ;; [%%expect {| Line 3, characters 2-27: 3 | type unused = A of unused ^^^^^^^^^^^^^^^^^^^^^^^^^ Warning 34: unused type unused. Line 3, characters 16-27: 3 | type unused = A of unused ^^^^^^^^^^^ Warning 37: unused constructor A. module Unused_rec : sig end |}] module Used_constructor : sig type t val t : t end = struct type t = T let t = T end ;; [%%expect {| module Used_constructor : sig type t val t : t end |}] module Unused_constructor : sig type t end = struct type t = T end ;; [%%expect {| Line 4, characters 11-12: 4 | type t = T ^ Warning 37: unused constructor T. module Unused_constructor : sig type t end |}] module Unused_constructor_outside_patterns : sig type t val nothing : t -> unit end = struct type t = T let nothing = function | T -> () end ;; [%%expect {| Line 5, characters 11-12: 5 | type t = T ^ Warning 37: constructor T is never used to build values. (However, this constructor appears in patterns.) module Unused_constructor_outside_patterns : sig type t val nothing : t -> unit end |}] module Unused_constructor_exported_private : sig type t = private T end = struct type t = T end ;; [%%expect {| Line 4, characters 11-12: 4 | type t = T ^ Warning 37: constructor T is never used to build values. Its type is exported as a private type. module Unused_constructor_exported_private : sig type t = private T end |}] module Used_private_constructor : sig type t val nothing : t -> unit end = struct type t = private T let nothing = function | T -> () end ;; [%%expect {| module Used_private_constructor : sig type t val nothing : t -> unit end |}] module Unused_private_constructor : sig type t end = struct type t = private T end ;; [%%expect {| Line 4, characters 19-20: 4 | type t = private T ^ Warning 37: unused constructor T. module Unused_private_constructor : sig type t end |}] module Exported_private_constructor : sig type t = private T end = struct type t = private T end ;; [%%expect {| module Exported_private_constructor : sig type t = private T end |}] module Used_exception : sig val e : exn end = struct exception Somebody_uses_me let e = Somebody_uses_me end ;; [%%expect {| module Used_exception : sig val e : exn end |}] module Used_extension_constructor : sig type t val t : t end = struct type t = .. type t += Somebody_uses_me let t = Somebody_uses_me end ;; [%%expect {| module Used_extension_constructor : sig type t val t : t end |}] module Unused_exception : sig end = struct exception Nobody_uses_me end ;; [%%expect {| Line 3, characters 2-26: 3 | exception Nobody_uses_me ^^^^^^^^^^^^^^^^^^^^^^^^ Warning 38: unused exception Nobody_uses_me module Unused_exception : sig end |}] module Unused_extension_constructor : sig type t = .. end = struct type t = .. type t += Nobody_uses_me end ;; [%%expect {| Line 5, characters 12-26: 5 | type t += Nobody_uses_me ^^^^^^^^^^^^^^ Warning 38: unused extension constructor Nobody_uses_me module Unused_extension_constructor : sig type t = .. end |}] module Unused_exception_outside_patterns : sig val falsity : exn -> bool end = struct exception Nobody_constructs_me let falsity = function | Nobody_constructs_me -> true | _ -> false end ;; [%%expect {| Line 4, characters 2-32: 4 | exception Nobody_constructs_me ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Warning 38: exception Nobody_constructs_me is never used to build values. (However, this constructor appears in patterns.) module Unused_exception_outside_patterns : sig val falsity : exn -> bool end |}] module Unused_extension_outside_patterns : sig type t = .. val falsity : t -> bool end = struct type t = .. type t += Noone_builds_me let falsity = function | Noone_builds_me -> true | _ -> false end ;; [%%expect {| Line 6, characters 12-27: 6 | type t += Noone_builds_me ^^^^^^^^^^^^^^^ Warning 38: extension constructor Noone_builds_me is never used to build values. (However, this constructor appears in patterns.) module Unused_extension_outside_patterns : sig type t = .. val falsity : t -> bool end |}] module Unused_exception_exported_private : sig type exn += private Private_exn end = struct exception Private_exn end ;; [%%expect {| Line 4, characters 2-23: 4 | exception Private_exn ^^^^^^^^^^^^^^^^^^^^^ Warning 38: exception Private_exn is never used to build values. It is exported or rebound as a private extension. module Unused_exception_exported_private : sig type exn += private Private_exn end |}] module Unused_extension_exported_private : sig type t = .. type t += private Private_ext end = struct type t = .. type t += Private_ext end ;; [%%expect {| Line 6, characters 12-23: 6 | type t += Private_ext ^^^^^^^^^^^ Warning 38: extension constructor Private_ext is never used to build values. It is exported or rebound as a private extension. module Unused_extension_exported_private : sig type t = .. type t += private Private_ext end |}] module Used_private_extension : sig type t val nothing : t -> unit end = struct type t = .. type t += private Private_ext let nothing = function | Private_ext | _ -> () end ;; [%%expect {| module Used_private_extension : sig type t val nothing : t -> unit end |}] module Unused_private_extension : sig type t end = struct type t = .. type t += private Private_ext end ;; [%%expect {| Line 5, characters 20-31: 5 | type t += private Private_ext ^^^^^^^^^^^ Warning 38: unused extension constructor Private_ext module Unused_private_extension : sig type t end |}] module Exported_private_extension : sig type t = .. type t += private Private_ext end = struct type t = .. type t += private Private_ext end ;; [%%expect {| module Exported_private_extension : sig type t = .. type t += private Private_ext end |}] module Pr7438 : sig end = struct module type S = sig type t = private [> `Foo] end module type X = sig type t = private [> `Foo | `Bar] include S with type t := t end end;; [%%expect {| module Pr7438 : sig end |}] module Unused_type_disable_warning : sig end = struct type t = A [@@warning "-34"] end;; [%%expect {| Line 3, characters 11-12: 3 | type t = A [@@warning "-34"] ^ Warning 37: unused constructor A. module Unused_type_disable_warning : sig end |}] module Unused_constructor_disable_warning : sig end = struct type t = A [@@warning "-37"] end;; [%%expect {| Line 3, characters 2-30: 3 | type t = A [@@warning "-37"] ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Warning 34: unused type t. module Unused_constructor_disable_warning : sig end |}]
null
https://raw.githubusercontent.com/metaocaml/ber-metaocaml/4992d1f87fc08ccb958817926cf9d1d739caf3a2/testsuite/tests/typing-warnings/unused_types.ml
ocaml
TEST flags = " -w A -strict-sequence " * expect
module Unused : sig end = struct type unused = int end ;; [%%expect {| Line 3, characters 2-19: 3 | type unused = int ^^^^^^^^^^^^^^^^^ Warning 34: unused type unused. module Unused : sig end |}] module Unused_nonrec : sig end = struct type nonrec used = int type nonrec unused = used end ;; [%%expect {| Line 4, characters 2-27: 4 | type nonrec unused = used ^^^^^^^^^^^^^^^^^^^^^^^^^ Warning 34: unused type unused. module Unused_nonrec : sig end |}] module Unused_rec : sig end = struct type unused = A of unused end ;; [%%expect {| Line 3, characters 2-27: 3 | type unused = A of unused ^^^^^^^^^^^^^^^^^^^^^^^^^ Warning 34: unused type unused. Line 3, characters 16-27: 3 | type unused = A of unused ^^^^^^^^^^^ Warning 37: unused constructor A. module Unused_rec : sig end |}] module Used_constructor : sig type t val t : t end = struct type t = T let t = T end ;; [%%expect {| module Used_constructor : sig type t val t : t end |}] module Unused_constructor : sig type t end = struct type t = T end ;; [%%expect {| Line 4, characters 11-12: 4 | type t = T ^ Warning 37: unused constructor T. module Unused_constructor : sig type t end |}] module Unused_constructor_outside_patterns : sig type t val nothing : t -> unit end = struct type t = T let nothing = function | T -> () end ;; [%%expect {| Line 5, characters 11-12: 5 | type t = T ^ Warning 37: constructor T is never used to build values. (However, this constructor appears in patterns.) module Unused_constructor_outside_patterns : sig type t val nothing : t -> unit end |}] module Unused_constructor_exported_private : sig type t = private T end = struct type t = T end ;; [%%expect {| Line 4, characters 11-12: 4 | type t = T ^ Warning 37: constructor T is never used to build values. Its type is exported as a private type. module Unused_constructor_exported_private : sig type t = private T end |}] module Used_private_constructor : sig type t val nothing : t -> unit end = struct type t = private T let nothing = function | T -> () end ;; [%%expect {| module Used_private_constructor : sig type t val nothing : t -> unit end |}] module Unused_private_constructor : sig type t end = struct type t = private T end ;; [%%expect {| Line 4, characters 19-20: 4 | type t = private T ^ Warning 37: unused constructor T. module Unused_private_constructor : sig type t end |}] module Exported_private_constructor : sig type t = private T end = struct type t = private T end ;; [%%expect {| module Exported_private_constructor : sig type t = private T end |}] module Used_exception : sig val e : exn end = struct exception Somebody_uses_me let e = Somebody_uses_me end ;; [%%expect {| module Used_exception : sig val e : exn end |}] module Used_extension_constructor : sig type t val t : t end = struct type t = .. type t += Somebody_uses_me let t = Somebody_uses_me end ;; [%%expect {| module Used_extension_constructor : sig type t val t : t end |}] module Unused_exception : sig end = struct exception Nobody_uses_me end ;; [%%expect {| Line 3, characters 2-26: 3 | exception Nobody_uses_me ^^^^^^^^^^^^^^^^^^^^^^^^ Warning 38: unused exception Nobody_uses_me module Unused_exception : sig end |}] module Unused_extension_constructor : sig type t = .. end = struct type t = .. type t += Nobody_uses_me end ;; [%%expect {| Line 5, characters 12-26: 5 | type t += Nobody_uses_me ^^^^^^^^^^^^^^ Warning 38: unused extension constructor Nobody_uses_me module Unused_extension_constructor : sig type t = .. end |}] module Unused_exception_outside_patterns : sig val falsity : exn -> bool end = struct exception Nobody_constructs_me let falsity = function | Nobody_constructs_me -> true | _ -> false end ;; [%%expect {| Line 4, characters 2-32: 4 | exception Nobody_constructs_me ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Warning 38: exception Nobody_constructs_me is never used to build values. (However, this constructor appears in patterns.) module Unused_exception_outside_patterns : sig val falsity : exn -> bool end |}] module Unused_extension_outside_patterns : sig type t = .. val falsity : t -> bool end = struct type t = .. type t += Noone_builds_me let falsity = function | Noone_builds_me -> true | _ -> false end ;; [%%expect {| Line 6, characters 12-27: 6 | type t += Noone_builds_me ^^^^^^^^^^^^^^^ Warning 38: extension constructor Noone_builds_me is never used to build values. (However, this constructor appears in patterns.) module Unused_extension_outside_patterns : sig type t = .. val falsity : t -> bool end |}] module Unused_exception_exported_private : sig type exn += private Private_exn end = struct exception Private_exn end ;; [%%expect {| Line 4, characters 2-23: 4 | exception Private_exn ^^^^^^^^^^^^^^^^^^^^^ Warning 38: exception Private_exn is never used to build values. It is exported or rebound as a private extension. module Unused_exception_exported_private : sig type exn += private Private_exn end |}] module Unused_extension_exported_private : sig type t = .. type t += private Private_ext end = struct type t = .. type t += Private_ext end ;; [%%expect {| Line 6, characters 12-23: 6 | type t += Private_ext ^^^^^^^^^^^ Warning 38: extension constructor Private_ext is never used to build values. It is exported or rebound as a private extension. module Unused_extension_exported_private : sig type t = .. type t += private Private_ext end |}] module Used_private_extension : sig type t val nothing : t -> unit end = struct type t = .. type t += private Private_ext let nothing = function | Private_ext | _ -> () end ;; [%%expect {| module Used_private_extension : sig type t val nothing : t -> unit end |}] module Unused_private_extension : sig type t end = struct type t = .. type t += private Private_ext end ;; [%%expect {| Line 5, characters 20-31: 5 | type t += private Private_ext ^^^^^^^^^^^ Warning 38: unused extension constructor Private_ext module Unused_private_extension : sig type t end |}] module Exported_private_extension : sig type t = .. type t += private Private_ext end = struct type t = .. type t += private Private_ext end ;; [%%expect {| module Exported_private_extension : sig type t = .. type t += private Private_ext end |}] module Pr7438 : sig end = struct module type S = sig type t = private [> `Foo] end module type X = sig type t = private [> `Foo | `Bar] include S with type t := t end end;; [%%expect {| module Pr7438 : sig end |}] module Unused_type_disable_warning : sig end = struct type t = A [@@warning "-34"] end;; [%%expect {| Line 3, characters 11-12: 3 | type t = A [@@warning "-34"] ^ Warning 37: unused constructor A. module Unused_type_disable_warning : sig end |}] module Unused_constructor_disable_warning : sig end = struct type t = A [@@warning "-37"] end;; [%%expect {| Line 3, characters 2-30: 3 | type t = A [@@warning "-37"] ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Warning 34: unused type t. module Unused_constructor_disable_warning : sig end |}]
1ef11836eadde984e04c6705b849ebcec3eb7ddb00d014098db5ccdd0fb9f336
BorjaEst/enn
nn_sup.erl
%%%------------------------------------------------------------------- %%% @doc %%% %%% @end -module(nn_sup). -behaviour(supervisor). %% API -export([id/1, start_link/1, start_neuron/2]). -export_type([id/0]). %% Supervisor callbacks -export([init/1]). -type id() :: {nn_sup, Ref :: reference()}. -define(SPECS_NEURON(Neuron_id), #{ id => Neuron_id, start => {neuron, start_link, [Neuron_id]}, restart => transient, shutdown => 500, modules => [neuron] }). %%%=================================================================== %%% API functions %%%=================================================================== %%-------------------------------------------------------------------- %% @doc Returns the supervisor id of from a network id. %% @end %%-------------------------------------------------------------------- -spec id(Network :: netwrok:id()) -> Supervisor :: id(). id(Network) -> {nn_sup, element(2, Network)}. %%-------------------------------------------------------------------- %% @doc Starts the supervisor %% @end %%-------------------------------------------------------------------- % TODO: To make description and specs start_link(Network) -> supervisor:start_link(?MODULE, [Network]). %%-------------------------------------------------------------------- %% @doc Starts the neural network cortex %% @end %%-------------------------------------------------------------------- % TODO: To make description and specs start_neuron(Supervisor, Neuron_id) -> supervisor:start_child(Supervisor, ?SPECS_NEURON(Neuron_id)). %%==================================================================== %% Supervisor callbacks %%==================================================================== %% Child :: #{id => Id, start => {M, F, A}} %% Optional keys are restart, shutdown, type, modules. Before OTP 18 tuples must be used to specify a child . e.g. Child : : { Id , StartFunc , Restart , Shutdown , Type , Modules } init([Network]) -> All down if one down Restart is not allowed Any as intensity = 0 ChildSpecs = [], true = enn_pool:register_as_nn_supervisor(Network), {ok, {SupFlags, ChildSpecs}}. %%%=================================================================== Internal functions %%%===================================================================
null
https://raw.githubusercontent.com/BorjaEst/enn/fa6c18913f3fb3e9391234c5e90cbcb432355bc0/src/nn_sup.erl
erlang
------------------------------------------------------------------- @doc @end API Supervisor callbacks =================================================================== API functions =================================================================== -------------------------------------------------------------------- @doc Returns the supervisor id of from a network id. @end -------------------------------------------------------------------- -------------------------------------------------------------------- @doc Starts the supervisor @end -------------------------------------------------------------------- TODO: To make description and specs -------------------------------------------------------------------- @doc Starts the neural network cortex @end -------------------------------------------------------------------- TODO: To make description and specs ==================================================================== Supervisor callbacks ==================================================================== Child :: #{id => Id, start => {M, F, A}} Optional keys are restart, shutdown, type, modules. =================================================================== ===================================================================
-module(nn_sup). -behaviour(supervisor). -export([id/1, start_link/1, start_neuron/2]). -export_type([id/0]). -export([init/1]). -type id() :: {nn_sup, Ref :: reference()}. -define(SPECS_NEURON(Neuron_id), #{ id => Neuron_id, start => {neuron, start_link, [Neuron_id]}, restart => transient, shutdown => 500, modules => [neuron] }). -spec id(Network :: netwrok:id()) -> Supervisor :: id(). id(Network) -> {nn_sup, element(2, Network)}. start_link(Network) -> supervisor:start_link(?MODULE, [Network]). start_neuron(Supervisor, Neuron_id) -> supervisor:start_child(Supervisor, ?SPECS_NEURON(Neuron_id)). Before OTP 18 tuples must be used to specify a child . e.g. Child : : { Id , StartFunc , Restart , Shutdown , Type , Modules } init([Network]) -> All down if one down Restart is not allowed Any as intensity = 0 ChildSpecs = [], true = enn_pool:register_as_nn_supervisor(Network), {ok, {SupFlags, ChildSpecs}}. Internal functions
1443ad852e21c1f84c4aca28535f7fba55286764b5295a47bbd92d1a0cb776b8
Elzair/nazghul
bole.scm
;;---------------------------------------------------------------------------- ;; Map ;;---------------------------------------------------------------------------- (kern-mk-map 'm_bole 48 39 pal_expanded (list "^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ~6 ^a ^^ ^c ~6 ^a ^^ ^^ ~6 || || || || || || || || || ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ " "^^ ^^ ^^ ^^ ^c t7 ^^ ^^ ^^ ^^ ^^ ^^ ^^ ~6 |B || |% ~6 |# |% ^e ~6 || || || || || || || || || ^a ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ " "^^ ^^ ^c t3 tt tc {5 ^^ ^^ ^^ ^^ ^^ ^^ ~a ~5 |A |C ~6 |A |C ~3 ~c || || || || || || || || || |% ^a ^^ ^^ ^^ ^^ ^c |& ^a ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ " "^^ ^^ t3 tt tc t# .. {1 {5 ^^ ^^ ^^ ^c |& ~a ~1 ~~ ~~ ~~ ~1 ~c |# || || || || || || || || || || |% ^^ ^^ ^c |# || || |% ^e t3 tt tt tt t5 ^^ ^^ " "^^ ^c tt t# .. .. .. .. .. {5 ^c tb tt || |% ~a ~~ bb ~~ ~c |# || || || tt tt tt tt tt tt tt tt || ^a ^c |# || || || || tt tc bb .. bb te ^a ^^ " "^^ t3 tc .. .. .. .. .. .. .. bb .. t% tt || tH ~a ~~ ~c tG || || || tc t# .. .. .. t% ta tt tt || || || || || || |C ^7 tt bb .. .. .. bb t7 ^^ " "^^ tt t# .. .. .. .. .. .. bb .. .. .. ta tt tt td ~6 tb tt || || tt t# tC t3 tt t5 tA .. t% ta tt tt tt || || || ^3 ^^ tt .. .. .. .. tb tt ^^ " "^^ tt .. .. rr rr rr rr rr rr rr .. .. .. .. .. .. == .. t% ta tt tc .. t3 || || || || t5 .. .. .. t% tt || || |C ^^ ^^ tt bb .. .. .. bb tt ^^ " "^^ tt .. .. rr .. .. .. .. .. rr .. .. tC t3 tt td ~6 t7 tA .. .. .. tC tt || || || || tt tA .. .. tC tt || |C ^3 ^^ ^^ ta t5 bb .. bb t3 tc ^^ " "^^ tt .. .. rr .. .. .. .. .. rr .. .. t3 || || ~3 ~c || tt tt tt tt tt || || || || || tt t5 .. .. t3 tt || ^3 ^^ ^^ ^^ ^5 ta tt tt tt tc ^3 ^^ " "^^ tt .. .. rr .. .. && .. .. .. .. .. tt || || ~6 |# || || || || || || || || || || || || tt .. tC tt || |C ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ " "^^ tt .. .. rr .. .. .. .. .. rr .. .. tt || |C ~6 || || || || || || || || || || tt tt tt tc .. t3 || |C ^3 ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ " "^^ tt .. .. rr .. .. .. .. .. rr .. .. tt || ~3 ~c tt tt tt tt tt tt tt tt || || tt t# .. .. tC tt || ^b ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ " "^^ tt .. .. rr rr rr .. rr rr rr .. .. || |C ~6 t3 tt tt tt tt tt tt tt tt tt || tt .. t3 tt tt || || |% ^a ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ " "^^ tt tA .. .. .. .. .. .. bb .. .. tC || ~3 ~c tt xx xx xx xx xx xx xx xx tt tt tc .. tt tt tt tt tt tt t5 ^a ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ " "^^ tt t5 tA .. .. .. .. bb {8 tC t3 tt || ~6 t3 tt xx cc cc cc cc cc cc xx te bb .. tC tt tt tt tt tt tt tt tt td ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ " "^^ ta tt t5 .. .. .. {c ^^ ^c t3 tt || || ~6 tt tt xx cc xx cc cc cc cc xx .. .. .. t3 tt xx xx xx xx xx xx xx xx xx xx xx xx xx xx xx xx ^^ ^^ " "^^ ^5 tt tt tA .. {c ^^ ^^ t3 tt || tt tc ~6 tt tt xx xx xx cc cc cc cc cc .. .. bb tt tt xx cc cc cc cc cc x! cc cc xx cc cc cc cc cc xx ^^ ^^ " "^^ ^^ ta tt tt td ^^ ^^ ^c tt tt || tt ~3 ~c tt tt tt t5 xx cc cc cc cc xx .. .. tb tt tt xx cc cc x! cc cc cc cc cc xx cc cc cc cc cc xx ^^ ^^ " "^^ ^^ ^5 ta tc ^3 ^^ ^^ t3 tt tt || tt ~6 t3 tt tt tt tt xx cc cc cc cc xx .. .. bb tt tt xx xx xx xx cc cc xx xx xx xx cc cc cc cc cc xx ^^ ^^ " "^^ ^^ ^^ ^^ ^^ ^^ ^^ ^c tt || || tt tc ~6 tt || || tt tt xx xx xx && xx xx .. .. .. ta tt xx cc cc cc cc cc cc cc cc xx cc cc cc cc cc xx ^^ ^^ " "^^ ^^ ^^ ^^ ^^ ^^ ^c t3 tt || tt tc ~3 ~c tt || || tt tt tt t5 xx xx xx t7 bb .. .. bb tt xx cc cc x! cc cc x! cc cc xx cc cc cc cc cc xx ^^ ^^ " "^^ ^^ ^^ ^^ ^^ t3 tt tt tt tt tc ~3 ~c t3 tt || || || tt tt tt tt tt tt tt td .. .. tb tt xx xx xx xx cc cc xx xx xx xx xx xx xx cc cc xx ^^ ^^ " "^^ ^^ ^^ ^^ ^^ tt || || || tt ~3 ~c t3 tt || || || || || || tt tt tt tt tt bb .. .. bb tt xx cc cc cc cc cc cc cc cc cc cc 00 xx cc cc xx ^^ ^^ " "^^ ^^ ^^ ^^ ^^ tt || || tt tc ~6 t3 tt || || || || || || || || || tt tt tt td .. .. tb tt xx cc cc cc cc cc cc cc cc cc cc 00 xx cc cc xx ^^ ^^ " "^^ |& ^a ^^ ^c ta tt tt tc ~3 ~c tt || || || || || || || || || || || tt bb .. .. .. bb te xx cc cc 00 cc cc xx xx xx cc cc cc cc cc cc xx ^^ ^^ " "|| || |% ^a td td ta tL ~3 ~4 t3 tt || || || || || || || || || || || tc .. .. .. .. .. .. sI cc cc 00 cc cc && xx && cc cc cc xx cc cc xx ^^ ^^ " "|| || tt td td tL ~3 ~~ ~~ ~4 tt || || || || || || tt tt tt || || || bb .. .. .. .. .. .. cc cc cc 00 cc cc && xx && cc cc cc xx xx xx xx ^^ ^^ " "|| tt tt ~3 ~1 ~~ ~~ ~~ ~~ ~4 tt || || || || || tt tt tt tt tt || || t5 .. .. .. .. .. .. xx cc cc 00 cc cc xx xx xx cc cc cc cc cc cc xx ^^ ^^ " "tt tt tt ~2 ~~ b~ ~~ ~~ ~~ ~c tt || || || || tt tt tc ^7 ta tt tt || tt bb .. .. .. bb t7 xx cc cc cc cc cc cc cc cc cc cc 00 xx cc cc xx ^^ ^^ " "tt tt tt ~a ~~ ~~ ~~ b~ ~~ tG tt || || || tt tt tc ^3 ^^ ^5 ta tt || || tt td .. .. tb tt xx cc cc cc cc cc cc cc cc cc cc 00 xx cc cc xx ^^ ^^ " "tt tt tt tH ~a ~~ ~~ ~~ ~c tt || || || || tt tt ^b ^^ ^^ ^^ ^d tt tt || || bb .. .. bb tt xx xx xx xx xx xx xx xx xx xx xx xx xx xx xx xx ^^ ^^ " "|| tt tt tt tH ~a ~8 ~c tG tt || || || || tt tt t5 ^a ^^ ^c t3 tt tt || || td .. .. tb tt tt tt tt tt tt tt tt tt tt tt tt tt tt tt t5 ^^ ^^ ^^ " "|| || || tt tt tt tt tt tt || || || tt tt tt tt tt tt tt tt tt tt || || tt bb .. .. bb tt tt tt tt tt tt tt tt tt tt tt tt tt tt tt tt t5 ^a ^^ " "|| || || || || tt tt tt || || || tt tt tt tt tt tt tt tt tt tt || || || tc .. .. .. tb tt tt || || || || || || || || || || || tt tt tt tt td ^^ " "|| || || || || tt bb tt || || tt tt bb tt || || || || || || || || || || bb .. .. .. bb || || || || || || || || || || || || || || || tt tc ^3 ^^ " "|| || || || || tt tt tt tt tt tt tt tt tt || || || || || || || || || || td .. .. tb tt || || || || || || || || || || || || || || || tt ^b ^^ ^^ " "|| || || || || || tt tt tt tt tt tt || || || || || || || || || || || || bb .. .. bb || || || || || || || || || || || || || || || || tt t5 ^a ^^ " "|| || || || || || || || || || || || || || || || || || || || || || || || t5 .. .. t3 || || || || || || || || || || || || || || || || || tt t5 ^^ " ) ) ;;---------------------------------------------------------------------------- ;; Characters ;;---------------------------------------------------------------------------- (kern-load "may.scm") (mk-may) (kern-load "kathryn.scm") (mk-kathryn) (kern-load "thud.scm") (mk-thud) (kern-load "bill.scm") (mk-bill) (kern-load "melvin.scm") (mk-melvin) (kern-load "hackle.scm") (mk-hackle) ;;---------------------------------------------------------------------------- ;; Place ;;---------------------------------------------------------------------------- (kern-mk-place 'p_bole ; tag "Bole" ; name s_hamlet ; sprite m_bole ; map #f ; wraps #f ; underground #f ; large-scale (wilderness) #f ; tmp combat place nil ; subplaces nil ; neighbors (list ;; objects ;; Tag the special door used as the player's guest room: (list (kern-tag 'bole-inn-room-door (mk-locked-door)) 33 17) (list (mk-locked-door) 36 18) (list (mk-locked-door) 33 20) (list (mk-locked-door) 36 20) (list (mk-locked-door) 42 25) (list (mk-door) 42 28) (list (mk-windowed-door) 30 27) (list (mk-bed) 31 18) (list (mk-bed) 38 18) (list (mk-bed) 31 21) (list (mk-bed) 38 21) (list (mk-bed) 40 17) (list (mk-bed) 44 17) (list (mk-clock) 35 17) ;; Bill's hut (list (mk-locked-door) 24 17) (list (mk-locked-door) 19 15) (list (mk-bed) 23 19) Hackle 's hut (list (mk-bed) 5 8) (list (mk-windowed-door-in-rock) 7 13) (list (mk-windowed-door-in-rock) 10 10) ;; Thief's door (put (mk-thief-door 'p_traps_1 4 16) 43 6) ;; npc's (list ch_may 44 17) (list ch_kathryn 31 18) (list ch_thud 32 18) (list ch_bill 22 8) (put ch_melvin 44 17) (put ch_hackle 0 0) (put (mk-npc 'bull 1) 6 4) ) ;; on-entry-hook (list 'lock-inn-room-doors) (list ;; edge entrances (list north 26 38) (list east 0 30) (list northeast 7 38) (list northwest 45 38) ) ) (mk-place-music p_bole 'ml-small-town) ;;----------------------------------------------------------------------------- ;; Make a special cave for the dryad so it doen't kill the town with its wolves ;;----------------------------------------------------------------------------- (kern-mk-map 'm_dryad_grove 19 19 pal_expanded (list "^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ " "^^ ^^ ^^ ^^ ^c |# || || || || || || || || || || |% ^a ^^ " "^^ ^^ ^^ {3 tb tt tt || || tt tt tt || || || || || |% ^^ " "^^ ^^ {3 .. tD tt tt tt tt tc t& ta tt tt || || || || || " "^^ ^c t7 tE t3 tt tt tt tt tB .. tD tt tt tt tt || || || " "^^ |# tt tt tt || || tt tt t5 tE t3 tt tt tt tt tt tt tt " "^^ || || || || || || || || tt tt tt || || tt tt tt tt tt " "^^ || || || || || || || || || || || || || tt tt tc t# .. " "^^ || || || || || || || || || || || || || tt tt t# .. .. " "^^ || || || || || || || || || || || || || tt tt .. .. .. " "^^ || || tt tt tt || || || || || || || || tt tt tA .. .. " "^^ || tt tt tt tt tt || || || || || || || tt tt t5 tA .. " "^^ || tt tt tt tt tt tt || || || || || tt tt tt tt tt tt " "^^ || tt tt tt tt tt tt tt || || || || tt tt tt tt tt tt " "^^ || tt tt tt tt tt tt tt || || || tt tt tt || || || || " "^^ || || tt tt tt tt tt tt || || || tt tt tt || || || || " "^^ || || || tt tt tt tt || || || tt tc t& ta tt || |C ^^ " "^^ |A || || || || || || || || || tc t# {8 t% ta |C ^3 ^^ " "^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ " ) ) (kern-mk-place 'p_dryad_grove ; tag "Dryad Grove" ; name nil ; sprite m_dryad_grove ; map #f ; wraps #f ; underground #f ; large-scale (wilderness) #f ; tmp combat place nil ; subplaces ;; neighbors (list ) ;; objects (list (put (mk-npc 'dryad 8) 4 14) (put (kern-mk-obj t_2H_axe 1) 5 15) ) nil ; hooks nil ; edge entrances ) (mk-dungeon-level (list p_dryad_grove p_bole) ) (mk-place-music p_dryad_grove 'ml-small-town)
null
https://raw.githubusercontent.com/Elzair/nazghul/8f3a45ed6289cd9f469c4ff618d39366f2fbc1d8/worlds/haxima-1.002/bole.scm
scheme
---------------------------------------------------------------------------- Map ---------------------------------------------------------------------------- ---------------------------------------------------------------------------- Characters ---------------------------------------------------------------------------- ---------------------------------------------------------------------------- Place ---------------------------------------------------------------------------- tag name sprite map wraps underground large-scale (wilderness) tmp combat place subplaces neighbors objects Tag the special door used as the player's guest room: Bill's hut Thief's door npc's on-entry-hook edge entrances ----------------------------------------------------------------------------- Make a special cave for the dryad so it doen't kill the town with its wolves ----------------------------------------------------------------------------- tag name sprite map wraps underground large-scale (wilderness) tmp combat place subplaces neighbors objects hooks edge entrances
(kern-mk-map 'm_bole 48 39 pal_expanded (list "^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ~6 ^a ^^ ^c ~6 ^a ^^ ^^ ~6 || || || || || || || || || ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ " "^^ ^^ ^^ ^^ ^c t7 ^^ ^^ ^^ ^^ ^^ ^^ ^^ ~6 |B || |% ~6 |# |% ^e ~6 || || || || || || || || || ^a ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ " "^^ ^^ ^c t3 tt tc {5 ^^ ^^ ^^ ^^ ^^ ^^ ~a ~5 |A |C ~6 |A |C ~3 ~c || || || || || || || || || |% ^a ^^ ^^ ^^ ^^ ^c |& ^a ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ " "^^ ^^ t3 tt tc t# .. {1 {5 ^^ ^^ ^^ ^c |& ~a ~1 ~~ ~~ ~~ ~1 ~c |# || || || || || || || || || || |% ^^ ^^ ^c |# || || |% ^e t3 tt tt tt t5 ^^ ^^ " "^^ ^c tt t# .. .. .. .. .. {5 ^c tb tt || |% ~a ~~ bb ~~ ~c |# || || || tt tt tt tt tt tt tt tt || ^a ^c |# || || || || tt tc bb .. bb te ^a ^^ " "^^ t3 tc .. .. .. .. .. .. .. bb .. t% tt || tH ~a ~~ ~c tG || || || tc t# .. .. .. t% ta tt tt || || || || || || |C ^7 tt bb .. .. .. bb t7 ^^ " "^^ tt t# .. .. .. .. .. .. bb .. .. .. ta tt tt td ~6 tb tt || || tt t# tC t3 tt t5 tA .. t% ta tt tt tt || || || ^3 ^^ tt .. .. .. .. tb tt ^^ " "^^ tt .. .. rr rr rr rr rr rr rr .. .. .. .. .. .. == .. t% ta tt tc .. t3 || || || || t5 .. .. .. t% tt || || |C ^^ ^^ tt bb .. .. .. bb tt ^^ " "^^ tt .. .. rr .. .. .. .. .. rr .. .. tC t3 tt td ~6 t7 tA .. .. .. tC tt || || || || tt tA .. .. tC tt || |C ^3 ^^ ^^ ta t5 bb .. bb t3 tc ^^ " "^^ tt .. .. rr .. .. .. .. .. rr .. .. t3 || || ~3 ~c || tt tt tt tt tt || || || || || tt t5 .. .. t3 tt || ^3 ^^ ^^ ^^ ^5 ta tt tt tt tc ^3 ^^ " "^^ tt .. .. rr .. .. && .. .. .. .. .. tt || || ~6 |# || || || || || || || || || || || || tt .. tC tt || |C ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ " "^^ tt .. .. rr .. .. .. .. .. rr .. .. tt || |C ~6 || || || || || || || || || || tt tt tt tc .. t3 || |C ^3 ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ " "^^ tt .. .. rr .. .. .. .. .. rr .. .. tt || ~3 ~c tt tt tt tt tt tt tt tt || || tt t# .. .. tC tt || ^b ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ " "^^ tt .. .. rr rr rr .. rr rr rr .. .. || |C ~6 t3 tt tt tt tt tt tt tt tt tt || tt .. t3 tt tt || || |% ^a ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ " "^^ tt tA .. .. .. .. .. .. bb .. .. tC || ~3 ~c tt xx xx xx xx xx xx xx xx tt tt tc .. tt tt tt tt tt tt t5 ^a ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ " "^^ tt t5 tA .. .. .. .. bb {8 tC t3 tt || ~6 t3 tt xx cc cc cc cc cc cc xx te bb .. tC tt tt tt tt tt tt tt tt td ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ " "^^ ta tt t5 .. .. .. {c ^^ ^c t3 tt || || ~6 tt tt xx cc xx cc cc cc cc xx .. .. .. t3 tt xx xx xx xx xx xx xx xx xx xx xx xx xx xx xx xx ^^ ^^ " "^^ ^5 tt tt tA .. {c ^^ ^^ t3 tt || tt tc ~6 tt tt xx xx xx cc cc cc cc cc .. .. bb tt tt xx cc cc cc cc cc x! cc cc xx cc cc cc cc cc xx ^^ ^^ " "^^ ^^ ta tt tt td ^^ ^^ ^c tt tt || tt ~3 ~c tt tt tt t5 xx cc cc cc cc xx .. .. tb tt tt xx cc cc x! cc cc cc cc cc xx cc cc cc cc cc xx ^^ ^^ " "^^ ^^ ^5 ta tc ^3 ^^ ^^ t3 tt tt || tt ~6 t3 tt tt tt tt xx cc cc cc cc xx .. .. bb tt tt xx xx xx xx cc cc xx xx xx xx cc cc cc cc cc xx ^^ ^^ " "^^ ^^ ^^ ^^ ^^ ^^ ^^ ^c tt || || tt tc ~6 tt || || tt tt xx xx xx && xx xx .. .. .. ta tt xx cc cc cc cc cc cc cc cc xx cc cc cc cc cc xx ^^ ^^ " "^^ ^^ ^^ ^^ ^^ ^^ ^c t3 tt || tt tc ~3 ~c tt || || tt tt tt t5 xx xx xx t7 bb .. .. bb tt xx cc cc x! cc cc x! cc cc xx cc cc cc cc cc xx ^^ ^^ " "^^ ^^ ^^ ^^ ^^ t3 tt tt tt tt tc ~3 ~c t3 tt || || || tt tt tt tt tt tt tt td .. .. tb tt xx xx xx xx cc cc xx xx xx xx xx xx xx cc cc xx ^^ ^^ " "^^ ^^ ^^ ^^ ^^ tt || || || tt ~3 ~c t3 tt || || || || || || tt tt tt tt tt bb .. .. bb tt xx cc cc cc cc cc cc cc cc cc cc 00 xx cc cc xx ^^ ^^ " "^^ ^^ ^^ ^^ ^^ tt || || tt tc ~6 t3 tt || || || || || || || || || tt tt tt td .. .. tb tt xx cc cc cc cc cc cc cc cc cc cc 00 xx cc cc xx ^^ ^^ " "^^ |& ^a ^^ ^c ta tt tt tc ~3 ~c tt || || || || || || || || || || || tt bb .. .. .. bb te xx cc cc 00 cc cc xx xx xx cc cc cc cc cc cc xx ^^ ^^ " "|| || |% ^a td td ta tL ~3 ~4 t3 tt || || || || || || || || || || || tc .. .. .. .. .. .. sI cc cc 00 cc cc && xx && cc cc cc xx cc cc xx ^^ ^^ " "|| || tt td td tL ~3 ~~ ~~ ~4 tt || || || || || || tt tt tt || || || bb .. .. .. .. .. .. cc cc cc 00 cc cc && xx && cc cc cc xx xx xx xx ^^ ^^ " "|| tt tt ~3 ~1 ~~ ~~ ~~ ~~ ~4 tt || || || || || tt tt tt tt tt || || t5 .. .. .. .. .. .. xx cc cc 00 cc cc xx xx xx cc cc cc cc cc cc xx ^^ ^^ " "tt tt tt ~2 ~~ b~ ~~ ~~ ~~ ~c tt || || || || tt tt tc ^7 ta tt tt || tt bb .. .. .. bb t7 xx cc cc cc cc cc cc cc cc cc cc 00 xx cc cc xx ^^ ^^ " "tt tt tt ~a ~~ ~~ ~~ b~ ~~ tG tt || || || tt tt tc ^3 ^^ ^5 ta tt || || tt td .. .. tb tt xx cc cc cc cc cc cc cc cc cc cc 00 xx cc cc xx ^^ ^^ " "tt tt tt tH ~a ~~ ~~ ~~ ~c tt || || || || tt tt ^b ^^ ^^ ^^ ^d tt tt || || bb .. .. bb tt xx xx xx xx xx xx xx xx xx xx xx xx xx xx xx xx ^^ ^^ " "|| tt tt tt tH ~a ~8 ~c tG tt || || || || tt tt t5 ^a ^^ ^c t3 tt tt || || td .. .. tb tt tt tt tt tt tt tt tt tt tt tt tt tt tt tt t5 ^^ ^^ ^^ " "|| || || tt tt tt tt tt tt || || || tt tt tt tt tt tt tt tt tt tt || || tt bb .. .. bb tt tt tt tt tt tt tt tt tt tt tt tt tt tt tt tt t5 ^a ^^ " "|| || || || || tt tt tt || || || tt tt tt tt tt tt tt tt tt tt || || || tc .. .. .. tb tt tt || || || || || || || || || || || tt tt tt tt td ^^ " "|| || || || || tt bb tt || || tt tt bb tt || || || || || || || || || || bb .. .. .. bb || || || || || || || || || || || || || || || tt tc ^3 ^^ " "|| || || || || tt tt tt tt tt tt tt tt tt || || || || || || || || || || td .. .. tb tt || || || || || || || || || || || || || || || tt ^b ^^ ^^ " "|| || || || || || tt tt tt tt tt tt || || || || || || || || || || || || bb .. .. bb || || || || || || || || || || || || || || || || tt t5 ^a ^^ " "|| || || || || || || || || || || || || || || || || || || || || || || || t5 .. .. t3 || || || || || || || || || || || || || || || || || tt t5 ^^ " ) ) (kern-load "may.scm") (mk-may) (kern-load "kathryn.scm") (mk-kathryn) (kern-load "thud.scm") (mk-thud) (kern-load "bill.scm") (mk-bill) (kern-load "melvin.scm") (mk-melvin) (kern-load "hackle.scm") (mk-hackle) (kern-mk-place (list (kern-tag 'bole-inn-room-door (mk-locked-door)) 33 17) (list (mk-locked-door) 36 18) (list (mk-locked-door) 33 20) (list (mk-locked-door) 36 20) (list (mk-locked-door) 42 25) (list (mk-door) 42 28) (list (mk-windowed-door) 30 27) (list (mk-bed) 31 18) (list (mk-bed) 38 18) (list (mk-bed) 31 21) (list (mk-bed) 38 21) (list (mk-bed) 40 17) (list (mk-bed) 44 17) (list (mk-clock) 35 17) (list (mk-locked-door) 24 17) (list (mk-locked-door) 19 15) (list (mk-bed) 23 19) Hackle 's hut (list (mk-bed) 5 8) (list (mk-windowed-door-in-rock) 7 13) (list (mk-windowed-door-in-rock) 10 10) (put (mk-thief-door 'p_traps_1 4 16) 43 6) (list ch_may 44 17) (list ch_kathryn 31 18) (list ch_thud 32 18) (list ch_bill 22 8) (put ch_melvin 44 17) (put ch_hackle 0 0) (put (mk-npc 'bull 1) 6 4) ) (list 'lock-inn-room-doors) (list north 26 38) (list east 0 30) (list northeast 7 38) (list northwest 45 38) ) ) (mk-place-music p_bole 'ml-small-town) (kern-mk-map 'm_dryad_grove 19 19 pal_expanded (list "^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ " "^^ ^^ ^^ ^^ ^c |# || || || || || || || || || || |% ^a ^^ " "^^ ^^ ^^ {3 tb tt tt || || tt tt tt || || || || || |% ^^ " "^^ ^^ {3 .. tD tt tt tt tt tc t& ta tt tt || || || || || " "^^ ^c t7 tE t3 tt tt tt tt tB .. tD tt tt tt tt || || || " "^^ |# tt tt tt || || tt tt t5 tE t3 tt tt tt tt tt tt tt " "^^ || || || || || || || || tt tt tt || || tt tt tt tt tt " "^^ || || || || || || || || || || || || || tt tt tc t# .. " "^^ || || || || || || || || || || || || || tt tt t# .. .. " "^^ || || || || || || || || || || || || || tt tt .. .. .. " "^^ || || tt tt tt || || || || || || || || tt tt tA .. .. " "^^ || tt tt tt tt tt || || || || || || || tt tt t5 tA .. " "^^ || tt tt tt tt tt tt || || || || || tt tt tt tt tt tt " "^^ || tt tt tt tt tt tt tt || || || || tt tt tt tt tt tt " "^^ || tt tt tt tt tt tt tt || || || tt tt tt || || || || " "^^ || || tt tt tt tt tt tt || || || tt tt tt || || || || " "^^ || || || tt tt tt tt || || || tt tc t& ta tt || |C ^^ " "^^ |A || || || || || || || || || tc t# {8 t% ta |C ^3 ^^ " "^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ " ) ) (kern-mk-place (list ) (list (put (mk-npc 'dryad 8) 4 14) (put (kern-mk-obj t_2H_axe 1) 5 15) ) ) (mk-dungeon-level (list p_dryad_grove p_bole) ) (mk-place-music p_dryad_grove 'ml-small-town)
a1b2881ae8f1e06125a8501b1461b5740ec6c1a5efcdfc8a409a0cb79b4a05f8
theodormoroianu/SecondYearCourses
HaskellChurch_20210415162336.hs
{-# LANGUAGE RankNTypes #-} module HaskellChurch where A boolean is any way to choose between two alternatives newtype CBool = CBool {cIf :: forall t. t -> t -> t} An instance to show as regular Booleans instance Show CBool where show b = show $ cIf b True False The boolean constant true always chooses the first alternative cTrue :: CBool cTrue = undefined The boolean constant false always chooses the second alternative cFalse :: CBool cFalse = undefined --The boolean negation switches the alternatives cNot :: CBool -> CBool cNot = undefined --The boolean conjunction can be built as a conditional (&&:) :: CBool -> CBool -> CBool (&&:) = undefined infixr 3 &&: --The boolean disjunction can be built as a conditional (||:) :: CBool -> CBool -> CBool (||:) = undefined infixr 2 ||: -- a pair is a way to compute something based on the values -- contained within the pair. newtype CPair a b = CPair { cOn :: forall c . (a -> b -> c) -> c } An instance to show CPairs as regular pairs . instance (Show a, Show b) => Show (CPair a b) where show p = show $ cOn p (,) builds a pair out of two values as an object which , when given --a function to be applied on the values, it will apply it on them. cPair :: a -> b -> CPair a b cPair = undefined first projection uses the function selecting first component on a pair cFst :: CPair a b -> a cFst = undefined second projection cSnd :: CPair a b -> b cSnd = undefined -- A natural number is any way to iterate a function s a number of times -- over an initial value z newtype CNat = CNat { cFor :: forall t. (t -> t) -> t -> t } -- An instance to show CNats as regular natural numbers instance Show CNat where show n = show $ cFor n (1 +) (0 :: Integer) --0 will iterate the function s 0 times over z, producing z c0 :: CNat c0 = undefined 1 is the the function s iterated 1 times over z , that is , z c1 :: CNat c1 = undefined --Successor n either - applies s one more time in addition to what n does -- - iterates s n times over (s z) cS :: CNat -> CNat cS = undefined --Addition of m and n is done by iterating s n times over m (+:) :: CNat -> CNat -> CNat (+:) = undefined infixl 6 +: --Multiplication of m and n can be done by composing n and m (*:) :: CNat -> CNat -> CNat (*:) = \n m -> CNat $ cFor n . cFor m infixl 7 *: --Exponentiation of m and n can be done by applying n to m (^:) :: CNat -> CNat -> CNat (^:) = \m n -> CNat $ cFor n (cFor m) infixr 8 ^: --Testing whether a value is 0 can be done through iteration -- using a function constantly false and an initial value true cIs0 :: CNat -> CBool cIs0 = \n -> cFor n (\_ -> cFalse) cTrue Predecessor ( evaluating to 0 for 0 ) can be defined iterating over pairs , starting from an initial value ( 0 , 0 ) cPred :: CNat -> CNat cPred = undefined substraction from m n ( evaluating to 0 if m < n ) is repeated application -- of the predeccesor function (-:) :: CNat -> CNat -> CNat (-:) = \m n -> cFor n cPred m Transform a value into a CNat ( should yield c0 for nums < = 0 ) cNat :: (Ord p, Num p) => p -> CNat cNat n = undefined We can define an instance Num CNat which will allow us to see any integer constant as a CNat ( e.g. 12 : : CNat ) and also use regular -- arithmetic instance Num CNat where (+) = (+:) (*) = (*:) (-) = (-:) abs = id signum n = cIf (cIs0 n) 0 1 fromInteger = cNat -- m is less than (or equal to) n if when substracting n from m we get 0 (<=:) :: CNat -> CNat -> CBool (<=:) = undefined infix 4 <=: (>=:) :: CNat -> CNat -> CBool (>=:) = \m n -> n <=: m infix 4 >=: (<:) :: CNat -> CNat -> CBool (<:) = \m n -> cNot (m >=: n) infix 4 <: (>:) :: CNat -> CNat -> CBool (>:) = \m n -> n <: m infix 4 >: -- equality on naturals can be defined my means of comparisons (==:) :: CNat -> CNat -> CBool (==:) = undefined --Fun with arithmetic and pairs --Define factorial. You can iterate over a pair to contain the current index and so far factorial cFactorial :: CNat -> CNat cFactorial = undefined Define Fibonacci . You can iterate over a pair to contain two consecutive numbers in the sequence cFibonacci :: CNat -> CNat cFibonacci = undefined --Given m and n, compute q and r satisfying m = q * n + r. If n /= 0quotient and reminder for m / n cDivMod :: CNat -> CNat -> CPair CNat CNat cDivMod = \m n -> cFor m (\p -> cIf (n <=: cSnd p) (cPair (cS (cFst p)) (cSnd p - n)) p) (cPair 0 m)
null
https://raw.githubusercontent.com/theodormoroianu/SecondYearCourses/5e359e6a7cf588a527d27209bf53b4ce6b8d5e83/FLP/Laboratoare/Lab%209/.history/HaskellChurch_20210415162336.hs
haskell
# LANGUAGE RankNTypes # The boolean negation switches the alternatives The boolean conjunction can be built as a conditional The boolean disjunction can be built as a conditional a pair is a way to compute something based on the values contained within the pair. a function to be applied on the values, it will apply it on them. A natural number is any way to iterate a function s a number of times over an initial value z An instance to show CNats as regular natural numbers 0 will iterate the function s 0 times over z, producing z Successor n either - iterates s n times over (s z) Addition of m and n is done by iterating s n times over m Multiplication of m and n can be done by composing n and m Exponentiation of m and n can be done by applying n to m Testing whether a value is 0 can be done through iteration using a function constantly false and an initial value true of the predeccesor function arithmetic m is less than (or equal to) n if when substracting n from m we get 0 equality on naturals can be defined my means of comparisons Fun with arithmetic and pairs Define factorial. You can iterate over a pair to contain the current index and so far factorial Given m and n, compute q and r satisfying m = q * n + r. If n /= 0quotient and reminder for m / n
module HaskellChurch where A boolean is any way to choose between two alternatives newtype CBool = CBool {cIf :: forall t. t -> t -> t} An instance to show as regular Booleans instance Show CBool where show b = show $ cIf b True False The boolean constant true always chooses the first alternative cTrue :: CBool cTrue = undefined The boolean constant false always chooses the second alternative cFalse :: CBool cFalse = undefined cNot :: CBool -> CBool cNot = undefined (&&:) :: CBool -> CBool -> CBool (&&:) = undefined infixr 3 &&: (||:) :: CBool -> CBool -> CBool (||:) = undefined infixr 2 ||: newtype CPair a b = CPair { cOn :: forall c . (a -> b -> c) -> c } An instance to show CPairs as regular pairs . instance (Show a, Show b) => Show (CPair a b) where show p = show $ cOn p (,) builds a pair out of two values as an object which , when given cPair :: a -> b -> CPair a b cPair = undefined first projection uses the function selecting first component on a pair cFst :: CPair a b -> a cFst = undefined second projection cSnd :: CPair a b -> b cSnd = undefined newtype CNat = CNat { cFor :: forall t. (t -> t) -> t -> t } instance Show CNat where show n = show $ cFor n (1 +) (0 :: Integer) c0 :: CNat c0 = undefined 1 is the the function s iterated 1 times over z , that is , z c1 :: CNat c1 = undefined - applies s one more time in addition to what n does cS :: CNat -> CNat cS = undefined (+:) :: CNat -> CNat -> CNat (+:) = undefined infixl 6 +: (*:) :: CNat -> CNat -> CNat (*:) = \n m -> CNat $ cFor n . cFor m infixl 7 *: (^:) :: CNat -> CNat -> CNat (^:) = \m n -> CNat $ cFor n (cFor m) infixr 8 ^: cIs0 :: CNat -> CBool cIs0 = \n -> cFor n (\_ -> cFalse) cTrue Predecessor ( evaluating to 0 for 0 ) can be defined iterating over pairs , starting from an initial value ( 0 , 0 ) cPred :: CNat -> CNat cPred = undefined substraction from m n ( evaluating to 0 if m < n ) is repeated application (-:) :: CNat -> CNat -> CNat (-:) = \m n -> cFor n cPred m Transform a value into a CNat ( should yield c0 for nums < = 0 ) cNat :: (Ord p, Num p) => p -> CNat cNat n = undefined We can define an instance Num CNat which will allow us to see any integer constant as a CNat ( e.g. 12 : : CNat ) and also use regular instance Num CNat where (+) = (+:) (*) = (*:) (-) = (-:) abs = id signum n = cIf (cIs0 n) 0 1 fromInteger = cNat (<=:) :: CNat -> CNat -> CBool (<=:) = undefined infix 4 <=: (>=:) :: CNat -> CNat -> CBool (>=:) = \m n -> n <=: m infix 4 >=: (<:) :: CNat -> CNat -> CBool (<:) = \m n -> cNot (m >=: n) infix 4 <: (>:) :: CNat -> CNat -> CBool (>:) = \m n -> n <: m infix 4 >: (==:) :: CNat -> CNat -> CBool (==:) = undefined cFactorial :: CNat -> CNat cFactorial = undefined Define Fibonacci . You can iterate over a pair to contain two consecutive numbers in the sequence cFibonacci :: CNat -> CNat cFibonacci = undefined cDivMod :: CNat -> CNat -> CPair CNat CNat cDivMod = \m n -> cFor m (\p -> cIf (n <=: cSnd p) (cPair (cS (cFst p)) (cSnd p - n)) p) (cPair 0 m)
9f6aa1405620f1c8b644fe4fcea902cf34ba3db0afadaac95c1fb9340207dcbb
simonmichael/hledger
Import.hs
module Hledger.Web.Import ( module Import ) where import Prelude as Import hiding (head, init, last, readFile, tail, writeFile) import Yesod as Import hiding (Route (..), parseTime) import Control.Monad as Import import Data.Bifunctor as Import import Data.ByteString as Import (ByteString) import Data.Default as Import import Data.Either as Import import Data.Foldable as Import import Data.List as Import (unfoldr) import Data.Maybe as Import import Data.Text as Import (Text) import Data.Time as Import import Data.Traversable as Import import Data.Void as Import (Void) import Text.Blaze as Import (Markup) import Hledger.Web.Foundation as Import import Hledger.Web.Settings as Import import Hledger.Web.Settings.StaticFiles as Import import Hledger.Web.WebOptions as Import (Capability(..))
null
https://raw.githubusercontent.com/simonmichael/hledger/33d15df879b43e69cb3e2f35a0a44c1a88b1f7a7/hledger-web/Hledger/Web/Import.hs
haskell
module Hledger.Web.Import ( module Import ) where import Prelude as Import hiding (head, init, last, readFile, tail, writeFile) import Yesod as Import hiding (Route (..), parseTime) import Control.Monad as Import import Data.Bifunctor as Import import Data.ByteString as Import (ByteString) import Data.Default as Import import Data.Either as Import import Data.Foldable as Import import Data.List as Import (unfoldr) import Data.Maybe as Import import Data.Text as Import (Text) import Data.Time as Import import Data.Traversable as Import import Data.Void as Import (Void) import Text.Blaze as Import (Markup) import Hledger.Web.Foundation as Import import Hledger.Web.Settings as Import import Hledger.Web.Settings.StaticFiles as Import import Hledger.Web.WebOptions as Import (Capability(..))
4b858cf37294774f53438bf6a40c53229a5c38f4eef8d3ebfa5f110cac55074d
rabbitmq/looking_glass
looking_glass_app.erl
%% Copyright (c) 2017-Present Pivotal Software, Inc. All rights reserved. %% This package , Looking , is double - licensed under the Mozilla Public License 1.1 ( " MPL " ) and the Apache License version 2 ( " ASL " ) . For the MPL , please see LICENSE - MPL - RabbitMQ . For the ASL , %% please see LICENSE-APACHE2. %% This software is distributed on an " AS IS " basis , WITHOUT WARRANTY OF ANY KIND , %% either express or implied. See the LICENSE file for specific language governing %% rights and limitations of this software. %% %% If you have any questions regarding licensing, please contact us at %% . -module(looking_glass_app). -behaviour(application). -export([start/2]). -export([stop/1]). start(_Type, _Args) -> looking_glass_sup:start_link(). stop(_State) -> ok.
null
https://raw.githubusercontent.com/rabbitmq/looking_glass/0ae891a8cee16603cdead0caf2d4c0b0800b22c9/src/looking_glass_app.erl
erlang
Copyright (c) 2017-Present Pivotal Software, Inc. All rights reserved. please see LICENSE-APACHE2. either express or implied. See the LICENSE file for specific language governing rights and limitations of this software. If you have any questions regarding licensing, please contact us at .
This package , Looking , is double - licensed under the Mozilla Public License 1.1 ( " MPL " ) and the Apache License version 2 ( " ASL " ) . For the MPL , please see LICENSE - MPL - RabbitMQ . For the ASL , This software is distributed on an " AS IS " basis , WITHOUT WARRANTY OF ANY KIND , -module(looking_glass_app). -behaviour(application). -export([start/2]). -export([stop/1]). start(_Type, _Args) -> looking_glass_sup:start_link(). stop(_State) -> ok.
2ed0c2f461539b0e21865a27b3e256619fed43fe2d8be06087365f06febc7dae
rtrusso/scp
badsrlo.scm
(define x (make-string 3 #\a)) (display (string-ref x -1)) (newline)
null
https://raw.githubusercontent.com/rtrusso/scp/2051e76df14bd36aef81aba519ffafa62b260f5c/src/tests/badsrlo.scm
scheme
(define x (make-string 3 #\a)) (display (string-ref x -1)) (newline)
d05dd1e38d1ded472ff3a55c56862ac5606993469e0d8943b10467a00c8e448b
tomhanika/conexp-clj
latex.clj
;; Copyright ⓒ the conexp-clj developers; all rights reserved. ;; The use and distribution terms for this software are covered by the Eclipse Public License 1.0 ( -1.0.php ) ;; which can be found in the file LICENSE at the root of this distribution. ;; By using this software in any fashion, you are agreeing to be bound by ;; the terms of this license. ;; You must not remove this notice, or any other, from this software. (ns conexp.io.latex "Provides functionality to represent conexp-clj datastructures as latex code." (:use conexp.base [conexp.fca.contexts :only (objects attributes incidence)] conexp.fca.lattices conexp.fca.many-valued-contexts [conexp.layouts.base :only (positions connections nodes inf-irreducibles sup-irreducibles annotation valuations)])) ;;; (defn tex-escape "Escapes all significant characters used by LaTeX." [string] (clojure.string/escape (str string) {\& "\\&" \% "\\%" \$ "\\$" \# "\\#" \_ "\\_" \{ "\\{" \} "\\}" \< "\\textless " \> "\\textgreater " \~ "\\textasciitilde " \^ "\\textasciicircum " \\ "\\textbackslash "})) ;;; (defprotocol LaTeX "Implements conversion to latex code." (latex [this] [this choice] "Returns a string representation of this.")) ;;; Default (extend-type Object LaTeX (latex ([this] (.toString this)) ([this choice] (.toString this)))) ;;; Contexts (extend-type conexp.fca.contexts.Context LaTeX (latex ([this] (latex this :plain)) ([this choice] (case choice :plain (with-out-str (println "$") (println (str "\\begin{array}{l||*{" (count (attributes this)) "}{c|}}")) (doseq [m (map tex-escape (attributes this))] (print (str "& " m))) (println "\\\\\\hline\\hline") (doseq [g (objects this)] (print (tex-escape (str g))) (doseq [m (attributes this)] (print (str "& " (if ((incidence this) [g m]) "\\times" "\\cdot")))) (println "\\\\\\hline")) (println (str "\\end{array}")) (println "$")) :fca (with-out-str (println "\\begin{cxt}%") (println " \\cxtName{}%") (doseq [m (attributes this)] (if (>= 2 (count m)) (println (str " \\att{" (tex-escape m) "}%")) (println (str " \\atr{" (tex-escape m) "}%")))) (let [inz (incidence this)] (doseq [g (objects this)] (print " \\obj{") (doseq [m (attributes this)] (print (if (inz [g m]) "x" "."))) (println (str "}{" (tex-escape g) "}")))) (println "\\end{cxt}")) true (illegal-argument "Unsupported latex format " choice " for contexts."))))) ;;; Layouts (declare layout->tikz) (extend-type conexp.layouts.base.Layout LaTeX (latex ([this] (latex this :tikz)) ([this choice] (case choice :tikz (layout->tikz this) true (illegal-argument "Unsupported latex format " choice " for layouts."))))) (defn- layout->tikz [layout] (let [vertex-pos (positions layout), sorted-vertices (sort #(let [[x_1 y_1] (vertex-pos %1), [x_2 y_2] (vertex-pos %2)] (or (< y_1 y_2) (and (= y_1 y_2) (< x_1 x_2)))) (nodes layout)), vertex-idx (into {} (map-indexed (fn [i v] [v i]) sorted-vertices)), value-fn #(if (nil? ((valuations layout) %)) "" ((valuations layout) %))] (with-out-str (println "\\colorlet{mivertexcolor}{blue}") (println "\\colorlet{jivertexcolor}{red}") (println "\\colorlet{vertexcolor}{mivertexcolor!50}") (println "\\colorlet{bordercolor}{black!80}") (println "\\colorlet{linecolor}{gray}") (println "% parameter corresponds to the used valuation function and can be addressed by #1") (println "\\tikzset{vertexbase/.style 2 args={semithick, shape=circle, inner sep=2pt, outer sep=0pt, draw=bordercolor},%") (println " vertex/.style 2 args={vertexbase={#1}{}, fill=vertexcolor!45},%") (println " mivertex/.style 2 args={vertexbase={#1}{}, fill=mivertexcolor!45},%") (println " jivertex/.style 2 args={vertexbase={#1}{}, fill=jivertexcolor!45},%") (println " divertex/.style 2 args={vertexbase={#1}{}, top color=mivertexcolor!45, bottom color=jivertexcolor!45},%") (println " conn/.style={-, thick, color=linecolor}%") (println "}") (println "\\begin{tikzpicture}") (println " \\begin{scope} %for scaling and the like") (println " \\begin{scope} %draw vertices") (println " \\foreach \\nodename/\\nodetype/\\param/\\xpos/\\ypos in {%") (let [infs (set (inf-irreducibles layout)), sups (set (sup-irreducibles layout)), insu (intersection infs sups), vertex-lines (map (fn [v] (let [i (vertex-idx v), [x y] (vertex-pos v)] (str " " i "/" (cond (contains? insu v) "divertex" (contains? sups v) "jivertex" (contains? infs v) "mivertex" :else "vertex") "/" (value-fn v) "/" x "/" y))) sorted-vertices)] (doseq [x (interpose ",\n" vertex-lines)] (print x)) (println)) (println " } \\node[\\nodetype={\\param}{}] (\\nodename) at (\\xpos, \\ypos) {};") (println " \\end{scope}") (println " \\begin{scope} %draw connections") (doseq [[v w] (connections layout)] (println (str " \\path (" (vertex-idx v) ") edge[conn] (" (vertex-idx w) ");"))) (println " \\end{scope}") (println " \\begin{scope} %add labels") (println " \\foreach \\nodename/\\labelpos/\\labelopts/\\labelcontent in {%") (let [ann (annotation layout), ann-lines (mapcat (fn [v] (let [[u _] (map tex-escape (ann v)), lines (if-not (= "" u) (list (str " " (vertex-idx v) "/above//{" u "}")) ())] lines)) sorted-vertices) ann-lines (concat ann-lines (mapcat (fn [v] (let [[_ l] (map tex-escape (ann v)), val (value-fn v), lines (if-not (= "" l) (list (str " " (vertex-idx v) "/below//{" l "}")) ())] lines)) sorted-vertices)) ann-lines (concat ann-lines (mapcat (fn [v] (let [val (value-fn v), lines (if-not (= "" val) (list (str " " (vertex-idx v) "/right//{" val "}")) ())] lines)) sorted-vertices))] (doseq [x (interpose ",\n" ann-lines)] (print x)) (println)) (println " } \\coordinate[label={[\\labelopts]\\labelpos:{\\labelcontent}}](c) at (\\nodename);") (println " \\end{scope}") (println " \\end{scope}") (println "\\end{tikzpicture}")))) ;;; nil
null
https://raw.githubusercontent.com/tomhanika/conexp-clj/cd6b02cb5bb63d813cb9fcc78b1c0ce11992b51e/src/main/clojure/conexp/io/latex.clj
clojure
Copyright ⓒ the conexp-clj developers; all rights reserved. The use and distribution terms for this software are covered by the which can be found in the file LICENSE at the root of this distribution. By using this software in any fashion, you are agreeing to be bound by the terms of this license. You must not remove this notice, or any other, from this software. Default Contexts Layouts
Eclipse Public License 1.0 ( -1.0.php ) (ns conexp.io.latex "Provides functionality to represent conexp-clj datastructures as latex code." (:use conexp.base [conexp.fca.contexts :only (objects attributes incidence)] conexp.fca.lattices conexp.fca.many-valued-contexts [conexp.layouts.base :only (positions connections nodes inf-irreducibles sup-irreducibles annotation valuations)])) (defn tex-escape "Escapes all significant characters used by LaTeX." [string] (clojure.string/escape (str string) {\& "\\&" \% "\\%" \$ "\\$" \# "\\#" \_ "\\_" \{ "\\{" \} "\\}" \< "\\textless " \> "\\textgreater " \~ "\\textasciitilde " \^ "\\textasciicircum " \\ "\\textbackslash "})) (defprotocol LaTeX "Implements conversion to latex code." (latex [this] [this choice] "Returns a string representation of this.")) (extend-type Object LaTeX (latex ([this] (.toString this)) ([this choice] (.toString this)))) (extend-type conexp.fca.contexts.Context LaTeX (latex ([this] (latex this :plain)) ([this choice] (case choice :plain (with-out-str (println "$") (println (str "\\begin{array}{l||*{" (count (attributes this)) "}{c|}}")) (doseq [m (map tex-escape (attributes this))] (print (str "& " m))) (println "\\\\\\hline\\hline") (doseq [g (objects this)] (print (tex-escape (str g))) (doseq [m (attributes this)] (print (str "& " (if ((incidence this) [g m]) "\\times" "\\cdot")))) (println "\\\\\\hline")) (println (str "\\end{array}")) (println "$")) :fca (with-out-str (println "\\begin{cxt}%") (println " \\cxtName{}%") (doseq [m (attributes this)] (if (>= 2 (count m)) (println (str " \\att{" (tex-escape m) "}%")) (println (str " \\atr{" (tex-escape m) "}%")))) (let [inz (incidence this)] (doseq [g (objects this)] (print " \\obj{") (doseq [m (attributes this)] (print (if (inz [g m]) "x" "."))) (println (str "}{" (tex-escape g) "}")))) (println "\\end{cxt}")) true (illegal-argument "Unsupported latex format " choice " for contexts."))))) (declare layout->tikz) (extend-type conexp.layouts.base.Layout LaTeX (latex ([this] (latex this :tikz)) ([this choice] (case choice :tikz (layout->tikz this) true (illegal-argument "Unsupported latex format " choice " for layouts."))))) (defn- layout->tikz [layout] (let [vertex-pos (positions layout), sorted-vertices (sort #(let [[x_1 y_1] (vertex-pos %1), [x_2 y_2] (vertex-pos %2)] (or (< y_1 y_2) (and (= y_1 y_2) (< x_1 x_2)))) (nodes layout)), vertex-idx (into {} (map-indexed (fn [i v] [v i]) sorted-vertices)), value-fn #(if (nil? ((valuations layout) %)) "" ((valuations layout) %))] (with-out-str (println "\\colorlet{mivertexcolor}{blue}") (println "\\colorlet{jivertexcolor}{red}") (println "\\colorlet{vertexcolor}{mivertexcolor!50}") (println "\\colorlet{bordercolor}{black!80}") (println "\\colorlet{linecolor}{gray}") (println "% parameter corresponds to the used valuation function and can be addressed by #1") (println "\\tikzset{vertexbase/.style 2 args={semithick, shape=circle, inner sep=2pt, outer sep=0pt, draw=bordercolor},%") (println " vertex/.style 2 args={vertexbase={#1}{}, fill=vertexcolor!45},%") (println " mivertex/.style 2 args={vertexbase={#1}{}, fill=mivertexcolor!45},%") (println " jivertex/.style 2 args={vertexbase={#1}{}, fill=jivertexcolor!45},%") (println " divertex/.style 2 args={vertexbase={#1}{}, top color=mivertexcolor!45, bottom color=jivertexcolor!45},%") (println " conn/.style={-, thick, color=linecolor}%") (println "}") (println "\\begin{tikzpicture}") (println " \\begin{scope} %for scaling and the like") (println " \\begin{scope} %draw vertices") (println " \\foreach \\nodename/\\nodetype/\\param/\\xpos/\\ypos in {%") (let [infs (set (inf-irreducibles layout)), sups (set (sup-irreducibles layout)), insu (intersection infs sups), vertex-lines (map (fn [v] (let [i (vertex-idx v), [x y] (vertex-pos v)] (str " " i "/" (cond (contains? insu v) "divertex" (contains? sups v) "jivertex" (contains? infs v) "mivertex" :else "vertex") "/" (value-fn v) "/" x "/" y))) sorted-vertices)] (doseq [x (interpose ",\n" vertex-lines)] (print x)) (println)) (println " } \\node[\\nodetype={\\param}{}] (\\nodename) at (\\xpos, \\ypos) {};") (println " \\end{scope}") (println " \\begin{scope} %draw connections") (doseq [[v w] (connections layout)] (println (str " \\path (" (vertex-idx v) ") edge[conn] (" (vertex-idx w) ");"))) (println " \\end{scope}") (println " \\begin{scope} %add labels") (println " \\foreach \\nodename/\\labelpos/\\labelopts/\\labelcontent in {%") (let [ann (annotation layout), ann-lines (mapcat (fn [v] (let [[u _] (map tex-escape (ann v)), lines (if-not (= "" u) (list (str " " (vertex-idx v) "/above//{" u "}")) ())] lines)) sorted-vertices) ann-lines (concat ann-lines (mapcat (fn [v] (let [[_ l] (map tex-escape (ann v)), val (value-fn v), lines (if-not (= "" l) (list (str " " (vertex-idx v) "/below//{" l "}")) ())] lines)) sorted-vertices)) ann-lines (concat ann-lines (mapcat (fn [v] (let [val (value-fn v), lines (if-not (= "" val) (list (str " " (vertex-idx v) "/right//{" val "}")) ())] lines)) sorted-vertices))] (doseq [x (interpose ",\n" ann-lines)] (print x)) (println)) (println " } \\coordinate[label={[\\labelopts]\\labelpos:{\\labelcontent}}](c) at (\\nodename);") (println " \\end{scope}") (println " \\end{scope}") (println "\\end{tikzpicture}")))) nil
523b3ea6ccf5be45c95011846af7e5a08bd5ca706d6f6719acc3ee0ad97786d6
exoscale/exopaste
store.clj
(ns exopaste.store (:require [com.stuartsierra.component :as component])) (defn add-new-paste "Insert a new paste in the database, then return its UUID." [store content] (let [uuid (.toString (java.util.UUID/randomUUID))] (swap! (:data store) assoc (keyword uuid) {:content content}) uuid)) (defn get-paste-by-uuid "Find the paste corresponding to the passed-in uuid, then return it." [store uuid] ((keyword uuid) @(:data store))) (defrecord InMemoryStore [data] component/Lifecycle (start [this] (assoc this :data (atom {}))) (stop [this] this)) (defn make-store [] (map->InMemoryStore {}))
null
https://raw.githubusercontent.com/exoscale/exopaste/be1ee7a5cc2e87124b6588076ea0946f5f52f560/src/exopaste/store.clj
clojure
(ns exopaste.store (:require [com.stuartsierra.component :as component])) (defn add-new-paste "Insert a new paste in the database, then return its UUID." [store content] (let [uuid (.toString (java.util.UUID/randomUUID))] (swap! (:data store) assoc (keyword uuid) {:content content}) uuid)) (defn get-paste-by-uuid "Find the paste corresponding to the passed-in uuid, then return it." [store uuid] ((keyword uuid) @(:data store))) (defrecord InMemoryStore [data] component/Lifecycle (start [this] (assoc this :data (atom {}))) (stop [this] this)) (defn make-store [] (map->InMemoryStore {}))
ef4cb13216516eb93934f47e2299f47142e8ee246191e479700c9df5942d1574
mhallin/graphql_ppx
graphql_ast.ml
open Source_pos type type_ref = | Tr_named of string spanning | Tr_list of type_ref spanning | Tr_non_null_named of string spanning | Tr_non_null_list of type_ref spanning type input_value = | Iv_null | Iv_int of int | Iv_float of float | Iv_string of string | Iv_boolean of bool | Iv_enum of string | Iv_variable of string | Iv_list of input_value spanning list | Iv_object of (string spanning * input_value spanning) list type variable_definition = { vd_type: type_ref spanning; vd_default_value: input_value spanning option } type variable_definitions = (string spanning * variable_definition) list type arguments = (string spanning * input_value spanning) list type directive = { d_name: string spanning; d_arguments: arguments spanning option; } type fragment_spread = { fs_name: string spanning; fs_directives: directive spanning list } type field = { fd_alias: string spanning option; fd_name: string spanning; fd_arguments: arguments spanning option; fd_directives: directive spanning list; fd_selection_set: selection list spanning option; } and inline_fragment = { if_type_condition: string spanning option; if_directives: directive spanning list; if_selection_set: selection list spanning; } and selection = | Field of field spanning | FragmentSpread of fragment_spread spanning | InlineFragment of inline_fragment spanning type operation_type = Query | Mutation | Subscription type operation = { o_type: operation_type; o_name: string spanning option; o_variable_definitions: variable_definitions spanning option; o_directives: directive spanning list; o_selection_set: selection list spanning; } type fragment = { fg_name: string spanning; fg_type_condition: string spanning; fg_directives: directive spanning list; fg_selection_set: selection list spanning; } type definition = | Operation of operation spanning | Fragment of fragment spanning type document = definition list let rec innermost_name = function | Tr_named { item; _ } | Tr_non_null_named { item; _ } -> item | Tr_list { item; _ } | Tr_non_null_list { item; _ } -> innermost_name item
null
https://raw.githubusercontent.com/mhallin/graphql_ppx/5796b3759bdf0d29112f48e43a2f0623f7466e8a/src/base/graphql_ast.ml
ocaml
open Source_pos type type_ref = | Tr_named of string spanning | Tr_list of type_ref spanning | Tr_non_null_named of string spanning | Tr_non_null_list of type_ref spanning type input_value = | Iv_null | Iv_int of int | Iv_float of float | Iv_string of string | Iv_boolean of bool | Iv_enum of string | Iv_variable of string | Iv_list of input_value spanning list | Iv_object of (string spanning * input_value spanning) list type variable_definition = { vd_type: type_ref spanning; vd_default_value: input_value spanning option } type variable_definitions = (string spanning * variable_definition) list type arguments = (string spanning * input_value spanning) list type directive = { d_name: string spanning; d_arguments: arguments spanning option; } type fragment_spread = { fs_name: string spanning; fs_directives: directive spanning list } type field = { fd_alias: string spanning option; fd_name: string spanning; fd_arguments: arguments spanning option; fd_directives: directive spanning list; fd_selection_set: selection list spanning option; } and inline_fragment = { if_type_condition: string spanning option; if_directives: directive spanning list; if_selection_set: selection list spanning; } and selection = | Field of field spanning | FragmentSpread of fragment_spread spanning | InlineFragment of inline_fragment spanning type operation_type = Query | Mutation | Subscription type operation = { o_type: operation_type; o_name: string spanning option; o_variable_definitions: variable_definitions spanning option; o_directives: directive spanning list; o_selection_set: selection list spanning; } type fragment = { fg_name: string spanning; fg_type_condition: string spanning; fg_directives: directive spanning list; fg_selection_set: selection list spanning; } type definition = | Operation of operation spanning | Fragment of fragment spanning type document = definition list let rec innermost_name = function | Tr_named { item; _ } | Tr_non_null_named { item; _ } -> item | Tr_list { item; _ } | Tr_non_null_list { item; _ } -> innermost_name item
3ca4ec66f6e5bdbc6b2baf1c213ec59f0bc9a2a1f5b64c705898f7566c4f41c2
iamFIREcracker/adventofcode
day11.lisp
(defpackage :aoc/2019/11 #.cl-user::*aoc-use*) (in-package :aoc/2019/11) (defstruct (robot (:constructor make-robot%)) program in out direction) (defun make-robot (program) (let* ((in (make-queue)) (out (make-queue)) (program (intcode:make-program (copy-hash-table (intcode:program-memory program)) in out))) (make-robot% :program program :in in :out out :direction #C(0 1)))) (defun robot-rotate (robot dir-change) (setf (robot-direction robot) (case dir-change (0 (complex-rotate-ccw (robot-direction robot))) (1 (complex-rotate-cw (robot-direction robot)))))) (defun robot-run (robot input) (enqueue input (robot-in robot)) (let ((still-running (intcode:program-run (robot-program robot)))) (when still-running (prog1 (dequeue (robot-out robot)) (let ((dir-change (dequeue (robot-out robot)))) (robot-rotate robot dir-change)))))) (defun paint-panels (initial-color robot &aux (panels (make-hash-table))) (prog1 panels (loop :with pos = 0 :initially (hash-table-insert panels pos initial-color) :for input = (gethash pos panels 0) :for color = (robot-run robot input) :while color :do (hash-table-insert panels pos color) :do (incf pos (robot-direction robot)) :finally (return panels)))) (defun print-registration-identifier (panels) (with-output-to-string (s) (format s "~%") ;; add a leading new-line, to make testing easier/nicer (print-hash-table-map panels (lambda (value key) (declare (ignore key)) (if (eql 1 value) #\# #\Space)) s))) (define-solution (2019 11) (program intcode:read-program) (values (hash-table-count (paint-panels 0 (make-robot program))) (print-registration-identifier (paint-panels 1 (make-robot program))))) (define-test (2019 11) (1747 " #### ## ## ### # # # # # ### # # # # # # # # # # # # # # # # # # # #### ## # ### # # # ## ### # # # # # # # # # # # # # # # # # # # # # #### ## ### # # # # # # #### ### "))
null
https://raw.githubusercontent.com/iamFIREcracker/adventofcode/c395df5e15657f0b9be6ec555e68dc777b0eb7ab/src/2019/day11.lisp
lisp
add a leading new-line, to make testing easier/nicer
(defpackage :aoc/2019/11 #.cl-user::*aoc-use*) (in-package :aoc/2019/11) (defstruct (robot (:constructor make-robot%)) program in out direction) (defun make-robot (program) (let* ((in (make-queue)) (out (make-queue)) (program (intcode:make-program (copy-hash-table (intcode:program-memory program)) in out))) (make-robot% :program program :in in :out out :direction #C(0 1)))) (defun robot-rotate (robot dir-change) (setf (robot-direction robot) (case dir-change (0 (complex-rotate-ccw (robot-direction robot))) (1 (complex-rotate-cw (robot-direction robot)))))) (defun robot-run (robot input) (enqueue input (robot-in robot)) (let ((still-running (intcode:program-run (robot-program robot)))) (when still-running (prog1 (dequeue (robot-out robot)) (let ((dir-change (dequeue (robot-out robot)))) (robot-rotate robot dir-change)))))) (defun paint-panels (initial-color robot &aux (panels (make-hash-table))) (prog1 panels (loop :with pos = 0 :initially (hash-table-insert panels pos initial-color) :for input = (gethash pos panels 0) :for color = (robot-run robot input) :while color :do (hash-table-insert panels pos color) :do (incf pos (robot-direction robot)) :finally (return panels)))) (defun print-registration-identifier (panels) (with-output-to-string (s) (print-hash-table-map panels (lambda (value key) (declare (ignore key)) (if (eql 1 value) #\# #\Space)) s))) (define-solution (2019 11) (program intcode:read-program) (values (hash-table-count (paint-panels 0 (make-robot program))) (print-registration-identifier (paint-panels 1 (make-robot program))))) (define-test (2019 11) (1747 " #### ## ## ### # # # # # ### # # # # # # # # # # # # # # # # # # # #### ## # ### # # # ## ### # # # # # # # # # # # # # # # # # # # # # #### ## ### # # # # # # #### ### "))
c383ff23f38b7877e275de8357fb689297840371d04b1c361ff7405b4954d0d5
mk270/archipelago
digraph.mli
Archipelago , a multi - user dungeon ( MUD ) server , by ( C ) 2009 - 2012 This programme is free software ; you may redistribute and/or modify it under the terms of the GNU Affero General Public Licence as published by the Free Software Foundation , either version 3 of said Licence , or ( at your option ) any later version . Archipelago, a multi-user dungeon (MUD) server, by Martin Keegan Copyright (C) 2009-2012 Martin Keegan This programme is free software; you may redistribute and/or modify it under the terms of the GNU Affero General Public Licence as published by the Free Software Foundation, either version 3 of said Licence, or (at your option) any later version. *) type 'a digraph val create : 'a -> 'a digraph val remove_arc : src : 'a digraph -> dst : 'a digraph -> unit val add_arc : src : 'a digraph -> dst : 'a digraph -> unit val inbound : 'a digraph -> 'a digraph list val outbound : 'a digraph -> 'a digraph list val contained : 'a digraph -> 'a
null
https://raw.githubusercontent.com/mk270/archipelago/4241bdc994da6d846637bcc079051405ee905c9b/src/model/digraph.mli
ocaml
Archipelago , a multi - user dungeon ( MUD ) server , by ( C ) 2009 - 2012 This programme is free software ; you may redistribute and/or modify it under the terms of the GNU Affero General Public Licence as published by the Free Software Foundation , either version 3 of said Licence , or ( at your option ) any later version . Archipelago, a multi-user dungeon (MUD) server, by Martin Keegan Copyright (C) 2009-2012 Martin Keegan This programme is free software; you may redistribute and/or modify it under the terms of the GNU Affero General Public Licence as published by the Free Software Foundation, either version 3 of said Licence, or (at your option) any later version. *) type 'a digraph val create : 'a -> 'a digraph val remove_arc : src : 'a digraph -> dst : 'a digraph -> unit val add_arc : src : 'a digraph -> dst : 'a digraph -> unit val inbound : 'a digraph -> 'a digraph list val outbound : 'a digraph -> 'a digraph list val contained : 'a digraph -> 'a
5491e3f5b5c58ef802ec71d27cadcbdfca8e6faa5a498b3348ab5d4cc89a8b3e
jrm-code-project/LISP-Machine
page-fault.lisp
-*- Mode : LISP ; Base:8 ; : ZL -*- * * ( c ) Copyright 1983 Lisp Machine Inc * * Notes for explorer gc - pace Nov 20 , 1985 ;;; ;;; The per page volatility bits for the explorer are in L2-MAP-CONTROL<12.:11.>, ;;; but on the lambda its L2-MAP-CONTROL<1:0>. Therefore, where ever we write ;;; L2-MAP-CONTROL, put in another instruction for the explorer to copy the bits to the other field . -done RG 1/20/86 ;;; Secondly , the OLD - SPACE bit on the explorer ( and on the lambda AVP ) is in L1 - MAP<10 . > 1 means newspace , 0 means oldspace . ;;; This bit needs to be correctly set when regions are allocated or flipped. ;;; ;;; The region volatility bits stored in the L1-MAP are the same place and have the same ;;; meanings. ;;; There is code at INIMAP1 to set all of the L1 - MAP to " newspace " when booting . ;;; This may have to be replaced by a thing to set all of the oldspace bits by running ;;; through the region tables. -no, would not win much to boot with oldspace in existance. ;;; Timing restrictions concerning 2nd level map : on LAMBDA , a instruction must intervene between the being changed and the map being ;;; used as a SOURCE. No NO-OP is necessary if map is used as a DESTINATION, however. on EXP , instructions must intervene both places ( as per " special considerations " ) . (DEFCONST UC-LAMBDA-PAGE-FAULT '( ;;; page fault handler THIS FILE FOR LAMBDA ONLY . However , some cadr stuff is still present in conditionalized form for reference . On LAMBDA as on CADR , there are three complex data structures ( the level-2 map , the % PHT2- fields and the % % REGION- fields ) which share some of the same fields . Eventually , we will want to " decouple " all three . For now , however , we will leave % PHT2- and % % REGION- " coupled " but we must deal with the issue of the level 2 map , since it is split into two pieces on LAMBDA . ( Even eventually , all three will still have the same 10 . bit byte of ACCESS - STATUS - AND - META bits . ;;; Its just that it may be shifted to different places in the word in the various places . ) % % MAP2C- prefix is used to refer to the bits " in position " for the level2 map . PAGE FAULTS GENERALLY DO NOT CLOBBER ANYTHING . ;EXCEPTIONS: ; THE A-PGF-MUMBLE REGISTERS ARE CLOBBERED. ONLY THE PAGE FAULT ; ROUTINES SHOULD USE THEM. ; M-TEM, A-TEM1, A-TEM2, AND A-TEM3 ARE CLOBBERED. THEY ARE SUPER-TEMPORARY. THE DISPATCH CONSTANT AND THE Q REGISTER ARE CLOBBERED . THE DATA - TYPE OF VMA -MUST NOT- BE CLOBBERED . ; THE PDL-BUFFER-INDEX ISN'T CLOBBERED, BUT IT SHOULD BE. ; ;IF AN INTERRUPT OCCURS, IT HAS ALMOST NO SIDE-EFFECTS OTHER THAN WHAT PAGE FAULTS HAVE . ; IF A SEQUENCE BREAK IS ALLOWED AND , IT AFTER A WRITE CYCLE ;IS SUCCESSFULLY COMPLETED, BUT EFFECTIVELY BEFORE A READ CYCLE. THE MD IS RESET FROM THE VMA . THE LETTERED M ACS ARE SAVED , AND MUST CONTAIN GC MARKABLE STUFF OR DTP TRAP ( OR -1 ) . MISCELLANEOUS ACS LIKE A - TEM 'S ARE CLOBBERED BY SEQUENCE BREAKS . Fields in first level map . Lambda only , since on cadr the 5 bit l2 - map - block - index is all there is . The L1 map meta - bits are a function of the region . Since each L1 map entry corresponds to 32 . virtual pages , this means regions must be at least 32 pages , etc . This is no further restriction , since the address space quantuum was already 64 pages . For hardware convenience , all three L1 map meta bits are stored in COMPLEMENTED form . The L1 map MB codes are : ( in parens is the inverted value actually seen in hardware ) . 0 - > static region ( 3 ) 1 - > dynamic region ( 2 ) 2 - > active consing region ( ie , copy space ) ( 1 ) 3 - > extra pdl region ( 0 ) ;gc bits same between lambda and explorer if 1 , MB1 and MB0 are INVALID . (def-data-field map1-volatility-invalid 1 9) (def-data-field map1-volatility 2 7) (DEF-DATA-FIELD L1-MAP-MB1-BAR 1 8) (DEF-DATA-FIELD L1-MAP-MB0-BAR 1 7) (DEF-DATA-FIELD L1-MAP-META-BITS #+lambda 3 #+exp 5 7) (DEF-DATA-FIELD L1-MAP-L2-BLOCK-SELECT 7 0) #+exp (def-data-field l1-map-old-exp 1 10.) #+exp (def-data-field l1-map-valid-exp 1 11.) #+exp (def-data-field l1-map-all-but-old-and-valid 9 0) ; DEFINITIONS OF FIELDS IN THE MAP HARDWARE ; BITS IN MEMORY-MAP-DATA. CADR DEFINITIONS : ;;(DEF-DATA-FIELD MAP-READ-FAULT-BIT 1 30.) ;this symbol not used ;;(DEF-DATA-FIELD MAP-WRITE-FAULT-BIT 1 31.) ;this symbol not used ;;(DEF-DATA-FIELD MAP-PHYSICAL-PAGE-NUMBER 14. 0) ( DEF - DATA - FIELD MAP - META - BITS 6 14 . ) ; THE HIGH TWO OF THESE ARE HACKABLE BY ;; ; DISPATCH INSTRUCTION ;; ;THE REST ARE JUST FOR SOFTWARE TO LOOK AT ;;(DEF-DATA-FIELD MAP-STATUS-CODE 3 20.) ( DEF - DATA - FIELD MAP - ACCESS - CODE 2 22 . ) ; NOTE BIT 22 IS IN TWO FIELDS ;;(DEF-DATA-FIELD MAP-FIRST-LEVEL-MAP 5 24.) ;NOTE NOT THE SAME AS WHERE IT WRITES ( DEF - DATA - FIELD MAP - SECOND - LEVEL - MAP 24 . 0 ) ( DEF - DATA - FIELD MAP - ACCESS - STATUS - AND - META - BITS 10 . 14 . ) ( DEF - DATA - FIELD MAP - HARDWARE - READ - ACCESS 1 23 . ) ; HARDWARE PERMITS ( AT LEAST ) READ ACCESS ;; ; IF THIS BIT SET. ( DEF - DATA - FIELD CADR - MAP - ACCESS - CODE 2 22 . ) ; czrr , inimap , phys - mem - read ;(DEF-DATA-FIELD CADR-MAP-STATUS-CODE 3 20.) ( DEF - DATA - FIELD CADR - MAP - META - BITS 6 14 . ) ; used in inimap and phys - mem - read ( DEF - DATA - FIELD CADR - ACCESS - STATUS - AND - META - BITS 10 . 14 . ) ; load - l2 - map - from - cadr - physical ( DEF - DATA - FIELD CADR - PHYSICAL - PAGE - NUMBER 14 . 0 ) ; load - l2 - map - from - cadr - physical , czrr high two are hackable by dispatch inst . (DEF-DATA-FIELD MAP2C-STATUS-CODE 3 6) note one bit overlap with status - code (DEF-DATA-FIELD MAP2C-ACCESS-STATUS-AND-META-BITS 10. 0) (DEF-DATA-FIELD MAP2C-HARDWARE-READ-ACCESS 1 9.) ;hardware permits (at least) read access if force , ( ie 40 bit in func dest that ;starts memory cycle) this bit used by hardware instead of above bit. This ;allows PDL buffer routines to hack without clobbering map, etc. this bit turns out to be in same place for LAMBDA and EXP ! (def-data-field map2c-volatility 2 0) ;explorer has below fields in hardware. We keep bits in usual place, frotzing them just ; before loading into hardware in LOAD-L2-MAP-FROM-CADR-PHYSICAL. #+exp(def-data-field exp-map2c-volatility 2 11.) ;Note forced-bit is same for both, so definition above suffices. (DEF-DATA-FIELD MAP2C-REPRESENTATION-TYPE 2 2) on CADR , this was looked at by hardware ;by DISPATCH-ON-MAP-18 feature. On LAMBDA and EXPLORER, the hardware function is replaced by the GC - VOLATILITY gate , so the bit has no special hardware function . on CADR , this was looked at by hardware DISPATCH - ON - MAP-19 feature . On LAMBDA , it still is . EXPLORER and AVP , this hardware ;function comes instead from the level-1 map. (DEF-DATA-FIELD MAP2P-PHYSICAL-PAGE-NUMBER 22. 0) 0 unless trying to hack bytes or 16 bit wds ;these definitions reduce need to conditionalize things per processor as well as being ; more modular. (assign l2-map-status-code (plus map2c-status-code l2-map-control)) (assign l2-map-access-status-and-meta-bits (plus map2c-access-status-and-meta-bits l2-map-control)) (assign l2-map-representation-type (plus map2c-representation-type l2-map-control)) (assign l2-map-extra-pdl-meta-bit (plus map2c-extra-pdl-meta-bit l2-map-control)) (assign l2-map-oldspace-meta-bit (plus map2c-oldspace-meta-bit l2-map-control)) (assign l2-map-physical-page-number (plus map2p-physical-page-number l2-map-physical-page)) FIELDS IN VMA WHEN WRITING MAP . ( DEF - DATA - FIELD MAP - WRITE - SECOND - LEVEL - MAP 24 . 0 ) ;;(DEF-DATA-FIELD MAP-WRITE-ENABLE-SECOND-LEVEL-WRITE 1 25.) ( DEF - DATA - FIELD MAP - WRITE - ENABLE - FIRST - LEVEL - WRITE 1 26 . ) ( DEF - DATA - FIELD MAP - WRITE - FIRST - LEVEL - MAP 5 27 . ) ; NOTE NOT THE SAME AS WHERE IT READS ; DEFINITIONS OF FIELDS IN PAGE HASH TABLE WORD 1 SAME AS VMA (DEF-DATA-FIELD PHT1-SWAP-STATUS-CODE 3 0) (DEF-DATA-FIELD PHT1-ALL-BUT-SWAP-STATUS-CODE 29. 3) (DEF-DATA-FIELD PHT1-AGE 2 3) (DEF-DATA-FIELD PHT1-ALL-BUT-AGE-AND-SWAP-STATUS-CODE 27. 5) (DEF-DATA-FIELD PHT1-MODIFIED-BIT 1 5) ;SET IF PAGE MODIFIED (DEF-DATA-FIELD PHT1-VALID-BIT 1 6) WORD 2 THESE ARE NOW THE SAME BIT POSITIONS AS IN THE SECOND LEVEL MAP on CADR . (DEF-DATA-FIELD PHT2-META-BITS 6 26) (def-data-field pht2-extra-pdl-meta-bit 1 32) (def-data-field pht2-oldspace-meta-bit 1 33) (def-data-field pht2-map-volatility 2 26) (DEF-DATA-FIELD PHT2-MAP-STATUS-CODE 3 34) (DEF-DATA-FIELD PHT2-MAP-ACCESS-CODE 2 36) (DEF-DATA-FIELD PHT2-MAP-ACCESS-AND-STATUS-CODE 4 34) (DEF-DATA-FIELD PHT2-ACCESS-STATUS-AND-META-BITS 12 26) (def-data-field pht2-access-status-and-meta-bits-except-volatility 10 30) (DEF-DATA-FIELD PHT2-PHYSICAL-PAGE-NUMBER 26 0) ; DEFINITIONS OF FIELDS IN THE ADDRESS ADDRESS BLOCK OF 32 . PAGES (DEF-DATA-FIELD VMA-PAGE-ADDR-PART 17. 8) ;VIRTUAL PAGE NUMBER (DEF-DATA-FIELD VMA-PHYS-PAGE-ADDR-PART 14. 8) ;PHYSICAL PAGE NUMBER ADDR WITHIN PAGE (DEF-DATA-FIELD ALL-BUT-VMA-LOW-BITS 24. 8) NOTE : PGF - R , ETC CAN BE ENTERED RECURSIVELY IF THE PAGE IS SWAPPED OUT AND THE DISK ROUTINES FAULT WHEN REFERENCING THE DISK CONTROL . ;THESE COMMENTS APPLY TO SEQUENCE BREAK INTERRUPT MAY BE INSERTED -AFTER- THE READ CYCLE , HOWEVER IT IS EFFECTIVELY BEFORE SINCE ON DISMISS READ - MEMORY - DATA RESTORED FROM VMA ! ! ;NOTE THAT THIS ORDERING ALLOWS AN EFFECTIVE READ-PAUSE-WRITE CYCLE ;TO BE DONE JUST BY DOING A READ THEN A WRITE, EVEN ;THOUGH AFTER EACH CYCLE IS STARTED INTERRUPTS ARE CHECKED. ;To request a sequence-break, do ; ((LOCATION-COUNTER) LOCATION-COUNTER) ;Assure PC gets fetched ( ( RG - MODE ) ANDCA RG - MODE ( A - CONSTANT 1_26 . ) ) . ( note sense opposite from CADR ) PUSHJ HERE ON PAGE FAULT , INTERRUPT REQUEST , OR SEQUENCE BREAK DURING READ CYCLE PGF-R-SB-save-vma-in-t (JUMP-CONDITIONAL PG-FAULT-OR-INTERRUPT PGF-R-I) can clobber VMA , MD . ((m-t) q-typed-pointer vma) ((vma-start-read) m-t) (check-page-read) (popj) must not loop a la CADR because PGF could be handled w/o mem cycle , so page - fault ;may persist even if memory cycle completed ok. SBSER #+lambda(POPJ-IF-BIT-SET (BYTE-FIELD 1 26.) RG-MODE) ;Flush on no SB req #+exp (popj-if-bit-clear (byte-field 1 14.) mcr) ((M-TEM) M-FLAGS-NO-SEQUENCE-BREAK) ;TURN INTO ILLOP IF TRAP AT BAD TIME (CALL-NOT-EQUAL M-TEM A-ZERO ILLOP) ;NOTE WOULD PROBABLY DIE LATER ANYWAY #+lambda((RG-MODE) IOR RG-MODE (A-CONSTANT 1_26.)) #+exp ((mcr) andca mcr (a-constant 1_14.)) (jump-not-equal m-zero a-defer-boot-char-mode sbser-process-boot-char) ((M-TEM) A-INHIBIT-SCHEDULING-FLAG) (JUMP-NOT-EQUAL M-TEM A-V-NIL SB-DEFER) ;---new run light ((m-tem3) vma) ((md) setz) ((vma) a-disk-run-light) ((vma-start-write) sub vma (a-constant 12)) (check-page-write-map-reload-only) ((vma) m-tem3) ;---new run light ((M-DEFERRED-SEQUENCE-BREAK-FLAG) DPB M-ZERO A-FLAGS) ((M-TEM) DPB M-ZERO Q-ALL-BUT-TYPED-POINTER A-QSSTKG) SCHEDULER SHOULD HAVE DEFERED INTERRUPTS ENSURE NO SPECIAL PDL OVERFLOW STORING STATUS REGULAR PDL IS PREWITHDRAWN , CAN'T OVERFLOW (CALL-XCT-NEXT SGLV) ;STORE CURRENT STATUS ((M-TEM) (A-CONSTANT (EVAL SG-STATE-RESUMABLE))) ;AND SWAP SPECIAL-PDL ((A-SG-TEM) A-V-NIL) ;Transmit NIL " CALL " SCHEDULER STACK GROUP ((M-A) A-QSSTKG) SB-DEFER ;---new run light ((m-tem3) vma) ((m-tem4) md) ((vma) a-disk-run-light) ((vma) sub vma (a-constant 12)) ((md) m-minus-one) ((m-tem) dpb m-zero q-all-but-typed-pointer a-qsstkg) (jump-equal m-tem a-qcstkg sb-light-off) ((vma-start-read) vma) (check-page-read-map-reload-only) sb-light-off ((md) xor md a-minus-one) ((vma-start-write) vma) (check-page-write-map-reload-only) ((vma) m-tem3) ((md) m-tem4) ;---end of new run light (POPJ-AFTER-NEXT (M-DEFERRED-SEQUENCE-BREAK-FLAG) DPB (M-CONSTANT -1) A-FLAGS) (NO-OP) sbser-process-boot-char ((M-DEFERRED-SEQUENCE-BREAK-FLAG) DPB M-ZERO A-FLAGS) ENSURE NO SPECIAL PDL OVERFLOW STORING STATUS REGULAR PDL IS PREWITHDRAWN , CAN'T OVERFLOW this seems to be preserved by SGLV (CALL-XCT-NEXT SGLV) ;STORE CURRENT STATUS ((M-TEM) (A-CONSTANT (EVAL SG-STATE-RESUMABLE))) ;AND SWAP SPECIAL-PDL (call kbd-boot-char-xct-now) here is an attempt at returning via an SDU continue command -- I do n't know if it will work . ((m-a) a-sg-tem) ;try to return to prev stack group ;(can't go to scheduler since we ; may have interrupted it with ; inhibit scheduling flag on) ((A-SG-TEM) A-V-NIL) ;Transmit NIL (JUMP SG-ENTER) PUSHJ HERE ON PAGE FAULT OR INTERRUPT REQUEST DURING READ CYCLE PGF-R-I (declare (clobbers a-tem)) (JUMP-CONDITIONAL NO-PG-FAULT INTR) ;IF NO PG FAULT, TAKE INTERRUPT ;PUSHJ HERE ON READ CYCLE PAGE FAULT WHEN DESIRE NOT TO TAKE INTERRUPT ;GUARANTEED TO RETURN WITHOUT ANY INTERRUPTS HAPPENING, OR ELSE TO GO TO ILLOP ;BUT SEE THE COMMENTS ON THE DEFINITION OF CHECK-PAGE-READ-NO-INTERRUPT PGF-R (declare (clobbers a-tem) (must-avoid intr)) ((MD) VMA) ;ADDRESS THE MAP (no-op) ;give map time to set up. (DISPATCH-XCT-NEXT L2-MAP-STATUS-CODE D-PGF) ((M-PGF-WRITE) DPB M-ZERO A-FLAGS) ;IF IT RETURNS HERE, WE RESTART THE READ REFERENCE ((VMA-START-READ) A-PGF-VMA) (POPJ-AFTER-NEXT NO-OP) (CHECK-PAGE-READ-NO-INTERRUPT) ;DIDN'T ENTIRELY SUCCEED, TRY AGAIN PGF-R-MAP-RELOAD-ONLY (declare (clobbers a-tem) (must-avoid intr)) ((MD) VMA) ;ADDRESS THE MAP (no-op) ;give map time to set up. (DISPATCH-XCT-NEXT L2-MAP-STATUS-CODE D-PGF-MAP-RELOAD-ONLY) ((M-PGF-WRITE) DPB M-ZERO A-FLAGS) ;IF IT RETURNS HERE, WE RESTART THE READ REFERENCE ((VMA-START-READ) A-PGF-VMA) (POPJ-AFTER-NEXT NO-OP) (CHECK-PAGE-READ-MAP-RELOAD-ONLY) ;DIDN'T ENTIRELY SUCCEED, TRY AGAIN PUSHJ HERE ON PAGE FAULT , INTERRUPT , OR SEQUENCE BREAK DURING WRITE CYCLE --not used . ;PGF-W-SB(declare (clobbers a-tem)) ( JUMP - CONDITIONAL PG - FAULT - OR - INTERRUPT PGF - W - I ) ;see note above ; (JUMP SBSER) PGF-W-BIND (declare (clobbers a-tem a-pgf-mode) (must-avoid intr)) (JUMP-XCT-NEXT PGF-W-1) ((A-PGF-MODE) A-V-TRUE) PGF-W-FORCE (declare (clobbers a-tem a-pgf-mode) (must-avoid intr)) (JUMP-XCT-NEXT PGF-W-1) ((A-PGF-MODE) M-MINUS-ONE) PUSHJ HERE ON PAGE FAULT OR INTERRUPT REQUEST DURING WRITE CYCLE PGF-W-I (declare (clobbers a-tem a-pgf-mode)) ( JUMP - CONDITIONAL NO - PG - FAULT INTR ) ; NO PAGE FAULT , THEN TAKE INTERRUPT ;; Interrupts on write cycles have to be sure to do a full vma-start-write on the original vma / returning , so the volatilities are correctly latched . (jump-if-page-fault pgf-w) (call intr) ((vma-start-write) vma) (check-page-write-no-interrupt) (popj) PUSHJ HERE ON PAGE FAULT WHEN DESIRE NOT TO TAKE INTERRUPT ;GUARANTEED TO RETURN WITH NO INTERRUPT, OR TO GO TO ILLOP ;BUT SEE THE COMMENTS ON THE DEFINITION OF CHECK-PAGE-READ-NO-INTERRUPT PGF-W (declare (clobbers a-tem a-pgf-mode)) ((A-PGF-MODE) A-V-NIL) SAVE DATA BEING WRITTEN ((MD) VMA) ;ADDRESS THE MAP ((a-pgf-vma) vma) ;give map time to set up. This instruction substituted for ; no-op to make code less marginal, ie, dependant on all paths in d-pgf ; getting to pgf-save. (DISPATCH-XCT-NEXT L2-MAP-STATUS-CODE D-PGF) ((M-PGF-WRITE) DPB (M-CONSTANT -1) A-FLAGS) ;IF IT RETURNS HERE, WE RESTART THE WRITE REFERENCE ((WRITE-MEMORY-DATA) A-PGF-WMD) ASSUMES WE WERE TRYING TO DO A WRITE CYCLE (POPJ-AFTER-NEXT NO-OP) (CHECK-PAGE-WRITE-RETRY) ;DIDN'T ENTIRELY SUCCEED, TRY AGAIN PGF-W-MAP-RELOAD-ONLY (declare (clobbers a-tem a-pgf-mode)) ((A-PGF-MODE) A-V-NIL) SAVE DATA BEING WRITTEN ((MD) VMA) ;ADDRESS THE MAP ((a-pgf-vma) vma) ;give map time to set up. This instruction substituted for ; no-op to make code less marginal, ie, dependant on all paths in d-pgf ; getting to pgf-save. (DISPATCH-XCT-NEXT L2-MAP-STATUS-CODE D-PGF-MAP-RELOAD-ONLY) ((M-PGF-WRITE) DPB (M-CONSTANT -1) A-FLAGS) ;IF IT RETURNS HERE, WE RESTART THE WRITE REFERENCE ((WRITE-MEMORY-DATA) A-PGF-WMD) ASSUMES WE WERE TRYING TO DO A WRITE CYCLE (POPJ-AFTER-NEXT NO-OP) (CHECK-PAGE-WRITE-MAP-RELOAD-ONLY) ;DIDN'T ENTIRELY SUCCEED, TRY AGAIN (LOCALITY D-MEM) (START-DISPATCH 3 0) ;DISPATCH ON MAP STATUS 0 LEVEL 1 OR 2 MAP NOT VALID 1 META BITS ONLY , TAKE AS MAP MISS 2 WRITE IN READ ONLY , note jump not PUSHJ 3 WRITE IN READ / WRITE FIRST 4 READ / WRITE 5 MAY BE IN PDL BUFFER , note jump . 6 POSSIBLE MAR BREAK , note jump . 7 nubus physical in pht2 (END-DISPATCH) (LOCALITY D-MEM) (START-DISPATCH 3 0) ;DISPATCH ON MAP STATUS D-PGF-MAP-RELOAD-ONLY 0 LEVEL 1 OR 2 MAP NOT VALID 1 META BITS ONLY , TAKE AS MAP MISS PGF - RDONLY ; 2 WRITE IN READ ONLY , note jump not PUSHJ PGF - RWF ; 3 WRITE IN READ / WRITE FIRST ; * * * 4 READ / WRITE PGF - PDL ; 5 MAY BE IN PDL BUFFER , note jump . PGF - MAR ; 6 POSSIBLE MAR BREAK , note jump . 7 nubus physical in pht2 (END-DISPATCH) (LOCALITY I-MEM) ;THIS DISPATCH IS FOR GETTING META BITS FROM MAP[MD] WITHOUT SWAPPING IN WHAT IT POINTS TO . SMASHES VMA . (LOCALITY D-MEM) (START-DISPATCH 3 0) D-GET-MAP-BITS 0 LEVEL 1 OR 2 MAP NOT VALID 1 GOT MAP BITS ANYWAY 2 READ ONLY 3 READ / WRITE FIRST 4 READ / WRITE 5 MAY BE IN PDL BUFFER 6 POSSIBLE MAR BREAK 7 nubus physical in pht2 (END-DISPATCH) (LOCALITY I-MEM) MAP MISS WHEN TRYING TO GET META BITS . GET FROM REGION TABLE , SET UP META - BITS - ONLY STATUS ;this runs at "page-fault" level and had better not be called by anything already ;within the page-fault handler or variables will be overstored. It can be called from ;extra-pdl-trap, which can be called from pdl-buffer-dump, but fortunately, none of that ;is within the page fault level. GET-MAP-BITS ((A-META-BITS-MAP-RELOADS) ADD M-ZERO A-META-BITS-MAP-RELOADS ALU-CARRY-IN-ONE) (CALL-XCT-NEXT PGF-SAVE-1) ;Save M-A, M-B, M-T Address of reference , also saves ;LEVEL-1-MAP-MISS also gets it out of here! Check for level 1 map miss (CALL-EQUAL M-TEM (A-CONSTANT 177) LEVEL-1-MAP-MISS) ((M-A) DPB M-ZERO Q-ALL-BUT-POINTER A-PGF-VMA) ;address of reference ;; This needs to change with new fixed area scheme. Right now fixed areas are ;; legislated to be contain homogeneous storage. (JUMP-GREATER-OR-EQUAL-XCT-NEXT ;Check for A-memory or I/O address M-A A-LOWEST-DIRECT-VIRTUAL-ADDRESS GET-MAP-BITS-1) ((MD) (A-CONSTANT (PLUS (BYTE-MASK %%REGION-OLDSPACE-META-BIT) (BYTE-MASK %%REGION-EXTRA-PDL-META-BIT) (BYTE-VALUE %%REGION-REPRESENTATION-TYPE %REGION-REPRESENTATION-TYPE-LISP)))) (CALL-XCT-NEXT XRGN1) ;Normal address, get meta bits from region ((M-A) Q-POINTER M-A (A-CONSTANT (BYTE-VALUE Q-DATA-TYPE DTP-FIX))) (CALL-EQUAL M-T A-V-NIL ILLOP) ;Region not found get-map-bits-2 ((VMA-START-READ) ADD M-T A-V-REGION-BITS) ;Fetch meta bits (ILLOP-IF-PAGE-FAULT) GET-MAP-BITS-1 ((m-a) (lisp-byte %%region-map-bits) md) ;save before gets clobbered. also right adjust ((m-lam) a-pgf-vma) (call-xct-next read-page-volatility) ((m-lam) q-page-number m-lam) ((m-tem) xor m-minus-one a-tem) ;Complement volatility. ((MD) A-PGF-VMA) ;address map ((m-a) dpb m-a MAP2C-META-BITS (A-CONSTANT (BYTE-VALUE MAP2C-STATUS-CODE %PHT-MAP-STATUS-META-BITS-ONLY))) #+lambda((l2-map-control) dpb m-tem map2c-volatility a-a) #+exp ((m-tem) dpb m-tem map2c-volatility a-a) #+exp ((vma-write-l2-map-control) dpb m-tem exp-map2c-volatility a-tem) ((#+lambda L2-MAP-PHYSICAL-PAGE #+exp vma-write-l2-map-physical-page) A-ZERO) ;CLEAR OUT TO REDUCE CONFUSION (JUMP-XCT-NEXT PGF-RESTORE) ;Restore M-A, M-B, M-T Do n't leave garbage in VMA . ;PDL BUFFER HANDLING CONVENTIONS: THE LINEAR PUSHDOWN LIST MUST ALWAYS BE COMPOSED OF PAGES FROM AN AREA WHOSE REGION - BITS Q HAS % PHT - MAP - STATUS - PDL - BUFFER IN THE MAP STATUS PORTION OF ITS % % REGION - MAP - BITS FIELD . THUS ANY MEMORY CYCLE REF'ING SUCH AN AREA WILL TRAP AND COME HERE , WHERE THE CODE CHECKS TO SEE IF IT IS REALLY IN THE PDL - BUFFER NOW . IF NOT , IT TURNS ON R / W ACCESS TEMPORARILY AND PERFORMS THE REQUESTED CYCLE , ETC . THESE PAGES ARE TREATED ENTIRELY AS NORMAL PAGES FOR SWAPPING PURPOSES , AND MAY EVEN BE SWAPPED OUT WHILE ACTUALLY RESIDENT IN THE PDL - BUFFER ! THE ONLY DIFFERENCE IS THAT THE PAGE MUST ALWAYS BE WRITTEN TO THE DISK ON SWAP - OUT , SINCE THE R - W - F MECHANISM IS NOT AVAILABLE TO KEEP TRACK OF WHETHER IT HAS MODIFIED . PDL - BUFFER - POINTER IS TAKEN TO MARK THE HIGHEST PDL - BUFFER LOCN WHICH IS REALLY VALID . PGF-PDL (JUMP-IF-BIT-SET M-PGF-WRITE PGF-W-PDL) ;READ REFERENCE TO LOCATION THAT MAY BE IN THE PDL BUFFER PGF-R-PDL (declare (local a-pdl-buffer-read-faults)) ((M-PGF-TEM) SUB PDL-BUFFER-POINTER A-PDL-BUFFER-HEAD) ((M-PGF-TEM) ADD M-PGF-TEM (A-CONSTANT 1)) ;*** THIS CODE COULD USE BUMMING *** ((M-PGF-TEM) PDL-BUFFER-ADDRESS-MASK M-PGF-TEM) ;COMPUTE # ACTIVE WDS IN PDL-BUFFER ((A-PGF-B) ADD M-PGF-TEM A-PDL-BUFFER-VIRTUAL-ADDRESS) ((M-PGF-TEM) Q-POINTER VMA) ;GET ADDRESS BEING REFERENCED SANS EXTRA BITS (JUMP-LESS-THAN M-PGF-TEM A-PDL-BUFFER-VIRTUAL-ADDRESS PGF-R-NOT-REALLY-IN-PDL-BUFFER) (JUMP-GREATER-THAN M-PGF-TEM A-PGF-B PGF-R-NOT-REALLY-IN-PDL-BUFFER) ;GREATER BECAUSE ( PP ) IS A VALID WD . ;READ REFERENCE TO LOCATION THAT IS IN THE PDL BUFFER ((A-PDL-BUFFER-READ-FAULTS) ADD A-PDL-BUFFER-READ-FAULTS M-ZERO ALU-CARRY-IN-ONE) ((M-PGF-TEM) SUB M-PGF-TEM A-PDL-BUFFER-VIRTUAL-ADDRESS) ;GET RELATIVE PDL LOC REFERENCED ((A-PGF-A) PDL-BUFFER-INDEX) ;DON'T CLOBBER PDL-BUFFER-INDEX TRUNCATES TO 10 BITS (POPJ-AFTER-NEXT (MD) C-PDL-BUFFER-INDEX) ((PDL-BUFFER-INDEX) A-PGF-A) READ REFERENCE TO LOCATION NOT IN THE PDL BUFFER , BUT IT HAVE . PGF-R-NOT-REALLY-IN-PDL-BUFFER #-LAMBDA(begin-comment) ((VMA-START-READ-FORCE) VMA) ;READ OUT THAT LOCATION (ILLOP-IF-PAGE-FAULT) ;VALID-IF-FORCE should be on for may-be-in-pdl-buffer (POPJ-AFTER-NEXT (A-PDL-BUFFER-MEMORY-FAULTS) ADD A-PDL-BUFFER-MEMORY-FAULTS M-ZERO ALU-CARRY-IN-ONE) (NO-OP) #-lambda (end-comment) #-exp(begin-comment) ;PDL-FORCE feature does not work on explorer.. so.. ((M-PGF-TEM) l2-map-control) ;SAVE CORRECT MAP CONTENTS ((vma-write-l2-map-control) IOR M-PGF-TEM ;TURN ON ACCESS (A-CONSTANT (BYTE-VALUE MAP2C-ACCESS-CODE 3))) ;R/W ;Maybe putting this insn here will avoid hardware lossage?? ((A-PDL-BUFFER-MEMORY-FAULTS) ADD A-PDL-BUFFER-MEMORY-FAULTS M-ZERO ALU-CARRY-IN-ONE) ((VMA-START-READ) MD) ;READ OUT THAT LOCATION I THOUGHT WE JUST TURNED ON ACCESS ((A-PGF-WMD) READ-MEMORY-DATA) ;SAVE CONTENTS ((MD) VMA) ;ADDRESS THE MAP (no-op) ((vma-write-l2-map-control) M-PGF-TEM) ;RESTORE THE MAP (POPJ-AFTER-NEXT ;RESTORE REGISTERS AND RETURN (VMA) MD) ((MD) A-PGF-WMD) #-exp(end-comment) ;WRITE REFERENCE TO LOCATION THAT MAY BE IN THE PDL BUFFER PGF-W-PDL (declare (local a-pdl-buffer-write-faults)) ((M-PGF-TEM) SUB PDL-BUFFER-POINTER A-PDL-BUFFER-HEAD) ((M-PGF-TEM) ADD M-PGF-TEM (A-CONSTANT 1)) ;*** THIS CODE COULD USE BUMMING *** ((M-PGF-TEM) PDL-BUFFER-ADDRESS-MASK M-PGF-TEM) ;COMPUTE # ACTIVE WDS IN PDL-BUFFER ((A-PGF-B) ADD M-PGF-TEM A-PDL-BUFFER-VIRTUAL-ADDRESS) ;HIGHEST VIRT LOC IN P.B, ((M-PGF-TEM) Q-POINTER VMA) ;GET ADDRESS BEING REFERENCED SANS EXTRA BITS (JUMP-LESS-THAN M-PGF-TEM A-PDL-BUFFER-VIRTUAL-ADDRESS PGF-W-NOT-REALLY-IN-PDL-BUFFER) (JUMP-GREATER-THAN M-PGF-TEM A-PGF-B PGF-W-NOT-REALLY-IN-PDL-BUFFER) ;GREATER BECAUSE ( PP ) IS A VALID WD ;WRITE REFERENCE TO LOCATION THAT IS IN THE PDL BUFFER ((A-PDL-BUFFER-WRITE-FAULTS) ADD A-PDL-BUFFER-WRITE-FAULTS M-ZERO ALU-CARRY-IN-ONE) ((M-PGF-TEM) SUB M-PGF-TEM A-PDL-BUFFER-VIRTUAL-ADDRESS) ;GET RELATIVE PDL LOC REFERENCED ((A-PGF-A) PDL-BUFFER-INDEX) ;DON'T CLOBBER PDL-BUFFER-INDEX TRUNCATES TO 10 BITS ((MD) A-PGF-WMD) ( POPJ - AFTER - NEXT ( C - PDL - BUFFER - INDEX ) ) ; DO THE WRITE ; ((PDL-BUFFER-INDEX) A-PGF-A) ;RESTORE REGS AND RETURN FROM FAULT ((c-pdl-buffer-index) md) ((pdl-buffer-index) a-pgf-a) #+exp ((md) a-pgf-vma) ;address the map since dropping through note that first inst does n't reference the map ;drop through WRITE REFERENCE TO LOCATION NOT IN THE PDL BUFFER , BUT IT HAVE ;** note ** volatility not maintained for PDL pages!! ;** not necessarily true: this can only be reached by ;(check-page-write) which is always followed by a gc-write-test ;in the caller. PGF-W-NOT-REALLY-IN-PDL-BUFFER (declare (local a-pdl-buffer-memory-faults)) #-lambda(begin-comment) ((WRITE-MEMORY-DATA-START-WRITE-FORCE) A-PGF-WMD) ;WRITE INTO THAT LOCATION (ILLOP-IF-PAGE-FAULT) ;VALID-IF-FORCE should be on for p.b. pages. (POPJ-AFTER-NEXT (A-PDL-BUFFER-MEMORY-FAULTS) ADD A-PDL-BUFFER-MEMORY-FAULTS M-ZERO ALU-CARRY-IN-ONE) (NO-OP) #-lambda(end-comment) #-exp(begin-comment) do n't use l2 - map on first inst here ((A-PDL-BUFFER-MEMORY-FAULTS) ADD A-PDL-BUFFER-MEMORY-FAULTS M-ZERO ALU-CARRY-IN-ONE) ((M-PGF-TEM) l2-map-control) ;SAVE CORRECT MAP CONTENTS ((vma-write-l2-map-control) IOR M-PGF-TEM ;TURN ON ACCESS (A-CONSTANT (BYTE-VALUE MAP2C-ACCESS-CODE 3))) ;R/W ((VMA) MD) ;WRITE INTO THAT LOCATION ((WRITE-MEMORY-DATA-START-WRITE) A-PGF-WMD) I THOUGHT WE JUST TURNED ON ACCESS ((MD) VMA) ;ADDRESS THE MAP (no-op) ((vma-write-l2-map-control) M-PGF-TEM) ;RESTORE THE MAP (POPJ-AFTER-NEXT ;RESTORE REGISTERS AND RETURN (VMA) MD) ((MD) A-PGF-WMD) #-exp(end-comment) pgf-r-pdl-check-immediately (call pgf-pdl-check-immediately) ((a-pdl-buffer-read-faults) add a-pdl-buffer-read-faults m-zero alu-carry-in-one) ((md) c-pdl-buffer-index) ((m-garbage) micro-stack-data-pop) ;; return address in pgf-map-miss pop return - address in pgf - r (popj-after-next (pdl-buffer-index) a-pgf-a) (no-op) ;;; Figure out how to deal with volatility here. pgf - w - pdl - check - immediately ; (call pgf-pdl-check-immediately) ; ((a-pdl-buffer-write-faults) add a-pdl-buffer-write-faults m-zero alu-carry-in-one) ( popj - after - next ( c - pdl - buffer - index ) md ) ; ((pdl-buffer-index) a-pgf-a) pgf-pdl-check-immediately ((m-pgf-tem) sub pdl-buffer-pointer a-pdl-buffer-head) ((m-pgf-tem) pdl-buffer-address-mask m-pgf-tem) ((a-pgf-b) m+a+1 m-pgf-tem a-pdl-buffer-virtual-address) ((m-pgf-tem) q-pointer vma) (jump-less-than m-pgf-tem a-pdl-buffer-virtual-address pgf-pdl-check-not-in-pdl-buffer) (jump-greater-than m-pgf-tem a-pgf-b pgf-pdl-check-not-in-pdl-buffer) ((m-pgf-tem) sub m-pgf-tem a-pdl-buffer-virtual-address) (popj-after-next (a-pgf-a) pdl-buffer-index) ((pdl-buffer-index) add m-pgf-tem a-pdl-buffer-head) pgf-pdl-check-not-in-pdl-buffer ((m-garbage) micro-stack-data-pop) (popj) SAVE REGISTERS UPON ENTERING PAGE FAULT HANDLER PGF-SAVE (declare (clobbers a-pgf-vma a-pgf-a a-pgf-b a-pgf-t) (saves (vma a-pgf-vma))) ((A-PGF-VMA) VMA) PGF-SAVE-1 (declare (clobbers a-pgf-a a-pgf-b a-pgf-t) (saves (a-a a-pgf-a) (a-b a-pgf-b) (a-t a-pgf-t))) ((A-PGF-A) M-A) (POPJ-AFTER-NEXT (A-PGF-B) M-B) ((A-PGF-T) M-T) RESTORE REGISTERS AND LEAVE PAGE FAULT HANDLER DOESN'T RESTORE VMA SINCE CYCLE RESTARTER ( POPJED TO ) WILL DO THAT PGF-RESTORE (declare (restores (a-a a-pgf-a) (a-b a-pgf-b) (a-t a-pgf-t))) ;; Tempoary map checking code ;CHECK-WIRED-LEVEL-2-MAP-CONTROL ( ( M - A ) DPB ( BYTE - FIELD 1 12 . ) M - MINUS - ONE A - ZERO ) ( JUMP - EQUAL M - A A - ZERO CHECK - WIRED - LEVEL-2 - MAP - CONTROL-2 ) ; ((M-T) MD) ; ((MD) SETZ) ;CHECK-WIRED-LEVEL-2-MAP-CONTROL-1 ; (CALL-EQUAL L2-MAP-CONTROL A-ZERO ILLOP-DEBUG) ( ( MD ) ADD ( A - CONSTANT ( EVAL PAGE - SIZE ) ) ) ; (JUMP-LESS-THAN MD A-A CHECK-WIRED-LEVEL-2-MAP-CONTROL-1) ; ((MD) M-T) ;CHECK-WIRED-LEVEL-2-MAP-CONTROL-2 ; ; end of tempoary code ((M-A) A-PGF-A) (POPJ-AFTER-NEXT (M-B) A-PGF-B) ((M-T) A-PGF-T) ;Page fault level routines call these in order to be able to take map-reload-type page ;faults recursively. Even after saving here, any recursive page fault which ;touched the disk would lose since these variables would get stored over by the ;call to DISK-PGF-SAVE at DISK-SWAP-HANDLER. DISK-PGF-SAVE (declare (saves (a-pgf-vma a-disk-save-pgf-vma) (a-pgf-wmd a-disk-save-pgf-wmd) (a-pgf-t a-disk-save-pgf-t) (a-pgf-a a-disk-save-pgf-a) (a-pgf-b a-disk-save-pgf-b) (a-pgf-mode a-disk-save-mode) (a-1 a-disk-save-1) (a-2 a-disk-save-2))) ((A-DISK-SAVE-PGF-VMA) A-PGF-VMA) ;Save page fault handler variables ((A-DISK-SAVE-PGF-WMD) A-PGF-WMD) ;in case of recursive fault ((A-DISK-SAVE-PGF-T) A-PGF-T) ((A-DISK-SAVE-PGF-A) A-PGF-A) ((A-DISK-SAVE-PGF-B) A-PGF-B) ((A-DISK-SAVE-MODE) A-PGF-MODE) (POPJ-AFTER-NEXT (A-DISK-SAVE-1) M-1) ;Clobbered by disk routine ((A-DISK-SAVE-2) M-2) ;.. DISK-PGF-RESTORE (declare (restores (a-pgf-vma a-disk-save-pgf-vma) (a-pgf-wmd a-disk-save-pgf-wmd) (a-pgf-t a-disk-save-pgf-t) (a-pgf-a a-disk-save-pgf-a) (a-pgf-b a-disk-save-pgf-b) (a-pgf-mode a-disk-save-mode) (a-1 a-disk-save-1) (a-2 a-disk-save-2))) ((M-2) A-DISK-SAVE-2) ;Restore registers ((M-1) A-DISK-SAVE-1) ((A-PGF-MODE) A-DISK-SAVE-MODE) ((A-PGF-B) A-DISK-SAVE-PGF-B) ((A-PGF-A) A-DISK-SAVE-PGF-A) ((A-PGF-T) A-DISK-SAVE-PGF-T) (POPJ-AFTER-NEXT (A-PGF-WMD) A-DISK-SAVE-PGF-WMD) ((A-PGF-VMA) A-DISK-SAVE-PGF-VMA) ;ROUTINE TO HANDLE LEVEL-1 MAP MISSES. CALLED FROM PGF-MAP-MISS AND FROM GET-MAP-BITS. ADDRESS IN MD ON CALL AND RETURN , VMA CLOBBERED . PGF - SAVE MUST HAVE CALLED . What we do here is throw away a section of the level 2 map and make the level 1 map point to it . When we go around again , we get a level 2 map miss and set it up properly . LEVEL-1-MAP-MISS (declare (clobbers a-pgf-tem) (values a-a a-t)) ((A-FIRST-LEVEL-MAP-RELOADS) ADD A-FIRST-LEVEL-MAP-RELOADS M-ZERO ALU-CARRY-IN-ONE) ((#+lambda L1-MAP #+exp vma-write-l1-map) SELECTIVE-DEPOSIT L1-MAP L1-MAP-META-BITS ;dont clobber meta bits. ALLOCATE A BLOCK OF LVL 2 MAP ((M-T) A-SECOND-LEVEL-MAP-REUSE-POINTER) ;note no meta bits. - > 1ST ENTRY IN BLOCK #-exp (begin-comment) REVERSE 1ST LVL MAP IN 1200 - 1377 ; (see uc-initialization) ((VMA-START-READ) M-PGF-TEM) (ILLOP-IF-PAGE-FAULT) #-exp (end-comment) #-lambda(begin-comment) reverse 1st level map in 2000 - 2177 of A mem ((OA-REG-HIGH) DPB M-PGF-TEM OAH-A-SRC A-ZERO) ((MD) A-GARBAGE) #-lambda(end-comment) (JUMP-LESS-THAN md A-ZERO PGF-L1C) ;DON'T WRITE MAP IF NO PREVIOUS #+exp ((m-tem) ldb (byte 12. 13.) md) #+exp (call-equal m-tem a-zero illop) ((#+lambda L1-MAP #+exp vma-write-l1-map) SELECTIVE-DEPOSIT L1-MAP L1-MAP-META-BITS AND 177 - IFY OLD 1ST LVL MAP PGF-L1C ((md) M-A) #-exp(begin-comment) ((vma-start-write) m-pgf-tem) (ILLOP-IF-PAGE-FAULT) #-exp(end-comment) #-lambda(begin-comment) ((OA-REG-LOW) DPB M-PGF-TEM OAL-A-DEST A-ZERO) ((A-GARBAGE) md) #-lambda(end-comment) DO ALL 32 . ENTRIES IN BLOCK PGF-L1A ((#+lambda L2-MAP-CONTROL #+exp vma-write-l2-map-control) (A-CONSTANT 0)) FILL 2ND - LEVEL MAP WITH MAP - MISS ( 0 ) ; (NO-OP) ((MD M-A) ADD M-A (A-CONSTANT (BYTE-VALUE VMA-PAGE-ADDR-PART 1))) (JUMP-GREATER-THAN-XCT-NEXT M-T (A-CONSTANT 1) PGF-L1A) ((M-T) SUB M-T (A-CONSTANT 1)) Do n't leave garbage in VMA . ;; Tempoary map checking code ;CHECK-PGF-L1-L2-MAP-CONTROL ( ( M - A ) DPB ( BYTE - FIELD 1 12 . ) M - MINUS - ONE A - ZERO ) ( JUMP - EQUAL M - A A - ZERO CHECK - PGF - L1 - L2 - MAP - CONTROL-2 ) ; ((MD) SETZ) ;CHECK-PGF-L1-L2-MAP-CONTROL-1 ; (CALL-EQUAL L2-MAP-CONTROL A-ZERO ILLOP-DEBUG) ( ( MD ) ADD ( A - CONSTANT ( EVAL PAGE - SIZE ) ) ) ; (JUMP-LESS-THAN MD A-A CHECK-PGF-L1-L2-MAP-CONTROL-1) ;CHECK-PGF-L1-L2-MAP-CONTROL-2 ; ; end of tempoary code RESTORE MD ( ADDRESS OF REFERENCE ) ;DROP THROUGH ADVANCE-SECOND-LEVEL-MAP-REUSE-POINTER, AND RETURN ;ROUTINE TO ADVANCE SECOND LEVEL MAP REUSE POINTER, WITH CARE. CLOBBERS Q-R ADVANCE-SECOND-LEVEL-MAP-REUSE-POINTER ((Q-R A-SECOND-LEVEL-MAP-REUSE-POINTER) ADD M-ZERO A-SECOND-LEVEL-MAP-REUSE-POINTER ALU-CARRY-IN-ONE) now use whole 2nd level map . (POPJ-AFTER-NEXT POPJ-LESS-THAN Q-R (A-CONSTANT 176)) ((A-SECOND-LEVEL-MAP-REUSE-POINTER) A-SECOND-LEVEL-MAP-REUSE-POINTER-INIT) ;WRAP AROUND TO AFTER THE WIRED ONES PGF-MAP-MISS-RELOAD-ONLY (declare (clobbers a-lam a-tem a-tem3 a-tem1) (local a-pgf-t a-pgf-a a-pgf-b)) SAVE A , B , T , VMA CHECK FOR 1ST - LEVEL MISS (CALL-EQUAL M-TEM (A-CONSTANT 177) LEVEL-1-MAP-MISS) MD HAS ADDRESS , VMA SAVED AND CLOBBERED . HANDLE 2ND - LEVEL MISS ((A-SECOND-LEVEL-MAP-RELOADS) ADD A-SECOND-LEVEL-MAP-RELOADS M-ZERO ALU-CARRY-IN-ONE) ((M-T) SELECTIVE-DEPOSIT M-ZERO Q-ALL-BUT-POINTER A-PGF-VMA) ;ADDRESS SANS EXTRA BITS (JUMP-LESS-THAN M-T A-LOWEST-DIRECT-VIRTUAL-ADDRESS PGF-L2A-RELOAD-ONLY) (JUMP PGF-MM-RELOAD-ONLY-1) MAP MISS COMES HERE . ADDRESS IN VMA AND BOTH . SET UP FIRST - LEVEL MAP IF NECESSARY . THEN DEAL WITH PAGE - FAULT . PGF-MAP-MISS Experimental . ( call pgf - r - pdl - check - immediately ) SAVE A , B , T , VMA CHECK FOR 1ST - LEVEL MISS (CALL-EQUAL M-TEM (A-CONSTANT 177) LEVEL-1-MAP-MISS) MD HAS ADDRESS , VMA SAVED AND CLOBBERED . HANDLE 2ND - LEVEL MISS ((A-SECOND-LEVEL-MAP-RELOADS) ADD A-SECOND-LEVEL-MAP-RELOADS M-ZERO ALU-CARRY-IN-ONE) ((M-T) SELECTIVE-DEPOSIT M-ZERO Q-ALL-BUT-POINTER A-PGF-VMA) ;ADDRESS SANS EXTRA BITS (JUMP-LESS-THAN M-T A-LOWEST-DIRECT-VIRTUAL-ADDRESS PGF-L2A) PGF-MM-RELOAD-ONLY-1 (JUMP-LESS-THAN M-T (A-CONSTANT LOWEST-A-MEM-VIRTUAL-ADDRESS) MAP-GREY) ;"direct mapping" cant win on LAMBDA. Someday, maybe we'll have some sort ; of main memory tables to allow various things to get mapped in. ;However, if A-LOWEST-DIRECT-VIRTUAL-ADDRESS has been moved down, ; we stick in the medium resolution color. (JUMP-LESS-THAN M-T (A-CONSTANT LOWEST-IO-SPACE-VIRTUAL-ADDRESS) PGF-SPECIAL-A-MEMORY-REFERENCE) REFERENCE TO UNIBUS OR X - BUS IO VIRTUAL ADDRESS ( on CADR ) . FAKE UP PAGE HASH TABLE ENTRY PGF-MM0 (JUMP-LESS-THAN M-T (A-CONSTANT 177100000) MAP-VIDEO-BUFFER) (JUMP-GREATER-OR-EQUAL M-T (A-CONSTANT LOWEST-UNIBUS-VIRTUAL-ADDRESS) MAP-MULTIBUS) CADR control registers . ;this page left blank so they will trap. (JUMP-GREATER-OR-EQUAL M-T (A-CONSTANT 177377000) MAP-MULTIBUS-IO) (JUMP-GREATER-OR-EQUAL M-T (A-CONSTANT 177371000) MAP-NU-MULTI-MAP-REGS) ;See below. (JUMP-GREATER-OR-EQUAL M-T (A-CONSTANT 177370400) MAP-TV-CONTROL-REGS) (JUMP-GREATER-OR-EQUAL M-T (A-CONSTANT 177370000) MAP-SDU-CONTROL-REGS) (JUMP-GREATER-OR-EQUAL M-T (A-CONSTANT 177360000) MAP-SHARED-PAGES-1) (CALL-GREATER-OR-EQUAL M-T (A-CONSTANT 177340000) ILLOP) ;Scratch block. (JUMP-GREATER-OR-EQUAL M-T (A-CONSTANT 177300000) MAP-SHARED-PAGES-2) #+lambda(jump-greater-or-equal m-t (a-constant 177277400) map-quad-video-control-regs) (CALL ILLOP) ( ( M - T ) VMA - PHYS - PAGE - ADDR - PART M - T ( A - CONSTANT ( BYTE - MASK MAP - WRITE - ENABLE - SECOND - LEVEL - WRITE ) ) ) ( ( M - A ) ( A - CONSTANT 1460 ) ) ; RW ACCESS , STATUS=4 , NO AREA TRAPS , REP TYPE 0 ( JUMP - XCT - NEXT PGF - RESTORE ) ; GO RETRY REFERENCE ( ( VMA - WRITE - MAP ) MAP - ACCESS - STATUS - AND - META - BITS A - T ) Returning to PGF - R or PGF - W , which will reload VMA with good data . MAP-MULTIBUS ;virtual address >=177,,400000. Extract bits 16 - 8 which are page number within multibus . These bits go in 8 - 0 of L2 map . Byte mask accounts for F in high 4 bits of NUBUS address . #-LAMBDA (BEGIN-COMMENT) ((M-T) LDB (BYTE-FIELD 9 8) M-T a-zero) SDU quad slot goes in bits 21 - 14 . ((L2-MAP-PHYSICAL-PAGE) DPB M-A (BYTE-FIELD 8 14.) A-T) (JUMP-XCT-NEXT PGF-RESTORE) ;GO RETRY REFERENCE ((L2-MAP-CONTROL) (A-CONSTANT 1460)) ;map2c-access-status-and-meta-bits is right adj. RW access , status 4 , no area traps . Returning to PGF - R or PGF - W , which will reload VMA with good data . #-LAMBDA (END-COMMENT) #+EXP (CALL ILLOP) (begin-comment) (end-comment) MAP-VIDEO-BUFFER #-lambda(begin-comment) ((l2-map-physical-page) LDB (BYTE-FIELD 7 8) M-T a-video-buffer-base-phys-page) ((m-a) a-processor-switches) ((m-a) ldb (lisp-byte %%processor-switch-cache-permit-for-video-buffer) m-a) (JUMP-XCT-NEXT PGF-RESTORE) ((L2-MAP-CONTROL) dpb m-a (byte-field 1 14.) (A-CONSTANT 1460)) #-lambda(end-comment) #-exp(begin-comment) ((m-t) ldb (byte-field 7 8) m-t (a-constant (eval (ash #xe80000 -10.)))) ((m-a) a-tv-quad-slot) ((vma-write-l2-map-physical-page) dpb m-a (byte-field 8 14.) a-t) (jump-xct-next pgf-restore) ((vma-write-l2-map-control) (a-constant 1460)) #-exp(end-comment) multibus io page . #-LAMBDA (BEGIN-COMMENT) ((M-A) A-SDU-quad-SLOT) ((L2-MAP-PHYSICAL-PAGE) DPB M-A (BYTE-FIELD 8 14.) (A-CONSTANT (BYTE-MASK (BYTE-FIELD 1 10.)))) (JUMP-XCT-NEXT PGF-RESTORE) packet size code 1 #-LAMBDA (END-COMMENT) #+exp(call illop) MAP-NU-MULTI-MAP-REGS #-LAMBDA (BEGIN-COMMENT) ((M-T) SUB M-T (A-CONSTANT 177371000)) ;relative adr within range ((M-T) LDB M-T (BYTE-FIELD 8 8) A-ZERO) ;relative page number within range. ((M-A) A-SDU-quad-SLOT) map regs begin at 18000(hex ) , ie 140 pages ((M-A) DPB M-A (BYTE-FIELD 8 14.) (A-CONSTANT 140)) four pages of mapping registers . ((M-T) LDB M-T (BYTE-FIELD 2 2) A-ZERO) ;high bits determine byte no to select. ((L2-MAP-PHYSICAL-PAGE) DPB M-T (BYTE-FIELD 2 22.) A-A) ;store byte code. (JUMP-XCT-NEXT PGF-RESTORE) packet size code 1 #-LAMBDA (END-COMMENT) #+EXP (CALL ILLOP) MAP-TV-CONTROL-REGS ;map a single page at base of TV slot space. #-lambda(begin-comment) ((M-A) A-TV-quad-SLOT) ((L2-MAP-PHYSICAL-PAGE) DPB M-A (BYTE-FIELD 8 14.) a-zero) (JUMP-XCT-NEXT PGF-RESTORE) ((L2-MAP-CONTROL) (A-CONSTANT 1460)) map-quad-video-control-regs ((m-a) a-video-buffer-base-phys-page) ((l2-map-physical-page) add m-a (a-constant (eval (ash #x80000 -10.)))) (jump-xct-next pgf-restore) ((l2-map-control) (a-constant 1460)) #-lambda(end-comment) #+exp (call illop) one page , mapped to low byte of # xff01c000 in the SDU ( ash # x1c000 -10 . ) = > page 160 on the SDU MAP-sdu-control-regs #-LAMBDA (BEGIN-COMMENT) ((m-a) a-sdu-quad-slot) ((l2-map-physical-page) dpb m-a (byte-field 8 14.) (a-constant 160)) (jump-xct-next pgf-restore) packet size code 1 = byte mode #-LAMBDA (END-COMMENT) #+EXP (CALL ILLOP) map the 32 . page segment map-shared-pages-1 #-lambda(begin-comment) ((m-t) sub m-t (a-constant 177360000)) ;relative adr within range ((m-t) ldb m-t (byte-field 8 8) a-zero) ;relative page number within range ((M-TEM) a-sys-conf-base-phys-page) ((M-TEM) add M-TEM (a-constant 64.)) ((l2-map-physical-page) add M-TEM a-t) (jump-xct-next pgf-restore) ((l2-map-control) (a-constant 1460)) #-lambda(end-comment) #+exp (call illop) this is the 64 . page segment map-shared-pages-2 #-lambda (begin-comment) ((m-t) sub m-t (a-constant 177300000)) ;relative adr within range ((m-t) ldb m-t (byte-field 8 8) a-zero) ;relative page number within range ((M-TEM) a-sys-conf-base-phys-page) ((l2-map-physical-page) add M-TEM a-t) (jump-xct-next pgf-restore) ((l2-map-control) (a-constant 1460)) #-lambda(end-comment) #+exp (call illop) map-grey ;; ACTUALLY GUYS, STEVE WARD AT MIT WANTS TO USE OUR COLOR BOARD ON THE EXPLORER. # + exp ( call illop ) ;;#-lambda (begin-comment) (call-less-than m-t (a-constant 176300000) illop) ;below anything reasonable ((m-a) a-grey-quad-slot) (jump-less-than m-t (a-constant 176500000) map-grey-pixel) (jump-less-than m-t (a-constant 176700000) map-grey-plane) ;fall thru in case of color-map, registers, and prom. ((m-t) sub m-t (a-constant 176700000)) ((m-t) ldb m-t (byte-field 5 8) (a-constant 37740)) ;base page number within slot space map-grey-x ((#+LAMBDA l2-map-physical-page #+EXPLORER vma-write-l2-map-physical-page) dpb m-a (byte-field 8 14.) a-t) (jump-xct-next pgf-restore) ((#+LAMBDA l2-map-control #+EXPLORER vma-write-l2-map-control) (a-constant 1460)) map-grey-pixel ((m-t) sub m-t (a-constant 176300000)) (jump-xct-next map-grey-x) to page 0 in slot space . map-grey-plane ((m-t) sub m-t (a-constant 176500000)) ((m-t) ldb m-t (byte-field 8 8) a-zero) (jump-xct-next map-grey-x) ((m-t) add m-t (a-constant 2000)) ;page number within slot space ;;#-lambda (end-comment) ;REFERENCE TO ORDINARY VIRTUAL ADDRESS. LOOK IN PAGE HASH TABLE PGF-L2A (CALL SEARCH-PAGE-HASH-TABLE) FOUND , CHK SW STS PGF-L2A-RELOAD-ONLY (declare (clobbers a-t a-tem a-tem3 a-tem1 a-lam)) (CALL SEARCH-PAGE-HASH-TABLE) FOUND , CHK SW STS (LOCALITY D-MEM) (START-DISPATCH 3 INHIBIT-XCT-NEXT-BIT) ;DISPATCH ON SWAP STATUS D-PGF-PHT 0 PHT ENTRY INVALID , GET PAGE FROM DISK 1 NORMAL , RELOAD PAGE MAP 2 FLUSHABLE , CHANGE BACK TO NORMAL 3 PREPAGED , CHANGE TO NORMAL , WE WANT IT NOW 4 AGE , CHANGE BACK TO NORMAL 5 WIRED DOWN , RELOAD PAGE MAP 6 NOT USED 7 NOT USED (END-DISPATCH) (LOCALITY D-MEM) (START-DISPATCH 3 INHIBIT-XCT-NEXT-BIT) ;DISPATCH ON SWAP STATUS D-PGF-PHT-RELOAD-ONLY 0 PHT ENTRY INVALID , GET PAGE FROM DISK 1 NORMAL , RELOAD PAGE MAP 2 FLUSHABLE , CHANGE BACK TO NORMAL 3 PREPAGED , CHANGE TO NORMAL , WE WANT IT NOW 4 AGE , CHANGE BACK TO NORMAL 5 WIRED DOWN , RELOAD PAGE MAP 6 NOT USED 7 NOT USED (END-DISPATCH) jumps to pgf - mar-{read , write}-trap , or drops through 0 READ , MAR DISABLED 1 READ , READ - TRAP 2 READ , WRITE - TRAP 3 READ , READ - WRITE - TRAP 4 WRITE , MAR DISABLED 5 WRITE , READ - TRAP 6 WRITE , WRITE - TRAP 7 WRITE , READ - WRITE - TRAP (END-DISPATCH) (LOCALITY I-MEM) ;Here on reference to page containing the MAR'ed location. The VMA is still valid , the MD has been clobbered to the VMA but if writing is saved in A - PGF - WMD , and M - PGF - WRITE says type of cycle . If this traps , VMA and M - PGF - WRITE will still be valid as saved by SGLV . ;In the case of a write, the data to be written will be on the stack. A read can be recovered just by returning from PGF - R , since the MAR is inhibited during stack - group switching . ;A write is continued by simulation in the error handler, followed ;by same continuation as a read. PGF-MAR ((M-PGF-TEM) M-FLAGS-NO-SEQUENCE-BREAK) ;If can't take trap now then do n't take one ((M-PGF-TEM) Q-POINTER VMA (A-CONSTANT (BYTE-VALUE Q-DATA-TYPE DTP-FIX))) (JUMP-LESS-THAN M-PGF-TEM A-MAR-LOW PGF-MAR1) ;Check address bounds (JUMP-GREATER-THAN M-PGF-TEM A-MAR-HIGH PGF-MAR1) Take MAR break if necessary PGF-MAR1 ;False alarm, simulate the memory cycle, ;but it might be in the PDL buffer, so simulate that trap. ;Anyway that code is pretty experienced at simulating memory cycles. (JUMP-IF-BIT-CLEAR M-PGF-WRITE PGF-R-PDL) (JUMP PGF-W-PDL) * * * following two should probably be pushing DTP - LOCATIVEs most of the time pgf-mar-read-trap ((pdl-push) dpb vma q-pointer (a-constant (byte-value q-data-type dtp-fix))) ((pdl-push) ldb q-data-type vma (a-constant (byte-value q-data-type dtp-fix))) (call trap) (ERROR-TABLE MAR-BREAK READ) to continue , the debugger should pop two , then exit without calling ;sg-proceed-micro-pc which will make PGF-R return. pgf-mar-write-trap ((pdl-push) dpb vma q-pointer (a-constant (byte-value q-data-type dtp-fix))) ((pdl-push) ldb q-data-type vma (a-constant (byte-value q-data-type dtp-fix))) ((m-tem) a-pgf-wmd) ((PDL-PUSH) DPB m-tem Q-POINTER (A-CONSTANT (BYTE-VALUE Q-DATA-TYPE DTP-FIX))) ((PDL-PUSH) LDB Q-DATA-TYPE m-tem (A-CONSTANT (BYTE-VALUE Q-DATA-TYPE DTP-FIX))) (call trap) (ERROR-TABLE MAR-BREAK WRITE) to continue , optionally do the write in macrocode , pop 4 , then exit without calling ;sg-proceed-micro-pc, which will make PGF-W return ;HERE ON REFERENCE TO LOCATION MAPPED INTO A/M SCRATCHPAD, ADDRESS IN M-T PGF-SPECIAL-A-MEMORY-REFERENCE JUMP IF CYCLE IS A WRITE ((M-GARBAGE) MICRO-STACK-DATA-POP) ;FLUSH RETRY-CYCLE RETURN ((OA-REG-HIGH) DPB M-T OAH-A-SRC-10-BITS A-ZERO) ;NOTE LOWEST-A-MEM-VIRTUAL-ADDRESS MUST BE 0 MODULO A - MEMORY SIZE (JUMP-XCT-NEXT PGF-RESTORE) ((VMA) A-PGF-VMA) ;NOBODY ELSE WILL PUT BACK VMA PGF-SA-W ((M-A) A-V-TRUE) (JUMP-NOT-EQUAL M-A A-PGF-MODE PGF-SA-W-NOT-BINDING) ; ((M-A) A-V-NIL) ( JUMP - EQUAL M - A A - AMEM - EVCP - VECTOR PGF - SA - W - NOT - BINDING ) ; ; Get a - mem address being bound . In range for EVCP hacking ? ( ( VMA ) ( BYTE - FIELD 22 . 10 . ) A - PGF - VMA ) ; Get low 10 bits ; (JUMP-GREATER-OR-EQUAL VMA (A-CONSTANT (A-MEM-LOC A-END-Q-POINTERS)) PGF - SA - W - NOT - BINDING ) ; ; We are binding or unbinding and must hack the EVCP vector . ; ; " restore " all info saved by PGF - W to its real home ; ;; or else save it on the stack ; ;; so we can be in a position to take recursive page faults. ; ;; Note: A-PGF-WMD can be untyped data, but since we ; ;; do not allow sequence breaks herein, that can't cause trouble. ; ;; Also, since this happens only from binding or unbinding, ; ;; we need not fear that PDL-BUFFER-POINTER doesn't really ; ;; point at the top of the stack. ; (CALL PGF-RESTORE) ; ((C-PDL-BUFFER-POINTER-PUSH) A-PGF-WMD) ; ((C-PDL-BUFFER-POINTER-PUSH) A-PGF-VMA) ; ;Now we can take page faults again! ; Get the current EVCP out of the EVCP vector . ( ( VMA - START - READ ) M+A+1 A - AMEM - EVCP - VECTOR VMA ) ; (CHECK-PAGE-READ) ; (DISPATCH TRANSPORT-NO-EVCP READ-MEMORY-DATA) ( ( ) Q - TYPED - POINTER MD ) ( JUMP - EQUAL MD A - V - NIL PGF - SA - BIND - NO - EVCP ) ; Write current contents of a - mem location into the EVCP , if any . ( ( VMA ) ) ( ( M - TEM ) ( BYTE - FIELD 10 . 0 ) C - PDL - BUFFER - POINTER ) ( ( OA - REG - HIGH ) A - ZERO ) ; NOTE LOWEST - A - MEM - VIRTUAL - ADDRESS ( ( MD - START - WRITE ) A - GARBAGE ) ; MUST BE 0 MODULO A - MEMORY SIZE ; (CHECK-PAGE-WRITE) ; (GC-WRITE-TEST) PGF - SA - BIND - NO - EVCP ; Replace the current EVCP with the old one , or NIL if not an EVCP . ( ( VMA ) C - PDL - BUFFER - POINTER - POP ) ; ((MD) C-PDL-BUFFER-POINTER) ( ( C - PDL - BUFFER - POINTER - PUSH ) VMA ) ; ((M-TEM) Q-DATA-TYPE MD) ( JUMP - EQUAL M - TEM ( A - CONSTANT ( EVAL DTP - EXTERNAL - VALUE - CELL - POINTER ) ) ; PGF-SA-BIND-NEW-EVCP) ( ( ) A - V - NIL ) PGF - SA - BIND - NEW - EVCP ( ( VMA ) ( BYTE - FIELD 10 . 0 ) VMA ) ( ( VMA - START - WRITE ) M+A+1 A - AMEM - EVCP - VECTOR VMA ) ; (CHECK-PAGE-WRITE) ( JUMP - EQUAL MD A - V - NIL PGF - SA - BIND - NO - NEW - EVCP ) If thing to be stored is an EVCP , store the contents of where it points . ((M-TEM) A-PGF-WMD) ; ((M-TEM) Q-DATA-TYPE M-TEM) ( JUMP - NOT - EQUAL M - TEM ( A - CONSTANT ( EVAL DTP - EXTERNAL - VALUE - CELL - POINTER ) ) PGF - SA - W - NOT - BINDING ) an attempt to store an EVCP in A - MEM must be part of an attempt to closure bind A - MEM , ; which cant work anyway. Furthermore, the call to the transporter below could lose ; due to numerous reasons. (call-data-type-equal m-tem (A-CONSTANT (BYTE-VALUE Q-DATA-TYPE DTP-EXTERNAL-VALUE-CELL-POINTER)) illop) ( JUMP - DATA - TYPE - NOT - EQUAL M - TEM ( A - CONSTANT ( BYTE - VALUE Q - DATA - TYPE DTP - EXTERNAL - VALUE - CELL - POINTER ) ) PGF - SA - W - NOT - BINDING ) ; (CALL PGF-RESTORE) ; ((C-PDL-BUFFER-POINTER-PUSH) A-PGF-VMA) ; ;Now safe to take page faults recursively. ; Get contents of the new EVCP , and put that in a mem instead of the EVCP . ( ( VMA - START - READ ) A - PGF - WMD ) ; (CHECK-PAGE-READ) ; (DISPATCH TRANSPORT-NO-EVCP) ; (CALL-XCT-NEXT PGF-SAVE) ( ( A - PGF - WMD ) MD ) ;; (CALL-XCT-NEXT PGF-SA-W-NOT-BINDING) ; ((A-PGF-VMA) C-PDL-BUFFER-POINTER-POP) ; ;Now we are inside a page fault again! ; Finish writing new contents into A memory . ;; ((MD) C-PDL-BUFFER-POINTER-POP) ( POPJ ) ;; PGF - SA - BIND - NO - NEW - EVCP ;; ((A-PGF-VMA) C-PDL-BUFFER-POINTER-POP) ;; ((A-PGF-WMD) C-PDL-BUFFER-POINTER-POP) ;; (CALL PGF-SAVE-1) PGF-SA-W-NOT-BINDING ((M-T) DPB M-ZERO (BYTE-FIELD 22. 10.) A-PGF-VMA) (JUMP-LESS-THAN M-T (A-CONSTANT 100) PGF-SM-W) ;LOCN REALLY IN M-MEM. ((OA-REG-LOW) DPB M-T OAL-A-DEST-10-BITS A-ZERO) ((A-GARBAGE) A-PGF-WMD) ((MD) A-PGF-WMD) (JUMP-XCT-NEXT PGF-RESTORE) ((VMA) A-PGF-VMA) ;NOBODY ELSE WILL PUT BACK VMA PGF-SM-W((OA-REG-LOW) DPB M-T OAL-M-DEST A-ZERO) ((M-GARBAGE MD) A-PGF-WMD) (JUMP-XCT-NEXT PGF-RESTORE) ((VMA) A-PGF-VMA) ;NOBODY ELSE WILL PUT BACK VMA ;Write in read-only. dispatch to here is a JUMP , not a PUSHJ . ;; Should not get here on a read. (CALL-IF-BIT-CLEAR M-PGF-WRITE ILLOP) ;; If this is a CHECK-PAGE-WRITE-FORCE, do it anyway. (JUMP-EQUAL A-PGF-MODE M-MINUS-ONE FORCE-WR-RDONLY) ((M-TEM) DPB M-ZERO Q-ALL-BUT-TYPED-POINTER A-INHIBIT-READ-ONLY) (CALL-EQUAL M-TEM A-V-NIL TRAP) (ERROR-TABLE WRITE-IN-READ-ONLY VMA) ;Not continuable! drop into FORCE - WR - RDONLY ;Forced write in nominally read-only area. Second - level map is set - up and grants read - only access . FORCE-WR-RDONLY (CALL PGF-SAVE) ;Find PHT entry to mark page as modified (CALL-XCT-NEXT SEARCH-PAGE-HASH-TABLE) ((VMA M-T) A-PGF-VMA) (CALL-IF-BIT-CLEAR PHT1-VALID-BIT READ-MEMORY-DATA ILLOP) ;not found? ((WRITE-MEMORY-DATA-START-WRITE) IOR READ-MEMORY-DATA (A-CONSTANT (BYTE-MASK PHT1-MODIFIED-BIT))) (ILLOP-IF-PAGE-FAULT) ((md) md) ;wait for cycle to finish ((#+lambda l2-map-control #+exp vma-write-l2-map-control m-tem) ior l2-map-control ;Force read/write access (A-CONSTANT (BYTE-VALUE MAP2C-ACCESS-CODE 3))) Note : this has to be careful to do a write cycle on the original VMA / MD , ;; then reset the maps to read-only and return without starting another ;; write cycle. Restore original VMA ((MD-START-WRITE) A-PGF-WMD) ;Do the write (ILLOP-IF-PAGE-FAULT) ((MD) VMA) ;Address map again ((vma) (a-constant 2)) ;map access code rd-only ;Set read-only access again ((#+lambda l2-map-control #+exp vma-write-l2-map-control) dpb vma map2c-access-code a-tem) (CALL PGF-RESTORE) (POPJ-AFTER-NEXT ;Memory cycle completed, return (VMA) A-PGF-VMA) ((MD) A-PGF-WMD) HERE FOR READ - WRITE - FIRST TRAP ;FIND PAGE HASH TABLE ENTRY, CHANGE STATUS TO READ/WRITE, AND RELOAD MAP PGF-RWF (CALL-IF-BIT-CLEAR M-PGF-WRITE ILLOP) (CALL PGF-SAVE) (CALL-XCT-NEXT SEARCH-PAGE-HASH-TABLE) ((M-T) A-PGF-VMA) (CALL-IF-BIT-CLEAR PHT1-VALID-BIT READ-MEMORY-DATA ILLOP) ;NOT IN PHT?? ((WRITE-MEMORY-DATA-START-WRITE) ;MARK PAGE MODIFIED IOR READ-MEMORY-DATA (A-CONSTANT (BYTE-MASK PHT1-MODIFIED-BIT))) (ILLOP-IF-PAGE-FAULT) GET SECOND WORD TABLE SUPPOSED TO BE WIRED (declare (restores (a-a a-pgf-a))) ((M-A) A-PGF-A) ;RESTORE A REG DURING MEM CYCLE ((M-LAM) (A-CONSTANT 4)) ;NORMAL STATUS ((M-B) READ-MEMORY-DATA) ((WRITE-MEMORY-DATA-START-WRITE M-LAM) DPB M-LAM PHT2-MAP-STATUS-CODE A-B) (ILLOP-IF-PAGE-FAULT) (declare (restores (a-b a-pgf-b))) ((M-B) A-PGF-B) ((MD) A-PGF-VMA) ;ADDRESS THE MAP (no xct-next to allow map to set up) PHT2 SAME AS TO 2ND LVL MAP ( ON CADR ) (POPJ-AFTER-NEXT NO-OP) (declare (restores (a-t a-pgf-t))) GO RETRY MEMORY CYCLE ( used to reload VMA randomly , as well ) ;REFERENCE TO PAGE THAT WAS PREPAGED AND HASN'T BEEN TOUCHED YET. GRAB IT. PGF-PRE (declare (clobbers a-tem a-lam)) ((A-DISK-PREPAGE-USED-COUNT) M+A+1 M-ZERO A-DISK-PREPAGE-USED-COUNT) ;REFERENCE TO PAGE MARKED FLUSHABLE. WE WANT THIS PAGE AFTER ALL, CHANGE BACK TO NORMAL PGF-FL ;drop through REFERENCE TO PAGE WITH AGE TRAP . CHANGE BACK TO NORMAL TO INDICATE PAGE HAS , AND SHOULDN'T BE SWAPPED OUT OR MADE FLUSHABLE . PGF-AG (declare (clobbers a-tem a-lam)) ((WRITE-MEMORY-DATA-START-WRITE) SELECTIVE-DEPOSIT READ-MEMORY-DATA SW STS : = NORMAL (ILLOP-IF-PAGE-FAULT) ;THEN DROP THROUGH ;RELOAD HARDWARE MAP FROM PAGE HASH TABLE PGF-RL (declare (clobbers a-tem a-lam)) ((MD) A-PGF-VMA) ;ADDRESS THE MAP (NO-OP) ;allow time. ((M-T) L1-MAP-L2-BLOCK-SELECT L1-MAP) (CALL-EQUAL M-T (A-CONSTANT 177) ILLOP) ;ABOUT TO CLOBBER ((VMA-START-READ) ADD VMA (A-CONSTANT 1)) ;GET SECOND WORD OF PHT ENTRY TABLE SUPPOSED TO BE WIRED (declare (restores (a-a a-pgf-a) (a-b a-pgf-b))) ((M-A) A-PGF-A) ;RESTORE REGS DURING MEM CYCLE ((M-B) A-PGF-B) (DISPATCH PHT2-MAP-STATUS-CODE READ-MEMORY-DATA D-SWAPAR) ;VERIFY THE BITS ;; This will go to ILLOP if this is a page of a free region COMES DIRECTLY FROM PHT2 ( on cadr ) ((MD) A-PGF-VMA) ;address map (no xct-next to allow map time) (CALL LOAD-L2-MAP-FROM-CADR-PHYSICAL) (POPJ-AFTER-NEXT NO-OP) (declare (restores (a-t a-pgf-t))) ((VMA M-T) A-PGF-T) ;ROUTINE TO LOOK FOR PAGE ADDRESSED BY M-T IN THE PAGE HASH TABLE ;RETURNS WITH VMA AND READ-MEMORY-DATA POINTING TO PHT1 WORD, OR VMA POINTING TO FIRST HOLE IN HASH TABLE AND PHT1 - VALID - BIT ;OF READ-MEMORY-DATA ZERO. IN THIS CASE, THE SWAP STATUS FIELD ;OF READ-MEMORY-DATA WILL ALSO BE ZERO. CLOBBERS M-A, M-B, M-T, A-TEM1, A-TEM3 ;;; a-tem3  virtual-page-number (m-t) This version is 7 cycles per iteration , as compared with 10 cycles for the ;;; old version below. search-page-hash-table (declare (args a-t) (values a-tem3 a-t) (clobbers a-tem a-tem1)) (call-xct-next compute-page-hash) ;M-T := hash (M-T) ((m-tem3) pht1-virtual-page-number m-t) ;Save for comparison below. spht1 ((vma-start-read) add a-v-page-table-area m-t) ;Get PHT1 entry. (illop-if-page-fault) ;Supposed to be wired. ((m-t) add m-t (a-constant 2)) ;Bump index for next iteration. (call-greater-or-equal m-t a-pht-index-limit pht-wraparound) ((m-tem) pht1-virtual-page-number md) ;Compare page numbers. We usually do n't win first time . Page not in PHT . (popj) XCPH (MISC-INST-ENTRY %COMPUTE-PAGE-HASH) (CALL-XCT-NEXT COMPUTE-PAGE-HASH) ((M-T) Q-POINTER C-PDL-BUFFER-POINTER-POP) (POPJ-AFTER-NEXT (M-T) Q-POINTER M-T (A-CONSTANT (BYTE-VALUE Q-DATA-TYPE DTP-FIX))) Execute one more instruction , clobbering A - TEM1 . ;;; I suspected that the old hash function (below) was not performing so well because physical memory sizes have increased by a factor of 4 - 8 times ;;; since it was written. I made some measurements of typical collision rates, ;;; and discovered that the simple "XOR the low bits with the high bits" outperforms ;;; more intricate functions by a significant amount. This function produces about 25 % fewer collisions than the old one . KHS 851222 . ;;; Foo. Somewhere in the system someone depends on some property of the old ;;; hash algorithm. I'm going to wimp out and revert it. ;compute-page-hash ; ; 15 bits assures reasonable hashing for up to 4 megawords of memory . ( ( m - tem1 ) ( byte 15 . 10 . ) m - t ) ; High 15 bits of page number . ( ( m - t ) a - tem1 ) ; ((m-t) and m-t a-pht-index-mask) ;pht-wraparound ( popj - after - next popj - less - than m - t a - pht - index - limit ) ; ((m-t) sub m-t a-pht-index-limit) ;Wrap around New algorithm , 3 - DEC-80 (declare (args a-t) (values a-t) (clobbers a-tem1)) VMA<23:14 > ((M-T) (BYTE-FIELD (DIFFERENCE Q-POINTER-WIDTH 4) 4) M-T) ;VMA<23:8>x16+C ((M-T) ANDCA M-T (A-CONSTANT 17)) ;-C ((M-T) XOR M-T A-TEM1) ((M-T) AND M-T A-PHT-INDEX-MASK) pht-wraparound (declare (args a-t) (values a-t)) (POPJ-AFTER-NEXT POPJ-LESS-THAN M-T A-PHT-INDEX-LIMIT) ((M-T) SUB M-T A-PHT-INDEX-LIMIT) ;Wrap around ;SEARCH-PAGE-HASH-TABLE ( ( M - TEM3 ) M - T ) ; SAVE FOR COMPARISON BELOW ; (CALL COMPUTE-PAGE-HASH) ;M-T := HASH (M-T) SPHT1 ( ( VMA - START - READ ) ADD A - V - PAGE - TABLE - AREA M - T ) ; GET PHT ENTRY ( ILLOP - IF - PAGE - FAULT ) ; SUPPOSED TO BE WIRED ( ( M - T ) ADD M - T ( A - CONSTANT 2 ) ) ; BUMP INDEX FOR NEXT ; (JUMP-LESS-THAN M-T A-PHT-INDEX-LIMIT SPHT2) ; ((M-T) SUB M-T A-PHT-INDEX-LIMIT) ;WRAP AROUND SPHT2 ( POPJ - IF - BIT - CLEAR PHT1 - VALID - BIT READ - MEMORY - DATA ) ; PAGE NOT IN PHT ; ((M-tem) XOR A-TEM3 READ-MEMORY-DATA) ;XOR VIRTUAL ADDRESSES ; (POPJ-AFTER-NEXT ;(HOPING WE'LL WIN AND RETURN) ( M - B ) PHT1 - VIRTUAL - PAGE - NUMBER M - tem ) ; ZERO IF MATCH ; (CALL-NOT-EQUAL M-B A-ZERO SPHT1) ;IF NOT FOUND, TRY NEXT ;COMES HERE WHEN A PAGE NEEDS TO BE READ IN FROM DISK. ; FIRST , FIND SOME MEMORY . ENTER A LOOP THAT SEARCHES PHYSICAL - PAGE - DATA , ;STARTING FROM LAST PLACE STOPPED, FOR A FLUSHABLE PAGE. IF NONE ;FOUND, SEARCH INSTEAD FOR ANY NON WIRED PAGE. (THE EMERGENCY CASE.) ; HAVING FOUND A PAGE TO REPLACE , WRITE IT TO THE DISK IF NECESSARY . THEN DELETE ;THAT ENTRY FROM THE PAGE HASH TABLE (HARD), AND FROM THE HARDWARE MAP (EASY). ; PERFORM THE DISK READ INTO THE CORE PAGE THUS MADE FREE . ; ;USE A PIPELINED LOOP TO SEARCH THE REGION TABLES AT MEMORY SPEED TO FIND THE REGION CONTAINING THE PAGE BEING REFERENCED , AND GET THE META BITS . ; ;NOW RE-HASH THE ADDRESS ORIGINALLY BEING REFERENCED TO FIND THE FIRST HOLE ( MAY HAVE MOVED DUE TO DELETION ) AND PUT IN AN ENTRY FOR THAT PAGE . RESTART THE REFERENCE ( SET UP THE MAP FIRST ? ) SWAPIN (declare (local a-disk-page-read-count a-disk-page-write-count a-disk-error-count a-disk-fresh-page-count a-disk-swapin-virtual-address a-disk-swap-in-ccw-pointer a-disk-swapin-size a-disk-read-compare-rewrites a-disk-ecc-count a-disk-read-compare-rereads a-disk-page-read-op-count a-disk-page-write-op-count a-disk-page-write-wait-count a-disk-page-write-busy-count a-disk-page-write-appends a-disk-page-read-appends)) (CALL-IF-BIT-SET M-INTERRUPT-FLAG ILLOP) ;Uh uh, no paging from interrupts decide how many pages to bring in with one disk op . Must not bring in again a page ;already in. Must not cross region boundaries. (There is no reason to believe we ;will need pages from another region and complications arise in making the pages known.) ((A-DISK-SWAPIN-VIRTUAL-ADDRESS) DPB M-ZERO Q-ALL-BUT-POINTER A-PGF-VMA) ((A-DISK-SWAP-IN-CCW-POINTER) (A-CONSTANT DISK-SWAP-IN-CCW-BASE)) ((A-DISK-SWAPIN-SIZE) (A-CONSTANT 1)) (JUMP-IF-BIT-SET M-DONT-SWAP-IN SWAPIN-SIZE-X) ;going to create 0 core, no disk op. ((M-TEM) A-DISK-SWITCHES) (JUMP-IF-BIT-CLEAR (BYTE-FIELD 1 3) M-TEM SWAPIN-SIZE-X) ;multi-swapin not enabled ((C-PDL-BUFFER-POINTER-PUSH) A-DISK-SWAPIN-VIRTUAL-ADDRESS) = > region number in M - T .. no XCT - NEXT . (CALL-EQUAL M-T A-V-NIL ILLOP) ;Swapping in a page not in a region ((A-DISK-SAVE-PGF-T) M-T) ((VMA-START-READ) ADD M-T A-V-REGION-BITS) (ILLOP-IF-PAGE-FAULT) ((A-DISK-SAVE-PGF-A) A-DISK-SWAPIN-VIRTUAL-ADDRESS) ((A-DISK-SAVE-1) (LISP-BYTE %%REGION-SWAPIN-QUANTUM) READ-MEMORY-DATA) SWAPIN-SIZE-LOOP (JUMP-GREATER-OR-EQUAL M-ZERO A-DISK-SAVE-1 SWAPIN-SIZE-X) ((M-A) (A-CONSTANT (EVAL PAGE-SIZE))) ((A-DISK-SAVE-PGF-A) ADD M-A A-DISK-SAVE-PGF-A) ((C-PDL-BUFFER-POINTER-PUSH) A-DISK-SAVE-PGF-A) (CALL XRGN) (JUMP-NOT-EQUAL M-T A-DISK-SAVE-PGF-T SWAPIN-SIZE-X) ;not same region (CALL-XCT-NEXT SEARCH-PAGE-HASH-TABLE) ((M-T) A-DISK-SAVE-PGF-A) (JUMP-IF-BIT-SET PHT1-VALID-BIT READ-MEMORY-DATA SWAPIN-SIZE-X) ;page in core. (jump-if-bit-set m-transport-flag swapin-append-page) (jump-if-bit-clear m-scavenge-flag swapin-append-page) ;; In scavenger -- stop appending if we don't need to look at this page. ((m-lam) a-disk-save-pgf-a) (call-xct-next read-page-volatility) ((m-lam) q-page-number m-lam) (jump-less-than m-tem a-scavenge-volatility swapin-size-x) swapin-append-page ;append to transfer ((A-DISK-PAGE-READ-APPENDS) M+A+1 M-ZERO A-DISK-PAGE-READ-APPENDS) ((A-DISK-SWAPIN-SIZE) M+A+1 M-ZERO A-DISK-SWAPIN-SIZE) (JUMP-XCT-NEXT SWAPIN-SIZE-LOOP) ((A-DISK-SAVE-1) ADD (M-CONSTANT -1) A-DISK-SAVE-1) SWAPIN-SIZE-X #+exp (jump swapin0-a) #-lambda(begin-comment) ((M-TEM) A-PROCESSOR-SWITCHES) JUMP ON NO FAST CACHE ((M-TEM3) A-DISK-SWAPIN-VIRTUAL-ADDRESS) LOW 4 BITS OF VIRTUAL PAGE NUMBER . (CALL LOAD-SCAN-FOR-HEXADEC) (CALL XFIND-HEXA0) (CALL STORE-SCAN-FOR-HEXADEC) (JUMP SWAPIN1) #-lambda(end-comment) SWAPIN-LOOP #+exp (jump swapin0-a) #-lambda(begin-comment) JUMP ON NO FAST CACHE ((M-TEM3) ADD M-TEM3 (A-CONSTANT 1)) ((M-TEM3) LDB M-TEM3 (BYTE-FIELD 4 0)) ;Next page into next hexadec (CALL LOAD-SCAN-FOR-HEXADEC) (CALL XFIND-HEXA0) (CALL STORE-SCAN-FOR-HEXADEC) (JUMP SWAPIN1) #-lambda(end-comment) XFINDCORE-HEXADEC (MISC-INST-ENTRY %FINDCORE-HEXADEC) #-exp(begin-comment) ((m-garbage) pdl-pop) (jump xfindcore) #-exp(end-comment) #-lambda(begin-comment) Find memory with specified low 4 bits of physical page number . ((M-TEM3) Q-POINTER C-PDL-BUFFER-POINTER-POP) (call load-scan-for-hexadec) (call XFIND-HEXA0) (call store-scan-for-hexadec) #-lambda(end-comment) return-m-b-as-fixnum (popj-after-next (m-t) dpb m-b q-pointer (a-constant (byte-value q-data-type dtp-fix))) (no-op) XFINDCORE (MISC-INST-ENTRY %FINDCORE) ((MICRO-STACK-DATA-PUSH) (A-CONSTANT (I-MEM-LOC RETURN-M-B-as-fixnum))) SWAPIN0 ((M-TEM3) SETO) ;Desired hexadec of memory page, or -1 if dont care. XFIND-HEXA0 ((M-B) A-FINDCORE-SCAN-POINTER) ;last page frame to returned FINDCORE0 ((m-b) add m-b (a-constant 1)) (CALL-GREATER-OR-EQUAL M-B A-V-PHYSICAL-PAGE-DATA-VALID-LENGTH FINDCORE2) ((VMA-START-READ) ADD M-B A-V-PHYSICAL-PAGE-DATA) (ILLOP-IF-PAGE-FAULT) ;Delayed for fencepost error Did all pages but 1 , no luck (JUMP-NOT-EQUAL M-TEM3 (A-CONSTANT -1) FINDCORE-IN-HEXADEC) Added I - LONG to this ldb , since it seems to lose occasionally . KHS 840912 #+LAMBDA((M-TEM) (BYTE-FIELD 20 0) READ-MEMORY-DATA I-LONG) ;PHT entry index #+EXP ((M-TEM) (BYTE-FIELD 20 0) READ-MEMORY-DATA) (JUMP-EQUAL-XCT-NEXT M-TEM (A-CONSTANT 177777) FINDCORE0) ;No page here ((A-COUNT-FINDCORE-STEPS) M+A+1 M-ZERO A-COUNT-FINDCORE-STEPS) ((VMA-START-READ M-T) ADD M-TEM A-V-PAGE-TABLE-AREA) (illop-if-page-fault) (DISPATCH PHT1-SWAP-STATUS-CODE READ-MEMORY-DATA D-FINDCORE) (CALL-GREATER-OR-EQUAL M-B A-V-PHYSICAL-PAGE-DATA-VALID-LENGTH FINDCORE2) Reached end of memory . Wrap around to page zero . There can be pageable ;memory in the middle of the wired pages on machines with small memory. (declare (values a-b)) (POPJ-AFTER-NEXT (M-B) A-ZERO) (NO-OP) FINDCORE-IN-HEXADEC ((M-TEM) LDB (BYTE-FIELD 4 0) M-B) (JUMP-NOT-EQUAL-XCT-NEXT M-TEM A-TEM3 FINDCORE0) ;physically not on right boundary. ((A-COUNT-FINDCORE-STEPS) M+A+1 M-ZERO A-COUNT-FINDCORE-STEPS) Added I - LONG to this ldb , since it seems to lose occasionally . KHS 840912 #+LAMBDA((M-TEM) (BYTE-FIELD 20 0) READ-MEMORY-DATA I-LONG) ;PHT entry index #+EXP ((M-TEM) (BYTE-FIELD 20 0) READ-MEMORY-DATA) (JUMP-EQUAL M-TEM (A-CONSTANT 177777) FINDCORE0) ;No page here ((VMA-START-READ M-T) ADD M-TEM A-V-PAGE-TABLE-AREA) (illop-if-page-fault) (DISPATCH PHT1-SWAP-STATUS-CODE READ-MEMORY-DATA D-FINDCORE) (CALL-GREATER-OR-EQUAL M-B A-V-PHYSICAL-PAGE-DATA-VALID-LENGTH FINDCORE2) ;; Searched all of memory (except for the last page brought in), time for emergency measures ;; Age all of the pages in memory, which should make some flushable FINDCORE3 ((A-COUNT-FINDCORE-EMERGENCIES) M+A+1 M-ZERO A-COUNT-FINDCORE-EMERGENCIES) ((M-T) M-1) ;Mustn't clobber M-1 (CALL-XCT-NEXT AGER) ((M-1) A-FINDCORE-SCAN-POINTER) (JUMP-XCT-NEXT FINDCORE0) ;Try again ((M-1) M-T) (LOCALITY D-MEM) (START-DISPATCH 3 0) ;DISPATCH TABLE TO LOOK FOR FLUSHABLE PAGES D-FINDCORE ;DISPATCH ON SWAP STATUS (FINDCORE0) ;0 ILLEGAL 1 NORMAL 2 FLUSHABLE 3 PREPAGE 4 AGE TRAP 5 WIRED DOWN 6 NOT USED 7 NOT USED (END-DISPATCH) ( START - DISPATCH 3 0 ) ; FOR SWAP - OUT CANDIDATE FROM SCAV WORKING - SET ;D-SCAV-SWAPOUT ;DISPATCH ON SWAP STATUS ; (INHIBIT-XCT-NEXT-BIT SWAPIN0) ;0 ILLEGAL ( P - BIT R - BIT INHIBIT - XCT - NEXT - BIT ) ; 1 NORMAL - TAKE ( P - BIT R - BIT INHIBIT - XCT - NEXT - BIT ) ; 2 FLUSHABLE - TAKE ( P - BIT R - BIT ) ; 3 PREPAGE - TAKE AND ( P - BIT R - BIT INHIBIT - XCT - NEXT - BIT ) ; 4 AGE TRAP - TAKE ( INHIBIT - XCT - NEXT - BIT SWAPIN0 ) ; 5 WIRED DOWN ( INHIBIT - XCT - NEXT - BIT SWAPIN0 ) ; 6 NOT USED ( INHIBIT - XCT - NEXT - BIT SWAPIN0 ) ; 7 NOT USED ;(END-DISPATCH) (START-DISPATCH 3 0) ;DISPATCH TABLE TO DROP THROUGH IF PAGE NEEDS WRITING D-WRITEBACK-NEEDED ;DISPATCH ON MAP STATUS 0 ILLEGAL ( LVL 1 MAP ) 1 ILLEGAL ( LVL 2 MAP ) 2 READ ONLY 3 READ / WRITE FIRST 4 READ / WRITE - INDICATES PAGE MODIFIED 5 PDL BUFFER , ALWAYS WRITE PDL - BUFFER PAGES ; SINCE R/W/F MECHANISM NOT AVAILABLE. 6 MAR BREAK , ALWAYS WRITE FOR SAME REASON 7 nubus physical in PHT2 (END-DISPATCH) (START-DISPATCH 3 0) ;DISPATCH TABLE TO DROP THROUGH IF PAGE NEEDS WRITING D-WRITEBACK-NEEDED-CCW ;DISPATCH ON MAP STATUS 0 ILLEGAL ( LVL 1 MAP ) 1 ILLEGAL ( LVL 2 MAP ) 2 READ ONLY 3 READ / WRITE FIRST 4 READ / WRITE - INDICATES PAGE MODIFIED 5 PDL BUFFER , ALWAYS WRITE PDL - BUFFER PAGES ; SINCE R/W/F MECHANISM NOT AVAILABLE. HOWEVER , WE DONT THESE . 6 MAR BREAK , ALWAYS WRITE FOR SAME REASON HOWEVER , WE DONT THESE . 7 nubus physical in PHT2 (END-DISPATCH) (LOCALITY I-MEM) ;Here when we've found a page to evict. M-B has the PFN+1. VMA and are for the PHT1 . M - T same as VMA . ;This version for the case where victim was pre-paged in and not used COREFOUND-PRE (JUMP-XCT-NEXT COREFOUND0) ((A-DISK-PREPAGE-NOT-USED-COUNT) M+A+1 M-ZERO A-DISK-PREPAGE-NOT-USED-COUNT) ;This version for the normal case COREFOUND COREFOUND0 ((A-FINDCORE-SCAN-POINTER) M-B) ;Next time, start search with page after this COREFOUND3 ;Enter here on %DELETE-PHYSICAL-PAGE. (CALL-IF-BIT-CLEAR PHT1-VALID-BIT READ-MEMORY-DATA ILLOP) ((M-A) READ-MEMORY-DATA) ;PHT1 COREFOUND1 Trace page eviction (CALL-IF-BIT-SET (LISP-BYTE %%METER-PAGE-FAULT-ENABLE) M-METER-ENABLES METER-PAGE-OUT) ;;*** When there is background writing, will have to synchronize here ;;*** This will require dual modified bits or something. ((VMA-START-READ) ADD M-T (A-CONSTANT 1)) ;Get PHT2 (ILLOP-IF-PAGE-FAULT) ;PHT should be addressable (JUMP-IF-BIT-SET PHT1-MODIFIED-BIT M-A COREFOUND1A) (DISPATCH PHT2-MAP-STATUS-CODE READ-MEMORY-DATA D-WRITEBACK-NEEDED) ;See if needs writing COREFOUND1A ;Page needs to be written back to disk PHT1 address . - randomly used below to restore m - t ; original use is at coref-ccw-x ((A-DISK-SWAP-OUT-CCW-POINTER) (A-CONSTANT DISK-SWAP-OUT-CCW-BASE)) ((A-DISK-PAGE-WRITE-COUNT) M+A+1 M-ZERO A-DISK-PAGE-WRITE-COUNT) add main memory page frame number in M - B to CCW list . #-lambda(begin-comment) ((WRITE-MEMORY-DATA) DPB M-B VMA-PHYS-PAGE-ADDR-PART (A-CONSTANT 1)) ((VMA-START-WRITE) A-DISK-SWAP-OUT-CCW-POINTER) (ILLOP-IF-PAGE-FAULT) ((A-DISK-SWAP-OUT-CCW-POINTER) ADD A-DISK-SWAP-OUT-CCW-POINTER M-ZERO ALU-CARRY-IN-ONE) #-lambda(end-comment) #-exp(begin-comment) ((m-t) dpb m-b vma-phys-page-addr-part a-zero) (call translate-cadr-physical-to-nubus) ((md) m-lam) ((vma-start-write) a-disk-swap-out-ccw-pointer) (illop-if-page-fault) ((md) (a-constant 1024.)) ((vma-start-write) add vma (a-constant 1)) (illop-if-page-fault) ((a-disk-swap-out-ccw-pointer) add vma (a-constant 1)) ((m-t) pdl-top) #-exp(end-comment) ((A-DISK-SAVE-PGF-A) M-A) ((A-DISK-SAVE-PGF-B) M-B) ((M-TEM) A-DISK-SWITCHES) ;Multiple page swapouts enabled? (JUMP-IF-BIT-CLEAR (BYTE-FIELD 1 2) M-TEM COREF-CCW-X) ((A-DISK-SAVE-1) M-A) COREF-CCW-0 ((M-T) (A-CONSTANT (EVAL PAGE-SIZE))) ((A-DISK-SAVE-1) ADD M-T A-DISK-SAVE-1) (CALL-XCT-NEXT SEARCH-PAGE-HASH-TABLE) ;Is next higher page in core? virt adr in M - T. ; clobbers m-a m-b m-t a-tem1 a-tem3 (JUMP-IF-BIT-CLEAR PHT1-VALID-BIT READ-MEMORY-DATA COREF-CCW-X) ;not found. ;That page in core, does it need to be written? ((M-T) VMA) ;Save PHT1 adr. ((M-A) MD) ;Save PHT1. ((VMA-START-READ) ADD M-T (A-CONSTANT 1)) ;get PHT2 (ILLOP-IF-PAGE-FAULT) ((M-B) READ-MEMORY-DATA) (JUMP-IF-BIT-SET PHT1-MODIFIED-BIT M-A COREF-CCW-ADD) (DISPATCH PHT2-MAP-STATUS-CODE M-B D-WRITEBACK-NEEDED-CCW) ;See if needs writing COREF-CCW-ADD ((WRITE-MEMORY-DATA M-A) ANDCA M-A (A-CONSTANT (BYTE-MASK PHT1-MODIFIED-BIT))) ;clear modified flag ((VMA-START-WRITE) M-T) (ILLOP-IF-PAGE-FAULT) ((M-TEM) PHT2-MAP-STATUS-CODE M-B) change RW to RWF ((M-TEM) (A-CONSTANT 3)) ((WRITE-MEMORY-DATA M-B) DPB M-TEM PHT2-MAP-STATUS-CODE A-B) ((VMA-START-WRITE) ADD M-T (A-CONSTANT 1)) (ILLOP-IF-PAGE-FAULT) ((MD) M-A) ;address the map (no-op) ;allow time ((M-TEM) L2-MAP-STATUS-CODE) ;see if map is set up (JUMP-LESS-THAN M-TEM (A-CONSTANT 2) COREF-CCW-ADD-1) PHT2 same as 2ND LVL MAP(on cadr ) ((M-LAM) M-B) COREF-CCW-ADD-1 ((A-DISK-PAGE-WRITE-APPENDS) M+A+1 M-ZERO A-DISK-PAGE-WRITE-APPENDS) ((A-DISK-PAGE-WRITE-COUNT) M+A+1 M-ZERO A-DISK-PAGE-WRITE-COUNT) add main memory page frame number in M - B to CCW list . #-lambda(begin-comment) ((WRITE-MEMORY-DATA) DPB M-B VMA-PHYS-PAGE-ADDR-PART (A-CONSTANT 1)) ((VMA-START-WRITE) A-DISK-SWAP-OUT-CCW-POINTER) (ILLOP-IF-PAGE-FAULT) ((A-DISK-SWAP-OUT-CCW-POINTER) M+A+1 A-DISK-SWAP-OUT-CCW-POINTER M-ZERO) #-lambda(end-comment) #-exp (begin-comment) ((m-tem1) m-t) ((m-t) dpb m-b vma-phys-page-addr-part a-zero) (call translate-cadr-physical-to-nubus) ((md) m-lam) ((vma-start-write) a-disk-swap-out-ccw-pointer) (illop-if-page-fault) ((md) (a-constant 1024.)) ((vma-start-write) add vma (a-constant 1)) (illop-if-page-fault) ((a-disk-swap-out-ccw-pointer) add vma (a-constant 1)) ((m-t) m-tem1) #-exp(end-comment) ((M-TEM) A-DISK-SWAP-OUT-CCW-POINTER) (JUMP-LESS-THAN M-TEM (A-CONSTANT DISK-SWAP-OUT-CCW-MAX) COREF-CCW-0) COREF-CCW-X #-lambda(begin-comment) ((VMA-START-READ) ADD A-DISK-SWAP-OUT-CCW-POINTER (M-CONSTANT -1)) (ILLOP-IF-PAGE-FAULT) last CCW (ILLOP-IF-PAGE-FAULT) #-lambda(end-comment) ((A-DISK-PAGE-WRITE-OP-COUNT) M+A+1 M-ZERO A-DISK-PAGE-WRITE-OP-COUNT) ((M-A) A-DISK-SAVE-PGF-A) ;get back base virt adr. get back page frame number of first ; page. It is no longer used by ; disk swap handler, but is needed ; by COREFOUND2. ((C-PDL-BUFFER-POINTER-PUSH) M-C) M - C ((m-tem4) a-disk-swap-out-ccw-pointer) ((m-tem4) sub m-tem4 a-c) ;length of transfer in pages (for hexadec aging hack). divide by 2 Do the write ( virt adr in M - A ) ((M-T) (A-CONSTANT DISK-WRITE-COMMAND)) ((M-C) C-PDL-BUFFER-POINTER-POP) ((A-DISK-PAGE-WRITE-WAIT-COUNT) M+A+1 M-ZERO A-DISK-PAGE-WRITE-WAIT-COUNT) RESTORE PHT ENTRY ADDRESS ;DROPS THROUGH ;DROPS IN AT THIS POINT , M - T HAS ADDR OF PHT ENTRY TO BE DELETED , ;M-A HAS ITS VIRTUAL ADDRESS, M-B HAS ITS PAGE FRAME NUMBER (NOT! PHYSICAL ADDRESS) DELETION WORKS BY FINDING PAGES THAT SHOULD HAVE HASHED TO THE ;HOLE WHERE THE THING WAS DELETED, AND EXCHANGING THEM WITH THE HOLE. ;NOTE THAT THE ALGORITHM IN THE PAGING MEMO IS WRONG. CONVENTIONS : M - B POINTS AT THE HOLE , VMA POINTS AT THE ITEM SUSPECTED OF BEING IN THE WRONG PLACE , M - PGF - TEM POINTS AT THE UPPERMOST ENTRY IN THE PHT , M - T POINTS AT WHERE ( VMA ) SHOULD HAVE HASHED TO . THESE ARE TYPELESS ABSOLUTE ADDRESSES . COREFOUND2 ((C-PDL-BUFFER-POINTER-PUSH) M-B) ;Save page frame number Remove pointer to PHT entry ((VMA-START-WRITE) ADD M-B A-V-PHYSICAL-PAGE-DATA) (ILLOP-IF-PAGE-FAULT) ((M-B) M-T) ;-> PHT entry to delete ((M-PGF-TEM) DPB M-ZERO Q-ALL-BUT-POINTER A-V-PAGE-TABLE-AREA) ((M-PGF-TEM) ADD M-PGF-TEM A-PHT-INDEX-LIMIT) ;-> last entry in table +2 PHTDEL1 ((WRITE-MEMORY-DATA) a-zero) ;Delete PHT entry. ((VMA-START-WRITE M-B) Q-POINTER M-B) (ILLOP-IF-PAGE-FAULT) ;Supposed to be wired PHTDEL2 ((VMA-START-READ) ADD VMA (A-CONSTANT 2)) ;Check location following hole (JUMP-GREATER-OR-EQUAL VMA A-PGF-TEM PHTDEL5) ;Jump if wrap around PHTDEL3 (ILLOP-IF-PAGE-FAULT) (JUMP-IF-BIT-CLEAR PHT1-VALID-BIT READ-MEMORY-DATA PHTDELX) ((M-T) SELECTIVE-DEPOSIT READ-MEMORY-DATA ;Check for dummy entry PHT1-VIRTUAL-PAGE-NUMBER (A-CONSTANT -1)) ;which has an address of -1 (JUMP-EQUAL-XCT-NEXT M-T (A-CONSTANT -1) PHTDEL7) ;Dummy always hashes ((M-T) M-B) ; to the hole (CALL-XCT-NEXT COMPUTE-PAGE-HASH) ;Something there, rehash it ((M-T) READ-MEMORY-DATA) ((M-T) ADD M-T A-V-PAGE-TABLE-AREA) ;Convert fixnum hash to address ((M-T) Q-POINTER M-T) ; sans extra bits PHTDEL7 (JUMP-LESS-THAN VMA A-T PHTDEL4) ;Jump on funny wrap around case (JUMP-GREATER-THAN M-T A-B PHTDEL2) ;Jump if hole is not between where (JUMP-LESS-THAN VMA A-B PHTDEL2) ; the frob is and where it hashes to PHTDEL6 ((C-PDL-BUFFER-POINTER-PUSH) READ-MEMORY-DATA) ;Move the cell into the hole ((VMA-START-READ) ADD VMA (A-CONSTANT 1)) (ILLOP-IF-PAGE-FAULT) ((M-T) SUB VMA (A-CONSTANT 1)) ;Save pointer to moved cell ((WRITE-MEMORY-DATA) READ-MEMORY-DATA) ;Complete the cycle Address the hole , store PHT2 (ILLOP-IF-PAGE-FAULT) ((M-TEM) PHT2-PHYSICAL-PAGE-NUMBER MD) ;Fix up physical-page-data error check for clobbering PPD entry 0 (call-equal m-tem a-zero illop) ((VMA-START-READ) ADD M-TEM A-V-PHYSICAL-PAGE-DATA) (ILLOP-IF-PAGE-FAULT) ((M-TEM) SUB M-B A-V-PAGE-TABLE-AREA) ;New PHT index * * * Will need to be changed if gets Bigger * * * ((WRITE-MEMORY-DATA-START-WRITE) SELECTIVE-DEPOSIT READ-MEMORY-DATA (BYTE-FIELD 20 20) A-TEM) (ILLOP-IF-PAGE-FAULT) ((VMA) M-B) ((WRITE-MEMORY-DATA-START-WRITE) C-PDL-BUFFER-POINTER-POP) ;Store PHT1 (ILLOP-IF-PAGE-FAULT) (JUMP-XCT-NEXT PHTDEL1) ;Make the moved cell into new hole ((M-B) M-T) PHTDEL4 (JUMP-LESS-OR-EQUAL M-T A-B PHTDEL6) ;Jump if hole is between where the (JUMP-GREATER-OR-EQUAL VMA A-B PHTDEL6) ; frob is and where it hashes to (JUMP PHTDEL2) ;It's not, loop more Wrap around to beg of ((VMA-START-READ) DPB M-ZERO Q-ALL-BUT-POINTER A-V-PAGE-TABLE-AREA) PHTDELX ((M-B) C-PDL-BUFFER-POINTER-POP) ;Restore found page frame number (?) ((MD) M-A) ;Access map for virt page deleted #+exp (no-op) (POPJ-AFTER-NEXT (#+lambda L2-MAP-CONTROL #+exp vma-write-l2-map-control) (A-CONSTANT 0)) ;Flush 2nd lvl map, if any Note that if we have a first - level map miss , this does no harm Do n't leave garbage in VMA . swapin0-a (call swapin0) We have found one page of core , store it away in the CCW and loop ; until we have got enuf for the transfer we intend. add main memory page frame number in M - B to CCW list . #-lambda(begin-comment) ((WRITE-MEMORY-DATA) DPB M-B VMA-PHYS-PAGE-ADDR-PART (A-CONSTANT 1)) ((VMA-START-WRITE) A-DISK-SWAP-IN-CCW-POINTER) (ILLOP-IF-PAGE-FAULT) ((A-DISK-SWAP-IN-CCW-POINTER) M+A+1 A-DISK-SWAP-IN-CCW-POINTER M-ZERO) #-lambda(end-comment) #-exp(begin-comment) ((m-tem1) m-t) ((m-t) dpb m-b vma-phys-page-addr-part a-zero) (call translate-cadr-physical-to-nubus) ((md) m-lam) ((vma-start-write) a-disk-swap-in-ccw-pointer) (illop-if-page-fault) ((md) (a-constant 1024.)) ((vma-start-write) add vma (a-constant 1)) (illop-if-page-fault) ((a-disk-swap-in-ccw-pointer) add vma (a-constant 1)) ((m-t) m-tem1) #-exp(end-comment) ((A-DISK-PAGE-READ-COUNT) ADD M-ZERO A-DISK-PAGE-READ-COUNT ALU-CARRY-IN-ONE) ((A-DISK-SWAPIN-SIZE) ADD A-DISK-SWAPIN-SIZE (M-CONSTANT -1)) (JUMP-NOT-EQUAL A-DISK-SWAPIN-SIZE M-ZERO SWAPIN-LOOP) #-lambda(begin-comment) finish ccw list (ILLOP-IF-PAGE-FAULT) ((WRITE-MEMORY-DATA-START-WRITE) SUB WRITE-MEMORY-DATA (A-CONSTANT 1)) ;last (ILLOP-IF-PAGE-FAULT) #-lambda(end-comment) ;SWAPIN1-GO CONTINUE SWAPPING IN . NEXT STEP IS TO SEARCH REGION TABLES TO FIND META BITS . (CALL PAGE-IN-GET-MAP-BITS) ;note M-B still holds page frame number in path to CZRR . (JUMP-IF-BIT-SET M-DONT-SWAP-IN CZRR) ;IF FRESH PAGE DON'T REALLY SWAP IN ((C-PDL-BUFFER-POINTER-PUSH) M-C) CCW list pointer ( CLP ) ((m-tem4) a-disk-swap-in-ccw-pointer) ((m-tem4) sub m-tem4 a-c) ;transfer size in pages for hexadec aging. divide by 2 (CALL-XCT-NEXT DISK-SWAP-HANDLER) ;Do actual disk transfer ((M-T) (A-CONSTANT DISK-READ-COMMAND)) ((M-C) C-PDL-BUFFER-POINTER-POP) SWAPIN2 Now loop through ccw list making the pages known . ((M-B) (A-CONSTANT DISK-SWAP-IN-CCW-BASE)) First page in gets normal swap - status ((A-PAGE-IN-PHT1) (A-CONSTANT (PLUS (BYTE-VALUE PHT1-VALID-BIT 1) (BYTE-VALUE PHT1-SWAP-STATUS-CODE 1)))) ((A-DISK-PAGE-READ-OP-COUNT) ADD M-ZERO A-DISK-PAGE-READ-OP-COUNT ALU-CARRY-IN-ONE) SWAPIN2-LOOP Trace page swapin (CALL-IF-BIT-SET (LISP-BYTE %%METER-PAGE-FAULT-ENABLE) M-METER-ENABLES METER-PAGE-IN) ((VMA-START-READ) M-B) (ILLOP-IF-PAGE-FAULT) #-exp (begin-comment) ((m-lam) md) (call translate-nubus-to-cadr-physical) ((md) m-lam) #-exp (end-comment) ((A-DISK-SWAPIN-PAGE-FRAME) LDB VMA-PHYS-PAGE-ADDR-PART READ-MEMORY-DATA A-ZERO) ((C-PDL-BUFFER-POINTER-PUSH) M-B) (CALL PAGE-IN-MAKE-KNOWN) ((M-B) C-PDL-BUFFER-POINTER-POP) ((M-A) (A-CONSTANT (EVAL PAGE-SIZE))) ((A-DISK-SWAPIN-VIRTUAL-ADDRESS) ADD M-A A-DISK-SWAPIN-VIRTUAL-ADDRESS) ((m-b) add m-b (a-constant #+lambda 1 #+exp 2)) (JUMP-LESS-THAN-XCT-NEXT M-B A-DISK-SWAP-IN-CCW-POINTER SWAPIN2-LOOP) Pages after the first get pre - paged swap - status ((A-PAGE-IN-PHT1) (A-CONSTANT (PLUS (BYTE-VALUE PHT1-VALID-BIT 1) (BYTE-VALUE PHT1-SWAP-STATUS-CODE 3)))) SWAPIN2-X (JUMP PGF-RESTORE) ;TAKE FAULT AGAIN SINCE DISK XFER ;MAY HAVE FAULTED AND FLUSHED SECOND LEVEL MAP BLOCK. Get PHT2 bits and leave them in A - DISK - SWAPIN - PHT2 - BITS . ((C-PDL-BUFFER-POINTER-PUSH) A-DISK-SWAPIN-VIRTUAL-ADDRESS) (CALL XRGN) ;=> region number in M-T (CALL-EQUAL M-T A-V-NIL ILLOP) ;Swapping in a page not in a region ((VMA-START-READ) ADD M-T A-V-REGION-BITS) ;Get misc bits word (ILLOP-IF-PAGE-FAULT) ;Should be wired down ((M-A) DPB M-ZERO Q-ALL-BUT-POINTER A-DISK-SWAPIN-VIRTUAL-ADDRESS) ((m-tem) ldb (lisp-byte %%region-map-bits) md) ((a-disk-swapin-pht2-bits) dpb m-tem pht2-access-status-and-meta-bits a-zero) ; ((m-lam) a-disk-swapin-virtual-address) ; (call-xct-next read-page-volatility) ; ((m-lam) q-page-number m-lam) ( ( a - disk - swapin - pht2 - bits ) pht2 - map - volatility a - disk - swapin - pht2 - bits ) ( ( M - TEM ) SELECTIVE - DEPOSIT READ - MEMORY - DATA ( LISP - BYTE % % REGION - MAP - BITS ) a - zero ) ( ( A - DISK - SWAPIN - PHT2 - BITS ) M - TEM ) Check VMA against MAR ((M-T) SELECTIVE-DEPOSIT M-T VMA-PAGE-ADDR-PART A-ZERO) (POPJ-LESS-THAN M-A A-T) ((M-T) A-MAR-HIGH) ((M-T) SELECTIVE-DEPOSIT M-T VMA-PAGE-ADDR-PART (A-CONSTANT (EVAL (1- PAGE-SIZE)))) If MAR to be set , change map status and turn off (POPJ-AFTER-NEXT (M-T) (A-CONSTANT (EVAL %PHT-MAP-STATUS-MAR))) ; hardware access ((A-DISK-SWAPIN-PHT2-BITS) DPB M-T PHT2-MAP-ACCESS-AND-STATUS-CODE A-disk-swapin-pht2-bits) Second part . Make physical page frame number A - DISK - SWAPIN - PHYSICAL - PAGE - FRAME ;;; known at A-DISK-SWAPIN-VIRTUAL-ADDRESS. PHT2 bits are in A - DISK - SWAPIN - PHT2 - BITS . A - PAGE - IN - PHT1 contains the bits desired in the PHT1 ( swap status mainly ) ;;; Clobbers M-A, M-B, M-T, A-TEM1, A-TEM3 PAGE-IN-MAKE-KNOWN ((m-t) a-disk-swapin-virtual-address) (call-xct-next read-page-volatility) ((m-lam) q-page-number m-t) ((a-disk-swapin-pht2-bits) dpb m-tem pht2-map-volatility a-disk-swapin-pht2-bits) (call search-page-hash-table) ( CALL - XCT - NEXT SEARCH - PAGE - HASH - TABLE ) ; Find hole in PHT for it ; ((M-T) A-DISK-SWAPIN-VIRTUAL-ADDRESS) (CALL-IF-BIT-SET PHT1-VALID-BIT READ-MEMORY-DATA ILLOP) ;Supposed to be a hole! ((M-A) A-DISK-SWAPIN-VIRTUAL-ADDRESS) Construct and store PHT1 word SELECTIVE-DEPOSIT M-A PHT1-VIRTUAL-PAGE-NUMBER A-PAGE-IN-PHT1) (ILLOP-IF-PAGE-FAULT) ;Should be wired ((M-PGF-TEM) A-DISK-SWAPIN-PAGE-FRAME) ((WRITE-MEMORY-DATA) SELECTIVE-DEPOSIT M-PGF-TEM PHT2-PHYSICAL-PAGE-NUMBER ;Restore access, status, and meta bits A-DISK-SWAPIN-PHT2-BITS) (DISPATCH (LISP-BYTE %%PHT2-MAP-STATUS-CODE) MD D-SWAPAR) ;Verify the bits ;; This will go to ILLOP if this is a page of a free region ((VMA-START-WRITE) ADD VMA (A-CONSTANT 1)) ;Store PHT2 (ILLOP-IF-PAGE-FAULT) ;Should be wired ;error check ((md) pht2-physical-page-number md) (call-equal md a-zero illop) 0,,Index in PHT ((VMA) A-DISK-SWAPIN-PAGE-FRAME) error check for clobbering PPD entry 0 (call-equal vma a-zero illop) (POPJ-AFTER-NEXT (VMA-START-WRITE) ADD VMA A-V-PHYSICAL-PAGE-DATA) (ILLOP-IF-PAGE-FAULT) (LOCALITY D-MEM) (START-DISPATCH 3 0) ;DISPATCH ON MAP-STATUS VERIFY MAP STATUS CODE FROM CORE (P-BIT INHIBIT-XCT-NEXT-BIT ILLOP) ;0 MAP NOT SET UP ERRONEOUS 1 META BITS ONLY ERRONEOUS 2 READ ONLY 3 READ WRITE FIRST 4 READ WRITE 5 PDL BUFFER 6 MAR BREAK 7 nubus physical in PHT2 (END-DISPATCH) (LOCALITY I-MEM) INITIALIZE A FRESH PAGE BY FILLING IT WITH < DTP - TRAP . > Virtual adr in A - DISK - SWAPIN - VIRTUAL - ADDRESS ( no type bits ) , M - B/ PAGE FRAME NUMBER CZRR ((MD) A-MAP-SCRATCH-BLOCK) (CALL-XCT-NEXT LOAD-L2-MAP-FROM-CADR-PHYSICAL) ((M-LAM) DPB M-B pht2-PHYSICAL-PAGE-NUMBER (A-CONSTANT (BYTE-VALUE pht2-MAP-ACCESS-CODE 3))) ;R/W ((VMA) A-MAP-SCRATCH-BLOCK) ;COMPUTE PAGE BASE ADDRESS ((M-TEM1) SELECTIVE-DEPOSIT M-ZERO VMA-LOW-BITS A-DISK-SWAPIN-VIRTUAL-ADDRESS) ((M-LAM) A-ZERO) CZRR1 ((WRITE-MEMORY-DATA-START-WRITE) ;STORE TRAPS POINTING TO SELF NOTE DTP - TRAP = 0 (ILLOP-IF-PAGE-FAULT) ((VMA) ADD VMA (A-CONSTANT 1)) (JUMP-LESS-THAN-XCT-NEXT M-LAM (A-CONSTANT 377) CZRR1) ((M-LAM) ADD M-LAM (A-CONSTANT 1)) ((A-FRESH-PAGE-COUNT) ADD M-ZERO A-FRESH-PAGE-COUNT ALU-CARRY-IN-ONE) (JUMP-XCT-NEXT SWAPIN2) ;RETURN TO MAIN SWAP-IN CODE ((VMA) A-V-NIL) #-lambda(begin-comment) hexadec in M - TEM3 (declare (args a-tem3)) ((oa-reg-low) dpb m-tem3 oal-a-dest-4-bits (a-constant (byte-value oal-a-dest 1740))) ((a-garbage) a-findcore-scan-pointer) (popj-after-next (oa-reg-low) dpb m-tem3 oal-a-dest-4-bits (a-constant (byte-value oal-a-dest 1760))) ((a-garbage) a-aging-scan-pointer) hexadec in M - TEM3 (declare (args a-tem3)) ((oa-reg-high) dpb m-tem3 oah-a-src-4-bits (a-constant (byte-value oah-a-src 1740))) ((a-findcore-scan-pointer) seta a-garbage) (popj-after-next (oa-reg-high) dpb m-tem3 oah-a-src-4-bits (a-constant (byte-value oah-a-src 1760))) ((a-aging-scan-pointer) seta a-garbage) #-lambda(end-comment) Ager . Called from DISK - SWAP - HANDLER , may clobber M-1 , A - TEM1 , A - TEM2 , A - TEM3 , M - TEM . Must be called with A - AGING - SCAN - POINTER in M-1 . ;This advances A-AGING-SCAN-POINTER through main memory until it catches up ;to A-FINDCORE-SCAN-POINTER, skipping over the page which is being read in now. ;If a page is found with normal swap-status, it is changed to age trap. ;If a page is found with age-trap status, it is changed to flushable. AGER ((A-AGING-SCAN-POINTER) A-FINDCORE-SCAN-POINTER) ;Will advance to here AGER0 ((M-1) ADD M-1 (A-CONSTANT 1)) (CALL-GREATER-OR-EQUAL M-1 A-V-PHYSICAL-PAGE-DATA-VALID-LENGTH AGER1) ;If wrap around ((VMA-START-READ) ADD M-1 A-V-PHYSICAL-PAGE-DATA) (ILLOP-IF-PAGE-FAULT) Return if caught up , skipping this one ((M-TEM) (BYTE-FIELD 20 0) READ-MEMORY-DATA) ;PHT entry index (JUMP-EQUAL M-TEM (A-CONSTANT 177777) AGER0) ;No page here ((VMA-START-READ) ADD M-TEM A-V-PAGE-TABLE-AREA) (ILLOP-IF-PAGE-FAULT) (DISPATCH PHT1-SWAP-STATUS-CODE READ-MEMORY-DATA D-AGER) AGER1 (declare (values a-1)) Wrap around to page zero (no-op) (LOCALITY D-MEM) (START-DISPATCH 3 INHIBIT-XCT-NEXT-BIT) 0 PHT ENTRY INVALID , IGNORE 1 NORMAL , SET AGE TRAP 2 FLUSHABLE , IGNORE 3 PREPAGED , IGNORE 4 AGE TRAP , CHANGE TO FLUSHABLE IF AGED ENOUGH 5 WIRED , IGNORE 6 NOT USED , ERROR 7 NOT USED , ERROR (END-DISPATCH) (LOCALITY I-MEM) CHANGE NORMAL TO AGE - TRAP , ALSO TURN OFF HARDWARE MAP ACCESS , SET AGE TO 0 AGER2 ((A-PAGE-AGE-COUNT) ADD M-ZERO A-PAGE-AGE-COUNT ALU-CARRY-IN-ONE) ((WRITE-MEMORY-DATA-START-WRITE) SELECTIVE-DEPOSIT READ-MEMORY-DATA PHT1-ALL-BUT-AGE-AND-SWAP-STATUS-CODE (A-CONSTANT (EVAL %PHT-SWAP-STATUS-AGE-TRAP))) (ILLOP-IF-PAGE-FAULT) ((md) md) (JUMP-XCT-NEXT AGER0) ((#+lambda l2-map-control FLUSH 2ND LVL MAP , IF ANY AGER0 will put good data in VMA . CHANGE AGE - TRAP TO FLUSHABLE IF HAS ENOUGH AGER3 ((M-TEM) PHT1-AGE READ-MEMORY-DATA) (JUMP-GREATER-OR-EQUAL M-TEM A-AGING-DEPTH AGER4) ;AGED ENOUGH ((WRITE-MEMORY-DATA-START-WRITE) ADD READ-MEMORY-DATA ;AGE MORE BEFORE MAKING (A-CONSTANT (BYTE-VALUE PHT1-AGE 1))) ; FLUSHABLE (ILLOP-IF-PAGE-FAULT) (JUMP AGER0) AGER4 ((A-PAGE-FLUSH-COUNT) ADD M-ZERO A-PAGE-FLUSH-COUNT ALU-CARRY-IN-ONE) ((WRITE-MEMORY-DATA-START-WRITE) SELECTIVE-DEPOSIT READ-MEMORY-DATA PHT1-ALL-BUT-SWAP-STATUS-CODE (A-CONSTANT (EVAL %PHT-SWAP-STATUS-FLUSHABLE))) (ILLOP-IF-PAGE-FAULT) (JUMP AGER0) ;GIVEN AN ADDRESS FIND WHAT AREA IT IS IN. RETURNS THE AREA NUMBER OR NIL. ;THIS WORKS BY FINDING THE REGION NUMBER, THEN FINDING WHAT AREA THAT REGION LIES IN. XARN (MISC-INST-ENTRY %AREA-NUMBER) GET REGION NUMBER FROM ARG ON PDL (POPJ-EQUAL M-T A-V-NIL) ;NONE ;GIVEN A REGION NUMBER IN M-T, FIND THE AREA-NUMBER (IN M-T WITH DATA-TYPE) REGION-TO-AREA ((vma-start-read) add m-t a-v-region-area-map) (check-page-read) (popj-after-next no-op) ((m-t) q-pointer md (a-constant (byte-value q-data-type dtp-fix))) ; Winning REGION-AREA-MAP superseded this bagbiting code. ( ( VMA - START - READ ) ADD M - T A - V - REGION - LIST - THREAD ) ; (CHECK-PAGE-READ) ( JUMP - IF - BIT - CLEAR - XCT - NEXT BOXED - SIGN - BIT READ - MEMORY - DATA REGION - TO - AREA ) ; ((M-T) BOXED-NUM-EXCEPT-SIGN-BIT READ-MEMORY-DATA ;GET NEXT IN LIST ( A - CONSTANT ( BYTE - VALUE Q - DATA - TYPE DTP - FIX ) ) ) ; (POPJ) ;END OF LIST, M-T HAS AREA NUMBER ;GIVEN AN ADDRESS FIND WHAT REGION IT IS IN. RETURNS THE REGION NUMBER OR NIL IF NOT IN ANY REGION , IN M - T. RETURNS ( OR TAKES AT XRGN1 ) THE POINTER IN M - A. ;MUST CLOBBER ONLY M-T, M-TEM, Q-R, A-TEM1, A-TEM2, A-TEM3, M-A SINCE IT IS CALLED BY THE PAGE FAULT ROUTINES . XRGN (declare (values a-t) (clobbers a-tem a-a)) (MISC-INST-ENTRY %REGION-NUMBER) ((M-A) Q-POINTER C-PDL-BUFFER-POINTER-POP ;An address in the region (A-CONSTANT (BYTE-VALUE Q-DATA-TYPE DTP-FIX))) * * datatype of M - A really should be DTP - LOCATIVE , since it is a pointer . Get word from ADDRESS - SPACE - MAP . (declare (args a-a) (values a-t) (clobbers a-tem)) ((vma) address-space-map-word-index-byte m-a) ((vma-start-read) add vma a-v-address-space-map) (ILLOP-IF-PAGE-FAULT) Byte number in that word ((M-TEM) DPB M-TEM ADDRESS-SPACE-MAP-BYTE-MROT A-ZERO) 40 does n't hurt here , IORed in #+exp ((oa-reg-low) add m-tem (a-constant 1_16.)) ;rotate right ((M-T) (BYTE-FIELD (EVAL %ADDRESS-SPACE-MAP-BYTE-SIZE) 0) READ-MEMORY-DATA (A-CONSTANT (BYTE-VALUE Q-DATA-TYPE DTP-FIX))) (POPJ-NOT-EQUAL M-T (A-CONSTANT (BYTE-VALUE Q-DATA-TYPE DTP-FIX))) ;Low areas do not start on proper quantuum boundaries, so above code does not work for them. ; Scan region origins, etc to get answer if pointer is below FIRST-UNFIXED-AREA. Note ; INITIAL-LIST-AREA is below FIRST-UNFIXED-AREA. ;; 0 in table, is either free space or fixed area (JUMP-GREATER-OR-EQUAL M-A A-V-FIRST-UNFIXED-AREA XFALSE) ;Free space ;; Search table of area origins. I guess linear search is fast enough. ;; Note: each entry in this table is a fixnum. ((M-T) (A-CONSTANT (A-MEM-LOC A-V-INIT-LIST-AREA))) XRGN2 ;; This cannot happen under any circumstances. A-V-RESIDENT-SYMBOL-AREA is fixnum zero -- if it were less than that the test above would have indicated it as free . ( call - less - than m - t ( a - constant ( a - mem - loc a - v - resident - symbol - area ) ) illop ) ((OA-REG-HIGH) DPB M-T OAH-A-SRC A-ZERO) (JUMP-LESS-THAN-XCT-NEXT M-A A-GARBAGE XRGN2) ((M-T) SUB M-T (A-CONSTANT 1)) (POPJ-AFTER-NEXT (M-T) SUB M-T (A-CONSTANT (DIFFERENCE (A-MEM-LOC A-V-RESIDENT-SYMBOL-AREA) 1))) ((M-T) Q-POINTER M-T (A-CONSTANT (BYTE-VALUE Q-DATA-TYPE DTP-FIX))) ;;; MISCELLANEOUS FUNCTIONS FOR LISP PROGRAMS TO HACK THE PAGE HASH TABLE XCPGS (MISC-INST-ENTRY %CHANGE-PAGE-STATUS) ARGS ARE VIRTUAL ADDRESS , SWAP STATUS CODE , ACCESS STATUS AND META BITS ;DOESN'T DO ERROR CHECKING, IF YOU DO THE WRONG THING YOU WILL LOSE. ((M-E) Q-TYPED-POINTER C-PDL-BUFFER-POINTER-POP) ;Access, status, and meta bits ((M-D) Q-TYPED-POINTER C-PDL-BUFFER-POINTER-POP) ;Swap status code Here from UPDATE - REGION - PHT . Must bash only M - A , M - B , M - T , tems . Returns address which came in on pdl , in MD . Bit 24 . means disconnect virtual page completely , for % GC - FREE - REGION . Bit 23 . means clear modified bit , for CLEAN - DIRTY - PAGES . XCPGS0 (CALL-XCT-NEXT SEARCH-PAGE-HASH-TABLE) ((M-T) Q-POINTER C-PDL-BUFFER-POINTER) ;Virtual address If not swapped in , return NIL , and make PHT1-VALID-BIT READ-MEMORY-DATA XCPGS2) ; sure to clear the map ((M-T) A-V-NIL) ((M-T) A-V-TRUE) ;Get ready to return T (JUMP-EQUAL M-D A-V-NIL XCPGS1) ;See if should change swap-status (jump-if-bit-set (byte-field 1 23.) m-d xcpgs4) ;other special kludge, clear modified (JUMP-IF-BIT-CLEAR (BYTE-FIELD 1 24.) M-D XCPGS3) ;If sign bit of M-D set, ((M-TEM2) ANDCA MD (A-CONSTANT (BYTE-MASK PHT1-MODIFIED-BIT))) ;clear modified flag ((MD) DPB (M-CONSTANT -1) PHT1-VIRTUAL-PAGE-NUMBER A-TEM2) ;and forget virtual page XCPGS3 ((WRITE-MEMORY-DATA-START-WRITE) pht1 - swap - status is low 3 bits . (ILLOP-IF-PAGE-FAULT) XCPGS1 (JUMP-EQUAL M-E A-V-NIL XCPGS2) ((m-tem3) (byte-field (difference q-pointer-width 2) 2) m-e) ((VMA-START-READ) ADD VMA (A-CONSTANT 1)) (ILLOP-IF-PAGE-FAULT) ((M-TEM2) READ-MEMORY-DATA) ((WRITE-MEMORY-DATA-START-WRITE) DPB m-tem3 PHT2-ACCESS-STATUS-AND-META-BITS-except-volatility A-TEM2) (ILLOP-IF-PAGE-FAULT) XCPGS2 ((MD) C-PDL-BUFFER-POINTER-POP) ;ADDRESS LOCATION BEING HACKED (no-op) ;supposedly necessary only on exp, try it on lambda to be sure. ((#+lambda l2-map-control FLUSH 2ND LVL MAP , IF ANY ((VMA) A-V-NIL) ;INSTRUCTIONS MUST LEAVE VMA NON-GARBAGE On popj cycle , MUSTN'T MAP - WRITE or affect VMA . xcpgs4 (jump-xct-next xcpgs3) ((md) andca md (A-CONSTANT (BYTE-MASK PHT1-MODIFIED-BIT))) XCPPG (MISC-INST-ENTRY %CREATE-PHYSICAL-PAGE) ; (CALL LOAD-PHYSICAL-MEMORY-SETUP-FROM-SYS-COM) ;ARG IS PHYSICAL ADDRESS ((VMA-START-READ) A-V-PAGE-TABLE-AREA) ;FIND FIRST HOLE XCPPG0 (ILLOP-IF-PAGE-FAULT) ((M-TEM) SUB VMA A-V-PAGE-TABLE-AREA) (CALL-GREATER-OR-EQUAL M-TEM A-PHT-INDEX-LIMIT ILLOP) ;OUT OF BOUNDS (JUMP-IF-BIT-SET-XCT-NEXT PHT1-VALID-BIT READ-MEMORY-DATA XCPPG0) ((VMA-START-READ) ADD VMA (A-CONSTANT 2)) USELESS MEM CYCLE ((VMA) SUB VMA (A-CONSTANT 2)) ;ADDRESS PHT1 OF HOLE Enter here from COLD - REINIT - PHT . May smash only M - T. XCPPG1 ((WRITE-MEMORY-DATA-START-WRITE) DPB (M-CONSTANT -1) ;FAKE VIRTUAL ADDRESS PHT1-VIRTUAL-PAGE-NUMBER (A-CONSTANT (PLUS (BYTE-VALUE PHT1-SWAP-STATUS-CODE 2) ;FLUSHABLE (BYTE-VALUE PHT1-VALID-BIT 1)))) (ILLOP-IF-PAGE-FAULT) ((M-T) VMA-PHYS-PAGE-ADDR-PART C-PDL-BUFFER-POINTER-POP);PAGE FRAME NUMBER 0,,PHT INDEX ((VMA-START-WRITE) ADD M-T A-V-PHYSICAL-PAGE-DATA) (ILLOP-IF-PAGE-FAULT) (JUMP-LESS-THAN M-T A-V-PHYSICAL-PAGE-DATA-VALID-LENGTH XCPPG2) ;See if table getting bigger (CALL-GREATER-OR-EQUAL VMA A-V-ADDRESS-SPACE-MAP ILLOP) ;Bigger than space allocated ((A-V-PHYSICAL-PAGE-DATA-VALID-LENGTH) ADD M-T (A-CONSTANT 1)) XCPPG2 ((VMA) M+A+1 MD A-V-PAGE-TABLE-AREA) ;Address PHT2 ((WRITE-MEMORY-DATA-START-WRITE) IOR M-T (A-CONSTANT (BYTE-VALUE PHT2-ACCESS-STATUS-AND-META-BITS 1200))) ;RO (ILLOP-IF-PAGE-FAULT) (JUMP XTRUE) XDPPG (MISC-INST-ENTRY %DELETE-PHYSICAL-PAGE) ; (CALL LOAD-PHYSICAL-MEMORY-SETUP-FROM-SYS-COM) ARG is physical address ((M-B) VMA-PHYS-PAGE-ADDR-PART C-PDL-BUFFER-POINTER-POP);Page frame number PFN too big ((VMA-START-READ) ADD M-B A-V-PHYSICAL-PAGE-DATA) (ILLOP-IF-PAGE-FAULT) ((M-TEM) (BYTE-FIELD 20 0) READ-MEMORY-DATA) ;PHT entry index (JUMP-EQUAL M-TEM (A-CONSTANT 177777) XFALSE) ;Already deleted or wired ((VMA-START-READ M-T) ADD M-TEM A-V-PAGE-TABLE-AREA) (ILLOP-IF-PAGE-FAULT) Swap it out , delete PHT entry XDPPG1 (POPJ-AFTER-NEXT (M-T) A-V-TRUE) ;Done, return T ((VMA) A-V-NIL) ;INSTRUCTIONS MUST LEAVE VMA NON-GARBAGE XPAGE-IN (MISC-INST-ENTRY %PAGE-IN) ((A-DISK-SWAPIN-VIRTUAL-ADDRESS) DPB ;ARG 2 - VIRTUAL PAGE NUMBER C-PDL-BUFFER-POINTER-POP VMA-PAGE-ADDR-PART A-ZERO) (CALL-XCT-NEXT SEARCH-PAGE-HASH-TABLE) ;SEE IF ALREADY IN ((M-T) A-DISK-SWAPIN-VIRTUAL-ADDRESS) (JUMP-IF-BIT-SET-XCT-NEXT PHT1-VALID-BIT READ-MEMORY-DATA XFALSE) ;YES, RETURN NIL ((A-DISK-SWAPIN-PAGE-FRAME) Q-POINTER C-PDL-BUFFER-POINTER-POP) ;ARG 1 - PAGE FRAME (CALL PAGE-IN-GET-MAP-BITS) ;NO, PUT IT IN (CALL-XCT-NEXT PAGE-IN-MAKE-KNOWN) ((A-PAGE-IN-PHT1) (A-CONSTANT (PLUS (BYTE-VALUE PHT1-VALID-BIT 1) (BYTE-VALUE PHT1-SWAP-STATUS-CODE 1)))) (JUMP XDPPG1) ;RETURN T, FIX VMA ;NIL if not swapped in, else PHT1 value, except: ;the modified bit in our value is always up to date, even though that in the PHT1 is not . XPGSTS (MISC-INST-ENTRY %PAGE-STATUS) (CALL-XCT-NEXT SEARCH-PAGE-HASH-TABLE) ((M-T) C-PDL-BUFFER-POINTER-POP) (JUMP-IF-BIT-CLEAR PHT1-VALID-BIT MD XFALSE) (POPJ-IF-BIT-SET-XCT-NEXT PHT1-MODIFIED-BIT MD) ((M-T) DPB MD Q-POINTER (A-CONSTANT (BYTE-VALUE Q-DATA-TYPE DTP-FIX))) If modified bit is set in PHT1 , that must be accurate , so return the PHT1 . ;Otherwise must check the PHT2 to know for sure. ((VMA-START-READ) ADD VMA (A-CONSTANT 1)) ;Get PHT2 (ILLOP-IF-PAGE-FAULT) ((M-TEM) PHT2-MAP-STATUS-CODE READ-MEMORY-DATA) (POPJ-AFTER-NEXT POPJ-LESS M-TEM (A-CONSTANT (EVAL %PHT-MAP-STATUS-READ-WRITE))) If PHT2 implies page is modified , return value with modified - bit set . ((M-T) DPB (M-CONSTANT -1) PHT1-MODIFIED-BIT A-T) XPHYADR (MISC-INST-ENTRY %PHYSICAL-ADDRESS) ( ( VMA - START - READ ) C - PDL - BUFFER - POINTER - POP ) ; ADDRESS THE MAP ; (CHECK-PAGE-READ-NO-INTERRUPT) ;BE SURE INTERRUPT DOESN'T DISTURB MAP ; ((MD) VMA) ;ADDRESS MAP (DELAYS UNTIL READ CYCLE OVER) ( POPJ - AFTER - NEXT ( M - T ) DPB l2 - map - physical - page VMA - PHYS - PAGE - ADDR - PART ( A - CONSTANT ( BYTE - VALUE Q - DATA - TYPE DTP - FIX ) ) ) ( ( M - T ) VMA - LOW - BITS MD A - T ) ((M-C) Q-TYPED-POINTER C-PDL-BUFFER-POINTER-POP) (CALL-XCT-NEXT SEARCH-PAGE-HASH-TABLE) ((M-T) M-C) (JUMP-IF-BIT-CLEAR PHT1-VALID-BIT MD XFALSE) ((VMA-START-READ) ADD VMA (A-CONSTANT 1)) ;Get PHT2 (ILLOP-IF-PAGE-FAULT) (POPJ-AFTER-NEXT (M-T) DPB MD VMA-PHYS-PAGE-ADDR-PART (A-CONSTANT (BYTE-VALUE Q-DATA-TYPE DTP-FIX))) ((M-T) VMA-LOW-BITS M-C A-T) ;PDL-BUFFER LOADING CONVENTIONS: ; 1. THE CURRENT RUNNING FRAME IS ALWAYS COMPLETELY CONTAINED WITHIN THE PDL-BUFFER. ; 2. SO IS ITS CALLING ADI (LOCATED IMMEDIATELY BEFORE IT ON PDL). 3 . POINTERS ASSOCIATED WITH ADI ( SUCH AS MULTIPLE VALUE STORING POINTERS ; AND INDIRECT-ADI POINTERS) MAY POINT AT REGIONS OF THE PDL WHICH ; ARE NOT CONTAINED WITHIN THE PDL-BUFFER. ;CHECKING TO SEE IF PDL-BUFFER NEEDS TO BE REFILLED: ; SINCE M-AP CHANGES MUCH LESS FREQUENTLY THAN THE PDL-BUFFER POINTER ITSELF, ; ALL TESTING FOR PDL-BUFFER DUMPING/REFILLING IS DONE WITH REFERENCE TO M-AP. AS A RESULT , 400 ( OCTAL ) WORDS ( THE MAXIMUM FRAME SIZE ) EXTRA SLOP MUST BE LEFT . ; M-PDL-BUFFER-ACTIVE-QS CONTAINS THE NUMBER OF QS BETWEEN A-PDL-BUFFER-HEAD AND M - AP ( MOMENTARILY , IT MAY BE NEGATIVE ) . WHENEVER M - AP IS CHANGED , M - PDL - BUFFER - ACTIVE - QS MUST LIKEWISE BE ADJUSTED . ; CLEARLY, M-PDL-BUFFER-ACTIVE-QS MUST BE AT LEAST 4 FOR ANY CODE TO BE RUNNABLE. ; IN ADDITION, THE ADI OF THE RUNNING FRAME, IF ANY, MUST ALSO BE IN THE PDL-BUFFER. ; IF M-PDL-BUFFER-ACTIVE-QS IS GREATER THAN THE CONSTANT PDL-BUFFER-LOW-WARNING ( SET TO 4 + MAX LENGTH OF ADI ) , IT MAY SAFELY BE ASSUMED THAT THE ADI , IF ANY , ; IS IN. WHENEVER M - AP IS ADJUSTED DOWNWARD ( POPPED ) , M - AP SHOULD BE ADJUSTED BEFORE ; M-PDL-BUFFER-ACTIVE-QS TESTED, SO THAT M-AP IS AT ITS NEW VALUE IF AND WHEN ; PDL-BUFFER-REFILL IS REACHED. ;ROUTINE TO UNLOAD PDL-BUFFER INTO MAIN MEMORY, MAKING AT LEAST N WDS ; OF ROOM IN PDL BUFFER. GENERAL IDEA IS START AT PDL-BUFFER INDEX A-PDL-BUFFER-HEAD ; AND VIRTUAL ADDRESS A-PDL-BUFFER-VIRTUAL-ADDRESS, WRITING OUT CRUFT AND INCREMENTING BOTH POINTERS . ONE OPTIMIZATION IS WE FIDDLE MAP TO AVOID GOING THRU ; PAGE FAULT HANDLER ON EVERY CYCLE (WHICH WOULDNT QUITE WORK ANYWAY SINCE IT ; WOULD WRITE THE STUFF BACK IN THE PDL-BUFFER). THUS, WE HAVE TO KEEP TRACK OF ; WHICH MAP PAGE WE HAVE HACKED AND PUT IT BACK AT END. ALSO, CHECK IF MOVING TO A NEW PAGE , ETC . PDL-BUFFER-DUMP-RESET-FLAGS ;; Special entrypoint for QMRCL and MMCAL4, which, for convenience and speed, require ;; M-FLAGS to be cleared. ((M-FLAGS) SELECTIVE-DEPOSIT M-FLAGS M-FLAGS-EXCEPT-PROCESSOR-FLAGS A-ZERO) PDL-BUFFER-DUMP ((M-2) (A-CONSTANT PDL-BUFFER-HIGH-LIMIT)) (CALL-NOT-EQUAL M-2 A-PDL-BUFFER-HIGH-WARNING TRAP) ;PUSH-DOWN CAPACITY EXCEEDED I.E. ALREADY NEAR END , THERE IS PROBABLY JUST ;ENOUGH SPACE LEFT TO DUMP WHAT'S IN THE PDL BUFFER NOW ;HERE I AM ASSUMING THAT A-PDL-BUFFER-HIGH-WARNING IS GUARANTEED ;NOT TO COME OUT NEGATIVE AFTER PDL-BUFFER-MAKE-ROOM RETURNS, ;BECAUSE OF THE CHECK ABOVE. THIS USED TO BE CHECKED. ;ARG IN M-2 -> HIGHEST "SATISFACTORY" VALUE FOR M-PDL-BUFFER-ACTIVE-QS. ; COMMON VALUES ARE PDL-BUFFER-HIGH-LIMIT TO UNBLOAT PDL-BUFFER OR ; 0 TO COMPLETELY DUMP PDL-BUFFER (THRU M-AP) OR - ( PP - M - AP ) [ MINUS SIZE OF ACTIVE FRAME ] TO REALLY COMPLETELY DUMP PDL - BUFFER ;;; Clobbers M-1. #-lambda(begin-comment) PDL-BUFFER-MAKE-ROOM ;ARG IN M-2 ((A-PDLB-TEM) PDL-BUFFER-INDEX) ;PRESERVE.. P-B-MR0 (JUMP-LESS-OR-EQUAL M-PDL-BUFFER-ACTIVE-QS A-2 P-B-X1) ;If nothing to do, done ((PDL-BUFFER-INDEX) A-PDL-BUFFER-HEAD) ;Starting pdl-buffer address ((VMA m-lam) A-PDL-BUFFER-VIRTUAL-ADDRESS) ;Starting virtual-memory address ((M-TEM) SUB M-PDL-BUFFER-ACTIVE-QS A-2) ;Number locations to do total ((A-PDL-FINAL-VMA) ADD m-lam A-TEM) P-B-MR1 ((WRITE-MEMORY-DATA-START-WRITE-FORCE) C-PDL-BUFFER-INDEX) ;Write next Q into memory (JUMP-IF-PAGE-FAULT P-B-MR-PF) ;Interpreter now puts forwards into stack frames. So can lexical scoping in compiled code. ; (DISPATCH Q-DATA-TYPE WRITE-MEMORY-DATA D-ILLOP-IF-BAD-DATA-TYPE) ;Error-check stuff being written (GC-WRITE-TEST (I-ARG 1)) ;Check for writing ptr to extra-pdl If traps , will clean up & return to P - B - MR0 unfortunately , various paths in gc - write - test can clobber M - LAM , so we have to depend on VMA . ((VMA m-lam) ADD VMA (A-CONSTANT 1)) ;Close loop (JUMP-LESS-THAN-XCT-NEXT m-lam A-PDL-FINAL-VMA P-B-MR1) ((PDL-BUFFER-INDEX) ADD PDL-BUFFER-INDEX (A-CONSTANT 1)) ((M-TEM) SUB m-lam A-PDL-BUFFER-VIRTUAL-ADDRESS) ;Number of locations dumped ((M-PDL-BUFFER-ACTIVE-QS) SUB M-PDL-BUFFER-ACTIVE-QS A-TEM) ((A-PDL-BUFFER-VIRTUAL-ADDRESS) m-lam) ((A-PDL-BUFFER-HEAD) PDL-BUFFER-INDEX) ;drops-thru #-lambda(end-comment) #-exp(BEGIN-COMMENT) PDL-BUFFER-MAKE-ROOM ;ARG IN M-2 ((A-PDLB-TEM) PDL-BUFFER-INDEX) ;PRESERVE.. P-B-MR0 (JUMP-LESS-OR-EQUAL M-PDL-BUFFER-ACTIVE-QS A-2 P-B-X1) ;If nothing to do, done ((VMA-START-READ) A-PDL-BUFFER-VIRTUAL-ADDRESS) ;Take a read cycle to make sure 2nd lvl map set up , etc Note a reference is guaranteed to set up 2nd level map ;even if it turns out to be in the pdl-buffer and no main memory ;cycle is made. * * * bug ! this is present in CADR too . Q - R could get clobbered by extra pdl trap ! ! ; gee, maybe not, but boy is it marginal.. ((MD Q-R) VMA) ;Address the map, Q-R saves addr (no-op) ;allow time ((M-1) l2-map-control) ;Save correct map contents ((vma-write-L2-MAP-CONTROL) IOR M-1 ;Turn on access (A-CONSTANT (BYTE-VALUE MAP2C-ACCESS-CODE 3))) ;R/W ((M-TEM) DPB (M-CONSTANT -1) ALL-BUT-VMA-LOW-BITS A-PDL-BUFFER-VIRTUAL-ADDRESS) ((A-PDL-FINAL-VMA) SUB M-ZERO A-TEM) ;Number locations left in page ((M-TEM) SUB M-PDL-BUFFER-ACTIVE-QS A-2) ;Number locations to do total (JUMP-GREATER-OR-EQUAL M-TEM A-PDL-FINAL-VMA P-B-MR3) ((A-PDL-FINAL-VMA) M-TEM) ;Don't do a full page P-B-MR3 ((PDL-BUFFER-INDEX) A-PDL-BUFFER-HEAD) ;Starting pdl-buffer address ((VMA m-lam) A-PDL-BUFFER-VIRTUAL-ADDRESS) ;Starting virtual-memory address ((A-PDL-FINAL-VMA) ADD m-lam A-PDL-FINAL-VMA) ;Ending virtual-memory address +1 P-B-MR1 ((WRITE-MEMORY-DATA-START-WRITE) C-PDL-BUFFER-INDEX) ;Write next Q into memory (ILLOP-IF-PAGE-FAULT) ;Write-access supposedly turned on. ;Interpreter now puts forwards into stack frames. So can lexical scoping in compiled code. ; (DISPATCH Q-DATA-TYPE WRITE-MEMORY-DATA D-ILLOP-IF-BAD-DATA-TYPE) ;Error-check stuff being written (GC-WRITE-TEST (I-ARG 1)) ;Check for writing ptr to extra-pdl If traps , will clean up & return to P - B - MR0 ((VMA m-lam) ADD VMA (A-CONSTANT 1)) ;Close loop (JUMP-LESS-THAN-XCT-NEXT m-lam A-PDL-FINAL-VMA P-B-MR1) ((PDL-BUFFER-INDEX) ADD PDL-BUFFER-INDEX (A-CONSTANT 1)) ;Clean up and restore the map. ((M-TEM) SUB m-lam A-PDL-BUFFER-VIRTUAL-ADDRESS) ;Number of locations dumped ((M-PDL-BUFFER-ACTIVE-QS) SUB M-PDL-BUFFER-ACTIVE-QS A-TEM) ((A-PDL-BUFFER-VIRTUAL-ADDRESS) m-lam) ((A-PDL-BUFFER-HEAD) PDL-BUFFER-INDEX) ((MD) Q-R) ;Address the map (JUMP-GREATER-THAN-XCT-NEXT ;Loop back for next page M-PDL-BUFFER-ACTIVE-QS A-2 P-B-MR0) ((vma-write-l2-map-control) M-1) ;Restore the map for this page ;drops through #-exp(END-COMMENT) ;drops in. ;Here when we're done. This exit used by both PDL-BUFFER-MAKE-ROOM and PDL-BUFFER-REFILL. Do n't leave VMA nil . ((m-2) a-pdl-buffer-virtual-address) (call-less-than m-2 a-qlpdlo illop) ;not in range of PDL ((M-2) A-QLPDLH) ;Recompute A-PDL-BUFFER-HIGH-WARNING (call-less-or-equal m-2 a-pdl-buffer-virtual-address illop) ;not in range of PDL ((M-2) SUB M-2 A-PDL-BUFFER-VIRTUAL-ADDRESS) ((M-2) SUB M-2 (A-CONSTANT PDL-BUFFER-SIZE-IN-WORDS)) ;Result negative if within ; pdl-buffer size of the end of the regular-pdl in virt mem (JUMP-LESS-THAN M-2 A-ZERO P-B-SL-1) Enough room , allow P.B. to fill (A-PDL-BUFFER-HIGH-WARNING) (A-CONSTANT PDL-BUFFER-HIGH-LIMIT)) ((PDL-BUFFER-INDEX) A-PDLB-TEM) ;Restore ;Getting near the end of the stack. Set A-PDL-BUFFER-HIGH-WARNING ;so that we will trap to PDL-BUFFER-DUMP before getting more stuff ;into the pdl buffer than there is room to store into virtual memory. ;Note that this result can actually be negative if we are currently ;in the process of taking a pdl-overflow trap. P-B-SL-1(POPJ-AFTER-NEXT (A-PDL-BUFFER-HIGH-WARNING) ADD M-2 (A-CONSTANT PDL-BUFFER-HIGH-LIMIT)) ((PDL-BUFFER-INDEX) A-PDLB-TEM) ;Restore ;Attempt to refill pdl-buffer from virtual memory such that M - PDL - BUFFER - ACTIVE - QS is at least PDL - BUFFER - LOW - WARNING . #-lambda(begin-comment) PDL-BUFFER-REFILL ((A-PDLB-TEM) PDL-BUFFER-INDEX) ;Preserve PI ((M-2) A-QLPDLO) ;Get base address of pdl into M memory P-R-0 (JUMP-GREATER-OR-EQUAL M-2 A-PDL-BUFFER-VIRTUAL-ADDRESS P-R-AT-BOTTOM) ;No more pdl to reload, exit (JUMP-GREATER-OR-EQUAL M-PDL-BUFFER-ACTIVE-QS (A-CONSTANT PDL-BUFFER-LOW-WARNING) P-R-AT-BOTTOM) ;Enough in there to win ((M-TEM) SUB M-PDL-BUFFER-ACTIVE-QS ;Negative number of words to do total (A-CONSTANT PDL-BUFFER-LOW-WARNING)) ((M-1) SUB M-2 A-PDL-BUFFER-VIRTUAL-ADDRESS) ;Negative number of words left in pdl (JUMP-GREATER-OR-EQUAL M-TEM A-1 P-R-2) ((M-TEM) M-1) number of words for those reasons ( -1 ) ((VMA m-lam) A-PDL-BUFFER-VIRTUAL-ADDRESS) ;Initial virtual-memory address +1 Initial P.B. address +1 P-R-1 ((VMA-START-READ-FORCE m-lam) SUB m-lam (A-CONSTANT 1)) (JUMP-IF-PAGE-FAULT P-R-PF) ((PDL-BUFFER-INDEX) SUB PDL-BUFFER-INDEX (A-CONSTANT 1)) (DISPATCH Q-DATA-TYPE-PLUS-ONE-BIT ;Transport the data just read from memory DISPATCH-ON-MAP-19 Running cleanup handler first ((C-PDL-BUFFER-INDEX) READ-MEMORY-DATA) (JUMP-LESS-THAN-XCT-NEXT M-ZERO A-PDL-LOOP-COUNT P-R-1) ((A-PDL-LOOP-COUNT) ADD (M-CONSTANT -1) A-PDL-LOOP-COUNT) ;Now clean up (call-not-equal vma a-lam illop) ((M-TEM) SUB VMA A-PDL-BUFFER-VIRTUAL-ADDRESS) ;Minus number of Q's moved ((M-PDL-BUFFER-ACTIVE-QS) SUB M-PDL-BUFFER-ACTIVE-QS A-TEM) ;Increase this ((A-PDL-BUFFER-VIRTUAL-ADDRESS) m-lam) ((A-PDL-BUFFER-HEAD) PDL-BUFFER-INDEX) ;DROP THRU #-lambda(end-comment) #-exp(BEGIN-COMMENT) PDL-BUFFER-REFILL ((A-PDLB-TEM) PDL-BUFFER-INDEX) ;Preserve PI ((M-2) A-QLPDLO) ;Get base address of pdl into M memory ;this is just left in M-2 as a constant in below code. P-R-0 (JUMP-GREATER-OR-EQUAL M-2 A-PDL-BUFFER-VIRTUAL-ADDRESS P-R-AT-BOTTOM) ;No more pdl to reload, exit (JUMP-GREATER-OR-EQUAL M-PDL-BUFFER-ACTIVE-QS (A-CONSTANT PDL-BUFFER-LOW-WARNING) P-R-AT-BOTTOM) ;Enough in there to win ((VMA-START-READ) ADD (M-CONSTANT -1) A-PDL-BUFFER-VIRTUAL-ADDRESS) Take cycle to assure 2nd lvl map set up ;bug!? Can Q-R get clobbered?? *** well maybe its OK, but... ((MD Q-R) VMA) ;Address the map (no-op) ;allow time ((M-PGF-TEM) l2-map-control) ;Save correct map contents Turn on access to mem which shadows pdl buf (A-CONSTANT (BYTE-VALUE MAP2C-ACCESS-CODE 3))) ;R/W ((M-TEM) SUB M-PDL-BUFFER-ACTIVE-QS ;Negative number of words to do total (A-CONSTANT PDL-BUFFER-LOW-WARNING)) ((M-1) SUB M-2 A-PDL-BUFFER-VIRTUAL-ADDRESS) ;Negative number of words left in pdl (JUMP-GREATER-OR-EQUAL M-TEM A-1 P-R-2) ((M-TEM) M-1) number of words for those reasons ((A-PDL-LOOP-COUNT) VMA-LOW-BITS Q-R) ;Number of words on this page -1 (JUMP-GREATER-THAN M-TEM A-PDL-LOOP-COUNT P-R-3) ((A-PDL-LOOP-COUNT) SUB M-TEM (A-CONSTANT 1)) ;Won't be able to do full page P-R-3 ((VMA m-lam) A-PDL-BUFFER-VIRTUAL-ADDRESS) ;Initial virtual-memory address +1 Initial P.B. address +1 P-R-1 ((VMA-START-READ m-lam) SUB m-lam (A-CONSTANT 1)) (ILLOP-IF-PAGE-FAULT) ;Map should be hacked ((PDL-BUFFER-INDEX) SUB PDL-BUFFER-INDEX (A-CONSTANT 1)) (DISPATCH Q-DATA-TYPE-PLUS-ONE-BIT ;Transport the data just read from memory DISPATCH-ON-MAP-19 Running cleanup handler first ((C-PDL-BUFFER-INDEX) READ-MEMORY-DATA) (JUMP-LESS-THAN-XCT-NEXT M-ZERO A-PDL-LOOP-COUNT P-R-1) ((A-PDL-LOOP-COUNT) ADD (M-CONSTANT -1) A-PDL-LOOP-COUNT) ;Now clean up (call-not-equal vma a-lam illop) ((M-TEM) SUB VMA A-PDL-BUFFER-VIRTUAL-ADDRESS) ;Minus number of Q's moved ((M-PDL-BUFFER-ACTIVE-QS) SUB M-PDL-BUFFER-ACTIVE-QS A-TEM) ;Increase this ((A-PDL-BUFFER-VIRTUAL-ADDRESS) m-lam) ((A-PDL-BUFFER-HEAD) PDL-BUFFER-INDEX) ((MD) Q-R) ;Address the map (JUMP-LESS-THAN-XCT-NEXT ;Loop back for next page M-2 A-PDL-BUFFER-VIRTUAL-ADDRESS P-R-0) ; unless at bottom of pdl ((vma-write-l2-map-control) M-PGF-TEM) ;Restore the map #-exp(END-COMMENT) ;DROPS IN. P-R-AT-BOTTOM (JUMP-XCT-NEXT P-B-X1) (CALL-LESS-THAN M-PDL-BUFFER-ACTIVE-QS (A-CONSTANT 4) ILLOP) ;Over pop Here if transport required while reloading pdl . Clean up first . ;Note that the transport happens with the bottom pdl word not stored into ;yet. This should be all right. PB-TRANS(call-not-equal vma a-lam illop) ((M-TEM) SUB m-lam A-PDL-BUFFER-VIRTUAL-ADDRESS) ;Minus number of Q's moved ((M-PDL-BUFFER-ACTIVE-QS) SUB M-PDL-BUFFER-ACTIVE-QS A-TEM) ;Increase this ((A-PDL-BUFFER-VIRTUAL-ADDRESS) m-lam) ((A-PDL-BUFFER-HEAD) PDL-BUFFER-INDEX) ((C-PDL-BUFFER-POINTER-PUSH) A-PDLB-TEM);Save stuff momentarily #-exp(begin-comment) ((C-PDL-BUFFER-POINTER-PUSH) MD) ((MD) VMA) ;Address the map (no-op) ((vma-write-l2-map-control) M-PGF-TEM) ;Restore the map ((VMA) MD) ;Restore VMA ((MD) C-PDL-BUFFER-POINTER-POP) ;Restore MD #-exp(end-comment) ;This used to be just TRANSPORT. Changed to allow EVCPs on PDL. There is some loss of error checking ( for DTP - NULL , etc ) involved in this , so we may eventually want another ;dispatch table. (DISPATCH TRANSPORT-NO-EVCP-FOR-PDL-RELOAD MD) ;Now invoke the transporter ((A-PDLB-TEM) C-PDL-BUFFER-POINTER-POP) ;Restore A-PDLB-TEM, lost by transporter ((PDL-BUFFER-INDEX) A-PDL-BUFFER-HEAD) (JUMP-XCT-NEXT P-R-0) ;Now re-start fast loop for next word ((C-PDL-BUFFER-INDEX) MD) ;Put the transported datum on the pdl TOOK PAGE FAULT DUMPING PDL BUFFER . CLEAN UP THEN PROCESS IT . (call-not-equal vma a-lam illop) ((M-TEM) SUB m-lam A-PDL-BUFFER-VIRTUAL-ADDRESS) ;Number of locations dumped ((M-PDL-BUFFER-ACTIVE-QS) SUB M-PDL-BUFFER-ACTIVE-QS A-TEM) ((A-PDL-BUFFER-VIRTUAL-ADDRESS) m-lam) ((A-PDL-BUFFER-HEAD) PDL-BUFFER-INDEX) (CHECK-PAGE-WRITE-NO-INTERRUPT) (JUMP P-B-MR0) P-R-PF ;TOOK PAGE FAULT RELOADING PDL BUFFER, CLEAR UP THEN PROCESS IT. (call-not-equal vma a-lam illop) ((M-LAM) ADD m-lam (A-CONSTANT 1)) ;LAST ACTUALLY TRANSFERRED. ((M-TEM) SUB M-LAM A-PDL-BUFFER-VIRTUAL-ADDRESS) ;Minus number of Q's moved ((M-PDL-BUFFER-ACTIVE-QS) SUB M-PDL-BUFFER-ACTIVE-QS A-TEM) ;Increase this ((A-PDL-BUFFER-VIRTUAL-ADDRESS) M-LAM) ((A-PDL-BUFFER-HEAD) PDL-BUFFER-INDEX) (CHECK-PAGE-READ-NO-INTERRUPT) (JUMP P-R-0) ))
null
https://raw.githubusercontent.com/jrm-code-project/LISP-Machine/0a448d27f40761fafabe5775ffc550637be537b2/lambda/pace/page-fault.lisp
lisp
Base:8 ; : ZL -*- The per page volatility bits for the explorer are in L2-MAP-CONTROL<12.:11.>, but on the lambda its L2-MAP-CONTROL<1:0>. Therefore, where ever we write L2-MAP-CONTROL, put in another instruction for the explorer to copy This bit needs to be correctly set when regions are allocated or flipped. The region volatility bits stored in the L1-MAP are the same place and have the same meanings. This may have to be replaced by a thing to set all of the oldspace bits by running through the region tables. -no, would not win much to boot with oldspace in existance. used as a SOURCE. No NO-OP is necessary if map is used as a DESTINATION, however. page fault handler Its just that it may be shifted to different places in the word in the various EXCEPTIONS: THE A-PGF-MUMBLE REGISTERS ARE CLOBBERED. ONLY THE PAGE FAULT ROUTINES SHOULD USE THEM. M-TEM, A-TEM1, A-TEM2, AND A-TEM3 ARE CLOBBERED. THEY ARE SUPER-TEMPORARY. THE PDL-BUFFER-INDEX ISN'T CLOBBERED, BUT IT SHOULD BE. IF AN INTERRUPT OCCURS, IT HAS ALMOST NO SIDE-EFFECTS OTHER THAN WHAT IS SUCCESSFULLY COMPLETED, BUT EFFECTIVELY BEFORE A READ CYCLE. gc bits same between lambda and explorer DEFINITIONS OF FIELDS IN THE MAP HARDWARE BITS IN MEMORY-MAP-DATA. (DEF-DATA-FIELD MAP-READ-FAULT-BIT 1 30.) ;this symbol not used (DEF-DATA-FIELD MAP-WRITE-FAULT-BIT 1 31.) ;this symbol not used (DEF-DATA-FIELD MAP-PHYSICAL-PAGE-NUMBER 14. 0) THE HIGH TWO OF THESE ARE HACKABLE BY ; DISPATCH INSTRUCTION ;THE REST ARE JUST FOR SOFTWARE TO LOOK AT (DEF-DATA-FIELD MAP-STATUS-CODE 3 20.) NOTE BIT 22 IS IN TWO FIELDS (DEF-DATA-FIELD MAP-FIRST-LEVEL-MAP 5 24.) ;NOTE NOT THE SAME AS WHERE IT WRITES HARDWARE PERMITS ( AT LEAST ) READ ACCESS ; IF THIS BIT SET. czrr , inimap , phys - mem - read (DEF-DATA-FIELD CADR-MAP-STATUS-CODE 3 20.) used in inimap and phys - mem - read load - l2 - map - from - cadr - physical load - l2 - map - from - cadr - physical , czrr hardware permits (at least) read access starts memory cycle) this bit used by hardware instead of above bit. This allows PDL buffer routines to hack without clobbering map, etc. explorer has below fields in hardware. We keep bits in usual place, frotzing them just before loading into hardware in LOAD-L2-MAP-FROM-CADR-PHYSICAL. Note forced-bit is same for both, so definition above suffices. by DISPATCH-ON-MAP-18 feature. On LAMBDA and EXPLORER, the hardware function is function comes instead from the level-1 map. these definitions reduce need to conditionalize things per processor as well as being more modular. (DEF-DATA-FIELD MAP-WRITE-ENABLE-SECOND-LEVEL-WRITE 1 25.) NOTE NOT THE SAME AS WHERE IT READS DEFINITIONS OF FIELDS IN PAGE HASH TABLE SET IF PAGE MODIFIED DEFINITIONS OF FIELDS IN THE ADDRESS VIRTUAL PAGE NUMBER PHYSICAL PAGE NUMBER THESE COMMENTS APPLY TO SEQUENCE BREAK NOTE THAT THIS ORDERING ALLOWS AN EFFECTIVE READ-PAUSE-WRITE CYCLE TO BE DONE JUST BY DOING A READ THEN A WRITE, EVEN THOUGH AFTER EACH CYCLE IS STARTED INTERRUPTS ARE CHECKED. To request a sequence-break, do ((LOCATION-COUNTER) LOCATION-COUNTER) ;Assure PC gets fetched may persist even if memory cycle completed ok. Flush on no SB req TURN INTO ILLOP IF TRAP AT BAD TIME NOTE WOULD PROBABLY DIE LATER ANYWAY ---new run light ---new run light STORE CURRENT STATUS AND SWAP SPECIAL-PDL Transmit NIL ---new run light ---end of new run light STORE CURRENT STATUS AND SWAP SPECIAL-PDL try to return to prev stack group (can't go to scheduler since we may have interrupted it with inhibit scheduling flag on) Transmit NIL IF NO PG FAULT, TAKE INTERRUPT PUSHJ HERE ON READ CYCLE PAGE FAULT WHEN DESIRE NOT TO TAKE INTERRUPT GUARANTEED TO RETURN WITHOUT ANY INTERRUPTS HAPPENING, OR ELSE TO GO TO ILLOP BUT SEE THE COMMENTS ON THE DEFINITION OF CHECK-PAGE-READ-NO-INTERRUPT ADDRESS THE MAP give map time to set up. IF IT RETURNS HERE, WE RESTART THE READ REFERENCE DIDN'T ENTIRELY SUCCEED, TRY AGAIN ADDRESS THE MAP give map time to set up. IF IT RETURNS HERE, WE RESTART THE READ REFERENCE DIDN'T ENTIRELY SUCCEED, TRY AGAIN PGF-W-SB(declare (clobbers a-tem)) see note above (JUMP SBSER) NO PAGE FAULT , THEN TAKE INTERRUPT Interrupts on write cycles have to be sure to do a full vma-start-write on the GUARANTEED TO RETURN WITH NO INTERRUPT, OR TO GO TO ILLOP BUT SEE THE COMMENTS ON THE DEFINITION OF CHECK-PAGE-READ-NO-INTERRUPT ADDRESS THE MAP give map time to set up. This instruction substituted for no-op to make code less marginal, ie, dependant on all paths in d-pgf getting to pgf-save. IF IT RETURNS HERE, WE RESTART THE WRITE REFERENCE DIDN'T ENTIRELY SUCCEED, TRY AGAIN ADDRESS THE MAP give map time to set up. This instruction substituted for no-op to make code less marginal, ie, dependant on all paths in d-pgf getting to pgf-save. IF IT RETURNS HERE, WE RESTART THE WRITE REFERENCE DIDN'T ENTIRELY SUCCEED, TRY AGAIN DISPATCH ON MAP STATUS DISPATCH ON MAP STATUS 2 WRITE IN READ ONLY , note jump not PUSHJ 3 WRITE IN READ / WRITE FIRST ; * * * 5 MAY BE IN PDL BUFFER , note jump . 6 POSSIBLE MAR BREAK , note jump . THIS DISPATCH IS FOR GETTING META BITS FROM MAP[MD] WITHOUT SWAPPING IN this runs at "page-fault" level and had better not be called by anything already within the page-fault handler or variables will be overstored. It can be called from extra-pdl-trap, which can be called from pdl-buffer-dump, but fortunately, none of that is within the page fault level. Save M-A, M-B, M-T LEVEL-1-MAP-MISS also gets it out of here! address of reference This needs to change with new fixed area scheme. Right now fixed areas are legislated to be contain homogeneous storage. Check for A-memory or I/O address Normal address, get meta bits from region Region not found Fetch meta bits save before gets clobbered. also right adjust Complement volatility. address map CLEAR OUT TO REDUCE CONFUSION Restore M-A, M-B, M-T PDL BUFFER HANDLING CONVENTIONS: READ REFERENCE TO LOCATION THAT MAY BE IN THE PDL BUFFER *** THIS CODE COULD USE BUMMING *** COMPUTE # ACTIVE WDS IN PDL-BUFFER GET ADDRESS BEING REFERENCED SANS EXTRA BITS GREATER BECAUSE READ REFERENCE TO LOCATION THAT IS IN THE PDL BUFFER GET RELATIVE PDL LOC REFERENCED DON'T CLOBBER PDL-BUFFER-INDEX READ OUT THAT LOCATION VALID-IF-FORCE should be on for may-be-in-pdl-buffer PDL-FORCE feature does not work on explorer.. so.. SAVE CORRECT MAP CONTENTS TURN ON ACCESS R/W Maybe putting this insn here will avoid hardware lossage?? READ OUT THAT LOCATION SAVE CONTENTS ADDRESS THE MAP RESTORE THE MAP RESTORE REGISTERS AND RETURN WRITE REFERENCE TO LOCATION THAT MAY BE IN THE PDL BUFFER *** THIS CODE COULD USE BUMMING *** COMPUTE # ACTIVE WDS IN PDL-BUFFER HIGHEST VIRT LOC IN P.B, GET ADDRESS BEING REFERENCED SANS EXTRA BITS GREATER BECAUSE WRITE REFERENCE TO LOCATION THAT IS IN THE PDL BUFFER GET RELATIVE PDL LOC REFERENCED DON'T CLOBBER PDL-BUFFER-INDEX DO THE WRITE ((PDL-BUFFER-INDEX) A-PGF-A) ;RESTORE REGS AND RETURN FROM FAULT address the map since dropping through drop through ** note ** volatility not maintained for PDL pages!! ** not necessarily true: this can only be reached by (check-page-write) which is always followed by a gc-write-test in the caller. WRITE INTO THAT LOCATION VALID-IF-FORCE should be on for p.b. pages. SAVE CORRECT MAP CONTENTS TURN ON ACCESS R/W WRITE INTO THAT LOCATION ADDRESS THE MAP RESTORE THE MAP RESTORE REGISTERS AND RETURN return address in pgf-map-miss Figure out how to deal with volatility here. (call pgf-pdl-check-immediately) ((a-pdl-buffer-write-faults) add a-pdl-buffer-write-faults m-zero alu-carry-in-one) ((pdl-buffer-index) a-pgf-a) Tempoary map checking code CHECK-WIRED-LEVEL-2-MAP-CONTROL ((M-T) MD) ((MD) SETZ) CHECK-WIRED-LEVEL-2-MAP-CONTROL-1 (CALL-EQUAL L2-MAP-CONTROL A-ZERO ILLOP-DEBUG) (JUMP-LESS-THAN MD A-A CHECK-WIRED-LEVEL-2-MAP-CONTROL-1) ((MD) M-T) CHECK-WIRED-LEVEL-2-MAP-CONTROL-2 end of tempoary code Page fault level routines call these in order to be able to take map-reload-type page faults recursively. Even after saving here, any recursive page fault which touched the disk would lose since these variables would get stored over by the call to DISK-PGF-SAVE at DISK-SWAP-HANDLER. Save page fault handler variables in case of recursive fault Clobbered by disk routine .. Restore registers ROUTINE TO HANDLE LEVEL-1 MAP MISSES. CALLED FROM PGF-MAP-MISS AND FROM GET-MAP-BITS. dont clobber meta bits. note no meta bits. (see uc-initialization) DON'T WRITE MAP IF NO PREVIOUS (NO-OP) Tempoary map checking code CHECK-PGF-L1-L2-MAP-CONTROL ((MD) SETZ) CHECK-PGF-L1-L2-MAP-CONTROL-1 (CALL-EQUAL L2-MAP-CONTROL A-ZERO ILLOP-DEBUG) (JUMP-LESS-THAN MD A-A CHECK-PGF-L1-L2-MAP-CONTROL-1) CHECK-PGF-L1-L2-MAP-CONTROL-2 end of tempoary code DROP THROUGH ADVANCE-SECOND-LEVEL-MAP-REUSE-POINTER, AND RETURN ROUTINE TO ADVANCE SECOND LEVEL MAP REUSE POINTER, WITH CARE. CLOBBERS Q-R WRAP AROUND TO AFTER THE WIRED ONES ADDRESS SANS EXTRA BITS ADDRESS SANS EXTRA BITS "direct mapping" cant win on LAMBDA. Someday, maybe we'll have some sort of main memory tables to allow various things to get mapped in. However, if A-LOWEST-DIRECT-VIRTUAL-ADDRESS has been moved down, we stick in the medium resolution color. this page left blank so they will trap. See below. Scratch block. RW ACCESS , STATUS=4 , NO AREA TRAPS , REP TYPE 0 GO RETRY REFERENCE virtual address >=177,,400000. GO RETRY REFERENCE map2c-access-status-and-meta-bits is right adj. relative adr within range relative page number within range. high bits determine byte no to select. store byte code. map a single page at base of TV slot space. relative adr within range relative page number within range relative adr within range relative page number within range ACTUALLY GUYS, STEVE WARD AT MIT WANTS TO USE OUR COLOR BOARD ON THE EXPLORER. #-lambda (begin-comment) below anything reasonable fall thru in case of color-map, registers, and prom. base page number within slot space page number within slot space #-lambda (end-comment) REFERENCE TO ORDINARY VIRTUAL ADDRESS. LOOK IN PAGE HASH TABLE DISPATCH ON SWAP STATUS DISPATCH ON SWAP STATUS Here on reference to page containing the MAR'ed location. In the case of a write, the data to be written will be on the stack. A write is continued by simulation in the error handler, followed by same continuation as a read. If can't take trap now Check address bounds False alarm, simulate the memory cycle, but it might be in the PDL buffer, so simulate that trap. Anyway that code is pretty experienced at simulating memory cycles. sg-proceed-micro-pc which will make PGF-R return. sg-proceed-micro-pc, which will make PGF-W return HERE ON REFERENCE TO LOCATION MAPPED INTO A/M SCRATCHPAD, ADDRESS IN M-T FLUSH RETRY-CYCLE RETURN NOTE LOWEST-A-MEM-VIRTUAL-ADDRESS NOBODY ELSE WILL PUT BACK VMA ((M-A) A-V-NIL) ; Get a - mem address being bound . In range for EVCP hacking ? Get low 10 bits (JUMP-GREATER-OR-EQUAL VMA (A-CONSTANT (A-MEM-LOC A-END-Q-POINTERS)) ; We are binding or unbinding and must hack the EVCP vector . ; " restore " all info saved by PGF - W to its real home ;; or else save it on the stack ;; so we can be in a position to take recursive page faults. ;; Note: A-PGF-WMD can be untyped data, but since we ;; do not allow sequence breaks herein, that can't cause trouble. ;; Also, since this happens only from binding or unbinding, ;; we need not fear that PDL-BUFFER-POINTER doesn't really ;; point at the top of the stack. (CALL PGF-RESTORE) ((C-PDL-BUFFER-POINTER-PUSH) A-PGF-WMD) ((C-PDL-BUFFER-POINTER-PUSH) A-PGF-VMA) ;Now we can take page faults again! Get the current EVCP out of the EVCP vector . (CHECK-PAGE-READ) (DISPATCH TRANSPORT-NO-EVCP READ-MEMORY-DATA) Write current contents of a - mem location into the EVCP , if any . NOTE LOWEST - A - MEM - VIRTUAL - ADDRESS MUST BE 0 MODULO A - MEMORY SIZE (CHECK-PAGE-WRITE) (GC-WRITE-TEST) Replace the current EVCP with the old one , or NIL if not an EVCP . ((MD) C-PDL-BUFFER-POINTER) ((M-TEM) Q-DATA-TYPE MD) PGF-SA-BIND-NEW-EVCP) (CHECK-PAGE-WRITE) ((M-TEM) Q-DATA-TYPE M-TEM) which cant work anyway. Furthermore, the call to the transporter below could lose due to numerous reasons. (CALL PGF-RESTORE) ((C-PDL-BUFFER-POINTER-PUSH) A-PGF-VMA) ;Now safe to take page faults recursively. Get contents of the new EVCP , and put that in a mem instead of the EVCP . (CHECK-PAGE-READ) (DISPATCH TRANSPORT-NO-EVCP) (CALL-XCT-NEXT PGF-SAVE) (CALL-XCT-NEXT PGF-SA-W-NOT-BINDING) ((A-PGF-VMA) C-PDL-BUFFER-POINTER-POP) ;Now we are inside a page fault again! Finish writing new contents into A memory . ((MD) C-PDL-BUFFER-POINTER-POP) ((A-PGF-VMA) C-PDL-BUFFER-POINTER-POP) ((A-PGF-WMD) C-PDL-BUFFER-POINTER-POP) (CALL PGF-SAVE-1) LOCN REALLY IN M-MEM. NOBODY ELSE WILL PUT BACK VMA NOBODY ELSE WILL PUT BACK VMA Write in read-only. Should not get here on a read. If this is a CHECK-PAGE-WRITE-FORCE, do it anyway. Not continuable! Forced write in nominally read-only area. Find PHT entry to mark page as modified not found? wait for cycle to finish Force read/write access then reset the maps to read-only and return without starting another write cycle. Do the write Address map again map access code rd-only Set read-only access again Memory cycle completed, return FIND PAGE HASH TABLE ENTRY, CHANGE STATUS TO READ/WRITE, AND RELOAD MAP NOT IN PHT?? MARK PAGE MODIFIED RESTORE A REG DURING MEM CYCLE NORMAL STATUS ADDRESS THE MAP (no xct-next to allow map to set up) REFERENCE TO PAGE THAT WAS PREPAGED AND HASN'T BEEN TOUCHED YET. GRAB IT. REFERENCE TO PAGE MARKED FLUSHABLE. WE WANT THIS PAGE AFTER ALL, CHANGE BACK TO NORMAL drop through THEN DROP THROUGH RELOAD HARDWARE MAP FROM PAGE HASH TABLE ADDRESS THE MAP allow time. ABOUT TO CLOBBER GET SECOND WORD OF PHT ENTRY RESTORE REGS DURING MEM CYCLE VERIFY THE BITS This will go to ILLOP if this is a page of a free region address map (no xct-next to allow map time) ROUTINE TO LOOK FOR PAGE ADDRESSED BY M-T IN THE PAGE HASH TABLE RETURNS WITH VMA AND READ-MEMORY-DATA POINTING TO PHT1 WORD, OF READ-MEMORY-DATA ZERO. IN THIS CASE, THE SWAP STATUS FIELD OF READ-MEMORY-DATA WILL ALSO BE ZERO. CLOBBERS M-A, M-B, M-T, A-TEM1, A-TEM3 a-tem3  virtual-page-number (m-t) old version below. M-T := hash (M-T) Save for comparison below. Get PHT1 entry. Supposed to be wired. Bump index for next iteration. Compare page numbers. I suspected that the old hash function (below) was not performing since it was written. I made some measurements of typical collision rates, and discovered that the simple "XOR the low bits with the high bits" outperforms more intricate functions by a significant amount. This function produces Foo. Somewhere in the system someone depends on some property of the old hash algorithm. I'm going to wimp out and revert it. compute-page-hash ; 15 bits assures reasonable hashing for up to 4 megawords of memory . High 15 bits of page number . ((m-t) and m-t a-pht-index-mask) pht-wraparound ((m-t) sub m-t a-pht-index-limit) ;Wrap around VMA<23:8>x16+C -C Wrap around SEARCH-PAGE-HASH-TABLE SAVE FOR COMPARISON BELOW (CALL COMPUTE-PAGE-HASH) ;M-T := HASH (M-T) GET PHT ENTRY SUPPOSED TO BE WIRED BUMP INDEX FOR NEXT (JUMP-LESS-THAN M-T A-PHT-INDEX-LIMIT SPHT2) ((M-T) SUB M-T A-PHT-INDEX-LIMIT) ;WRAP AROUND PAGE NOT IN PHT ((M-tem) XOR A-TEM3 READ-MEMORY-DATA) ;XOR VIRTUAL ADDRESSES (POPJ-AFTER-NEXT ;(HOPING WE'LL WIN AND RETURN) ZERO IF MATCH (CALL-NOT-EQUAL M-B A-ZERO SPHT1) ;IF NOT FOUND, TRY NEXT COMES HERE WHEN A PAGE NEEDS TO BE READ IN FROM DISK. STARTING FROM LAST PLACE STOPPED, FOR A FLUSHABLE PAGE. IF NONE FOUND, SEARCH INSTEAD FOR ANY NON WIRED PAGE. (THE EMERGENCY CASE.) THAT ENTRY FROM THE PAGE HASH TABLE (HARD), AND FROM THE HARDWARE MAP (EASY). USE A PIPELINED LOOP TO SEARCH THE REGION TABLES AT MEMORY SPEED TO FIND THE NOW RE-HASH THE ADDRESS ORIGINALLY BEING Uh uh, no paging from interrupts already in. Must not cross region boundaries. (There is no reason to believe we will need pages from another region and complications arise in making the pages known.) going to create 0 core, no disk op. multi-swapin not enabled Swapping in a page not in a region not same region page in core. In scavenger -- stop appending if we don't need to look at this page. append to transfer Next page into next hexadec Desired hexadec of memory page, or -1 if dont care. last page frame to returned Delayed for fencepost error PHT entry index No page here memory in the middle of the wired pages on machines with small memory. physically not on right boundary. PHT entry index No page here Searched all of memory (except for the last page brought in), time for emergency measures Age all of the pages in memory, which should make some flushable Mustn't clobber M-1 Try again DISPATCH TABLE TO LOOK FOR FLUSHABLE PAGES DISPATCH ON SWAP STATUS 0 ILLEGAL FOR SWAP - OUT CANDIDATE FROM SCAV WORKING - SET D-SCAV-SWAPOUT ;DISPATCH ON SWAP STATUS (INHIBIT-XCT-NEXT-BIT SWAPIN0) ;0 ILLEGAL 1 NORMAL - TAKE 2 FLUSHABLE - TAKE 3 PREPAGE - TAKE AND 4 AGE TRAP - TAKE 5 WIRED DOWN 6 NOT USED 7 NOT USED (END-DISPATCH) DISPATCH TABLE TO DROP THROUGH IF PAGE NEEDS WRITING DISPATCH ON MAP STATUS SINCE R/W/F MECHANISM NOT AVAILABLE. DISPATCH TABLE TO DROP THROUGH IF PAGE NEEDS WRITING DISPATCH ON MAP STATUS SINCE R/W/F MECHANISM NOT AVAILABLE. Here when we've found a page to evict. M-B has the PFN+1. This version for the case where victim was pre-paged in and not used This version for the normal case Next time, start search with page after this Enter here on %DELETE-PHYSICAL-PAGE. PHT1 *** When there is background writing, will have to synchronize here *** This will require dual modified bits or something. Get PHT2 PHT should be addressable See if needs writing Page needs to be written back to disk original use is at coref-ccw-x Multiple page swapouts enabled? Is next higher page in core? clobbers m-a m-b m-t a-tem1 a-tem3 not found. That page in core, does it need to be written? Save PHT1 adr. Save PHT1. get PHT2 See if needs writing clear modified flag address the map allow time see if map is set up get back base virt adr. page. It is no longer used by disk swap handler, but is needed by COREFOUND2. length of transfer in pages (for hexadec aging hack). DROPS THROUGH DROPS IN M-A HAS ITS VIRTUAL ADDRESS, M-B HAS ITS PAGE FRAME NUMBER (NOT! PHYSICAL ADDRESS) HOLE WHERE THE THING WAS DELETED, AND EXCHANGING THEM WITH THE HOLE. NOTE THAT THE ALGORITHM IN THE PAGING MEMO IS WRONG. Save page frame number -> PHT entry to delete -> last entry in table +2 Delete PHT entry. Supposed to be wired Check location following hole Jump if wrap around Check for dummy entry which has an address of -1 Dummy always hashes to the hole Something there, rehash it Convert fixnum hash to address sans extra bits Jump on funny wrap around case Jump if hole is not between where the frob is and where it hashes to Move the cell into the hole Save pointer to moved cell Complete the cycle Fix up physical-page-data New PHT index Store PHT1 Make the moved cell into new hole Jump if hole is between where the frob is and where it hashes to It's not, loop more Restore found page frame number (?) Access map for virt page deleted Flush 2nd lvl map, if any until we have got enuf for the transfer we intend. last SWAPIN1-GO note M-B still holds page frame number in path IF FRESH PAGE DON'T REALLY SWAP IN transfer size in pages for hexadec aging. Do actual disk transfer TAKE FAULT AGAIN SINCE DISK XFER MAY HAVE FAULTED AND FLUSHED SECOND LEVEL MAP BLOCK. => region number in M-T Swapping in a page not in a region Get misc bits word Should be wired down ((m-lam) a-disk-swapin-virtual-address) (call-xct-next read-page-volatility) ((m-lam) q-page-number m-lam) hardware access known at A-DISK-SWAPIN-VIRTUAL-ADDRESS. PHT2 bits are in Clobbers M-A, M-B, M-T, A-TEM1, A-TEM3 Find hole in PHT for it ((M-T) A-DISK-SWAPIN-VIRTUAL-ADDRESS) Supposed to be a hole! Should be wired Restore access, status, and meta bits Verify the bits This will go to ILLOP if this is a page of a free region Store PHT2 Should be wired error check DISPATCH ON MAP-STATUS 0 MAP NOT SET UP ERRONEOUS R/W COMPUTE PAGE BASE ADDRESS STORE TRAPS POINTING TO SELF RETURN TO MAIN SWAP-IN CODE This advances A-AGING-SCAN-POINTER through main memory until it catches up to A-FINDCORE-SCAN-POINTER, skipping over the page which is being read in now. If a page is found with normal swap-status, it is changed to age trap. If a page is found with age-trap status, it is changed to flushable. Will advance to here If wrap around PHT entry index No page here AGED ENOUGH AGE MORE BEFORE MAKING FLUSHABLE GIVEN AN ADDRESS FIND WHAT AREA IT IS IN. RETURNS THE AREA NUMBER OR NIL. THIS WORKS BY FINDING THE REGION NUMBER, THEN FINDING WHAT AREA THAT REGION LIES IN. NONE GIVEN A REGION NUMBER IN M-T, FIND THE AREA-NUMBER (IN M-T WITH DATA-TYPE) Winning REGION-AREA-MAP superseded this bagbiting code. (CHECK-PAGE-READ) ((M-T) BOXED-NUM-EXCEPT-SIGN-BIT READ-MEMORY-DATA ;GET NEXT IN LIST (POPJ) ;END OF LIST, M-T HAS AREA NUMBER GIVEN AN ADDRESS FIND WHAT REGION IT IS IN. RETURNS THE REGION NUMBER OR NIL MUST CLOBBER ONLY M-T, M-TEM, Q-R, A-TEM1, A-TEM2, A-TEM3, M-A An address in the region rotate right Low areas do not start on proper quantuum boundaries, so above code does not work for them. Scan region origins, etc to get answer if pointer is below FIRST-UNFIXED-AREA. Note INITIAL-LIST-AREA is below FIRST-UNFIXED-AREA. 0 in table, is either free space or fixed area Free space Search table of area origins. I guess linear search is fast enough. Note: each entry in this table is a fixnum. This cannot happen under any circumstances. A-V-RESIDENT-SYMBOL-AREA is fixnum MISCELLANEOUS FUNCTIONS FOR LISP PROGRAMS TO HACK THE PAGE HASH TABLE DOESN'T DO ERROR CHECKING, IF YOU DO THE WRONG THING YOU WILL LOSE. Access, status, and meta bits Swap status code Virtual address sure to clear the map Get ready to return T See if should change swap-status other special kludge, clear modified If sign bit of M-D set, clear modified flag and forget virtual page ADDRESS LOCATION BEING HACKED supposedly necessary only on exp, try it on lambda to be sure. INSTRUCTIONS MUST LEAVE VMA NON-GARBAGE (CALL LOAD-PHYSICAL-MEMORY-SETUP-FROM-SYS-COM) ARG IS PHYSICAL ADDRESS FIND FIRST HOLE OUT OF BOUNDS ADDRESS PHT1 OF HOLE FAKE VIRTUAL ADDRESS FLUSHABLE PAGE FRAME NUMBER See if table getting bigger Bigger than space allocated Address PHT2 RO (CALL LOAD-PHYSICAL-MEMORY-SETUP-FROM-SYS-COM) Page frame number PHT entry index Already deleted or wired Done, return T INSTRUCTIONS MUST LEAVE VMA NON-GARBAGE ARG 2 - VIRTUAL PAGE NUMBER SEE IF ALREADY IN YES, RETURN NIL ARG 1 - PAGE FRAME NO, PUT IT IN RETURN T, FIX VMA NIL if not swapped in, else PHT1 value, except: the modified bit in our value is always up to date, Otherwise must check the PHT2 to know for sure. Get PHT2 ADDRESS THE MAP (CHECK-PAGE-READ-NO-INTERRUPT) ;BE SURE INTERRUPT DOESN'T DISTURB MAP ((MD) VMA) ;ADDRESS MAP (DELAYS UNTIL READ CYCLE OVER) Get PHT2 PDL-BUFFER LOADING CONVENTIONS: 1. THE CURRENT RUNNING FRAME IS ALWAYS COMPLETELY CONTAINED WITHIN THE PDL-BUFFER. 2. SO IS ITS CALLING ADI (LOCATED IMMEDIATELY BEFORE IT ON PDL). AND INDIRECT-ADI POINTERS) MAY POINT AT REGIONS OF THE PDL WHICH ARE NOT CONTAINED WITHIN THE PDL-BUFFER. CHECKING TO SEE IF PDL-BUFFER NEEDS TO BE REFILLED: SINCE M-AP CHANGES MUCH LESS FREQUENTLY THAN THE PDL-BUFFER POINTER ITSELF, ALL TESTING FOR PDL-BUFFER DUMPING/REFILLING IS DONE WITH REFERENCE TO M-AP. M-PDL-BUFFER-ACTIVE-QS CONTAINS THE NUMBER OF QS BETWEEN A-PDL-BUFFER-HEAD CLEARLY, M-PDL-BUFFER-ACTIVE-QS MUST BE AT LEAST 4 FOR ANY CODE TO BE RUNNABLE. IN ADDITION, THE ADI OF THE RUNNING FRAME, IF ANY, MUST ALSO BE IN THE PDL-BUFFER. IF M-PDL-BUFFER-ACTIVE-QS IS GREATER THAN THE CONSTANT PDL-BUFFER-LOW-WARNING IS IN. M-PDL-BUFFER-ACTIVE-QS TESTED, SO THAT M-AP IS AT ITS NEW VALUE IF AND WHEN PDL-BUFFER-REFILL IS REACHED. ROUTINE TO UNLOAD PDL-BUFFER INTO MAIN MEMORY, MAKING AT LEAST N WDS OF ROOM IN PDL BUFFER. GENERAL IDEA IS START AT PDL-BUFFER INDEX A-PDL-BUFFER-HEAD AND VIRTUAL ADDRESS A-PDL-BUFFER-VIRTUAL-ADDRESS, WRITING OUT CRUFT AND INCREMENTING PAGE FAULT HANDLER ON EVERY CYCLE (WHICH WOULDNT QUITE WORK ANYWAY SINCE IT WOULD WRITE THE STUFF BACK IN THE PDL-BUFFER). THUS, WE HAVE TO KEEP TRACK OF WHICH MAP PAGE WE HAVE HACKED AND PUT IT BACK AT END. ALSO, CHECK IF MOVING TO A Special entrypoint for QMRCL and MMCAL4, which, for convenience and speed, require M-FLAGS to be cleared. PUSH-DOWN CAPACITY EXCEEDED ENOUGH SPACE LEFT TO DUMP WHAT'S IN THE PDL BUFFER NOW HERE I AM ASSUMING THAT A-PDL-BUFFER-HIGH-WARNING IS GUARANTEED NOT TO COME OUT NEGATIVE AFTER PDL-BUFFER-MAKE-ROOM RETURNS, BECAUSE OF THE CHECK ABOVE. THIS USED TO BE CHECKED. ARG IN M-2 -> HIGHEST "SATISFACTORY" VALUE FOR M-PDL-BUFFER-ACTIVE-QS. COMMON VALUES ARE PDL-BUFFER-HIGH-LIMIT TO UNBLOAT PDL-BUFFER OR 0 TO COMPLETELY DUMP PDL-BUFFER (THRU M-AP) OR Clobbers M-1. ARG IN M-2 PRESERVE.. If nothing to do, done Starting pdl-buffer address Starting virtual-memory address Number locations to do total Write next Q into memory Interpreter now puts forwards into stack frames. So can lexical scoping in compiled code. (DISPATCH Q-DATA-TYPE WRITE-MEMORY-DATA D-ILLOP-IF-BAD-DATA-TYPE) Error-check stuff being written Check for writing ptr to extra-pdl Close loop Number of locations dumped drops-thru ARG IN M-2 PRESERVE.. If nothing to do, done Take a read cycle to even if it turns out to be in the pdl-buffer and no main memory cycle is made. gee, maybe not, but boy is it marginal.. Address the map, Q-R saves addr allow time Save correct map contents Turn on access R/W Number locations left in page Number locations to do total Don't do a full page Starting pdl-buffer address Starting virtual-memory address Ending virtual-memory address +1 Write next Q into memory Write-access supposedly turned on. Interpreter now puts forwards into stack frames. So can lexical scoping in compiled code. (DISPATCH Q-DATA-TYPE WRITE-MEMORY-DATA D-ILLOP-IF-BAD-DATA-TYPE) Error-check stuff being written Check for writing ptr to extra-pdl Close loop Clean up and restore the map. Number of locations dumped Address the map Loop back for next page Restore the map for this page drops through drops in. Here when we're done. This exit used by both PDL-BUFFER-MAKE-ROOM and PDL-BUFFER-REFILL. not in range of PDL Recompute A-PDL-BUFFER-HIGH-WARNING not in range of PDL Result negative if within pdl-buffer size of the end of the regular-pdl in virt mem Restore Getting near the end of the stack. Set A-PDL-BUFFER-HIGH-WARNING so that we will trap to PDL-BUFFER-DUMP before getting more stuff into the pdl buffer than there is room to store into virtual memory. Note that this result can actually be negative if we are currently in the process of taking a pdl-overflow trap. Restore Attempt to refill pdl-buffer from virtual memory such that Preserve PI Get base address of pdl into M memory No more pdl to reload, exit Enough in there to win Negative number of words to do total Negative number of words left in pdl Initial virtual-memory address +1 Transport the data just read from memory Now clean up Minus number of Q's moved Increase this DROP THRU Preserve PI Get base address of pdl into M memory this is just left in M-2 as a constant in below code. No more pdl to reload, exit Enough in there to win bug!? Can Q-R get clobbered?? *** well maybe its OK, but... Address the map allow time Save correct map contents R/W Negative number of words to do total Negative number of words left in pdl Number of words on this page -1 Won't be able to do full page Initial virtual-memory address +1 Map should be hacked Transport the data just read from memory Now clean up Minus number of Q's moved Increase this Address the map Loop back for next page unless at bottom of pdl Restore the map DROPS IN. Over pop Note that the transport happens with the bottom pdl word not stored into yet. This should be all right. Minus number of Q's moved Increase this Save stuff momentarily Address the map Restore the map Restore VMA Restore MD This used to be just TRANSPORT. Changed to allow EVCPs on PDL. There is some loss of dispatch table. Now invoke the transporter Restore A-PDLB-TEM, lost by transporter Now re-start fast loop for next word Put the transported datum on the pdl Number of locations dumped TOOK PAGE FAULT RELOADING PDL BUFFER, CLEAR UP THEN PROCESS IT. LAST ACTUALLY TRANSFERRED. Minus number of Q's moved Increase this
* * ( c ) Copyright 1983 Lisp Machine Inc * * Notes for explorer gc - pace Nov 20 , 1985 the bits to the other field . -done RG 1/20/86 Secondly , the OLD - SPACE bit on the explorer ( and on the lambda AVP ) is in L1 - MAP<10 . > 1 means newspace , 0 means oldspace . There is code at INIMAP1 to set all of the L1 - MAP to " newspace " when booting . Timing restrictions concerning 2nd level map : on LAMBDA , a instruction must intervene between the being changed and the map being on EXP , instructions must intervene both places ( as per " special considerations " ) . (DEFCONST UC-LAMBDA-PAGE-FAULT '( THIS FILE FOR LAMBDA ONLY . However , some cadr stuff is still present in conditionalized form for reference . On LAMBDA as on CADR , there are three complex data structures ( the level-2 map , the % PHT2- fields and the % % REGION- fields ) which share some of the same fields . Eventually , we will want to " decouple " all three . For now , however , we will leave % PHT2- and % % REGION- " coupled " but we must deal with the issue of the level 2 map , since it is split into two pieces on LAMBDA . ( Even eventually , all three will still have the same 10 . bit byte of ACCESS - STATUS - AND - META bits . places . ) % % MAP2C- prefix is used to refer to the bits " in position " for the level2 map . PAGE FAULTS GENERALLY DO NOT CLOBBER ANYTHING . THE DISPATCH CONSTANT AND THE Q REGISTER ARE CLOBBERED . THE DATA - TYPE OF VMA -MUST NOT- BE CLOBBERED . PAGE FAULTS HAVE . IF A SEQUENCE BREAK IS ALLOWED AND , IT AFTER A WRITE CYCLE THE MD IS RESET FROM THE VMA . THE LETTERED M ACS ARE SAVED , AND MUST CONTAIN GC MARKABLE STUFF OR DTP TRAP ( OR -1 ) . MISCELLANEOUS ACS LIKE A - TEM 'S ARE CLOBBERED BY SEQUENCE BREAKS . Fields in first level map . Lambda only , since on cadr the 5 bit l2 - map - block - index is all there is . The L1 map meta - bits are a function of the region . Since each L1 map entry corresponds to 32 . virtual pages , this means regions must be at least 32 pages , etc . This is no further restriction , since the address space quantuum was already 64 pages . For hardware convenience , all three L1 map meta bits are stored in COMPLEMENTED form . The L1 map MB codes are : ( in parens is the inverted value actually seen in hardware ) . 0 - > static region ( 3 ) 1 - > dynamic region ( 2 ) 2 - > active consing region ( ie , copy space ) ( 1 ) 3 - > extra pdl region ( 0 ) if 1 , MB1 and MB0 are INVALID . (def-data-field map1-volatility-invalid 1 9) (def-data-field map1-volatility 2 7) (DEF-DATA-FIELD L1-MAP-MB1-BAR 1 8) (DEF-DATA-FIELD L1-MAP-MB0-BAR 1 7) (DEF-DATA-FIELD L1-MAP-META-BITS #+lambda 3 #+exp 5 7) (DEF-DATA-FIELD L1-MAP-L2-BLOCK-SELECT 7 0) #+exp (def-data-field l1-map-old-exp 1 10.) #+exp (def-data-field l1-map-valid-exp 1 11.) #+exp (def-data-field l1-map-all-but-old-and-valid 9 0) CADR DEFINITIONS : ( DEF - DATA - FIELD MAP - SECOND - LEVEL - MAP 24 . 0 ) ( DEF - DATA - FIELD MAP - ACCESS - STATUS - AND - META - BITS 10 . 14 . ) high two are hackable by dispatch inst . (DEF-DATA-FIELD MAP2C-STATUS-CODE 3 6) note one bit overlap with status - code (DEF-DATA-FIELD MAP2C-ACCESS-STATUS-AND-META-BITS 10. 0) if force , ( ie 40 bit in func dest that this bit turns out to be in same place for LAMBDA and EXP ! (def-data-field map2c-volatility 2 0) #+exp(def-data-field exp-map2c-volatility 2 11.) (DEF-DATA-FIELD MAP2C-REPRESENTATION-TYPE 2 2) on CADR , this was looked at by hardware replaced by the GC - VOLATILITY gate , so the bit has no special hardware function . on CADR , this was looked at by hardware DISPATCH - ON - MAP-19 feature . On LAMBDA , it still is . EXPLORER and AVP , this hardware (DEF-DATA-FIELD MAP2P-PHYSICAL-PAGE-NUMBER 22. 0) 0 unless trying to hack bytes or 16 bit wds (assign l2-map-status-code (plus map2c-status-code l2-map-control)) (assign l2-map-access-status-and-meta-bits (plus map2c-access-status-and-meta-bits l2-map-control)) (assign l2-map-representation-type (plus map2c-representation-type l2-map-control)) (assign l2-map-extra-pdl-meta-bit (plus map2c-extra-pdl-meta-bit l2-map-control)) (assign l2-map-oldspace-meta-bit (plus map2c-oldspace-meta-bit l2-map-control)) (assign l2-map-physical-page-number (plus map2p-physical-page-number l2-map-physical-page)) FIELDS IN VMA WHEN WRITING MAP . ( DEF - DATA - FIELD MAP - WRITE - SECOND - LEVEL - MAP 24 . 0 ) ( DEF - DATA - FIELD MAP - WRITE - ENABLE - FIRST - LEVEL - WRITE 1 26 . ) WORD 1 SAME AS VMA (DEF-DATA-FIELD PHT1-SWAP-STATUS-CODE 3 0) (DEF-DATA-FIELD PHT1-ALL-BUT-SWAP-STATUS-CODE 29. 3) (DEF-DATA-FIELD PHT1-AGE 2 3) (DEF-DATA-FIELD PHT1-ALL-BUT-AGE-AND-SWAP-STATUS-CODE 27. 5) (DEF-DATA-FIELD PHT1-VALID-BIT 1 6) WORD 2 THESE ARE NOW THE SAME BIT POSITIONS AS IN THE SECOND LEVEL MAP on CADR . (DEF-DATA-FIELD PHT2-META-BITS 6 26) (def-data-field pht2-extra-pdl-meta-bit 1 32) (def-data-field pht2-oldspace-meta-bit 1 33) (def-data-field pht2-map-volatility 2 26) (DEF-DATA-FIELD PHT2-MAP-STATUS-CODE 3 34) (DEF-DATA-FIELD PHT2-MAP-ACCESS-CODE 2 36) (DEF-DATA-FIELD PHT2-MAP-ACCESS-AND-STATUS-CODE 4 34) (DEF-DATA-FIELD PHT2-ACCESS-STATUS-AND-META-BITS 12 26) (def-data-field pht2-access-status-and-meta-bits-except-volatility 10 30) (DEF-DATA-FIELD PHT2-PHYSICAL-PAGE-NUMBER 26 0) ADDRESS BLOCK OF 32 . PAGES ADDR WITHIN PAGE (DEF-DATA-FIELD ALL-BUT-VMA-LOW-BITS 24. 8) NOTE : PGF - R , ETC CAN BE ENTERED RECURSIVELY IF THE PAGE IS SWAPPED OUT AND THE DISK ROUTINES FAULT WHEN REFERENCING THE DISK CONTROL . INTERRUPT MAY BE INSERTED -AFTER- THE READ CYCLE , HOWEVER IT IS EFFECTIVELY BEFORE SINCE ON DISMISS READ - MEMORY - DATA RESTORED FROM VMA ! ! ( ( RG - MODE ) ANDCA RG - MODE ( A - CONSTANT 1_26 . ) ) . ( note sense opposite from CADR ) PUSHJ HERE ON PAGE FAULT , INTERRUPT REQUEST , OR SEQUENCE BREAK DURING READ CYCLE PGF-R-SB-save-vma-in-t (JUMP-CONDITIONAL PG-FAULT-OR-INTERRUPT PGF-R-I) can clobber VMA , MD . ((m-t) q-typed-pointer vma) ((vma-start-read) m-t) (check-page-read) (popj) must not loop a la CADR because PGF could be handled w/o mem cycle , so page - fault SBSER #+exp (popj-if-bit-clear (byte-field 1 14.) mcr) #+lambda((RG-MODE) IOR RG-MODE (A-CONSTANT 1_26.)) #+exp ((mcr) andca mcr (a-constant 1_14.)) (jump-not-equal m-zero a-defer-boot-char-mode sbser-process-boot-char) ((M-TEM) A-INHIBIT-SCHEDULING-FLAG) (JUMP-NOT-EQUAL M-TEM A-V-NIL SB-DEFER) ((m-tem3) vma) ((md) setz) ((vma) a-disk-run-light) ((vma-start-write) sub vma (a-constant 12)) (check-page-write-map-reload-only) ((vma) m-tem3) ((M-DEFERRED-SEQUENCE-BREAK-FLAG) DPB M-ZERO A-FLAGS) ((M-TEM) DPB M-ZERO Q-ALL-BUT-TYPED-POINTER A-QSSTKG) SCHEDULER SHOULD HAVE DEFERED INTERRUPTS ENSURE NO SPECIAL PDL OVERFLOW STORING STATUS REGULAR PDL IS PREWITHDRAWN , CAN'T OVERFLOW " CALL " SCHEDULER STACK GROUP ((M-A) A-QSSTKG) SB-DEFER ((m-tem3) vma) ((m-tem4) md) ((vma) a-disk-run-light) ((vma) sub vma (a-constant 12)) ((md) m-minus-one) ((m-tem) dpb m-zero q-all-but-typed-pointer a-qsstkg) (jump-equal m-tem a-qcstkg sb-light-off) ((vma-start-read) vma) (check-page-read-map-reload-only) sb-light-off ((md) xor md a-minus-one) ((vma-start-write) vma) (check-page-write-map-reload-only) ((vma) m-tem3) ((md) m-tem4) (POPJ-AFTER-NEXT (M-DEFERRED-SEQUENCE-BREAK-FLAG) DPB (M-CONSTANT -1) A-FLAGS) (NO-OP) sbser-process-boot-char ((M-DEFERRED-SEQUENCE-BREAK-FLAG) DPB M-ZERO A-FLAGS) ENSURE NO SPECIAL PDL OVERFLOW STORING STATUS REGULAR PDL IS PREWITHDRAWN , CAN'T OVERFLOW this seems to be preserved by SGLV (call kbd-boot-char-xct-now) here is an attempt at returning via an SDU continue command -- I do n't know if it will work . (JUMP SG-ENTER) PUSHJ HERE ON PAGE FAULT OR INTERRUPT REQUEST DURING READ CYCLE PGF-R-I (declare (clobbers a-tem)) PGF-R (declare (clobbers a-tem) (must-avoid intr)) (DISPATCH-XCT-NEXT L2-MAP-STATUS-CODE D-PGF) ((M-PGF-WRITE) DPB M-ZERO A-FLAGS) ((VMA-START-READ) A-PGF-VMA) (POPJ-AFTER-NEXT NO-OP) PGF-R-MAP-RELOAD-ONLY (declare (clobbers a-tem) (must-avoid intr)) (DISPATCH-XCT-NEXT L2-MAP-STATUS-CODE D-PGF-MAP-RELOAD-ONLY) ((M-PGF-WRITE) DPB M-ZERO A-FLAGS) ((VMA-START-READ) A-PGF-VMA) (POPJ-AFTER-NEXT NO-OP) PUSHJ HERE ON PAGE FAULT , INTERRUPT , OR SEQUENCE BREAK DURING WRITE CYCLE --not used . ( JUMP - CONDITIONAL PG - FAULT - OR - INTERRUPT PGF - W - I ) PGF-W-BIND (declare (clobbers a-tem a-pgf-mode) (must-avoid intr)) (JUMP-XCT-NEXT PGF-W-1) ((A-PGF-MODE) A-V-TRUE) PGF-W-FORCE (declare (clobbers a-tem a-pgf-mode) (must-avoid intr)) (JUMP-XCT-NEXT PGF-W-1) ((A-PGF-MODE) M-MINUS-ONE) PUSHJ HERE ON PAGE FAULT OR INTERRUPT REQUEST DURING WRITE CYCLE PGF-W-I (declare (clobbers a-tem a-pgf-mode)) original vma / returning , so the volatilities are correctly latched . (jump-if-page-fault pgf-w) (call intr) ((vma-start-write) vma) (check-page-write-no-interrupt) (popj) PUSHJ HERE ON PAGE FAULT WHEN DESIRE NOT TO TAKE INTERRUPT PGF-W (declare (clobbers a-tem a-pgf-mode)) ((A-PGF-MODE) A-V-NIL) SAVE DATA BEING WRITTEN (DISPATCH-XCT-NEXT L2-MAP-STATUS-CODE D-PGF) ((M-PGF-WRITE) DPB (M-CONSTANT -1) A-FLAGS) ((WRITE-MEMORY-DATA) A-PGF-WMD) ASSUMES WE WERE TRYING TO DO A WRITE CYCLE (POPJ-AFTER-NEXT NO-OP) PGF-W-MAP-RELOAD-ONLY (declare (clobbers a-tem a-pgf-mode)) ((A-PGF-MODE) A-V-NIL) SAVE DATA BEING WRITTEN (DISPATCH-XCT-NEXT L2-MAP-STATUS-CODE D-PGF-MAP-RELOAD-ONLY) ((M-PGF-WRITE) DPB (M-CONSTANT -1) A-FLAGS) ((WRITE-MEMORY-DATA) A-PGF-WMD) ASSUMES WE WERE TRYING TO DO A WRITE CYCLE (POPJ-AFTER-NEXT NO-OP) (LOCALITY D-MEM) 0 LEVEL 1 OR 2 MAP NOT VALID 1 META BITS ONLY , TAKE AS MAP MISS 2 WRITE IN READ ONLY , note jump not PUSHJ 3 WRITE IN READ / WRITE FIRST 4 READ / WRITE 5 MAY BE IN PDL BUFFER , note jump . 6 POSSIBLE MAR BREAK , note jump . 7 nubus physical in pht2 (END-DISPATCH) (LOCALITY D-MEM) D-PGF-MAP-RELOAD-ONLY 0 LEVEL 1 OR 2 MAP NOT VALID 1 META BITS ONLY , TAKE AS MAP MISS 4 READ / WRITE 7 nubus physical in pht2 (END-DISPATCH) (LOCALITY I-MEM) WHAT IT POINTS TO . SMASHES VMA . (LOCALITY D-MEM) (START-DISPATCH 3 0) D-GET-MAP-BITS 0 LEVEL 1 OR 2 MAP NOT VALID 1 GOT MAP BITS ANYWAY 2 READ ONLY 3 READ / WRITE FIRST 4 READ / WRITE 5 MAY BE IN PDL BUFFER 6 POSSIBLE MAR BREAK 7 nubus physical in pht2 (END-DISPATCH) (LOCALITY I-MEM) MAP MISS WHEN TRYING TO GET META BITS . GET FROM REGION TABLE , SET UP META - BITS - ONLY STATUS GET-MAP-BITS ((A-META-BITS-MAP-RELOADS) ADD M-ZERO A-META-BITS-MAP-RELOADS ALU-CARRY-IN-ONE) Address of reference , also saves Check for level 1 map miss (CALL-EQUAL M-TEM (A-CONSTANT 177) LEVEL-1-MAP-MISS) M-A A-LOWEST-DIRECT-VIRTUAL-ADDRESS GET-MAP-BITS-1) ((MD) (A-CONSTANT (PLUS (BYTE-MASK %%REGION-OLDSPACE-META-BIT) (BYTE-MASK %%REGION-EXTRA-PDL-META-BIT) (BYTE-VALUE %%REGION-REPRESENTATION-TYPE %REGION-REPRESENTATION-TYPE-LISP)))) ((M-A) Q-POINTER M-A (A-CONSTANT (BYTE-VALUE Q-DATA-TYPE DTP-FIX))) get-map-bits-2 (ILLOP-IF-PAGE-FAULT) GET-MAP-BITS-1 ((m-lam) a-pgf-vma) (call-xct-next read-page-volatility) ((m-lam) q-page-number m-lam) ((m-a) dpb m-a MAP2C-META-BITS (A-CONSTANT (BYTE-VALUE MAP2C-STATUS-CODE %PHT-MAP-STATUS-META-BITS-ONLY))) #+lambda((l2-map-control) dpb m-tem map2c-volatility a-a) #+exp ((m-tem) dpb m-tem map2c-volatility a-a) #+exp ((vma-write-l2-map-control) dpb m-tem exp-map2c-volatility a-tem) ((#+lambda L2-MAP-PHYSICAL-PAGE Do n't leave garbage in VMA . THE LINEAR PUSHDOWN LIST MUST ALWAYS BE COMPOSED OF PAGES FROM AN AREA WHOSE REGION - BITS Q HAS % PHT - MAP - STATUS - PDL - BUFFER IN THE MAP STATUS PORTION OF ITS % % REGION - MAP - BITS FIELD . THUS ANY MEMORY CYCLE REF'ING SUCH AN AREA WILL TRAP AND COME HERE , WHERE THE CODE CHECKS TO SEE IF IT IS REALLY IN THE PDL - BUFFER NOW . IF NOT , IT TURNS ON R / W ACCESS TEMPORARILY AND PERFORMS THE REQUESTED CYCLE , ETC . THESE PAGES ARE TREATED ENTIRELY AS NORMAL PAGES FOR SWAPPING PURPOSES , AND MAY EVEN BE SWAPPED OUT WHILE ACTUALLY RESIDENT IN THE PDL - BUFFER ! THE ONLY DIFFERENCE IS THAT THE PAGE MUST ALWAYS BE WRITTEN TO THE DISK ON SWAP - OUT , SINCE THE R - W - F MECHANISM IS NOT AVAILABLE TO KEEP TRACK OF WHETHER IT HAS MODIFIED . PDL - BUFFER - POINTER IS TAKEN TO MARK THE HIGHEST PDL - BUFFER LOCN WHICH IS REALLY VALID . PGF-PDL (JUMP-IF-BIT-SET M-PGF-WRITE PGF-W-PDL) PGF-R-PDL (declare (local a-pdl-buffer-read-faults)) ((M-PGF-TEM) SUB PDL-BUFFER-POINTER A-PDL-BUFFER-HEAD) ((A-PGF-B) ADD M-PGF-TEM A-PDL-BUFFER-VIRTUAL-ADDRESS) (JUMP-LESS-THAN M-PGF-TEM A-PDL-BUFFER-VIRTUAL-ADDRESS PGF-R-NOT-REALLY-IN-PDL-BUFFER) ( PP ) IS A VALID WD . ((A-PDL-BUFFER-READ-FAULTS) ADD A-PDL-BUFFER-READ-FAULTS M-ZERO ALU-CARRY-IN-ONE) ((M-PGF-TEM) SUB M-PGF-TEM TRUNCATES TO 10 BITS (POPJ-AFTER-NEXT (MD) C-PDL-BUFFER-INDEX) ((PDL-BUFFER-INDEX) A-PGF-A) READ REFERENCE TO LOCATION NOT IN THE PDL BUFFER , BUT IT HAVE . PGF-R-NOT-REALLY-IN-PDL-BUFFER #-LAMBDA(begin-comment) (POPJ-AFTER-NEXT (A-PDL-BUFFER-MEMORY-FAULTS) ADD A-PDL-BUFFER-MEMORY-FAULTS M-ZERO ALU-CARRY-IN-ONE) (NO-OP) #-lambda (end-comment) ((A-PDL-BUFFER-MEMORY-FAULTS) ADD A-PDL-BUFFER-MEMORY-FAULTS M-ZERO ALU-CARRY-IN-ONE) I THOUGHT WE JUST TURNED ON ACCESS (no-op) (VMA) MD) ((MD) A-PGF-WMD) #-exp(end-comment) PGF-W-PDL (declare (local a-pdl-buffer-write-faults)) ((M-PGF-TEM) SUB PDL-BUFFER-POINTER A-PDL-BUFFER-HEAD) (JUMP-LESS-THAN M-PGF-TEM A-PDL-BUFFER-VIRTUAL-ADDRESS PGF-W-NOT-REALLY-IN-PDL-BUFFER) ( PP ) IS A VALID WD ((A-PDL-BUFFER-WRITE-FAULTS) ADD A-PDL-BUFFER-WRITE-FAULTS M-ZERO ALU-CARRY-IN-ONE) ((M-PGF-TEM) SUB M-PGF-TEM TRUNCATES TO 10 BITS ((MD) A-PGF-WMD) ( POPJ - AFTER - NEXT ((c-pdl-buffer-index) md) ((pdl-buffer-index) a-pgf-a) note that first inst does n't reference the map WRITE REFERENCE TO LOCATION NOT IN THE PDL BUFFER , BUT IT HAVE PGF-W-NOT-REALLY-IN-PDL-BUFFER (declare (local a-pdl-buffer-memory-faults)) #-lambda(begin-comment) (POPJ-AFTER-NEXT (A-PDL-BUFFER-MEMORY-FAULTS) ADD A-PDL-BUFFER-MEMORY-FAULTS M-ZERO ALU-CARRY-IN-ONE) (NO-OP) #-lambda(end-comment) #-exp(begin-comment) do n't use l2 - map on first inst here ((A-PDL-BUFFER-MEMORY-FAULTS) ADD A-PDL-BUFFER-MEMORY-FAULTS M-ZERO ALU-CARRY-IN-ONE) ((WRITE-MEMORY-DATA-START-WRITE) A-PGF-WMD) I THOUGHT WE JUST TURNED ON ACCESS (no-op) (VMA) MD) ((MD) A-PGF-WMD) #-exp(end-comment) pgf-r-pdl-check-immediately (call pgf-pdl-check-immediately) ((a-pdl-buffer-read-faults) add a-pdl-buffer-read-faults m-zero alu-carry-in-one) ((md) c-pdl-buffer-index) pop return - address in pgf - r (popj-after-next (pdl-buffer-index) a-pgf-a) (no-op) pgf - w - pdl - check - immediately ( popj - after - next ( c - pdl - buffer - index ) md ) pgf-pdl-check-immediately ((m-pgf-tem) sub pdl-buffer-pointer a-pdl-buffer-head) ((m-pgf-tem) pdl-buffer-address-mask m-pgf-tem) ((a-pgf-b) m+a+1 m-pgf-tem a-pdl-buffer-virtual-address) ((m-pgf-tem) q-pointer vma) (jump-less-than m-pgf-tem a-pdl-buffer-virtual-address pgf-pdl-check-not-in-pdl-buffer) (jump-greater-than m-pgf-tem a-pgf-b pgf-pdl-check-not-in-pdl-buffer) ((m-pgf-tem) sub m-pgf-tem a-pdl-buffer-virtual-address) (popj-after-next (a-pgf-a) pdl-buffer-index) ((pdl-buffer-index) add m-pgf-tem a-pdl-buffer-head) pgf-pdl-check-not-in-pdl-buffer ((m-garbage) micro-stack-data-pop) (popj) SAVE REGISTERS UPON ENTERING PAGE FAULT HANDLER PGF-SAVE (declare (clobbers a-pgf-vma a-pgf-a a-pgf-b a-pgf-t) (saves (vma a-pgf-vma))) ((A-PGF-VMA) VMA) PGF-SAVE-1 (declare (clobbers a-pgf-a a-pgf-b a-pgf-t) (saves (a-a a-pgf-a) (a-b a-pgf-b) (a-t a-pgf-t))) ((A-PGF-A) M-A) (POPJ-AFTER-NEXT (A-PGF-B) M-B) ((A-PGF-T) M-T) RESTORE REGISTERS AND LEAVE PAGE FAULT HANDLER DOESN'T RESTORE VMA SINCE CYCLE RESTARTER ( POPJED TO ) WILL DO THAT PGF-RESTORE (declare (restores (a-a a-pgf-a) (a-b a-pgf-b) (a-t a-pgf-t))) ( ( M - A ) DPB ( BYTE - FIELD 1 12 . ) M - MINUS - ONE A - ZERO ) ( JUMP - EQUAL M - A A - ZERO CHECK - WIRED - LEVEL-2 - MAP - CONTROL-2 ) ( ( MD ) ADD ( A - CONSTANT ( EVAL PAGE - SIZE ) ) ) ((M-A) A-PGF-A) (POPJ-AFTER-NEXT (M-B) A-PGF-B) ((M-T) A-PGF-T) DISK-PGF-SAVE (declare (saves (a-pgf-vma a-disk-save-pgf-vma) (a-pgf-wmd a-disk-save-pgf-wmd) (a-pgf-t a-disk-save-pgf-t) (a-pgf-a a-disk-save-pgf-a) (a-pgf-b a-disk-save-pgf-b) (a-pgf-mode a-disk-save-mode) (a-1 a-disk-save-1) (a-2 a-disk-save-2))) ((A-DISK-SAVE-PGF-T) A-PGF-T) ((A-DISK-SAVE-PGF-A) A-PGF-A) ((A-DISK-SAVE-PGF-B) A-PGF-B) ((A-DISK-SAVE-MODE) A-PGF-MODE) (POPJ-AFTER-NEXT DISK-PGF-RESTORE (declare (restores (a-pgf-vma a-disk-save-pgf-vma) (a-pgf-wmd a-disk-save-pgf-wmd) (a-pgf-t a-disk-save-pgf-t) (a-pgf-a a-disk-save-pgf-a) (a-pgf-b a-disk-save-pgf-b) (a-pgf-mode a-disk-save-mode) (a-1 a-disk-save-1) (a-2 a-disk-save-2))) ((M-1) A-DISK-SAVE-1) ((A-PGF-MODE) A-DISK-SAVE-MODE) ((A-PGF-B) A-DISK-SAVE-PGF-B) ((A-PGF-A) A-DISK-SAVE-PGF-A) ((A-PGF-T) A-DISK-SAVE-PGF-T) (POPJ-AFTER-NEXT (A-PGF-WMD) A-DISK-SAVE-PGF-WMD) ((A-PGF-VMA) A-DISK-SAVE-PGF-VMA) ADDRESS IN MD ON CALL AND RETURN , VMA CLOBBERED . PGF - SAVE MUST HAVE CALLED . What we do here is throw away a section of the level 2 map and make the level 1 map point to it . When we go around again , we get a level 2 map miss and set it up properly . LEVEL-1-MAP-MISS (declare (clobbers a-pgf-tem) (values a-a a-t)) ((A-FIRST-LEVEL-MAP-RELOADS) ADD A-FIRST-LEVEL-MAP-RELOADS M-ZERO ALU-CARRY-IN-ONE) ((#+lambda L1-MAP #+exp vma-write-l1-map) ALLOCATE A BLOCK OF LVL 2 MAP - > 1ST ENTRY IN BLOCK #-exp (begin-comment) REVERSE 1ST LVL MAP IN 1200 - 1377 ((VMA-START-READ) M-PGF-TEM) (ILLOP-IF-PAGE-FAULT) #-exp (end-comment) #-lambda(begin-comment) reverse 1st level map in 2000 - 2177 of A mem ((OA-REG-HIGH) DPB M-PGF-TEM OAH-A-SRC A-ZERO) ((MD) A-GARBAGE) #-lambda(end-comment) #+exp ((m-tem) ldb (byte 12. 13.) md) #+exp (call-equal m-tem a-zero illop) ((#+lambda L1-MAP #+exp vma-write-l1-map) SELECTIVE-DEPOSIT L1-MAP L1-MAP-META-BITS AND 177 - IFY OLD 1ST LVL MAP PGF-L1C ((md) M-A) #-exp(begin-comment) ((vma-start-write) m-pgf-tem) (ILLOP-IF-PAGE-FAULT) #-exp(end-comment) #-lambda(begin-comment) ((OA-REG-LOW) DPB M-PGF-TEM OAL-A-DEST A-ZERO) ((A-GARBAGE) md) #-lambda(end-comment) DO ALL 32 . ENTRIES IN BLOCK PGF-L1A ((#+lambda L2-MAP-CONTROL #+exp vma-write-l2-map-control) (A-CONSTANT 0)) FILL 2ND - LEVEL MAP WITH MAP - MISS ( 0 ) ((MD M-A) ADD M-A (A-CONSTANT (BYTE-VALUE VMA-PAGE-ADDR-PART 1))) (JUMP-GREATER-THAN-XCT-NEXT M-T (A-CONSTANT 1) PGF-L1A) ((M-T) SUB M-T (A-CONSTANT 1)) Do n't leave garbage in VMA . ( ( M - A ) DPB ( BYTE - FIELD 1 12 . ) M - MINUS - ONE A - ZERO ) ( JUMP - EQUAL M - A A - ZERO CHECK - PGF - L1 - L2 - MAP - CONTROL-2 ) ( ( MD ) ADD ( A - CONSTANT ( EVAL PAGE - SIZE ) ) ) RESTORE MD ( ADDRESS OF REFERENCE ) ADVANCE-SECOND-LEVEL-MAP-REUSE-POINTER ((Q-R A-SECOND-LEVEL-MAP-REUSE-POINTER) ADD M-ZERO A-SECOND-LEVEL-MAP-REUSE-POINTER ALU-CARRY-IN-ONE) now use whole 2nd level map . (POPJ-AFTER-NEXT POPJ-LESS-THAN Q-R (A-CONSTANT 176)) ((A-SECOND-LEVEL-MAP-REUSE-POINTER) PGF-MAP-MISS-RELOAD-ONLY (declare (clobbers a-lam a-tem a-tem3 a-tem1) (local a-pgf-t a-pgf-a a-pgf-b)) SAVE A , B , T , VMA CHECK FOR 1ST - LEVEL MISS (CALL-EQUAL M-TEM (A-CONSTANT 177) LEVEL-1-MAP-MISS) MD HAS ADDRESS , VMA SAVED AND CLOBBERED . HANDLE 2ND - LEVEL MISS ((A-SECOND-LEVEL-MAP-RELOADS) ADD A-SECOND-LEVEL-MAP-RELOADS M-ZERO ALU-CARRY-IN-ONE) (JUMP-LESS-THAN M-T A-LOWEST-DIRECT-VIRTUAL-ADDRESS PGF-L2A-RELOAD-ONLY) (JUMP PGF-MM-RELOAD-ONLY-1) MAP MISS COMES HERE . ADDRESS IN VMA AND BOTH . SET UP FIRST - LEVEL MAP IF NECESSARY . THEN DEAL WITH PAGE - FAULT . PGF-MAP-MISS Experimental . ( call pgf - r - pdl - check - immediately ) SAVE A , B , T , VMA CHECK FOR 1ST - LEVEL MISS (CALL-EQUAL M-TEM (A-CONSTANT 177) LEVEL-1-MAP-MISS) MD HAS ADDRESS , VMA SAVED AND CLOBBERED . HANDLE 2ND - LEVEL MISS ((A-SECOND-LEVEL-MAP-RELOADS) ADD A-SECOND-LEVEL-MAP-RELOADS M-ZERO ALU-CARRY-IN-ONE) (JUMP-LESS-THAN M-T A-LOWEST-DIRECT-VIRTUAL-ADDRESS PGF-L2A) PGF-MM-RELOAD-ONLY-1 (JUMP-LESS-THAN M-T (A-CONSTANT LOWEST-A-MEM-VIRTUAL-ADDRESS) MAP-GREY) (JUMP-LESS-THAN M-T (A-CONSTANT LOWEST-IO-SPACE-VIRTUAL-ADDRESS) PGF-SPECIAL-A-MEMORY-REFERENCE) REFERENCE TO UNIBUS OR X - BUS IO VIRTUAL ADDRESS ( on CADR ) . FAKE UP PAGE HASH TABLE ENTRY PGF-MM0 (JUMP-LESS-THAN M-T (A-CONSTANT 177100000) MAP-VIDEO-BUFFER) (JUMP-GREATER-OR-EQUAL M-T (A-CONSTANT LOWEST-UNIBUS-VIRTUAL-ADDRESS) MAP-MULTIBUS) CADR control registers . (JUMP-GREATER-OR-EQUAL M-T (A-CONSTANT 177377000) MAP-MULTIBUS-IO) (JUMP-GREATER-OR-EQUAL M-T (A-CONSTANT 177370400) MAP-TV-CONTROL-REGS) (JUMP-GREATER-OR-EQUAL M-T (A-CONSTANT 177370000) MAP-SDU-CONTROL-REGS) (JUMP-GREATER-OR-EQUAL M-T (A-CONSTANT 177360000) MAP-SHARED-PAGES-1) (JUMP-GREATER-OR-EQUAL M-T (A-CONSTANT 177300000) MAP-SHARED-PAGES-2) #+lambda(jump-greater-or-equal m-t (a-constant 177277400) map-quad-video-control-regs) (CALL ILLOP) ( ( M - T ) VMA - PHYS - PAGE - ADDR - PART M - T ( A - CONSTANT ( BYTE - MASK MAP - WRITE - ENABLE - SECOND - LEVEL - WRITE ) ) ) ( ( VMA - WRITE - MAP ) MAP - ACCESS - STATUS - AND - META - BITS A - T ) Returning to PGF - R or PGF - W , which will reload VMA with good data . Extract bits 16 - 8 which are page number within multibus . These bits go in 8 - 0 of L2 map . Byte mask accounts for F in high 4 bits of NUBUS address . #-LAMBDA (BEGIN-COMMENT) ((M-T) LDB (BYTE-FIELD 9 8) M-T a-zero) SDU quad slot goes in bits 21 - 14 . ((L2-MAP-PHYSICAL-PAGE) DPB M-A (BYTE-FIELD 8 14.) A-T) RW access , status 4 , no area traps . Returning to PGF - R or PGF - W , which will reload VMA with good data . #-LAMBDA (END-COMMENT) #+EXP (CALL ILLOP) (begin-comment) (end-comment) MAP-VIDEO-BUFFER #-lambda(begin-comment) ((l2-map-physical-page) LDB (BYTE-FIELD 7 8) M-T a-video-buffer-base-phys-page) ((m-a) a-processor-switches) ((m-a) ldb (lisp-byte %%processor-switch-cache-permit-for-video-buffer) m-a) (JUMP-XCT-NEXT PGF-RESTORE) ((L2-MAP-CONTROL) dpb m-a (byte-field 1 14.) (A-CONSTANT 1460)) #-lambda(end-comment) #-exp(begin-comment) ((m-t) ldb (byte-field 7 8) m-t (a-constant (eval (ash #xe80000 -10.)))) ((m-a) a-tv-quad-slot) ((vma-write-l2-map-physical-page) dpb m-a (byte-field 8 14.) a-t) (jump-xct-next pgf-restore) ((vma-write-l2-map-control) (a-constant 1460)) #-exp(end-comment) multibus io page . #-LAMBDA (BEGIN-COMMENT) ((M-A) A-SDU-quad-SLOT) ((L2-MAP-PHYSICAL-PAGE) DPB M-A (BYTE-FIELD 8 14.) (A-CONSTANT (BYTE-MASK (BYTE-FIELD 1 10.)))) (JUMP-XCT-NEXT PGF-RESTORE) packet size code 1 #-LAMBDA (END-COMMENT) #+exp(call illop) MAP-NU-MULTI-MAP-REGS #-LAMBDA (BEGIN-COMMENT) ((M-A) A-SDU-quad-SLOT) map regs begin at 18000(hex ) , ie 140 pages ((M-A) DPB M-A (BYTE-FIELD 8 14.) (A-CONSTANT 140)) four pages of mapping registers . (JUMP-XCT-NEXT PGF-RESTORE) packet size code 1 #-LAMBDA (END-COMMENT) #+EXP (CALL ILLOP) #-lambda(begin-comment) ((M-A) A-TV-quad-SLOT) ((L2-MAP-PHYSICAL-PAGE) DPB M-A (BYTE-FIELD 8 14.) a-zero) (JUMP-XCT-NEXT PGF-RESTORE) ((L2-MAP-CONTROL) (A-CONSTANT 1460)) map-quad-video-control-regs ((m-a) a-video-buffer-base-phys-page) ((l2-map-physical-page) add m-a (a-constant (eval (ash #x80000 -10.)))) (jump-xct-next pgf-restore) ((l2-map-control) (a-constant 1460)) #-lambda(end-comment) #+exp (call illop) one page , mapped to low byte of # xff01c000 in the SDU ( ash # x1c000 -10 . ) = > page 160 on the SDU MAP-sdu-control-regs #-LAMBDA (BEGIN-COMMENT) ((m-a) a-sdu-quad-slot) ((l2-map-physical-page) dpb m-a (byte-field 8 14.) (a-constant 160)) (jump-xct-next pgf-restore) packet size code 1 = byte mode #-LAMBDA (END-COMMENT) #+EXP (CALL ILLOP) map the 32 . page segment map-shared-pages-1 #-lambda(begin-comment) ((M-TEM) a-sys-conf-base-phys-page) ((M-TEM) add M-TEM (a-constant 64.)) ((l2-map-physical-page) add M-TEM a-t) (jump-xct-next pgf-restore) ((l2-map-control) (a-constant 1460)) #-lambda(end-comment) #+exp (call illop) this is the 64 . page segment map-shared-pages-2 #-lambda (begin-comment) ((M-TEM) a-sys-conf-base-phys-page) ((l2-map-physical-page) add M-TEM a-t) (jump-xct-next pgf-restore) ((l2-map-control) (a-constant 1460)) #-lambda(end-comment) #+exp (call illop) map-grey # + exp ( call illop ) ((m-a) a-grey-quad-slot) (jump-less-than m-t (a-constant 176500000) map-grey-pixel) (jump-less-than m-t (a-constant 176700000) map-grey-plane) ((m-t) sub m-t (a-constant 176700000)) map-grey-x ((#+LAMBDA l2-map-physical-page #+EXPLORER vma-write-l2-map-physical-page) dpb m-a (byte-field 8 14.) a-t) (jump-xct-next pgf-restore) ((#+LAMBDA l2-map-control #+EXPLORER vma-write-l2-map-control) (a-constant 1460)) map-grey-pixel ((m-t) sub m-t (a-constant 176300000)) (jump-xct-next map-grey-x) to page 0 in slot space . map-grey-plane ((m-t) sub m-t (a-constant 176500000)) ((m-t) ldb m-t (byte-field 8 8) a-zero) (jump-xct-next map-grey-x) PGF-L2A (CALL SEARCH-PAGE-HASH-TABLE) FOUND , CHK SW STS PGF-L2A-RELOAD-ONLY (declare (clobbers a-t a-tem a-tem3 a-tem1 a-lam)) (CALL SEARCH-PAGE-HASH-TABLE) FOUND , CHK SW STS (LOCALITY D-MEM) D-PGF-PHT 0 PHT ENTRY INVALID , GET PAGE FROM DISK 1 NORMAL , RELOAD PAGE MAP 2 FLUSHABLE , CHANGE BACK TO NORMAL 3 PREPAGED , CHANGE TO NORMAL , WE WANT IT NOW 4 AGE , CHANGE BACK TO NORMAL 5 WIRED DOWN , RELOAD PAGE MAP 6 NOT USED 7 NOT USED (END-DISPATCH) (LOCALITY D-MEM) D-PGF-PHT-RELOAD-ONLY 0 PHT ENTRY INVALID , GET PAGE FROM DISK 1 NORMAL , RELOAD PAGE MAP 2 FLUSHABLE , CHANGE BACK TO NORMAL 3 PREPAGED , CHANGE TO NORMAL , WE WANT IT NOW 4 AGE , CHANGE BACK TO NORMAL 5 WIRED DOWN , RELOAD PAGE MAP 6 NOT USED 7 NOT USED (END-DISPATCH) jumps to pgf - mar-{read , write}-trap , or drops through 0 READ , MAR DISABLED 1 READ , READ - TRAP 2 READ , WRITE - TRAP 3 READ , READ - WRITE - TRAP 4 WRITE , MAR DISABLED 5 WRITE , READ - TRAP 6 WRITE , WRITE - TRAP 7 WRITE , READ - WRITE - TRAP (END-DISPATCH) (LOCALITY I-MEM) The VMA is still valid , the MD has been clobbered to the VMA but if writing is saved in A - PGF - WMD , and M - PGF - WRITE says type of cycle . If this traps , VMA and M - PGF - WRITE will still be valid as saved by SGLV . A read can be recovered just by returning from PGF - R , since the MAR is inhibited during stack - group switching . then do n't take one ((M-PGF-TEM) Q-POINTER VMA (A-CONSTANT (BYTE-VALUE Q-DATA-TYPE DTP-FIX))) (JUMP-GREATER-THAN M-PGF-TEM A-MAR-HIGH PGF-MAR1) Take MAR break if necessary PGF-MAR1 (JUMP-IF-BIT-CLEAR M-PGF-WRITE PGF-R-PDL) (JUMP PGF-W-PDL) * * * following two should probably be pushing DTP - LOCATIVEs most of the time pgf-mar-read-trap ((pdl-push) dpb vma q-pointer (a-constant (byte-value q-data-type dtp-fix))) ((pdl-push) ldb q-data-type vma (a-constant (byte-value q-data-type dtp-fix))) (call trap) (ERROR-TABLE MAR-BREAK READ) to continue , the debugger should pop two , then exit without calling pgf-mar-write-trap ((pdl-push) dpb vma q-pointer (a-constant (byte-value q-data-type dtp-fix))) ((pdl-push) ldb q-data-type vma (a-constant (byte-value q-data-type dtp-fix))) ((m-tem) a-pgf-wmd) ((PDL-PUSH) DPB m-tem Q-POINTER (A-CONSTANT (BYTE-VALUE Q-DATA-TYPE DTP-FIX))) ((PDL-PUSH) LDB Q-DATA-TYPE m-tem (A-CONSTANT (BYTE-VALUE Q-DATA-TYPE DTP-FIX))) (call trap) (ERROR-TABLE MAR-BREAK WRITE) to continue , optionally do the write in macrocode , pop 4 , then exit without calling PGF-SPECIAL-A-MEMORY-REFERENCE JUMP IF CYCLE IS A WRITE ((OA-REG-HIGH) DPB M-T OAH-A-SRC-10-BITS A-ZERO) MUST BE 0 MODULO A - MEMORY SIZE (JUMP-XCT-NEXT PGF-RESTORE) PGF-SA-W ((M-A) A-V-TRUE) (JUMP-NOT-EQUAL M-A A-PGF-MODE PGF-SA-W-NOT-BINDING) ( JUMP - EQUAL M - A A - AMEM - EVCP - VECTOR PGF - SA - W - NOT - BINDING ) PGF - SA - W - NOT - BINDING ) ( ( VMA - START - READ ) M+A+1 A - AMEM - EVCP - VECTOR VMA ) ( ( ) Q - TYPED - POINTER MD ) ( JUMP - EQUAL MD A - V - NIL PGF - SA - BIND - NO - EVCP ) ( ( VMA ) ) ( ( M - TEM ) ( BYTE - FIELD 10 . 0 ) C - PDL - BUFFER - POINTER ) PGF - SA - BIND - NO - EVCP ( ( VMA ) C - PDL - BUFFER - POINTER - POP ) ( ( C - PDL - BUFFER - POINTER - PUSH ) VMA ) ( JUMP - EQUAL M - TEM ( A - CONSTANT ( EVAL DTP - EXTERNAL - VALUE - CELL - POINTER ) ) ( ( ) A - V - NIL ) PGF - SA - BIND - NEW - EVCP ( ( VMA ) ( BYTE - FIELD 10 . 0 ) VMA ) ( ( VMA - START - WRITE ) M+A+1 A - AMEM - EVCP - VECTOR VMA ) ( JUMP - EQUAL MD A - V - NIL PGF - SA - BIND - NO - NEW - EVCP ) If thing to be stored is an EVCP , store the contents of where it points . ((M-TEM) A-PGF-WMD) ( JUMP - NOT - EQUAL M - TEM ( A - CONSTANT ( EVAL DTP - EXTERNAL - VALUE - CELL - POINTER ) ) PGF - SA - W - NOT - BINDING ) an attempt to store an EVCP in A - MEM must be part of an attempt to closure bind A - MEM , (call-data-type-equal m-tem (A-CONSTANT (BYTE-VALUE Q-DATA-TYPE DTP-EXTERNAL-VALUE-CELL-POINTER)) illop) ( JUMP - DATA - TYPE - NOT - EQUAL M - TEM ( A - CONSTANT ( BYTE - VALUE Q - DATA - TYPE DTP - EXTERNAL - VALUE - CELL - POINTER ) ) PGF - SA - W - NOT - BINDING ) ( ( VMA - START - READ ) A - PGF - WMD ) ( ( A - PGF - WMD ) MD ) ( POPJ ) PGF - SA - BIND - NO - NEW - EVCP PGF-SA-W-NOT-BINDING ((M-T) DPB M-ZERO (BYTE-FIELD 22. 10.) A-PGF-VMA) ((OA-REG-LOW) DPB M-T OAL-A-DEST-10-BITS A-ZERO) ((A-GARBAGE) A-PGF-WMD) ((MD) A-PGF-WMD) (JUMP-XCT-NEXT PGF-RESTORE) PGF-SM-W((OA-REG-LOW) DPB M-T OAL-M-DEST A-ZERO) ((M-GARBAGE MD) A-PGF-WMD) (JUMP-XCT-NEXT PGF-RESTORE) dispatch to here is a JUMP , not a PUSHJ . (CALL-IF-BIT-CLEAR M-PGF-WRITE ILLOP) (JUMP-EQUAL A-PGF-MODE M-MINUS-ONE FORCE-WR-RDONLY) ((M-TEM) DPB M-ZERO Q-ALL-BUT-TYPED-POINTER A-INHIBIT-READ-ONLY) (CALL-EQUAL M-TEM A-V-NIL TRAP) drop into FORCE - WR - RDONLY Second - level map is set - up and grants read - only access . FORCE-WR-RDONLY (CALL PGF-SAVE) (CALL-XCT-NEXT SEARCH-PAGE-HASH-TABLE) ((VMA M-T) A-PGF-VMA) ((WRITE-MEMORY-DATA-START-WRITE) IOR READ-MEMORY-DATA (A-CONSTANT (BYTE-MASK PHT1-MODIFIED-BIT))) (ILLOP-IF-PAGE-FAULT) ((#+lambda l2-map-control #+exp vma-write-l2-map-control (A-CONSTANT (BYTE-VALUE MAP2C-ACCESS-CODE 3))) Note : this has to be careful to do a write cycle on the original VMA / MD , Restore original VMA (ILLOP-IF-PAGE-FAULT) ((#+lambda l2-map-control #+exp vma-write-l2-map-control) dpb vma map2c-access-code a-tem) (CALL PGF-RESTORE) (VMA) A-PGF-VMA) ((MD) A-PGF-WMD) HERE FOR READ - WRITE - FIRST TRAP PGF-RWF (CALL-IF-BIT-CLEAR M-PGF-WRITE ILLOP) (CALL PGF-SAVE) (CALL-XCT-NEXT SEARCH-PAGE-HASH-TABLE) ((M-T) A-PGF-VMA) IOR READ-MEMORY-DATA (A-CONSTANT (BYTE-MASK PHT1-MODIFIED-BIT))) (ILLOP-IF-PAGE-FAULT) GET SECOND WORD TABLE SUPPOSED TO BE WIRED (declare (restores (a-a a-pgf-a))) ((M-B) READ-MEMORY-DATA) ((WRITE-MEMORY-DATA-START-WRITE M-LAM) DPB M-LAM PHT2-MAP-STATUS-CODE A-B) (ILLOP-IF-PAGE-FAULT) (declare (restores (a-b a-pgf-b))) ((M-B) A-PGF-B) PHT2 SAME AS TO 2ND LVL MAP ( ON CADR ) (POPJ-AFTER-NEXT NO-OP) (declare (restores (a-t a-pgf-t))) GO RETRY MEMORY CYCLE ( used to reload VMA randomly , as well ) PGF-PRE (declare (clobbers a-tem a-lam)) ((A-DISK-PREPAGE-USED-COUNT) M+A+1 M-ZERO A-DISK-PREPAGE-USED-COUNT) REFERENCE TO PAGE WITH AGE TRAP . CHANGE BACK TO NORMAL TO INDICATE PAGE HAS , AND SHOULDN'T BE SWAPPED OUT OR MADE FLUSHABLE . PGF-AG (declare (clobbers a-tem a-lam)) ((WRITE-MEMORY-DATA-START-WRITE) SELECTIVE-DEPOSIT READ-MEMORY-DATA SW STS : = NORMAL PGF-RL (declare (clobbers a-tem a-lam)) ((M-T) L1-MAP-L2-BLOCK-SELECT L1-MAP) TABLE SUPPOSED TO BE WIRED (declare (restores (a-a a-pgf-a) (a-b a-pgf-b))) ((M-B) A-PGF-B) COMES DIRECTLY FROM PHT2 ( on cadr ) (CALL LOAD-L2-MAP-FROM-CADR-PHYSICAL) (POPJ-AFTER-NEXT NO-OP) (declare (restores (a-t a-pgf-t))) ((VMA M-T) A-PGF-T) OR VMA POINTING TO FIRST HOLE IN HASH TABLE AND PHT1 - VALID - BIT This version is 7 cycles per iteration , as compared with 10 cycles for the search-page-hash-table (declare (args a-t) (values a-tem3 a-t) (clobbers a-tem a-tem1)) (call-greater-or-equal m-t a-pht-index-limit pht-wraparound) We usually do n't win first time . Page not in PHT . (popj) XCPH (MISC-INST-ENTRY %COMPUTE-PAGE-HASH) (CALL-XCT-NEXT COMPUTE-PAGE-HASH) ((M-T) Q-POINTER C-PDL-BUFFER-POINTER-POP) (POPJ-AFTER-NEXT (M-T) Q-POINTER M-T (A-CONSTANT (BYTE-VALUE Q-DATA-TYPE DTP-FIX))) Execute one more instruction , clobbering A - TEM1 . so well because physical memory sizes have increased by a factor of 4 - 8 times about 25 % fewer collisions than the old one . KHS 851222 . ( ( m - t ) a - tem1 ) ( popj - after - next popj - less - than m - t a - pht - index - limit ) New algorithm , 3 - DEC-80 (declare (args a-t) (values a-t) (clobbers a-tem1)) VMA<23:14 > ((M-T) XOR M-T A-TEM1) ((M-T) AND M-T A-PHT-INDEX-MASK) pht-wraparound (declare (args a-t) (values a-t)) (POPJ-AFTER-NEXT POPJ-LESS-THAN M-T A-PHT-INDEX-LIMIT) FIRST , FIND SOME MEMORY . ENTER A LOOP THAT SEARCHES PHYSICAL - PAGE - DATA , HAVING FOUND A PAGE TO REPLACE , WRITE IT TO THE DISK IF NECESSARY . THEN DELETE PERFORM THE DISK READ INTO THE CORE PAGE THUS MADE FREE . REGION CONTAINING THE PAGE BEING REFERENCED , AND GET THE META BITS . REFERENCED TO FIND THE FIRST HOLE ( MAY HAVE MOVED DUE TO DELETION ) AND PUT IN AN ENTRY FOR THAT PAGE . RESTART THE REFERENCE ( SET UP THE MAP FIRST ? ) SWAPIN (declare (local a-disk-page-read-count a-disk-page-write-count a-disk-error-count a-disk-fresh-page-count a-disk-swapin-virtual-address a-disk-swap-in-ccw-pointer a-disk-swapin-size a-disk-read-compare-rewrites a-disk-ecc-count a-disk-read-compare-rereads a-disk-page-read-op-count a-disk-page-write-op-count a-disk-page-write-wait-count a-disk-page-write-busy-count a-disk-page-write-appends a-disk-page-read-appends)) decide how many pages to bring in with one disk op . Must not bring in again a page ((A-DISK-SWAPIN-VIRTUAL-ADDRESS) DPB M-ZERO Q-ALL-BUT-POINTER A-PGF-VMA) ((A-DISK-SWAP-IN-CCW-POINTER) (A-CONSTANT DISK-SWAP-IN-CCW-BASE)) ((A-DISK-SWAPIN-SIZE) (A-CONSTANT 1)) ((M-TEM) A-DISK-SWITCHES) ((C-PDL-BUFFER-POINTER-PUSH) A-DISK-SWAPIN-VIRTUAL-ADDRESS) = > region number in M - T .. no XCT - NEXT . ((A-DISK-SAVE-PGF-T) M-T) ((VMA-START-READ) ADD M-T A-V-REGION-BITS) (ILLOP-IF-PAGE-FAULT) ((A-DISK-SAVE-PGF-A) A-DISK-SWAPIN-VIRTUAL-ADDRESS) ((A-DISK-SAVE-1) (LISP-BYTE %%REGION-SWAPIN-QUANTUM) READ-MEMORY-DATA) SWAPIN-SIZE-LOOP (JUMP-GREATER-OR-EQUAL M-ZERO A-DISK-SAVE-1 SWAPIN-SIZE-X) ((M-A) (A-CONSTANT (EVAL PAGE-SIZE))) ((A-DISK-SAVE-PGF-A) ADD M-A A-DISK-SAVE-PGF-A) ((C-PDL-BUFFER-POINTER-PUSH) A-DISK-SAVE-PGF-A) (CALL XRGN) (CALL-XCT-NEXT SEARCH-PAGE-HASH-TABLE) ((M-T) A-DISK-SAVE-PGF-A) (jump-if-bit-set m-transport-flag swapin-append-page) (jump-if-bit-clear m-scavenge-flag swapin-append-page) ((m-lam) a-disk-save-pgf-a) (call-xct-next read-page-volatility) ((m-lam) q-page-number m-lam) (jump-less-than m-tem a-scavenge-volatility swapin-size-x) swapin-append-page ((A-DISK-PAGE-READ-APPENDS) M+A+1 M-ZERO A-DISK-PAGE-READ-APPENDS) ((A-DISK-SWAPIN-SIZE) M+A+1 M-ZERO A-DISK-SWAPIN-SIZE) (JUMP-XCT-NEXT SWAPIN-SIZE-LOOP) ((A-DISK-SAVE-1) ADD (M-CONSTANT -1) A-DISK-SAVE-1) SWAPIN-SIZE-X #+exp (jump swapin0-a) #-lambda(begin-comment) ((M-TEM) A-PROCESSOR-SWITCHES) JUMP ON NO FAST CACHE ((M-TEM3) A-DISK-SWAPIN-VIRTUAL-ADDRESS) LOW 4 BITS OF VIRTUAL PAGE NUMBER . (CALL LOAD-SCAN-FOR-HEXADEC) (CALL XFIND-HEXA0) (CALL STORE-SCAN-FOR-HEXADEC) (JUMP SWAPIN1) #-lambda(end-comment) SWAPIN-LOOP #+exp (jump swapin0-a) #-lambda(begin-comment) JUMP ON NO FAST CACHE ((M-TEM3) ADD M-TEM3 (A-CONSTANT 1)) (CALL LOAD-SCAN-FOR-HEXADEC) (CALL XFIND-HEXA0) (CALL STORE-SCAN-FOR-HEXADEC) (JUMP SWAPIN1) #-lambda(end-comment) XFINDCORE-HEXADEC (MISC-INST-ENTRY %FINDCORE-HEXADEC) #-exp(begin-comment) ((m-garbage) pdl-pop) (jump xfindcore) #-exp(end-comment) #-lambda(begin-comment) Find memory with specified low 4 bits of physical page number . ((M-TEM3) Q-POINTER C-PDL-BUFFER-POINTER-POP) (call load-scan-for-hexadec) (call XFIND-HEXA0) (call store-scan-for-hexadec) #-lambda(end-comment) return-m-b-as-fixnum (popj-after-next (m-t) dpb m-b q-pointer (a-constant (byte-value q-data-type dtp-fix))) (no-op) XFINDCORE (MISC-INST-ENTRY %FINDCORE) ((MICRO-STACK-DATA-PUSH) (A-CONSTANT (I-MEM-LOC RETURN-M-B-as-fixnum))) XFIND-HEXA0 FINDCORE0 ((m-b) add m-b (a-constant 1)) (CALL-GREATER-OR-EQUAL M-B A-V-PHYSICAL-PAGE-DATA-VALID-LENGTH FINDCORE2) ((VMA-START-READ) ADD M-B A-V-PHYSICAL-PAGE-DATA) Did all pages but 1 , no luck (JUMP-NOT-EQUAL M-TEM3 (A-CONSTANT -1) FINDCORE-IN-HEXADEC) Added I - LONG to this ldb , since it seems to lose occasionally . KHS 840912 #+EXP ((M-TEM) (BYTE-FIELD 20 0) READ-MEMORY-DATA) ((A-COUNT-FINDCORE-STEPS) M+A+1 M-ZERO A-COUNT-FINDCORE-STEPS) ((VMA-START-READ M-T) ADD M-TEM A-V-PAGE-TABLE-AREA) (illop-if-page-fault) (DISPATCH PHT1-SWAP-STATUS-CODE READ-MEMORY-DATA D-FINDCORE) (CALL-GREATER-OR-EQUAL M-B A-V-PHYSICAL-PAGE-DATA-VALID-LENGTH FINDCORE2) Reached end of memory . Wrap around to page zero . There can be pageable (declare (values a-b)) (POPJ-AFTER-NEXT (M-B) A-ZERO) (NO-OP) FINDCORE-IN-HEXADEC ((M-TEM) LDB (BYTE-FIELD 4 0) M-B) ((A-COUNT-FINDCORE-STEPS) M+A+1 M-ZERO A-COUNT-FINDCORE-STEPS) Added I - LONG to this ldb , since it seems to lose occasionally . KHS 840912 #+EXP ((M-TEM) (BYTE-FIELD 20 0) READ-MEMORY-DATA) ((VMA-START-READ M-T) ADD M-TEM A-V-PAGE-TABLE-AREA) (illop-if-page-fault) (DISPATCH PHT1-SWAP-STATUS-CODE READ-MEMORY-DATA D-FINDCORE) (CALL-GREATER-OR-EQUAL M-B A-V-PHYSICAL-PAGE-DATA-VALID-LENGTH FINDCORE2) FINDCORE3 ((A-COUNT-FINDCORE-EMERGENCIES) M+A+1 M-ZERO A-COUNT-FINDCORE-EMERGENCIES) (CALL-XCT-NEXT AGER) ((M-1) A-FINDCORE-SCAN-POINTER) ((M-1) M-T) (LOCALITY D-MEM) 1 NORMAL 2 FLUSHABLE 3 PREPAGE 4 AGE TRAP 5 WIRED DOWN 6 NOT USED 7 NOT USED (END-DISPATCH) 0 ILLEGAL ( LVL 1 MAP ) 1 ILLEGAL ( LVL 2 MAP ) 2 READ ONLY 3 READ / WRITE FIRST 4 READ / WRITE - INDICATES PAGE MODIFIED 5 PDL BUFFER , ALWAYS WRITE PDL - BUFFER PAGES 6 MAR BREAK , ALWAYS WRITE FOR SAME REASON 7 nubus physical in PHT2 (END-DISPATCH) 0 ILLEGAL ( LVL 1 MAP ) 1 ILLEGAL ( LVL 2 MAP ) 2 READ ONLY 3 READ / WRITE FIRST 4 READ / WRITE - INDICATES PAGE MODIFIED 5 PDL BUFFER , ALWAYS WRITE PDL - BUFFER PAGES HOWEVER , WE DONT THESE . 6 MAR BREAK , ALWAYS WRITE FOR SAME REASON HOWEVER , WE DONT THESE . 7 nubus physical in PHT2 (END-DISPATCH) (LOCALITY I-MEM) VMA and are for the PHT1 . M - T same as VMA . COREFOUND-PRE (JUMP-XCT-NEXT COREFOUND0) ((A-DISK-PREPAGE-NOT-USED-COUNT) M+A+1 M-ZERO A-DISK-PREPAGE-NOT-USED-COUNT) COREFOUND COREFOUND0 (CALL-IF-BIT-CLEAR PHT1-VALID-BIT READ-MEMORY-DATA ILLOP) COREFOUND1 Trace page eviction (CALL-IF-BIT-SET (LISP-BYTE %%METER-PAGE-FAULT-ENABLE) M-METER-ENABLES METER-PAGE-OUT) (JUMP-IF-BIT-SET PHT1-MODIFIED-BIT M-A COREFOUND1A) (DISPATCH PHT2-MAP-STATUS-CODE PHT1 address . - randomly used below to restore m - t ((A-DISK-SWAP-OUT-CCW-POINTER) (A-CONSTANT DISK-SWAP-OUT-CCW-BASE)) ((A-DISK-PAGE-WRITE-COUNT) M+A+1 M-ZERO A-DISK-PAGE-WRITE-COUNT) add main memory page frame number in M - B to CCW list . #-lambda(begin-comment) ((WRITE-MEMORY-DATA) DPB M-B VMA-PHYS-PAGE-ADDR-PART (A-CONSTANT 1)) ((VMA-START-WRITE) A-DISK-SWAP-OUT-CCW-POINTER) (ILLOP-IF-PAGE-FAULT) ((A-DISK-SWAP-OUT-CCW-POINTER) ADD A-DISK-SWAP-OUT-CCW-POINTER M-ZERO ALU-CARRY-IN-ONE) #-lambda(end-comment) #-exp(begin-comment) ((m-t) dpb m-b vma-phys-page-addr-part a-zero) (call translate-cadr-physical-to-nubus) ((md) m-lam) ((vma-start-write) a-disk-swap-out-ccw-pointer) (illop-if-page-fault) ((md) (a-constant 1024.)) ((vma-start-write) add vma (a-constant 1)) (illop-if-page-fault) ((a-disk-swap-out-ccw-pointer) add vma (a-constant 1)) ((m-t) pdl-top) #-exp(end-comment) ((A-DISK-SAVE-PGF-A) M-A) ((A-DISK-SAVE-PGF-B) M-B) (JUMP-IF-BIT-CLEAR (BYTE-FIELD 1 2) M-TEM COREF-CCW-X) ((A-DISK-SAVE-1) M-A) COREF-CCW-0 ((M-T) (A-CONSTANT (EVAL PAGE-SIZE))) ((A-DISK-SAVE-1) ADD M-T A-DISK-SAVE-1) virt adr in M - T. (ILLOP-IF-PAGE-FAULT) ((M-B) READ-MEMORY-DATA) (JUMP-IF-BIT-SET PHT1-MODIFIED-BIT M-A COREF-CCW-ADD) COREF-CCW-ADD ((WRITE-MEMORY-DATA M-A) ANDCA M-A ((VMA-START-WRITE) M-T) (ILLOP-IF-PAGE-FAULT) ((M-TEM) PHT2-MAP-STATUS-CODE M-B) change RW to RWF ((M-TEM) (A-CONSTANT 3)) ((WRITE-MEMORY-DATA M-B) DPB M-TEM PHT2-MAP-STATUS-CODE A-B) ((VMA-START-WRITE) ADD M-T (A-CONSTANT 1)) (ILLOP-IF-PAGE-FAULT) (JUMP-LESS-THAN M-TEM (A-CONSTANT 2) COREF-CCW-ADD-1) PHT2 same as 2ND LVL MAP(on cadr ) ((M-LAM) M-B) COREF-CCW-ADD-1 ((A-DISK-PAGE-WRITE-APPENDS) M+A+1 M-ZERO A-DISK-PAGE-WRITE-APPENDS) ((A-DISK-PAGE-WRITE-COUNT) M+A+1 M-ZERO A-DISK-PAGE-WRITE-COUNT) add main memory page frame number in M - B to CCW list . #-lambda(begin-comment) ((WRITE-MEMORY-DATA) DPB M-B VMA-PHYS-PAGE-ADDR-PART (A-CONSTANT 1)) ((VMA-START-WRITE) A-DISK-SWAP-OUT-CCW-POINTER) (ILLOP-IF-PAGE-FAULT) ((A-DISK-SWAP-OUT-CCW-POINTER) M+A+1 A-DISK-SWAP-OUT-CCW-POINTER M-ZERO) #-lambda(end-comment) #-exp (begin-comment) ((m-tem1) m-t) ((m-t) dpb m-b vma-phys-page-addr-part a-zero) (call translate-cadr-physical-to-nubus) ((md) m-lam) ((vma-start-write) a-disk-swap-out-ccw-pointer) (illop-if-page-fault) ((md) (a-constant 1024.)) ((vma-start-write) add vma (a-constant 1)) (illop-if-page-fault) ((a-disk-swap-out-ccw-pointer) add vma (a-constant 1)) ((m-t) m-tem1) #-exp(end-comment) ((M-TEM) A-DISK-SWAP-OUT-CCW-POINTER) (JUMP-LESS-THAN M-TEM (A-CONSTANT DISK-SWAP-OUT-CCW-MAX) COREF-CCW-0) COREF-CCW-X #-lambda(begin-comment) ((VMA-START-READ) ADD A-DISK-SWAP-OUT-CCW-POINTER (M-CONSTANT -1)) (ILLOP-IF-PAGE-FAULT) last CCW (ILLOP-IF-PAGE-FAULT) #-lambda(end-comment) ((A-DISK-PAGE-WRITE-OP-COUNT) M+A+1 M-ZERO A-DISK-PAGE-WRITE-OP-COUNT) get back page frame number of first ((C-PDL-BUFFER-POINTER-PUSH) M-C) M - C ((m-tem4) a-disk-swap-out-ccw-pointer) divide by 2 Do the write ( virt adr in M - A ) ((M-T) (A-CONSTANT DISK-WRITE-COMMAND)) ((M-C) C-PDL-BUFFER-POINTER-POP) ((A-DISK-PAGE-WRITE-WAIT-COUNT) M+A+1 M-ZERO A-DISK-PAGE-WRITE-WAIT-COUNT) RESTORE PHT ENTRY ADDRESS AT THIS POINT , M - T HAS ADDR OF PHT ENTRY TO BE DELETED , DELETION WORKS BY FINDING PAGES THAT SHOULD HAVE HASHED TO THE CONVENTIONS : M - B POINTS AT THE HOLE , VMA POINTS AT THE ITEM SUSPECTED OF BEING IN THE WRONG PLACE , M - PGF - TEM POINTS AT THE UPPERMOST ENTRY IN THE PHT , M - T POINTS AT WHERE ( VMA ) SHOULD HAVE HASHED TO . THESE ARE TYPELESS ABSOLUTE ADDRESSES . COREFOUND2 Remove pointer to PHT entry ((VMA-START-WRITE) ADD M-B A-V-PHYSICAL-PAGE-DATA) (ILLOP-IF-PAGE-FAULT) ((M-PGF-TEM) DPB M-ZERO Q-ALL-BUT-POINTER A-V-PAGE-TABLE-AREA) ((VMA-START-WRITE M-B) Q-POINTER M-B) PHTDEL3 (ILLOP-IF-PAGE-FAULT) (JUMP-IF-BIT-CLEAR PHT1-VALID-BIT READ-MEMORY-DATA PHTDELX) ((M-T) READ-MEMORY-DATA) ((VMA-START-READ) ADD VMA (A-CONSTANT 1)) (ILLOP-IF-PAGE-FAULT) Address the hole , store PHT2 (ILLOP-IF-PAGE-FAULT) error check for clobbering PPD entry 0 (call-equal m-tem a-zero illop) ((VMA-START-READ) ADD M-TEM A-V-PHYSICAL-PAGE-DATA) (ILLOP-IF-PAGE-FAULT) * * * Will need to be changed if gets Bigger * * * ((WRITE-MEMORY-DATA-START-WRITE) SELECTIVE-DEPOSIT READ-MEMORY-DATA (BYTE-FIELD 20 20) A-TEM) (ILLOP-IF-PAGE-FAULT) ((VMA) M-B) (ILLOP-IF-PAGE-FAULT) ((M-B) M-T) Wrap around to beg of ((VMA-START-READ) DPB M-ZERO Q-ALL-BUT-POINTER A-V-PAGE-TABLE-AREA) #+exp (no-op) (POPJ-AFTER-NEXT (#+lambda L2-MAP-CONTROL Note that if we have a first - level map miss , this does no harm Do n't leave garbage in VMA . swapin0-a (call swapin0) We have found one page of core , store it away in the CCW and loop add main memory page frame number in M - B to CCW list . #-lambda(begin-comment) ((WRITE-MEMORY-DATA) DPB M-B VMA-PHYS-PAGE-ADDR-PART (A-CONSTANT 1)) ((VMA-START-WRITE) A-DISK-SWAP-IN-CCW-POINTER) (ILLOP-IF-PAGE-FAULT) ((A-DISK-SWAP-IN-CCW-POINTER) M+A+1 A-DISK-SWAP-IN-CCW-POINTER M-ZERO) #-lambda(end-comment) #-exp(begin-comment) ((m-tem1) m-t) ((m-t) dpb m-b vma-phys-page-addr-part a-zero) (call translate-cadr-physical-to-nubus) ((md) m-lam) ((vma-start-write) a-disk-swap-in-ccw-pointer) (illop-if-page-fault) ((md) (a-constant 1024.)) ((vma-start-write) add vma (a-constant 1)) (illop-if-page-fault) ((a-disk-swap-in-ccw-pointer) add vma (a-constant 1)) ((m-t) m-tem1) #-exp(end-comment) ((A-DISK-PAGE-READ-COUNT) ADD M-ZERO A-DISK-PAGE-READ-COUNT ALU-CARRY-IN-ONE) ((A-DISK-SWAPIN-SIZE) ADD A-DISK-SWAPIN-SIZE (M-CONSTANT -1)) (JUMP-NOT-EQUAL A-DISK-SWAPIN-SIZE M-ZERO SWAPIN-LOOP) #-lambda(begin-comment) finish ccw list (ILLOP-IF-PAGE-FAULT) (ILLOP-IF-PAGE-FAULT) #-lambda(end-comment) CONTINUE SWAPPING IN . NEXT STEP IS TO SEARCH REGION TABLES TO FIND META BITS . to CZRR . ((C-PDL-BUFFER-POINTER-PUSH) M-C) CCW list pointer ( CLP ) ((m-tem4) a-disk-swap-in-ccw-pointer) divide by 2 ((M-T) (A-CONSTANT DISK-READ-COMMAND)) ((M-C) C-PDL-BUFFER-POINTER-POP) SWAPIN2 Now loop through ccw list making the pages known . ((M-B) (A-CONSTANT DISK-SWAP-IN-CCW-BASE)) First page in gets normal swap - status ((A-PAGE-IN-PHT1) (A-CONSTANT (PLUS (BYTE-VALUE PHT1-VALID-BIT 1) (BYTE-VALUE PHT1-SWAP-STATUS-CODE 1)))) ((A-DISK-PAGE-READ-OP-COUNT) ADD M-ZERO A-DISK-PAGE-READ-OP-COUNT ALU-CARRY-IN-ONE) SWAPIN2-LOOP Trace page swapin (CALL-IF-BIT-SET (LISP-BYTE %%METER-PAGE-FAULT-ENABLE) M-METER-ENABLES METER-PAGE-IN) ((VMA-START-READ) M-B) (ILLOP-IF-PAGE-FAULT) #-exp (begin-comment) ((m-lam) md) (call translate-nubus-to-cadr-physical) ((md) m-lam) #-exp (end-comment) ((A-DISK-SWAPIN-PAGE-FRAME) LDB VMA-PHYS-PAGE-ADDR-PART READ-MEMORY-DATA A-ZERO) ((C-PDL-BUFFER-POINTER-PUSH) M-B) (CALL PAGE-IN-MAKE-KNOWN) ((M-B) C-PDL-BUFFER-POINTER-POP) ((M-A) (A-CONSTANT (EVAL PAGE-SIZE))) ((A-DISK-SWAPIN-VIRTUAL-ADDRESS) ADD M-A A-DISK-SWAPIN-VIRTUAL-ADDRESS) ((m-b) add m-b (a-constant #+lambda 1 #+exp 2)) (JUMP-LESS-THAN-XCT-NEXT M-B A-DISK-SWAP-IN-CCW-POINTER SWAPIN2-LOOP) Pages after the first get pre - paged swap - status ((A-PAGE-IN-PHT1) (A-CONSTANT (PLUS (BYTE-VALUE PHT1-VALID-BIT 1) (BYTE-VALUE PHT1-SWAP-STATUS-CODE 3)))) SWAPIN2-X Get PHT2 bits and leave them in A - DISK - SWAPIN - PHT2 - BITS . ((C-PDL-BUFFER-POINTER-PUSH) A-DISK-SWAPIN-VIRTUAL-ADDRESS) ((M-A) DPB M-ZERO Q-ALL-BUT-POINTER A-DISK-SWAPIN-VIRTUAL-ADDRESS) ((m-tem) ldb (lisp-byte %%region-map-bits) md) ((a-disk-swapin-pht2-bits) dpb m-tem pht2-access-status-and-meta-bits a-zero) ( ( a - disk - swapin - pht2 - bits ) pht2 - map - volatility a - disk - swapin - pht2 - bits ) ( ( M - TEM ) SELECTIVE - DEPOSIT READ - MEMORY - DATA ( LISP - BYTE % % REGION - MAP - BITS ) a - zero ) ( ( A - DISK - SWAPIN - PHT2 - BITS ) M - TEM ) Check VMA against MAR ((M-T) SELECTIVE-DEPOSIT M-T VMA-PAGE-ADDR-PART A-ZERO) (POPJ-LESS-THAN M-A A-T) ((M-T) A-MAR-HIGH) ((M-T) SELECTIVE-DEPOSIT M-T VMA-PAGE-ADDR-PART (A-CONSTANT (EVAL (1- PAGE-SIZE)))) If MAR to be set , change map status and turn off (POPJ-AFTER-NEXT ((A-DISK-SWAPIN-PHT2-BITS) DPB M-T PHT2-MAP-ACCESS-AND-STATUS-CODE A-disk-swapin-pht2-bits) Second part . Make physical page frame number A - DISK - SWAPIN - PHYSICAL - PAGE - FRAME A - DISK - SWAPIN - PHT2 - BITS . A - PAGE - IN - PHT1 contains the bits desired in the PHT1 ( swap status mainly ) PAGE-IN-MAKE-KNOWN ((m-t) a-disk-swapin-virtual-address) (call-xct-next read-page-volatility) ((m-lam) q-page-number m-t) ((a-disk-swapin-pht2-bits) dpb m-tem pht2-map-volatility a-disk-swapin-pht2-bits) (call search-page-hash-table) ((M-A) A-DISK-SWAPIN-VIRTUAL-ADDRESS) Construct and store PHT1 word SELECTIVE-DEPOSIT M-A PHT1-VIRTUAL-PAGE-NUMBER A-PAGE-IN-PHT1) ((M-PGF-TEM) A-DISK-SWAPIN-PAGE-FRAME) ((WRITE-MEMORY-DATA) SELECTIVE-DEPOSIT M-PGF-TEM A-DISK-SWAPIN-PHT2-BITS) ((md) pht2-physical-page-number md) (call-equal md a-zero illop) 0,,Index in PHT ((VMA) A-DISK-SWAPIN-PAGE-FRAME) error check for clobbering PPD entry 0 (call-equal vma a-zero illop) (POPJ-AFTER-NEXT (VMA-START-WRITE) ADD VMA A-V-PHYSICAL-PAGE-DATA) (ILLOP-IF-PAGE-FAULT) (LOCALITY D-MEM) VERIFY MAP STATUS CODE FROM CORE 1 META BITS ONLY ERRONEOUS 2 READ ONLY 3 READ WRITE FIRST 4 READ WRITE 5 PDL BUFFER 6 MAR BREAK 7 nubus physical in PHT2 (END-DISPATCH) (LOCALITY I-MEM) INITIALIZE A FRESH PAGE BY FILLING IT WITH < DTP - TRAP . > Virtual adr in A - DISK - SWAPIN - VIRTUAL - ADDRESS ( no type bits ) , M - B/ PAGE FRAME NUMBER CZRR ((MD) A-MAP-SCRATCH-BLOCK) (CALL-XCT-NEXT LOAD-L2-MAP-FROM-CADR-PHYSICAL) ((M-LAM) DPB M-B pht2-PHYSICAL-PAGE-NUMBER ((M-TEM1) SELECTIVE-DEPOSIT M-ZERO VMA-LOW-BITS A-DISK-SWAPIN-VIRTUAL-ADDRESS) ((M-LAM) A-ZERO) NOTE DTP - TRAP = 0 (ILLOP-IF-PAGE-FAULT) ((VMA) ADD VMA (A-CONSTANT 1)) (JUMP-LESS-THAN-XCT-NEXT M-LAM (A-CONSTANT 377) CZRR1) ((M-LAM) ADD M-LAM (A-CONSTANT 1)) ((A-FRESH-PAGE-COUNT) ADD M-ZERO A-FRESH-PAGE-COUNT ALU-CARRY-IN-ONE) ((VMA) A-V-NIL) #-lambda(begin-comment) hexadec in M - TEM3 (declare (args a-tem3)) ((oa-reg-low) dpb m-tem3 oal-a-dest-4-bits (a-constant (byte-value oal-a-dest 1740))) ((a-garbage) a-findcore-scan-pointer) (popj-after-next (oa-reg-low) dpb m-tem3 oal-a-dest-4-bits (a-constant (byte-value oal-a-dest 1760))) ((a-garbage) a-aging-scan-pointer) hexadec in M - TEM3 (declare (args a-tem3)) ((oa-reg-high) dpb m-tem3 oah-a-src-4-bits (a-constant (byte-value oah-a-src 1740))) ((a-findcore-scan-pointer) seta a-garbage) (popj-after-next (oa-reg-high) dpb m-tem3 oah-a-src-4-bits (a-constant (byte-value oah-a-src 1760))) ((a-aging-scan-pointer) seta a-garbage) #-lambda(end-comment) Ager . Called from DISK - SWAP - HANDLER , may clobber M-1 , A - TEM1 , A - TEM2 , A - TEM3 , M - TEM . Must be called with A - AGING - SCAN - POINTER in M-1 . AGER0 ((M-1) ADD M-1 (A-CONSTANT 1)) ((VMA-START-READ) ADD M-1 A-V-PHYSICAL-PAGE-DATA) (ILLOP-IF-PAGE-FAULT) Return if caught up , skipping this one ((VMA-START-READ) ADD M-TEM A-V-PAGE-TABLE-AREA) (ILLOP-IF-PAGE-FAULT) (DISPATCH PHT1-SWAP-STATUS-CODE READ-MEMORY-DATA D-AGER) AGER1 (declare (values a-1)) Wrap around to page zero (no-op) (LOCALITY D-MEM) (START-DISPATCH 3 INHIBIT-XCT-NEXT-BIT) 0 PHT ENTRY INVALID , IGNORE 1 NORMAL , SET AGE TRAP 2 FLUSHABLE , IGNORE 3 PREPAGED , IGNORE 4 AGE TRAP , CHANGE TO FLUSHABLE IF AGED ENOUGH 5 WIRED , IGNORE 6 NOT USED , ERROR 7 NOT USED , ERROR (END-DISPATCH) (LOCALITY I-MEM) CHANGE NORMAL TO AGE - TRAP , ALSO TURN OFF HARDWARE MAP ACCESS , SET AGE TO 0 AGER2 ((A-PAGE-AGE-COUNT) ADD M-ZERO A-PAGE-AGE-COUNT ALU-CARRY-IN-ONE) ((WRITE-MEMORY-DATA-START-WRITE) SELECTIVE-DEPOSIT READ-MEMORY-DATA PHT1-ALL-BUT-AGE-AND-SWAP-STATUS-CODE (A-CONSTANT (EVAL %PHT-SWAP-STATUS-AGE-TRAP))) (ILLOP-IF-PAGE-FAULT) ((md) md) (JUMP-XCT-NEXT AGER0) ((#+lambda l2-map-control FLUSH 2ND LVL MAP , IF ANY AGER0 will put good data in VMA . CHANGE AGE - TRAP TO FLUSHABLE IF HAS ENOUGH AGER3 ((M-TEM) PHT1-AGE READ-MEMORY-DATA) (ILLOP-IF-PAGE-FAULT) (JUMP AGER0) AGER4 ((A-PAGE-FLUSH-COUNT) ADD M-ZERO A-PAGE-FLUSH-COUNT ALU-CARRY-IN-ONE) ((WRITE-MEMORY-DATA-START-WRITE) SELECTIVE-DEPOSIT READ-MEMORY-DATA PHT1-ALL-BUT-SWAP-STATUS-CODE (A-CONSTANT (EVAL %PHT-SWAP-STATUS-FLUSHABLE))) (ILLOP-IF-PAGE-FAULT) (JUMP AGER0) XARN (MISC-INST-ENTRY %AREA-NUMBER) GET REGION NUMBER FROM ARG ON PDL REGION-TO-AREA ((vma-start-read) add m-t a-v-region-area-map) (check-page-read) (popj-after-next no-op) ((m-t) q-pointer md (a-constant (byte-value q-data-type dtp-fix))) ( ( VMA - START - READ ) ADD M - T A - V - REGION - LIST - THREAD ) ( JUMP - IF - BIT - CLEAR - XCT - NEXT BOXED - SIGN - BIT READ - MEMORY - DATA REGION - TO - AREA ) ( A - CONSTANT ( BYTE - VALUE Q - DATA - TYPE DTP - FIX ) ) ) IF NOT IN ANY REGION , IN M - T. RETURNS ( OR TAKES AT XRGN1 ) THE POINTER IN M - A. SINCE IT IS CALLED BY THE PAGE FAULT ROUTINES . XRGN (declare (values a-t) (clobbers a-tem a-a)) (MISC-INST-ENTRY %REGION-NUMBER) (A-CONSTANT (BYTE-VALUE Q-DATA-TYPE DTP-FIX))) * * datatype of M - A really should be DTP - LOCATIVE , since it is a pointer . Get word from ADDRESS - SPACE - MAP . (declare (args a-a) (values a-t) (clobbers a-tem)) ((vma) address-space-map-word-index-byte m-a) ((vma-start-read) add vma a-v-address-space-map) (ILLOP-IF-PAGE-FAULT) Byte number in that word ((M-TEM) DPB M-TEM ADDRESS-SPACE-MAP-BYTE-MROT A-ZERO) 40 does n't hurt here , IORed in ((M-T) (BYTE-FIELD (EVAL %ADDRESS-SPACE-MAP-BYTE-SIZE) 0) READ-MEMORY-DATA (A-CONSTANT (BYTE-VALUE Q-DATA-TYPE DTP-FIX))) (POPJ-NOT-EQUAL M-T (A-CONSTANT (BYTE-VALUE Q-DATA-TYPE DTP-FIX))) ((M-T) (A-CONSTANT (A-MEM-LOC A-V-INIT-LIST-AREA))) XRGN2 zero -- if it were less than that the test above would have indicated it as free . ( call - less - than m - t ( a - constant ( a - mem - loc a - v - resident - symbol - area ) ) illop ) ((OA-REG-HIGH) DPB M-T OAH-A-SRC A-ZERO) (JUMP-LESS-THAN-XCT-NEXT M-A A-GARBAGE XRGN2) ((M-T) SUB M-T (A-CONSTANT 1)) (POPJ-AFTER-NEXT (M-T) SUB M-T (A-CONSTANT (DIFFERENCE (A-MEM-LOC A-V-RESIDENT-SYMBOL-AREA) 1))) ((M-T) Q-POINTER M-T (A-CONSTANT (BYTE-VALUE Q-DATA-TYPE DTP-FIX))) XCPGS (MISC-INST-ENTRY %CHANGE-PAGE-STATUS) ARGS ARE VIRTUAL ADDRESS , SWAP STATUS CODE , ACCESS STATUS AND META BITS Here from UPDATE - REGION - PHT . Must bash only M - A , M - B , M - T , tems . Returns address which came in on pdl , in MD . Bit 24 . means disconnect virtual page completely , for % GC - FREE - REGION . Bit 23 . means clear modified bit , for CLEAN - DIRTY - PAGES . XCPGS0 (CALL-XCT-NEXT SEARCH-PAGE-HASH-TABLE) If not swapped in , return NIL , and make ((M-T) A-V-NIL) XCPGS3 ((WRITE-MEMORY-DATA-START-WRITE) pht1 - swap - status is low 3 bits . (ILLOP-IF-PAGE-FAULT) XCPGS1 (JUMP-EQUAL M-E A-V-NIL XCPGS2) ((m-tem3) (byte-field (difference q-pointer-width 2) 2) m-e) ((VMA-START-READ) ADD VMA (A-CONSTANT 1)) (ILLOP-IF-PAGE-FAULT) ((M-TEM2) READ-MEMORY-DATA) ((WRITE-MEMORY-DATA-START-WRITE) DPB m-tem3 PHT2-ACCESS-STATUS-AND-META-BITS-except-volatility A-TEM2) (ILLOP-IF-PAGE-FAULT) ((#+lambda l2-map-control FLUSH 2ND LVL MAP , IF ANY On popj cycle , MUSTN'T MAP - WRITE or affect VMA . xcpgs4 (jump-xct-next xcpgs3) ((md) andca md (A-CONSTANT (BYTE-MASK PHT1-MODIFIED-BIT))) XCPPG (MISC-INST-ENTRY %CREATE-PHYSICAL-PAGE) XCPPG0 (ILLOP-IF-PAGE-FAULT) ((M-TEM) SUB VMA A-V-PAGE-TABLE-AREA) (JUMP-IF-BIT-SET-XCT-NEXT PHT1-VALID-BIT READ-MEMORY-DATA XCPPG0) ((VMA-START-READ) ADD VMA (A-CONSTANT 2)) USELESS MEM CYCLE Enter here from COLD - REINIT - PHT . May smash only M - T. PHT1-VIRTUAL-PAGE-NUMBER (BYTE-VALUE PHT1-VALID-BIT 1)))) (ILLOP-IF-PAGE-FAULT) 0,,PHT INDEX ((VMA-START-WRITE) ADD M-T A-V-PHYSICAL-PAGE-DATA) (ILLOP-IF-PAGE-FAULT) (JUMP-LESS-THAN M-T A-V-PHYSICAL-PAGE-DATA-VALID-LENGTH ((A-V-PHYSICAL-PAGE-DATA-VALID-LENGTH) ADD M-T (A-CONSTANT 1)) ((WRITE-MEMORY-DATA-START-WRITE) IOR M-T (ILLOP-IF-PAGE-FAULT) (JUMP XTRUE) XDPPG (MISC-INST-ENTRY %DELETE-PHYSICAL-PAGE) ARG is physical address PFN too big ((VMA-START-READ) ADD M-B A-V-PHYSICAL-PAGE-DATA) (ILLOP-IF-PAGE-FAULT) ((VMA-START-READ M-T) ADD M-TEM A-V-PAGE-TABLE-AREA) (ILLOP-IF-PAGE-FAULT) Swap it out , delete PHT entry XPAGE-IN (MISC-INST-ENTRY %PAGE-IN) C-PDL-BUFFER-POINTER-POP VMA-PAGE-ADDR-PART A-ZERO) ((M-T) A-DISK-SWAPIN-VIRTUAL-ADDRESS) (CALL-XCT-NEXT PAGE-IN-MAKE-KNOWN) ((A-PAGE-IN-PHT1) (A-CONSTANT (PLUS (BYTE-VALUE PHT1-VALID-BIT 1) (BYTE-VALUE PHT1-SWAP-STATUS-CODE 1)))) even though that in the PHT1 is not . XPGSTS (MISC-INST-ENTRY %PAGE-STATUS) (CALL-XCT-NEXT SEARCH-PAGE-HASH-TABLE) ((M-T) C-PDL-BUFFER-POINTER-POP) (JUMP-IF-BIT-CLEAR PHT1-VALID-BIT MD XFALSE) (POPJ-IF-BIT-SET-XCT-NEXT PHT1-MODIFIED-BIT MD) ((M-T) DPB MD Q-POINTER (A-CONSTANT (BYTE-VALUE Q-DATA-TYPE DTP-FIX))) If modified bit is set in PHT1 , that must be accurate , so return the PHT1 . (ILLOP-IF-PAGE-FAULT) ((M-TEM) PHT2-MAP-STATUS-CODE READ-MEMORY-DATA) (POPJ-AFTER-NEXT POPJ-LESS M-TEM (A-CONSTANT (EVAL %PHT-MAP-STATUS-READ-WRITE))) If PHT2 implies page is modified , return value with modified - bit set . ((M-T) DPB (M-CONSTANT -1) PHT1-MODIFIED-BIT A-T) XPHYADR (MISC-INST-ENTRY %PHYSICAL-ADDRESS) ( POPJ - AFTER - NEXT ( M - T ) DPB l2 - map - physical - page VMA - PHYS - PAGE - ADDR - PART ( A - CONSTANT ( BYTE - VALUE Q - DATA - TYPE DTP - FIX ) ) ) ( ( M - T ) VMA - LOW - BITS MD A - T ) ((M-C) Q-TYPED-POINTER C-PDL-BUFFER-POINTER-POP) (CALL-XCT-NEXT SEARCH-PAGE-HASH-TABLE) ((M-T) M-C) (JUMP-IF-BIT-CLEAR PHT1-VALID-BIT MD XFALSE) (ILLOP-IF-PAGE-FAULT) (POPJ-AFTER-NEXT (M-T) DPB MD VMA-PHYS-PAGE-ADDR-PART (A-CONSTANT (BYTE-VALUE Q-DATA-TYPE DTP-FIX))) ((M-T) VMA-LOW-BITS M-C A-T) 3 . POINTERS ASSOCIATED WITH ADI ( SUCH AS MULTIPLE VALUE STORING POINTERS AS A RESULT , 400 ( OCTAL ) WORDS ( THE MAXIMUM FRAME SIZE ) EXTRA SLOP MUST BE LEFT . AND M - AP ( MOMENTARILY , IT MAY BE NEGATIVE ) . WHENEVER M - AP IS CHANGED , M - PDL - BUFFER - ACTIVE - QS MUST LIKEWISE BE ADJUSTED . ( SET TO 4 + MAX LENGTH OF ADI ) , IT MAY SAFELY BE ASSUMED THAT THE ADI , IF ANY , WHENEVER M - AP IS ADJUSTED DOWNWARD ( POPPED ) , M - AP SHOULD BE ADJUSTED BEFORE BOTH POINTERS . ONE OPTIMIZATION IS WE FIDDLE MAP TO AVOID GOING THRU NEW PAGE , ETC . PDL-BUFFER-DUMP-RESET-FLAGS ((M-FLAGS) SELECTIVE-DEPOSIT M-FLAGS M-FLAGS-EXCEPT-PROCESSOR-FLAGS A-ZERO) PDL-BUFFER-DUMP ((M-2) (A-CONSTANT PDL-BUFFER-HIGH-LIMIT)) I.E. ALREADY NEAR END , THERE IS PROBABLY JUST - ( PP - M - AP ) [ MINUS SIZE OF ACTIVE FRAME ] TO REALLY COMPLETELY DUMP PDL - BUFFER #-lambda(begin-comment) ((A-PDL-FINAL-VMA) ADD m-lam A-TEM) P-B-MR1 (JUMP-IF-PAGE-FAULT P-B-MR-PF) If traps , will clean up & return to P - B - MR0 unfortunately , various paths in gc - write - test can clobber M - LAM , so we have to depend on VMA . (JUMP-LESS-THAN-XCT-NEXT m-lam A-PDL-FINAL-VMA P-B-MR1) ((PDL-BUFFER-INDEX) ADD PDL-BUFFER-INDEX (A-CONSTANT 1)) ((M-PDL-BUFFER-ACTIVE-QS) SUB M-PDL-BUFFER-ACTIVE-QS A-TEM) ((A-PDL-BUFFER-VIRTUAL-ADDRESS) m-lam) ((A-PDL-BUFFER-HEAD) PDL-BUFFER-INDEX) #-lambda(end-comment) #-exp(BEGIN-COMMENT) make sure 2nd lvl map set up , etc Note a reference is guaranteed to set up 2nd level map * * * bug ! this is present in CADR too . Q - R could get clobbered by extra pdl trap ! ! ((M-TEM) DPB (M-CONSTANT -1) ALL-BUT-VMA-LOW-BITS A-PDL-BUFFER-VIRTUAL-ADDRESS) (JUMP-GREATER-OR-EQUAL M-TEM A-PDL-FINAL-VMA P-B-MR3) If traps , will clean up & return to P - B - MR0 (JUMP-LESS-THAN-XCT-NEXT m-lam A-PDL-FINAL-VMA P-B-MR1) ((PDL-BUFFER-INDEX) ADD PDL-BUFFER-INDEX (A-CONSTANT 1)) ((M-PDL-BUFFER-ACTIVE-QS) SUB M-PDL-BUFFER-ACTIVE-QS A-TEM) ((A-PDL-BUFFER-VIRTUAL-ADDRESS) m-lam) ((A-PDL-BUFFER-HEAD) PDL-BUFFER-INDEX) M-PDL-BUFFER-ACTIVE-QS A-2 P-B-MR0) #-exp(END-COMMENT) Do n't leave VMA nil . ((m-2) a-pdl-buffer-virtual-address) ((M-2) SUB M-2 A-PDL-BUFFER-VIRTUAL-ADDRESS) (JUMP-LESS-THAN M-2 A-ZERO P-B-SL-1) Enough room , allow P.B. to fill (A-PDL-BUFFER-HIGH-WARNING) (A-CONSTANT PDL-BUFFER-HIGH-LIMIT)) P-B-SL-1(POPJ-AFTER-NEXT (A-PDL-BUFFER-HIGH-WARNING) ADD M-2 (A-CONSTANT PDL-BUFFER-HIGH-LIMIT)) M - PDL - BUFFER - ACTIVE - QS is at least PDL - BUFFER - LOW - WARNING . #-lambda(begin-comment) PDL-BUFFER-REFILL P-R-0 (JUMP-GREATER-OR-EQUAL M-2 A-PDL-BUFFER-VIRTUAL-ADDRESS (JUMP-GREATER-OR-EQUAL M-PDL-BUFFER-ACTIVE-QS (A-CONSTANT PDL-BUFFER-LOW-WARNING)) (JUMP-GREATER-OR-EQUAL M-TEM A-1 P-R-2) ((M-TEM) M-1) number of words for those reasons ( -1 ) Initial P.B. address +1 P-R-1 ((VMA-START-READ-FORCE m-lam) SUB m-lam (A-CONSTANT 1)) (JUMP-IF-PAGE-FAULT P-R-PF) ((PDL-BUFFER-INDEX) SUB PDL-BUFFER-INDEX (A-CONSTANT 1)) DISPATCH-ON-MAP-19 Running cleanup handler first ((C-PDL-BUFFER-INDEX) READ-MEMORY-DATA) (JUMP-LESS-THAN-XCT-NEXT M-ZERO A-PDL-LOOP-COUNT P-R-1) ((A-PDL-LOOP-COUNT) ADD (M-CONSTANT -1) A-PDL-LOOP-COUNT) (call-not-equal vma a-lam illop) ((A-PDL-BUFFER-VIRTUAL-ADDRESS) m-lam) ((A-PDL-BUFFER-HEAD) PDL-BUFFER-INDEX) #-lambda(end-comment) #-exp(BEGIN-COMMENT) PDL-BUFFER-REFILL P-R-0 (JUMP-GREATER-OR-EQUAL M-2 A-PDL-BUFFER-VIRTUAL-ADDRESS (JUMP-GREATER-OR-EQUAL M-PDL-BUFFER-ACTIVE-QS ((VMA-START-READ) ADD (M-CONSTANT -1) A-PDL-BUFFER-VIRTUAL-ADDRESS) Take cycle to assure 2nd lvl map set up Turn on access to mem which shadows pdl buf (A-CONSTANT PDL-BUFFER-LOW-WARNING)) (JUMP-GREATER-OR-EQUAL M-TEM A-1 P-R-2) ((M-TEM) M-1) number of words for those reasons (JUMP-GREATER-THAN M-TEM A-PDL-LOOP-COUNT P-R-3) Initial P.B. address +1 P-R-1 ((VMA-START-READ m-lam) SUB m-lam (A-CONSTANT 1)) ((PDL-BUFFER-INDEX) SUB PDL-BUFFER-INDEX (A-CONSTANT 1)) DISPATCH-ON-MAP-19 Running cleanup handler first ((C-PDL-BUFFER-INDEX) READ-MEMORY-DATA) (JUMP-LESS-THAN-XCT-NEXT M-ZERO A-PDL-LOOP-COUNT P-R-1) ((A-PDL-LOOP-COUNT) ADD (M-CONSTANT -1) A-PDL-LOOP-COUNT) (call-not-equal vma a-lam illop) ((A-PDL-BUFFER-VIRTUAL-ADDRESS) m-lam) ((A-PDL-BUFFER-HEAD) PDL-BUFFER-INDEX) #-exp(END-COMMENT) P-R-AT-BOTTOM (JUMP-XCT-NEXT P-B-X1) Here if transport required while reloading pdl . Clean up first . PB-TRANS(call-not-equal vma a-lam illop) ((A-PDL-BUFFER-VIRTUAL-ADDRESS) m-lam) ((A-PDL-BUFFER-HEAD) PDL-BUFFER-INDEX) #-exp(begin-comment) ((C-PDL-BUFFER-POINTER-PUSH) MD) (no-op) #-exp(end-comment) error checking ( for DTP - NULL , etc ) involved in this , so we may eventually want another ((PDL-BUFFER-INDEX) A-PDL-BUFFER-HEAD) TOOK PAGE FAULT DUMPING PDL BUFFER . CLEAN UP THEN PROCESS IT . (call-not-equal vma a-lam illop) ((M-PDL-BUFFER-ACTIVE-QS) SUB M-PDL-BUFFER-ACTIVE-QS A-TEM) ((A-PDL-BUFFER-VIRTUAL-ADDRESS) m-lam) ((A-PDL-BUFFER-HEAD) PDL-BUFFER-INDEX) (CHECK-PAGE-WRITE-NO-INTERRUPT) (JUMP P-B-MR0) (call-not-equal vma a-lam illop) ((A-PDL-BUFFER-VIRTUAL-ADDRESS) M-LAM) ((A-PDL-BUFFER-HEAD) PDL-BUFFER-INDEX) (CHECK-PAGE-READ-NO-INTERRUPT) (JUMP P-R-0) ))
e89f2c92ca64b0191424ba93ab0f26361644c0663a7625b1fa4b65b585c639b2
rescript-lang/rescript-compiler
ppx_driver.ml
Copyright ( C ) 2019- , Authors of ReScript * * This program 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 of the License , or * ( at your option ) any later version . * * In addition to the permissions granted to you by the LGPL , you may combine * or link a " work that uses the Library " with a publicly distributed version * of this file to produce a combined library or application , then distribute * that combined work under the terms of your choosing , with no requirement * to comply with the obligations normally placed on you by section 4 of the * LGPL version 3 ( or the corresponding section of a later version of the LGPL * should you choose to use a later version ) . * * This program is distributed in the hope that it will be useful , * but WITHOUT ANY WARRANTY ; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the * GNU Lesser General Public License for more details . * * You should have received a copy of the GNU Lesser General Public License * along with this program ; if not , write to the Free Software * Foundation , Inc. , 59 Temple Place - Suite 330 , Boston , MA 02111 - 1307 , USA . * * This program 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 of the License, or * (at your option) any later version. * * In addition to the permissions granted to you by the LGPL, you may combine * or link a "work that uses the Library" with a publicly distributed version * of this file to produce a combined library or application, then distribute * that combined work under the terms of your choosing, with no requirement * to comply with the obligations normally placed on you by section 4 of the * LGPL version 3 (or the corresponding section of a later version of the LGPL * should you choose to use a later version). * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *) let usage = "Usage: [prog] [extra_args] <infile> <outfile>\n%!" let main impl intf = try let a = Sys.argv in let n = Array.length a in if n > 2 then ( Arg.parse_argv (Array.sub Sys.argv 0 (n - 2)) [ ( "-bs-jsx", Arg.Int (fun i -> Js_config.jsx_version := Js_config.jsx_version_of_int i), " Set jsx version" ); ( "-bs-jsx-module", Arg.String (fun i -> Js_config.jsx_module := Js_config.jsx_module_of_string i), " Set jsx module" ); ( "-bs-jsx-mode", Arg.String (fun i -> Js_config.jsx_mode := Js_config.jsx_mode_of_string i), " Set jsx mode" ); ] ignore usage; Ppx_apply.apply_lazy ~source:a.(n - 2) ~target:a.(n - 1) impl intf) else ( Printf.eprintf "%s" usage; exit 2) with exn -> Location.report_exception Format.err_formatter exn; exit 2
null
https://raw.githubusercontent.com/rescript-lang/rescript-compiler/bae82e1ddd265e5c8886ce1a6527e031d95416ed/jscomp/frontend/ppx_driver.ml
ocaml
Copyright ( C ) 2019- , Authors of ReScript * * This program 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 of the License , or * ( at your option ) any later version . * * In addition to the permissions granted to you by the LGPL , you may combine * or link a " work that uses the Library " with a publicly distributed version * of this file to produce a combined library or application , then distribute * that combined work under the terms of your choosing , with no requirement * to comply with the obligations normally placed on you by section 4 of the * LGPL version 3 ( or the corresponding section of a later version of the LGPL * should you choose to use a later version ) . * * This program is distributed in the hope that it will be useful , * but WITHOUT ANY WARRANTY ; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the * GNU Lesser General Public License for more details . * * You should have received a copy of the GNU Lesser General Public License * along with this program ; if not , write to the Free Software * Foundation , Inc. , 59 Temple Place - Suite 330 , Boston , MA 02111 - 1307 , USA . * * This program 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 of the License, or * (at your option) any later version. * * In addition to the permissions granted to you by the LGPL, you may combine * or link a "work that uses the Library" with a publicly distributed version * of this file to produce a combined library or application, then distribute * that combined work under the terms of your choosing, with no requirement * to comply with the obligations normally placed on you by section 4 of the * LGPL version 3 (or the corresponding section of a later version of the LGPL * should you choose to use a later version). * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *) let usage = "Usage: [prog] [extra_args] <infile> <outfile>\n%!" let main impl intf = try let a = Sys.argv in let n = Array.length a in if n > 2 then ( Arg.parse_argv (Array.sub Sys.argv 0 (n - 2)) [ ( "-bs-jsx", Arg.Int (fun i -> Js_config.jsx_version := Js_config.jsx_version_of_int i), " Set jsx version" ); ( "-bs-jsx-module", Arg.String (fun i -> Js_config.jsx_module := Js_config.jsx_module_of_string i), " Set jsx module" ); ( "-bs-jsx-mode", Arg.String (fun i -> Js_config.jsx_mode := Js_config.jsx_mode_of_string i), " Set jsx mode" ); ] ignore usage; Ppx_apply.apply_lazy ~source:a.(n - 2) ~target:a.(n - 1) impl intf) else ( Printf.eprintf "%s" usage; exit 2) with exn -> Location.report_exception Format.err_formatter exn; exit 2
72370ff96c0088a3420ec6bd9b610f624ecb1dd88ffd26a26c26d2c3b83c661e
oscarh/gen_httpd
http_client.erl
-module(http_client). -export([ connect/2, connect/3, format_request/4, format_request/5, format_headers/1, receive_response/1, receive_response/2, format_chunk/1 ]). connect(Port, Mod) -> connect(Port, Mod, []). connect(Port, Mod, Opts) -> Mod:connect({127,0,0,1}, Port, [{active, false}, binary | Opts]). format_request(Method, Path, Vsn, Headers) -> format_request(Method, Path, Vsn, Headers, []). format_request(Method, Path, Vsn, Headers, Body) -> StatusLine = [Method, $\ , Path, $\ , Vsn , "\r\n"], [StatusLine, format_headers(Headers), Body]. format_headers(Headers) -> format_headers(Headers, ["\r\n"]). format_headers([{Name, Value} | T], Acc) -> format_headers(T, [Name, $:, $\ , Value, "\r\n" | Acc]); format_headers([], Acc) -> Acc. format_chunk(Data) -> Size = iolist_size(Data), HexSize = erlang:integer_to_list(Size, 16), [HexSize, "\r\n", Data, "\r\n"]. receive_response(Socket) -> receive_response(Socket, gen_tcp). receive_response(Socket, Mod) -> setopts(Socket, Mod, [{packet, http}]), recv(Socket, Mod, nil, 0, [], 0, <<>>). setopts(Socket, gen_tcp, Options) -> inet:setopts(Socket, Options); setopts(Socket, ssl, Options) -> ssl:setopts(Socket, Options). recv(Socket, Mod, Vsn0, Status0, Hdrs0, ContentLength, Body0) -> case Mod:recv(Socket, 0) of {ok, {http_response, Vsn1, StatusCode, Description}} -> Status1 = {StatusCode, Description}, recv(Socket, Mod, Vsn1, Status1, Hdrs0, ContentLength, Body0); {ok, {http_header, _, 'Content-Length', _, Length}} -> Hdrs1 = [{"Content-Length", Length} | Hdrs0], ILength = list_to_integer(Length), recv(Socket, Mod, Vsn0, Status0, Hdrs1, ILength, Body0); {ok, {http_header, _, Name, _, Value}} when is_atom(Name) -> Hdrs1 = [{atom_to_list(Name), Value} | Hdrs0], recv(Socket, Mod, Vsn0, Status0, Hdrs1, ContentLength, Body0); {ok, {http_header, _, Name, _, Value}} when is_list(Name) -> Hdrs1 = [{Name, Value} | Hdrs0], recv(Socket, Mod, Vsn0, Status0, Hdrs1, ContentLength, Body0); {ok, http_eoh} -> if ContentLength > 0 -> setopts(Socket, Mod, [{packet, raw}]), case Mod:recv(Socket, ContentLength) of {ok, Body1} -> {ok, {Vsn0, Status0, Hdrs0, Body1}}; {error, Reason} -> exit(Reason) end; true -> {ok, {Vsn0, Status0, Hdrs0, Body0}} end; {error, closed} -> {error, closed} end.
null
https://raw.githubusercontent.com/oscarh/gen_httpd/5b48e33d8fac30c70e2d89d74c56e057d570064e/test/http_client.erl
erlang
-module(http_client). -export([ connect/2, connect/3, format_request/4, format_request/5, format_headers/1, receive_response/1, receive_response/2, format_chunk/1 ]). connect(Port, Mod) -> connect(Port, Mod, []). connect(Port, Mod, Opts) -> Mod:connect({127,0,0,1}, Port, [{active, false}, binary | Opts]). format_request(Method, Path, Vsn, Headers) -> format_request(Method, Path, Vsn, Headers, []). format_request(Method, Path, Vsn, Headers, Body) -> StatusLine = [Method, $\ , Path, $\ , Vsn , "\r\n"], [StatusLine, format_headers(Headers), Body]. format_headers(Headers) -> format_headers(Headers, ["\r\n"]). format_headers([{Name, Value} | T], Acc) -> format_headers(T, [Name, $:, $\ , Value, "\r\n" | Acc]); format_headers([], Acc) -> Acc. format_chunk(Data) -> Size = iolist_size(Data), HexSize = erlang:integer_to_list(Size, 16), [HexSize, "\r\n", Data, "\r\n"]. receive_response(Socket) -> receive_response(Socket, gen_tcp). receive_response(Socket, Mod) -> setopts(Socket, Mod, [{packet, http}]), recv(Socket, Mod, nil, 0, [], 0, <<>>). setopts(Socket, gen_tcp, Options) -> inet:setopts(Socket, Options); setopts(Socket, ssl, Options) -> ssl:setopts(Socket, Options). recv(Socket, Mod, Vsn0, Status0, Hdrs0, ContentLength, Body0) -> case Mod:recv(Socket, 0) of {ok, {http_response, Vsn1, StatusCode, Description}} -> Status1 = {StatusCode, Description}, recv(Socket, Mod, Vsn1, Status1, Hdrs0, ContentLength, Body0); {ok, {http_header, _, 'Content-Length', _, Length}} -> Hdrs1 = [{"Content-Length", Length} | Hdrs0], ILength = list_to_integer(Length), recv(Socket, Mod, Vsn0, Status0, Hdrs1, ILength, Body0); {ok, {http_header, _, Name, _, Value}} when is_atom(Name) -> Hdrs1 = [{atom_to_list(Name), Value} | Hdrs0], recv(Socket, Mod, Vsn0, Status0, Hdrs1, ContentLength, Body0); {ok, {http_header, _, Name, _, Value}} when is_list(Name) -> Hdrs1 = [{Name, Value} | Hdrs0], recv(Socket, Mod, Vsn0, Status0, Hdrs1, ContentLength, Body0); {ok, http_eoh} -> if ContentLength > 0 -> setopts(Socket, Mod, [{packet, raw}]), case Mod:recv(Socket, ContentLength) of {ok, Body1} -> {ok, {Vsn0, Status0, Hdrs0, Body1}}; {error, Reason} -> exit(Reason) end; true -> {ok, {Vsn0, Status0, Hdrs0, Body0}} end; {error, closed} -> {error, closed} end.
4243c954fd04a7cdf5a210992d7b2a6612b9fd92203e5a890cc485c324ed1911
dharrigan/startrek-clip
actuator.clj
(ns startrek.api.general.actuator {:author "David Harrigan"} (:require [startrek.api.general.metrics :as metrics] [startrek.components.database.interface :as db])) (set! *warn-on-reflection* true) (def ok 200) (defn ^:private database-health-check [app-config] (if (db/health-check app-config) {:db [{:status "UP"}] :starships {:status "There's Klingons on the starboard bow, starboard bow Jim!"}} {:db [{:status "DOWN"}]})) (defn ^:private health-check [app-config] (fn [_] {:status ok :body {:components (database-health-check app-config)}})) (defn routes [app-config] ["/actuator" ["/health" {:get {:handler (health-check app-config)}}] ["/prometheus" {:get {:handler (metrics/metrics)}}]])
null
https://raw.githubusercontent.com/dharrigan/startrek-clip/7383527b88c78ba136911c91b1dfc74e73239c1f/src/startrek/api/general/actuator.clj
clojure
(ns startrek.api.general.actuator {:author "David Harrigan"} (:require [startrek.api.general.metrics :as metrics] [startrek.components.database.interface :as db])) (set! *warn-on-reflection* true) (def ok 200) (defn ^:private database-health-check [app-config] (if (db/health-check app-config) {:db [{:status "UP"}] :starships {:status "There's Klingons on the starboard bow, starboard bow Jim!"}} {:db [{:status "DOWN"}]})) (defn ^:private health-check [app-config] (fn [_] {:status ok :body {:components (database-health-check app-config)}})) (defn routes [app-config] ["/actuator" ["/health" {:get {:handler (health-check app-config)}}] ["/prometheus" {:get {:handler (metrics/metrics)}}]])
146346aed5562da1d1b1727fbb2d486db0e6c6196b2bfff00672543896bd909d
Stratus3D/programming_erlang_exercises
math_functions.erl
-module(math_functions). -export([even/1, odd/1, filter/2]). even(Number) -> % Use `rem` to check if the remainder is 0 % if it is return true, otherwise false 0 =:= Number rem 2. odd(Number) -> Use ` rem ` to check if the remainder is 1 % if it is return true, otherwise false % (for odd numbers the remainder of division by 2 will always be 1 ) 1 =:= Number rem 2. filter(Fun, List) -> Invoke filter/3 , which does the real work % then reverse the resulting list, as filter/3 returns a list in reverse order . lists:reverse(filter(Fun, List, [])). filter(_Fun, [], Result) -> % If there are no more items in the list % return the result Result; filter(Fun, [Item|Remaining], Result) -> % If another item still exists in the list % Apply `Fun` to it and check the result, % if true, add the item to the result. case Fun(Item) of true -> filter(Fun, Remaining, [Item|Result]); _ -> filter(Fun, Remaining, Result) end.
null
https://raw.githubusercontent.com/Stratus3D/programming_erlang_exercises/e4fd01024812059d338facc20f551e7dff4dac7e/chapter_4/exercise_6/math_functions.erl
erlang
Use `rem` to check if the remainder is 0 if it is return true, otherwise false if it is return true, otherwise false (for odd numbers the remainder of then reverse the resulting list, as If there are no more items in the list return the result If another item still exists in the list Apply `Fun` to it and check the result, if true, add the item to the result.
-module(math_functions). -export([even/1, odd/1, filter/2]). even(Number) -> 0 =:= Number rem 2. odd(Number) -> Use ` rem ` to check if the remainder is 1 division by 2 will always be 1 ) 1 =:= Number rem 2. filter(Fun, List) -> Invoke filter/3 , which does the real work filter/3 returns a list in reverse order . lists:reverse(filter(Fun, List, [])). filter(_Fun, [], Result) -> Result; filter(Fun, [Item|Remaining], Result) -> case Fun(Item) of true -> filter(Fun, Remaining, [Item|Result]); _ -> filter(Fun, Remaining, Result) end.
44798987f6bf4ac493ad3527b5c15ed3d5ade995b98ea32cc2f7c00a786e296a
snmsts/cserial-port
ffi-types-unix.lisp
(in-package :cserial-port) (include "sys/ioctl.h") (include "termios.h") (constant (B0 "B0")) (constant (B50 "B50")) (constant (B75 "B75")) (constant (B110 "B110")) (constant (B134 "B134")) (constant (B150 "B150")) (constant (B200 "B200")) (constant (B300 "B300")) (constant (B600 "B600")) (constant (B1200 "B1200")) (constant (B1800 "B1800")) (constant (B2400 "B2400")) (constant (B4800 "B4800")) (constant (B9600 "B9600")) (constant (B19200 "B19200")) (constant (B38400 "B38400")) (constant (B57600 "B57600")) (constant (B115200 "B115200")) (constant (B230400 "B230400")) (constant (b460800 "B460800")) (constant (B500000 "B500000")) (constant (B576000 "B576000")) (constant (B921600 "B921600")) (constant (B1000000 "B1000000")) (constant (B1152000 "B1152000")) (constant (B1500000 "B1500000")) (constant (B2000000 "B2000000")) (constant (B2500000 "B2500000")) (constant (B3000000 "B3000000")) (constant (B3500000 "B3500000")) (constant (B4000000 "B4000000")) c_iflag (constant (IGNBRK "IGNBRK")) (constant (BRKINT "BRKINT")) (constant (IGNPAR "IGNPAR")) (constant (PARMRK "PARMRK")) (constant (INPCK "INPCK")) (constant (ISTRIP "ISTRIP")) (constant (INLCR "INLCR")) (constant (IGNCR "IGNCR")) (constant (ICRNL "ICRNL")) (constant (IXON "IXON")) (constant (IXANY "IXANY")) (constant (IXOFF "IXOFF")) ;;c_oflag (constant (OPOST "OPOST")) (constant (ONLCR "ONLCR")) (constant (OCRNL "OCRNL")) (constant (ONOCR "ONOCR")) (constant (ONLRET "ONLRET")) (constant (OFILL "OFILL")) c_cflag (constant (CSIZE "CSIZE")) (constant (CSTOPB "CSTOPB")) (constant (CREAD "CREAD")) (constant (PARENB "PARENB")) (constant (PARODD "PARODD")) (constant (HUPCL "HUPCL")) (constant (CLOCAL "CLOCAL")) (constant (CS5 "CS5")) (constant (CS6 "CS6")) (constant (CS7 "CS7")) (constant (CS8 "CS8")) ;;c_lflag (constant (ISIG "ISIG")) (constant (ICANON "ICANON")) (constant (ECHO "ECHO")) (constant (ECHOE "ECHOE")) (constant (ECHOK "ECHOK")) (constant (ECHONL "ECHONL")) (constant (NOFLSH "NOFLSH")) (constant (TOSTOP "TOSTOP")) (constant (IEXTEN "IEXTEN")) ;;c_cc (constant (VINTR "VINTR")) (constant (VQUIT "VQUIT")) (constant (VERASE "VERASE")) (constant (VKILL "VKILL")) (constant (VEOF "VEOF")) (constant (VMIN "VMIN")) (constant (VEOL "VEOL")) (constant (VTIME "VTIME")) (constant (VSTART "VSTART")) (constant (VSTOP "VSTOP")) (constant (VSUSP "VSUSP")) ;;tcsetattr optional_actions (constant (TCSANOW "TCSANOW")) (constant (TCSADRAIN "TCSADRAIN")) (constant (TCSAFLUSH "TCSAFLUSH")) (constant (NCCS "NCCS")) (ctype tcflag-t "tcflag_t") (ctype cc-t "cc_t") (ctype speed-t "speed_t") (ctype pid-t "pid_t") (cstruct termios "struct termios" "The termios structure" (iflag "c_iflag" :type tcflag-t) (oflag "c_oflag" :type tcflag-t) (cflag "c_cflag" :type tcflag-t) (lflag "c_lflag" :type tcflag-t) (cc "c_cc" :type cc-t :count NCCS)) ioctl (constant (TIOCMGET "TIOCMGET")) (constant (TIOCMSET "TIOCMSET")) (constant (TIOCMBIC "TIOCMBIC")) (constant (TIOCMBIS "TIOCMBIS")) (constant (FIONREAD "FIONREAD")) (bitfield modem-state ((:dsr "TIOCM_DSR")) ((:dtr "TIOCM_DTR")) ((:rts "TIOCM_RTS")) ((:cts "TIOCM_CTS")) ((:dcd "TIOCM_CAR")) ((:ring "TIOCM_RNG")))
null
https://raw.githubusercontent.com/snmsts/cserial-port/2dc21ba4d6650fe766aea4f3d1d9b99a25ae1c24/src/ffi-types-unix.lisp
lisp
c_oflag c_lflag c_cc tcsetattr optional_actions
(in-package :cserial-port) (include "sys/ioctl.h") (include "termios.h") (constant (B0 "B0")) (constant (B50 "B50")) (constant (B75 "B75")) (constant (B110 "B110")) (constant (B134 "B134")) (constant (B150 "B150")) (constant (B200 "B200")) (constant (B300 "B300")) (constant (B600 "B600")) (constant (B1200 "B1200")) (constant (B1800 "B1800")) (constant (B2400 "B2400")) (constant (B4800 "B4800")) (constant (B9600 "B9600")) (constant (B19200 "B19200")) (constant (B38400 "B38400")) (constant (B57600 "B57600")) (constant (B115200 "B115200")) (constant (B230400 "B230400")) (constant (b460800 "B460800")) (constant (B500000 "B500000")) (constant (B576000 "B576000")) (constant (B921600 "B921600")) (constant (B1000000 "B1000000")) (constant (B1152000 "B1152000")) (constant (B1500000 "B1500000")) (constant (B2000000 "B2000000")) (constant (B2500000 "B2500000")) (constant (B3000000 "B3000000")) (constant (B3500000 "B3500000")) (constant (B4000000 "B4000000")) c_iflag (constant (IGNBRK "IGNBRK")) (constant (BRKINT "BRKINT")) (constant (IGNPAR "IGNPAR")) (constant (PARMRK "PARMRK")) (constant (INPCK "INPCK")) (constant (ISTRIP "ISTRIP")) (constant (INLCR "INLCR")) (constant (IGNCR "IGNCR")) (constant (ICRNL "ICRNL")) (constant (IXON "IXON")) (constant (IXANY "IXANY")) (constant (IXOFF "IXOFF")) (constant (OPOST "OPOST")) (constant (ONLCR "ONLCR")) (constant (OCRNL "OCRNL")) (constant (ONOCR "ONOCR")) (constant (ONLRET "ONLRET")) (constant (OFILL "OFILL")) c_cflag (constant (CSIZE "CSIZE")) (constant (CSTOPB "CSTOPB")) (constant (CREAD "CREAD")) (constant (PARENB "PARENB")) (constant (PARODD "PARODD")) (constant (HUPCL "HUPCL")) (constant (CLOCAL "CLOCAL")) (constant (CS5 "CS5")) (constant (CS6 "CS6")) (constant (CS7 "CS7")) (constant (CS8 "CS8")) (constant (ISIG "ISIG")) (constant (ICANON "ICANON")) (constant (ECHO "ECHO")) (constant (ECHOE "ECHOE")) (constant (ECHOK "ECHOK")) (constant (ECHONL "ECHONL")) (constant (NOFLSH "NOFLSH")) (constant (TOSTOP "TOSTOP")) (constant (IEXTEN "IEXTEN")) (constant (VINTR "VINTR")) (constant (VQUIT "VQUIT")) (constant (VERASE "VERASE")) (constant (VKILL "VKILL")) (constant (VEOF "VEOF")) (constant (VMIN "VMIN")) (constant (VEOL "VEOL")) (constant (VTIME "VTIME")) (constant (VSTART "VSTART")) (constant (VSTOP "VSTOP")) (constant (VSUSP "VSUSP")) (constant (TCSANOW "TCSANOW")) (constant (TCSADRAIN "TCSADRAIN")) (constant (TCSAFLUSH "TCSAFLUSH")) (constant (NCCS "NCCS")) (ctype tcflag-t "tcflag_t") (ctype cc-t "cc_t") (ctype speed-t "speed_t") (ctype pid-t "pid_t") (cstruct termios "struct termios" "The termios structure" (iflag "c_iflag" :type tcflag-t) (oflag "c_oflag" :type tcflag-t) (cflag "c_cflag" :type tcflag-t) (lflag "c_lflag" :type tcflag-t) (cc "c_cc" :type cc-t :count NCCS)) ioctl (constant (TIOCMGET "TIOCMGET")) (constant (TIOCMSET "TIOCMSET")) (constant (TIOCMBIC "TIOCMBIC")) (constant (TIOCMBIS "TIOCMBIS")) (constant (FIONREAD "FIONREAD")) (bitfield modem-state ((:dsr "TIOCM_DSR")) ((:dtr "TIOCM_DTR")) ((:rts "TIOCM_RTS")) ((:cts "TIOCM_CTS")) ((:dcd "TIOCM_CAR")) ((:ring "TIOCM_RNG")))
87a0c1b61bc3d25542fb00b68a9c733a6e0b19d00c6d7ab12ae761409d9cbb36
haskell/haskell-language-server
PunMany.hs
data Many = Hello { world :: String } | Goodbye { a :: Int, b :: Bool, c :: Many } test :: Many -> Many test x = _
null
https://raw.githubusercontent.com/haskell/haskell-language-server/f3ad27ba1634871b2240b8cd7de9f31b91a2e502/plugins/hls-tactics-plugin/new/test/golden/PunMany.hs
haskell
data Many = Hello { world :: String } | Goodbye { a :: Int, b :: Bool, c :: Many } test :: Many -> Many test x = _
ecc9fd904d6bcc678ff8fa7429d82cec0fef6e05cc31339b56e73224df1272d6
beamparticle/beamparticle
beamparticle_erlparser.erl
%%% %CopyrightBegin% %%% Copyright < > 2017 . All Rights Reserved . %%% Licensed under the Apache License , Version 2.0 ( the " License " ) ; %%% you may not use this file except in compliance with the License. %%% You may obtain a copy of the License at %%% %%% -2.0 %%% %%% Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an " AS IS " BASIS , %%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %%% See the License for the specific language governing permissions and %%% limitations under the License. %%% %%% %CopyrightEnd% -module(beamparticle_erlparser). -include("beamparticle_constants.hrl"). -export([ extract_config/1, detect_language/1, get_filename_extension/1, is_valid_filename_extension/1, language_files/1, create_anonymous_function/1, extract_comments/1, evaluate_expression/1, evaluate_erlang_expression/2, execute_dynamic_function/2, calltrace_to_json_map/1, discover_function_calls/1, evaluate_erlang_parsed_expressions/2 ]). -spec extract_config(string() | binary()) -> {string(), string()} | {binary(), binary()}. extract_config(InputExpression) when is_list(InputExpression) -> extract_config(list_to_binary(InputExpression)); extract_config(InputExpression) -> %% If there is a configuration then it will be as a json binary/string as the first line and terminated with " ||||\n " case InputExpression of <<"{", _/binary>> -> try [Config, Code] = string:split(InputExpression, <<"||||\n">>), {beamparticle_util:trimbin(Config), Code} catch _:_ -> {<<>>, InputExpression} end; [${ | _] -> This is actually not required because of the first fuction %% clause InputExpression shall always be binary() try [Config, Code] = string:split(InputExpression, "||||\n"), {string:trim(Config), Code} catch _:_ -> {<<>>, InputExpression} end; _ -> {<<>>, InputExpression} end. %% @doc detect language used within the expression %% Supported programming languages are as follows: %% %% * Erlang %% * Elixir * %% * PHP %% -spec detect_language(string() | binary()) -> {erlang | elixir | efene | php | python | java, Code :: string() | binary(), Config :: string() | binary(), normal | optimize}. detect_language(InputExpression) -> {Config, Expression} = extract_config(InputExpression), [RawHeader | Rest] = string:split(Expression, "\n"), Header = string:trim(RawHeader), case Header of <<"#!elixir", Flags/binary>> -> [Code] = Rest, case Flags of <<"-opt", _/binary>> -> {elixir, Code, Config, optimize}; _ -> {elixir, Code, Config, normal} end; "#!elixir" ++ Flags -> [Code] = Rest, case Flags of "-opt" ++ _ -> {elixir, Code, Config, optimize}; _ -> {elixir, Code, Config, normal} end; <<"#!efene", Flags/binary>> -> [Code] = Rest, case Flags of <<"-opt", _/binary>> -> {efene, Code, Config, optimize}; _ -> {efene, Code, Config, normal} end; "#!efene" ++ Flags -> [Code] = Rest, case Flags of "-opt" ++ _ -> {efene, Code, Config, optimize}; _ -> {efene, Code, Config, normal} end; <<"#!php", Flags/binary>> -> [Code] = Rest, case Flags of <<"-opt", _/binary>> -> {php, Code, Config, optimize}; _ -> {php, Code, Config, normal} end; "#!php" ++ Flags -> [Code] = Rest, case Flags of "-opt" ++ _ -> {php, Code, Config, optimize}; _ -> {php, Code, Config, normal} end; <<"#!python", Flags/binary>> -> [Code] = Rest, case Flags of <<"-opt", _/binary>> -> {python, Code, Config, optimize}; _ -> {python, Code, Config, normal} end; "#!python" ++ Flags -> [Code] = Rest, case Flags of "-opt" ++ _ -> {python, Code, Config, optimize}; _ -> {python, Code, Config, normal} end; <<"#!java", Flags/binary>> -> [Code] = Rest, case Flags of <<"-opt", _/binary>> -> {java, Code, Config, optimize}; _ -> {java, Code, Config, normal} end; "#!java" ++ Flags -> [Code] = Rest, case Flags of "-opt" ++ _ -> {java, Code, Config, optimize}; _ -> {java, Code, Config, normal} end; <<"#!erlang", Flags/binary>> -> [Code] = Rest, case Flags of <<"-opt", _/binary>> -> {erlang, Code, Config, optimize}; _ -> {erlang, Code, Config, normal} end; "#!erlang" ++ Flags -> [Code] = Rest, case Flags of "-opt" ++ _ -> {erlang, Code, Config, optimize}; _ -> {erlang, Code, Config, normal} end; _ -> {erlang, Expression, Config, normal} end. -spec get_filename_extension(string() | binary()) -> string(). get_filename_extension(Expression) -> case beamparticle_erlparser:detect_language(Expression) of {erlang, _Code, _Config, _CompileType} -> ".erl.fun"; {elixir, _Code, _Config, _CompileType} -> ".ex.fun"; {efene, _Code, _Config, _CompileType} -> ".efe.fun"; {php, _Code, _Config, _CompileType} -> ".php.fun"; {python, _Code, _Config, _CompileType} -> ".py.fun"; {java, _Code, _Config, _CompileType} -> ".java.fun" end. %% Erlang - .erl.fun %% Elixir - .ex.fun %% PHP - .php.fun %% Python - .py.fun %% Java - .java.fun -spec is_valid_filename_extension(string()) -> boolean(). is_valid_filename_extension(".erl.fun") -> true; is_valid_filename_extension(".ex.fun") -> true; is_valid_filename_extension(".efe.fun") -> true; is_valid_filename_extension(".php.fun") -> true; is_valid_filename_extension(".py.fun") -> true; is_valid_filename_extension(".java.fun") -> true; is_valid_filename_extension(_) -> false. Erlang , Elixir , -spec language_files(Folder :: string()) -> [string()]. language_files(Folder) -> filelib:wildcard(Folder ++ "/*.{erl,ex,efe,php,py}.fun"). %% @doc Create an anonymous function enclosing expressions -spec create_anonymous_function(binary()) -> binary(). create_anonymous_function(Text) when is_binary(Text) -> %% Configuration must not be used here case detect_language(Text) of {erlang, Code, _Config, normal} -> iolist_to_binary([<<"fun() ->\n">>, Code, <<"\nend.">>]); {erlang, Code, _Config, optimize} -> iolist_to_binary([<<"#!erlang-opt\nfun() ->\n">>, Code, <<"\nend.">>]); {elixir, Code, _Config, normal} -> iolist_to_binary([<<"#!elixir\nfn ->\n">>, Code, <<"\nend">>]); {elixir, Code, _Config, optimize} -> iolist_to_binary([<<"#!elixir-opt\nfn ->\n">>, Code, <<"\nend">>]); {efene, Code, _Config, normal} -> iolist_to_binary([<<"#!efene\nfn\n">>, Code, <<"\nend">>]); {efene, Code, _Config, optimize} -> iolist_to_binary([<<"#!efene-opt\nfn\n">>, Code, <<"\nend">>]); {php, Code, _Config, normal} -> iolist_to_binary([<<"#!php\n">>, Code]); {php, Code, _Config, optimize} -> iolist_to_binary([<<"#!php-opt\n">>, Code]); {python, Code, _Config, normal} -> iolist_to_binary([<<"#!python\n">>, Code]); {python, Code, _Config, optimize} -> iolist_to_binary([<<"#!python-opt\n">>, Code]); {java, Code, _Config, normal} -> iolist_to_binary([<<"#!java\n">>, Code]); {java, Code, _Config, optimize} -> iolist_to_binary([<<"#!java-opt\n">>, Code]) end. %% @doc Get comments as list of string for any given language allowed %% %% Supported programming languages are as follows: %% %% * Erlang (comments starts with "%") %% * Elixir (comments starts with "#") * ( comment starts with " # _ " and has comments within double quotes ) %% * PHP (comments starts with "//" %% -spec extract_comments(string() | binary()) -> [string()]. extract_comments(Expression) when is_binary(Expression) orelse is_list(Expression) -> case detect_language(Expression) of {erlang, _Code, _Config, _CompileType} -> ExpressionStr = case is_binary(Expression) of true -> binary_to_list(Expression); false -> Expression end, lists:foldl(fun(E, AccIn) -> {_, _, _, Line} = E, [Line | AccIn] end, [], erl_comment_scan:scan_lines(ExpressionStr)); {elixir, Code, _Config, _CompileType} -> Lines = string:split(Code, "\n", all), CommentedLines = lists:foldl(fun(E, AccIn) -> EStripped = string:trim(E), case EStripped of [$# | Rest] -> [Rest | AccIn]; <<"#", Rest/binary>> -> [Rest | AccIn]; _ -> AccIn end end, [], Lines), lists:reverse(CommentedLines); {efene, Code, _Config, _CompileType} -> Lines = string:split(Code, "\n", all), CommentedLines = lists:foldl(fun(E, AccIn) -> EStripped = string:trim(E), case EStripped of [$#, $_ | Rest] -> [Rest | AccIn]; <<"#_", Rest/binary>> -> [Rest | AccIn]; _ -> AccIn end end, [], Lines), lists:reverse(CommentedLines); {php, Code, _Config, _CompileType} -> Lines = string:split(Code, "\n", all), CommentedLines = lists:foldl(fun(E, AccIn) -> EStripped = string:trim(E), case EStripped of [$/, $/ | Rest] -> [Rest | AccIn]; <<"//", Rest/binary>> -> [Rest | AccIn]; _ -> AccIn end end, [], Lines), lists:reverse(CommentedLines); {python, Code, _Config, _CompileType} -> Lines = string:split(Code, "\n", all), CommentedLines = lists:foldl(fun(E, AccIn) -> EStripped = string:trim(E), case EStripped of [$# | Rest] -> [Rest | AccIn]; <<"#", Rest/binary>> -> [Rest | AccIn]; _ -> AccIn end end, [], Lines), lists:reverse(CommentedLines); {java, Code, _Config, _CompileType} -> Lines = string:split(Code, "\n", all), CommentedLines = lists:foldl(fun(E, AccIn) -> EStripped = string:trim(E), case EStripped of [$/, $/ | Rest] -> [Rest | AccIn]; <<"//", Rest/binary>> -> [Rest | AccIn]; _ -> AccIn end end, [], Lines), lists:reverse(CommentedLines) end. %% @doc Evaluate any supported languages expression and give back result. %% %% Supported programming languages are as follows: %% %% * Erlang %% * Elixir * %% * PHP %% -spec evaluate_expression(string() | binary()) -> {any(), string() | binary()} | {php | python | java, binary(), binary(), normal | optimize}. evaluate_expression(Expression) -> case detect_language(Expression) of {erlang, Code, Config, CompileType} -> {beamparticle_erlparser:evaluate_erlang_expression( Code, CompileType), Config}; {elixir, Code, Config, CompileType} -> ErlangParsedExpressions = beamparticle_elixirparser:get_erlang_parsed_expressions(Code), {evaluate_erlang_parsed_expressions(ErlangParsedExpressions, CompileType), Config}; {efene, Code, Config, CompileType} -> ErlangParsedExpressions = beamparticle_efeneparser:get_erlang_parsed_expressions(Code), {evaluate_erlang_parsed_expressions(ErlangParsedExpressions, CompileType), Config}; {php, Code, Config, CompileType} -> %% cannot evaluate expression without Arguments %% beamparticle_phpparser:evaluate_php_expression(Code, Arguments) {php, Code, Config, CompileType}; {python, Code, Config, CompileType} -> %% cannot evaluate expression without Arguments %% beamparticle_pythonparser:evaluate_python_expression(FunctionNameBin, Code, Arguments) {python, Code, Config, CompileType}; {java, Code, Config, CompileType} -> %% cannot evaluate expression without Arguments %% beamparticle_javaparser:evaluate_java_expression(FunctionNameBin, Code, Arguments) {java, Code, Config, CompileType} end. -spec get_erlang_parsed_expressions(fun() | string() | binary()) -> any(). get_erlang_parsed_expressions(ErlangExpression) when is_binary(ErlangExpression) -> get_erlang_parsed_expressions(binary_to_list(ErlangExpression)); get_erlang_parsed_expressions(ErlangExpression) when is_list(ErlangExpression) -> {ok, ErlangTokens, _} = erl_scan:string(ErlangExpression), {ok, ErlangParsedExpressions} = erl_parse:parse_exprs(ErlangTokens), ErlangParsedExpressions. @doc Evaluate a given Erlang expression and give back result . %% %% intercept local and external functions, while the external %% functions are intercepted for tracing only. This is dangerous, %% but necessary for maximum flexibity to call any function. %% If required this can be modified to intercept external %% module functions as well to jail them within a limited set. -spec evaluate_erlang_expression(string() | binary(), normal | optimize) -> any(). evaluate_erlang_expression(ErlangExpression, CompileType) -> ErlangParsedExpressions = get_erlang_parsed_expressions(ErlangExpression), evaluate_erlang_parsed_expressions(ErlangParsedExpressions, CompileType). -spec evaluate_erlang_parsed_expressions(term(), normal | optimize) -> any(). evaluate_erlang_parsed_expressions(ErlangParsedExpressions, normal) -> bindings are also returned as third tuple element but not used {value, Result, _} = erl_eval:exprs(ErlangParsedExpressions, [], {value, fun intercept_local_function/2}, {value, fun intercept_nonlocal_function/2}), Result; evaluate_erlang_parsed_expressions(ErlangParsedExpressions, optimize) -> bindings are also returned as third tuple element but not used {value, Result, _} = erl_eval:exprs(ErlangParsedExpressions, [], {value, fun intercept_local_function/2}), Result. calltrace_to_json_map(CallTrace) when is_list(CallTrace) -> lists:foldl(fun({FunctionName, Arguments, DeltaUsec}, AccIn) -> [#{<<"function">> => FunctionName, <<"arguments">> => list_to_binary(io_lib:format("~p", [Arguments])), <<"delta_usec">> => DeltaUsec} | AccIn] end, [], CallTrace). @private %% @doc Intercept calls to local function and patch them in. -spec intercept_local_function(FunctionName :: atom(), Arguments :: list()) -> any(). intercept_local_function(FunctionName, Arguments) -> lager:debug("Local call to ~p with ~p~n", [FunctionName, Arguments]), TraceLog = list_to_binary( io_lib:format("{~p, ~p}", [FunctionName, Arguments])), otter_span_pdict_api:log(TraceLog), case FunctionName of _ -> FunctionNameBin = atom_to_binary(FunctionName, utf8), execute_dynamic_function(FunctionNameBin, Arguments) end. @private %% @doc Intercept calls to non-local function -spec intercept_nonlocal_function({ModuleName :: atom(), FunctionName :: atom()} | fun(), Arguments :: list()) -> any(). intercept_nonlocal_function({ModuleName, FunctionName}, Arguments) -> case erlang:get(?OPENTRACE_PDICT_CONFIG) of undefined -> ok; OpenTracingConfig -> Arity = length(Arguments), ShouldTraceLog = case beamparticle_util:is_operator({ModuleName, FunctionName, Arity}) of true -> proplists:get_value(trace_operator, OpenTracingConfig, true); false -> ModuleTraceOptions = proplists:get_value(trace_module, OpenTracingConfig, []), case proplists:get_value(ModuleName, ModuleTraceOptions, true) of true -> ModuleFunTraceOptions = proplists:get_value(trace_module_function, OpenTracingConfig, []), proplists:get_value({ModuleName, FunctionName}, ModuleFunTraceOptions, true); false -> false end end, case ShouldTraceLog of true -> TraceLog = list_to_binary( io_lib:format("{~p, ~p, ~p}", [ModuleName, FunctionName, Arguments])), otter_span_pdict_api:log(TraceLog); false -> ok end end, apply(ModuleName, FunctionName, Arguments); intercept_nonlocal_function(Fun, Arguments) when is_function(Fun) -> case erlang:get(?OPENTRACE_PDICT_CONFIG) of undefined -> ok; OpenTracingConfig -> ShouldTraceLog = proplists:get_value( trace_anonymous_function, OpenTracingConfig, true), case ShouldTraceLog of true -> TraceLog = list_to_binary( io_lib:format("{~p, ~p}", [Fun, Arguments])), otter_span_pdict_api:log(TraceLog); false -> ok end end, apply(Fun, Arguments); intercept_nonlocal_function(Fun, Arguments) when is_atom(Fun) -> %% When local function name are used within variables as atom, %% so they land here. %% Example: Functions = [ fun_a, fun_b ] intercept_local_function(Fun, Arguments). execute_dynamic_function(FunctionNameBin, Arguments) when is_binary(FunctionNameBin) andalso is_list(Arguments) -> RealFunctionNameBin = case FunctionNameBin of <<"__simple_http_", RestFunctionNameBin/binary>> -> RestFunctionNameBin; _ -> FunctionNameBin end, Arity = length(Arguments), ArityBin = integer_to_binary(Arity, 10), FullFunctionName = <<RealFunctionNameBin/binary, $/, ArityBin/binary>>, case erlang:get(?CALL_TRACE_ENV_KEY) of undefined -> ok; OldCallTrace -> T1 = erlang:monotonic_time(micro_seconds), T = erlang:get(?CALL_TRACE_BASE_TIME), erlang:put(?CALL_TRACE_ENV_KEY, [{RealFunctionNameBin, Arguments, T1 - T} | OldCallTrace]) end, FResp = case erlang:get(?CALL_ENV_KEY) of undefined -> run_function(FullFunctionName, function); prod -> run_function(FullFunctionName, function); stage -> case run_function(FullFunctionName, function_stage) of {ok, F2} -> {ok, F2}; {error, not_found} -> run_function(FullFunctionName, function) end end, case FResp of {ok, {F, <<>>}} when is_function(F) -> apply(F, Arguments); {ok, {F, ConfigMap}} when is_function(F) -> TODO remove this key once the original function is complete %% in case the actor is reused then configuration would leak %% through to other functions. beamparticle_dynamic:put_config(ConfigMap), apply(F, Arguments); {ok, {php, PhpCode, Config, _CompileType}} -> beamparticle_phpparser:evaluate_php_expression( PhpCode, Config, Arguments); {ok, {python, PythonCode, Config, _CompileType}} -> %% DONT pass stripped down function name That is do not use RealFunctionNameBin here beamparticle_pythonparser:evaluate_python_expression( FunctionNameBin, PythonCode, Config, Arguments); {ok, {java, JavaCode, Config, _CompileType}} -> %% DONT pass stripped down function name That is do not use RealFunctionNameBin here beamparticle_javaparser:evaluate_java_expression( FunctionNameBin, JavaCode, Config, Arguments); _ -> case {FunctionNameBin, Arity} of {<<"log_info">>, _} when Arity == 1 orelse Arity == 2 -> apply(beamparticle_dynamic, log_info, Arguments); {<<"log_error">>, _} when Arity == 1 orelse Arity == 2 -> apply(beamparticle_dynamic, log_error, Arguments); {<<"get_config">>, 0} -> apply(beamparticle_dynamic, get_config, Arguments); {<<"run_concurrent">>, 2} -> apply(beamparticle_dynamic, run_concurrent, Arguments); {<<"async_run_concurrent">>, 2} -> apply(beamparticle_dynamic, async_run_concurrent, Arguments); {<<"stage">>, 1} -> [Arg1] = Arguments, %% TODO empty State for now beamparticle_dynamic:stage(Arg1, []); {<<"release">>, 0} -> %% TODO empty State for now beamparticle_dynamic:release([]); _ -> lager:debug("FunctionNameBin=~p, Arguments=~p", [RealFunctionNameBin, Arguments]), R = list_to_binary(io_lib:format("Please teach me what must I do with ~s(~s)", [RealFunctionNameBin, lists:join(",", [io_lib:format("~p", [X]) || X <- Arguments])])), lager:debug("R=~p", [R]), erlang:throw({error, R}) end end. %% @doc Discover function calls from the given anonymous function. %% %% This function recurisively digs into the function body and finds %% any further function calls (local or remote) and returns back %% unique list of function calls made by the provided anonymous %% function. You could either give the function definition or %% compiled function. %% IMPORTANT : There is an order of 10 difference between the %% runtime when invoked with function body instead of the %% compiled function. Use the %% discover_function_calls(fun()) whenever possible to get 10x speed . %% %% ``` %% {ok, Content} = file:read_file("sample-2.erl.fun"), %% beamparticle_erlparser:discover_function_calls(Content). %% ''' %% %% ``` %% {ok, Content} = file:read_file("sample-2.efe.fun"), %% beamparticle_erlparser:discover_function_calls(Content). %% ''' -spec discover_function_calls(fun() | string() | binary()) -> any(). discover_function_calls(Expression) when is_binary(Expression) -> discover_function_calls(binary_to_list(Expression)); discover_function_calls(Expression) when is_list(Expression) -> ErlangParsedExpressions = case detect_language(Expression) of {erlang, Code, _Config, _CompileType} -> get_erlang_parsed_expressions(Code); {elixir, Code, _Config, _CompileType} -> beamparticle_elixirparser:get_erlang_parsed_expressions(Code); {efene, Code, _Config, _CompileType} -> beamparticle_efeneparser:get_erlang_parsed_expressions(Code); {php, _Code, _Config, _CompileType} -> %% TODO PHP can call into Erlang/... world %% via a special function, but dependency %% is not discovered automatically, so %% this needs to be done. []; {python, _Code, _Config, _CompileType} -> TODO %% at present python code cannot call into Erlang / Elixir / Efene world []; {java, _Code, _Config, _CompileType} -> TODO %% at present java code cannot call into Erlang / Elixir / Efene world [] end, Functions = recursive_dig_function_calls(ErlangParsedExpressions, []), lists:usort(Functions); discover_function_calls(F) when is_function(F) -> {env, FunCodeAsEnv} = erlang:fun_info(F, env), Functions = recursive_dig_function_calls(FunCodeAsEnv, []), lists:usort(Functions). @private %% @doc Recursively dig and extract function calls (if any) %% %% The function returns a list of {Module, Fun, Arity} or %% {Fun, Arity} (for local functions). -spec recursive_dig_function_calls(term(), list()) -> [{binary(), binary(), integer()} | {binary(), integer()}]. recursive_dig_function_calls([], AccIn) -> AccIn; recursive_dig_function_calls([H | Rest], AccIn) -> AccIn2 = recursive_dig_function_calls(H, AccIn), recursive_dig_function_calls(Rest, AccIn2); recursive_dig_function_calls({[], _, _, Clauses}, AccIn) -> This matches the case when : fun_info/1 is used recursive_dig_function_calls(Clauses, AccIn); recursive_dig_function_calls({'fun', _LineNum, ClausesRec}, AccIn) -> recursive_dig_function_calls(ClausesRec, AccIn); recursive_dig_function_calls({clauses, [H | RestClauses]}, AccIn) -> AccIn2 = recursive_dig_function_calls(H, AccIn), recursive_dig_function_calls(RestClauses, AccIn2); recursive_dig_function_calls({clause, _LineNum, _, _, Expressions}, AccIn) -> recursive_dig_function_calls(Expressions, AccIn); recursive_dig_function_calls({match, _LineNum, Lhs, Rhs}, AccIn) -> AccIn2 = recursive_dig_function_calls(Lhs, AccIn), recursive_dig_function_calls(Rhs, AccIn2); recursive_dig_function_calls({var, _LineNum, _VarName}, AccIn) -> AccIn; recursive_dig_function_calls({op, _LineNum, _Op, Lhs, Rhs}, AccIn) -> %% binary operator AccIn2 = recursive_dig_function_calls(Lhs, AccIn), recursive_dig_function_calls(Rhs, AccIn2); recursive_dig_function_calls({op, _LineNum, _Op, Rhs}, AccIn) -> %% unary operator recursive_dig_function_calls(Rhs, AccIn); recursive_dig_function_calls({'case', _LineNum, Condition, Branches}, AccIn) -> AccIn2 = recursive_dig_function_calls(Condition, AccIn), recursive_dig_function_calls(Branches, AccIn2); recursive_dig_function_calls({call, _LineNum, {atom, _LineNum2, FunNameAtom}, Args}, AccIn) -> Arity = length(Args), recursive_dig_function_calls(Args, [{atom_to_binary(FunNameAtom, utf8), Arity} | AccIn]); recursive_dig_function_calls({call, _LineNum, {remote, _LineNum2, {atom, _LineNum3, ModuleNameAtom}, {atom, _LineNum4, FunNameAtom}}, Args}, AccIn) -> Arity = length(Args), recursive_dig_function_calls(Args, [{atom_to_binary(ModuleNameAtom, utf8), atom_to_binary(FunNameAtom, utf8), Arity} | AccIn]); recursive_dig_function_calls({map, _LineNum, _Var, Fields}, AccIn) -> recursive_dig_function_calls(Fields, AccIn); recursive_dig_function_calls({map_field_assoc, _LineNum, Key, Value}, AccIn) -> AccIn2 = recursive_dig_function_calls(Key, AccIn), recursive_dig_function_calls(Value, AccIn2); recursive_dig_function_calls({tuple, _LineNum, Fields}, AccIn) -> recursive_dig_function_calls(Fields, AccIn); recursive_dig_function_calls({cons, _LineNum, Arg1, Arg2}, AccIn) -> AccIn2 = recursive_dig_function_calls(Arg1, AccIn), recursive_dig_function_calls(Arg2, AccIn2); recursive_dig_function_calls(_, AccIn) -> AccIn. run_function(FullFunctionName, function) -> FunctionCacheKey = beamparticle_storage_util:function_cache_key( FullFunctionName, function), case timer:tc(beamparticle_cache_util, get, [FunctionCacheKey]) of {CacheLookupTimeUsec, {ok, {Func, ConfigMap}}} -> lager:debug("Took ~p usec for cache hit of ~s", [CacheLookupTimeUsec, FullFunctionName]), lager:debug("Cache lookup ~p", [{FullFunctionName, {Func, ConfigMap}}]), {ok, {Func, ConfigMap}}; {CacheLookupTimeUsec, _} -> lager:debug("Took ~p usec for cache miss of ~s", [CacheLookupTimeUsec, FullFunctionName]), T2 = erlang:monotonic_time(micro_seconds), KvResp = beamparticle_storage_util:read( FullFunctionName, function), case KvResp of {ok, FunctionBody} -> Resp2 = beamparticle_erlparser:evaluate_expression( FunctionBody), case Resp2 of {Func3, Config} when is_function(Func3) -> T3 = erlang:monotonic_time(micro_seconds), lager:debug("Took ~p micro seconds to read and compile ~s function",[T3 - T2, FullFunctionName]), ConfigMap = case Config of <<>> -> #{}; _ -> jiffy:decode(Config, [return_maps]) end, beamparticle_cache_util:async_put(FunctionCacheKey, {Func3, ConfigMap}), {ok, {Func3, ConfigMap}}; _ -> this is for php , python and at present , which do not compile to erlang %% function, but needs to be %% evaluated each time %% TODO: at least parse the php or python or java %% code and cache the php parse %% tree. {ok, Resp2} end; _ -> {error, not_found} end end; run_function(FullFunctionName, function_stage) -> FunctionCacheKey = beamparticle_storage_util:function_cache_key( FullFunctionName, function_stage), case beamparticle_cache_util:get(FunctionCacheKey) of {ok, {Func, ConfigMap}} -> {ok, {Func, ConfigMap}}; _ -> KvResp = beamparticle_storage_util:read( FullFunctionName, function_stage), case KvResp of {ok, FunctionBody} -> Resp2 = beamparticle_erlparser:evaluate_expression( binary_to_list(FunctionBody)), case Resp2 of {Func3, Config} when is_function(Func3) -> ConfigMap = case Config of <<>> -> #{}; _ -> jiffy:decode(Config, [return_maps]) end, beamparticle_cache_util:async_put(FunctionCacheKey, {Func3, ConfigMap}), {ok, {Func3, ConfigMap}}; _ -> this is for php , python and at present , which do not compile to erlang %% function, but needs to be %% evaluated each time %% TODO: at least parse the php or python or java %% code and cache the php parse %% tree. {ok, Resp2} end; _ -> {error, not_found} end end.
null
https://raw.githubusercontent.com/beamparticle/beamparticle/65dcea1569d06b331b08cd9f8018ece4b176b690/src/beamparticle_erlparser.erl
erlang
%CopyrightBegin% you may not use this file except in compliance with the License. You may obtain a copy of the License at -2.0 Unless required by applicable law or agreed to in writing, software WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. %CopyrightEnd% If there is a configuration then it will be as a json binary/string clause InputExpression shall always be binary() @doc detect language used within the expression Supported programming languages are as follows: * Erlang * Elixir * PHP Erlang - .erl.fun Elixir - .ex.fun PHP - .php.fun Python - .py.fun Java - .java.fun @doc Create an anonymous function enclosing expressions Configuration must not be used here @doc Get comments as list of string for any given language allowed Supported programming languages are as follows: * Erlang (comments starts with "%") * Elixir (comments starts with "#") * PHP (comments starts with "//" @doc Evaluate any supported languages expression and give back result. Supported programming languages are as follows: * Erlang * Elixir * PHP cannot evaluate expression without Arguments beamparticle_phpparser:evaluate_php_expression(Code, Arguments) cannot evaluate expression without Arguments beamparticle_pythonparser:evaluate_python_expression(FunctionNameBin, Code, Arguments) cannot evaluate expression without Arguments beamparticle_javaparser:evaluate_java_expression(FunctionNameBin, Code, Arguments) intercept local and external functions, while the external functions are intercepted for tracing only. This is dangerous, but necessary for maximum flexibity to call any function. If required this can be modified to intercept external module functions as well to jail them within a limited set. @doc Intercept calls to local function and patch them in. @doc Intercept calls to non-local function When local function name are used within variables as atom, so they land here. Example: Functions = [ fun_a, fun_b ] in case the actor is reused then configuration would leak through to other functions. DONT pass stripped down function name DONT pass stripped down function name TODO empty State for now TODO empty State for now @doc Discover function calls from the given anonymous function. This function recurisively digs into the function body and finds any further function calls (local or remote) and returns back unique list of function calls made by the provided anonymous function. You could either give the function definition or compiled function. runtime when invoked with function body instead of the compiled function. Use the discover_function_calls(fun()) whenever possible to get ``` {ok, Content} = file:read_file("sample-2.erl.fun"), beamparticle_erlparser:discover_function_calls(Content). ''' ``` {ok, Content} = file:read_file("sample-2.efe.fun"), beamparticle_erlparser:discover_function_calls(Content). ''' TODO PHP can call into Erlang/... world via a special function, but dependency is not discovered automatically, so this needs to be done. at present python code cannot call into at present java code cannot call into @doc Recursively dig and extract function calls (if any) The function returns a list of {Module, Fun, Arity} or {Fun, Arity} (for local functions). binary operator unary operator function, but needs to be evaluated each time TODO: at least parse the php or python or java code and cache the php parse tree. function, but needs to be evaluated each time TODO: at least parse the php or python or java code and cache the php parse tree.
Copyright < > 2017 . All Rights Reserved . Licensed under the Apache License , Version 2.0 ( the " License " ) ; distributed under the License is distributed on an " AS IS " BASIS , -module(beamparticle_erlparser). -include("beamparticle_constants.hrl"). -export([ extract_config/1, detect_language/1, get_filename_extension/1, is_valid_filename_extension/1, language_files/1, create_anonymous_function/1, extract_comments/1, evaluate_expression/1, evaluate_erlang_expression/2, execute_dynamic_function/2, calltrace_to_json_map/1, discover_function_calls/1, evaluate_erlang_parsed_expressions/2 ]). -spec extract_config(string() | binary()) -> {string(), string()} | {binary(), binary()}. extract_config(InputExpression) when is_list(InputExpression) -> extract_config(list_to_binary(InputExpression)); extract_config(InputExpression) -> as the first line and terminated with " ||||\n " case InputExpression of <<"{", _/binary>> -> try [Config, Code] = string:split(InputExpression, <<"||||\n">>), {beamparticle_util:trimbin(Config), Code} catch _:_ -> {<<>>, InputExpression} end; [${ | _] -> This is actually not required because of the first fuction try [Config, Code] = string:split(InputExpression, "||||\n"), {string:trim(Config), Code} catch _:_ -> {<<>>, InputExpression} end; _ -> {<<>>, InputExpression} end. * -spec detect_language(string() | binary()) -> {erlang | elixir | efene | php | python | java, Code :: string() | binary(), Config :: string() | binary(), normal | optimize}. detect_language(InputExpression) -> {Config, Expression} = extract_config(InputExpression), [RawHeader | Rest] = string:split(Expression, "\n"), Header = string:trim(RawHeader), case Header of <<"#!elixir", Flags/binary>> -> [Code] = Rest, case Flags of <<"-opt", _/binary>> -> {elixir, Code, Config, optimize}; _ -> {elixir, Code, Config, normal} end; "#!elixir" ++ Flags -> [Code] = Rest, case Flags of "-opt" ++ _ -> {elixir, Code, Config, optimize}; _ -> {elixir, Code, Config, normal} end; <<"#!efene", Flags/binary>> -> [Code] = Rest, case Flags of <<"-opt", _/binary>> -> {efene, Code, Config, optimize}; _ -> {efene, Code, Config, normal} end; "#!efene" ++ Flags -> [Code] = Rest, case Flags of "-opt" ++ _ -> {efene, Code, Config, optimize}; _ -> {efene, Code, Config, normal} end; <<"#!php", Flags/binary>> -> [Code] = Rest, case Flags of <<"-opt", _/binary>> -> {php, Code, Config, optimize}; _ -> {php, Code, Config, normal} end; "#!php" ++ Flags -> [Code] = Rest, case Flags of "-opt" ++ _ -> {php, Code, Config, optimize}; _ -> {php, Code, Config, normal} end; <<"#!python", Flags/binary>> -> [Code] = Rest, case Flags of <<"-opt", _/binary>> -> {python, Code, Config, optimize}; _ -> {python, Code, Config, normal} end; "#!python" ++ Flags -> [Code] = Rest, case Flags of "-opt" ++ _ -> {python, Code, Config, optimize}; _ -> {python, Code, Config, normal} end; <<"#!java", Flags/binary>> -> [Code] = Rest, case Flags of <<"-opt", _/binary>> -> {java, Code, Config, optimize}; _ -> {java, Code, Config, normal} end; "#!java" ++ Flags -> [Code] = Rest, case Flags of "-opt" ++ _ -> {java, Code, Config, optimize}; _ -> {java, Code, Config, normal} end; <<"#!erlang", Flags/binary>> -> [Code] = Rest, case Flags of <<"-opt", _/binary>> -> {erlang, Code, Config, optimize}; _ -> {erlang, Code, Config, normal} end; "#!erlang" ++ Flags -> [Code] = Rest, case Flags of "-opt" ++ _ -> {erlang, Code, Config, optimize}; _ -> {erlang, Code, Config, normal} end; _ -> {erlang, Expression, Config, normal} end. -spec get_filename_extension(string() | binary()) -> string(). get_filename_extension(Expression) -> case beamparticle_erlparser:detect_language(Expression) of {erlang, _Code, _Config, _CompileType} -> ".erl.fun"; {elixir, _Code, _Config, _CompileType} -> ".ex.fun"; {efene, _Code, _Config, _CompileType} -> ".efe.fun"; {php, _Code, _Config, _CompileType} -> ".php.fun"; {python, _Code, _Config, _CompileType} -> ".py.fun"; {java, _Code, _Config, _CompileType} -> ".java.fun" end. -spec is_valid_filename_extension(string()) -> boolean(). is_valid_filename_extension(".erl.fun") -> true; is_valid_filename_extension(".ex.fun") -> true; is_valid_filename_extension(".efe.fun") -> true; is_valid_filename_extension(".php.fun") -> true; is_valid_filename_extension(".py.fun") -> true; is_valid_filename_extension(".java.fun") -> true; is_valid_filename_extension(_) -> false. Erlang , Elixir , -spec language_files(Folder :: string()) -> [string()]. language_files(Folder) -> filelib:wildcard(Folder ++ "/*.{erl,ex,efe,php,py}.fun"). -spec create_anonymous_function(binary()) -> binary(). create_anonymous_function(Text) when is_binary(Text) -> case detect_language(Text) of {erlang, Code, _Config, normal} -> iolist_to_binary([<<"fun() ->\n">>, Code, <<"\nend.">>]); {erlang, Code, _Config, optimize} -> iolist_to_binary([<<"#!erlang-opt\nfun() ->\n">>, Code, <<"\nend.">>]); {elixir, Code, _Config, normal} -> iolist_to_binary([<<"#!elixir\nfn ->\n">>, Code, <<"\nend">>]); {elixir, Code, _Config, optimize} -> iolist_to_binary([<<"#!elixir-opt\nfn ->\n">>, Code, <<"\nend">>]); {efene, Code, _Config, normal} -> iolist_to_binary([<<"#!efene\nfn\n">>, Code, <<"\nend">>]); {efene, Code, _Config, optimize} -> iolist_to_binary([<<"#!efene-opt\nfn\n">>, Code, <<"\nend">>]); {php, Code, _Config, normal} -> iolist_to_binary([<<"#!php\n">>, Code]); {php, Code, _Config, optimize} -> iolist_to_binary([<<"#!php-opt\n">>, Code]); {python, Code, _Config, normal} -> iolist_to_binary([<<"#!python\n">>, Code]); {python, Code, _Config, optimize} -> iolist_to_binary([<<"#!python-opt\n">>, Code]); {java, Code, _Config, normal} -> iolist_to_binary([<<"#!java\n">>, Code]); {java, Code, _Config, optimize} -> iolist_to_binary([<<"#!java-opt\n">>, Code]) end. * ( comment starts with " # _ " and has comments within double quotes ) -spec extract_comments(string() | binary()) -> [string()]. extract_comments(Expression) when is_binary(Expression) orelse is_list(Expression) -> case detect_language(Expression) of {erlang, _Code, _Config, _CompileType} -> ExpressionStr = case is_binary(Expression) of true -> binary_to_list(Expression); false -> Expression end, lists:foldl(fun(E, AccIn) -> {_, _, _, Line} = E, [Line | AccIn] end, [], erl_comment_scan:scan_lines(ExpressionStr)); {elixir, Code, _Config, _CompileType} -> Lines = string:split(Code, "\n", all), CommentedLines = lists:foldl(fun(E, AccIn) -> EStripped = string:trim(E), case EStripped of [$# | Rest] -> [Rest | AccIn]; <<"#", Rest/binary>> -> [Rest | AccIn]; _ -> AccIn end end, [], Lines), lists:reverse(CommentedLines); {efene, Code, _Config, _CompileType} -> Lines = string:split(Code, "\n", all), CommentedLines = lists:foldl(fun(E, AccIn) -> EStripped = string:trim(E), case EStripped of [$#, $_ | Rest] -> [Rest | AccIn]; <<"#_", Rest/binary>> -> [Rest | AccIn]; _ -> AccIn end end, [], Lines), lists:reverse(CommentedLines); {php, Code, _Config, _CompileType} -> Lines = string:split(Code, "\n", all), CommentedLines = lists:foldl(fun(E, AccIn) -> EStripped = string:trim(E), case EStripped of [$/, $/ | Rest] -> [Rest | AccIn]; <<"//", Rest/binary>> -> [Rest | AccIn]; _ -> AccIn end end, [], Lines), lists:reverse(CommentedLines); {python, Code, _Config, _CompileType} -> Lines = string:split(Code, "\n", all), CommentedLines = lists:foldl(fun(E, AccIn) -> EStripped = string:trim(E), case EStripped of [$# | Rest] -> [Rest | AccIn]; <<"#", Rest/binary>> -> [Rest | AccIn]; _ -> AccIn end end, [], Lines), lists:reverse(CommentedLines); {java, Code, _Config, _CompileType} -> Lines = string:split(Code, "\n", all), CommentedLines = lists:foldl(fun(E, AccIn) -> EStripped = string:trim(E), case EStripped of [$/, $/ | Rest] -> [Rest | AccIn]; <<"//", Rest/binary>> -> [Rest | AccIn]; _ -> AccIn end end, [], Lines), lists:reverse(CommentedLines) end. * -spec evaluate_expression(string() | binary()) -> {any(), string() | binary()} | {php | python | java, binary(), binary(), normal | optimize}. evaluate_expression(Expression) -> case detect_language(Expression) of {erlang, Code, Config, CompileType} -> {beamparticle_erlparser:evaluate_erlang_expression( Code, CompileType), Config}; {elixir, Code, Config, CompileType} -> ErlangParsedExpressions = beamparticle_elixirparser:get_erlang_parsed_expressions(Code), {evaluate_erlang_parsed_expressions(ErlangParsedExpressions, CompileType), Config}; {efene, Code, Config, CompileType} -> ErlangParsedExpressions = beamparticle_efeneparser:get_erlang_parsed_expressions(Code), {evaluate_erlang_parsed_expressions(ErlangParsedExpressions, CompileType), Config}; {php, Code, Config, CompileType} -> {php, Code, Config, CompileType}; {python, Code, Config, CompileType} -> {python, Code, Config, CompileType}; {java, Code, Config, CompileType} -> {java, Code, Config, CompileType} end. -spec get_erlang_parsed_expressions(fun() | string() | binary()) -> any(). get_erlang_parsed_expressions(ErlangExpression) when is_binary(ErlangExpression) -> get_erlang_parsed_expressions(binary_to_list(ErlangExpression)); get_erlang_parsed_expressions(ErlangExpression) when is_list(ErlangExpression) -> {ok, ErlangTokens, _} = erl_scan:string(ErlangExpression), {ok, ErlangParsedExpressions} = erl_parse:parse_exprs(ErlangTokens), ErlangParsedExpressions. @doc Evaluate a given Erlang expression and give back result . -spec evaluate_erlang_expression(string() | binary(), normal | optimize) -> any(). evaluate_erlang_expression(ErlangExpression, CompileType) -> ErlangParsedExpressions = get_erlang_parsed_expressions(ErlangExpression), evaluate_erlang_parsed_expressions(ErlangParsedExpressions, CompileType). -spec evaluate_erlang_parsed_expressions(term(), normal | optimize) -> any(). evaluate_erlang_parsed_expressions(ErlangParsedExpressions, normal) -> bindings are also returned as third tuple element but not used {value, Result, _} = erl_eval:exprs(ErlangParsedExpressions, [], {value, fun intercept_local_function/2}, {value, fun intercept_nonlocal_function/2}), Result; evaluate_erlang_parsed_expressions(ErlangParsedExpressions, optimize) -> bindings are also returned as third tuple element but not used {value, Result, _} = erl_eval:exprs(ErlangParsedExpressions, [], {value, fun intercept_local_function/2}), Result. calltrace_to_json_map(CallTrace) when is_list(CallTrace) -> lists:foldl(fun({FunctionName, Arguments, DeltaUsec}, AccIn) -> [#{<<"function">> => FunctionName, <<"arguments">> => list_to_binary(io_lib:format("~p", [Arguments])), <<"delta_usec">> => DeltaUsec} | AccIn] end, [], CallTrace). @private -spec intercept_local_function(FunctionName :: atom(), Arguments :: list()) -> any(). intercept_local_function(FunctionName, Arguments) -> lager:debug("Local call to ~p with ~p~n", [FunctionName, Arguments]), TraceLog = list_to_binary( io_lib:format("{~p, ~p}", [FunctionName, Arguments])), otter_span_pdict_api:log(TraceLog), case FunctionName of _ -> FunctionNameBin = atom_to_binary(FunctionName, utf8), execute_dynamic_function(FunctionNameBin, Arguments) end. @private -spec intercept_nonlocal_function({ModuleName :: atom(), FunctionName :: atom()} | fun(), Arguments :: list()) -> any(). intercept_nonlocal_function({ModuleName, FunctionName}, Arguments) -> case erlang:get(?OPENTRACE_PDICT_CONFIG) of undefined -> ok; OpenTracingConfig -> Arity = length(Arguments), ShouldTraceLog = case beamparticle_util:is_operator({ModuleName, FunctionName, Arity}) of true -> proplists:get_value(trace_operator, OpenTracingConfig, true); false -> ModuleTraceOptions = proplists:get_value(trace_module, OpenTracingConfig, []), case proplists:get_value(ModuleName, ModuleTraceOptions, true) of true -> ModuleFunTraceOptions = proplists:get_value(trace_module_function, OpenTracingConfig, []), proplists:get_value({ModuleName, FunctionName}, ModuleFunTraceOptions, true); false -> false end end, case ShouldTraceLog of true -> TraceLog = list_to_binary( io_lib:format("{~p, ~p, ~p}", [ModuleName, FunctionName, Arguments])), otter_span_pdict_api:log(TraceLog); false -> ok end end, apply(ModuleName, FunctionName, Arguments); intercept_nonlocal_function(Fun, Arguments) when is_function(Fun) -> case erlang:get(?OPENTRACE_PDICT_CONFIG) of undefined -> ok; OpenTracingConfig -> ShouldTraceLog = proplists:get_value( trace_anonymous_function, OpenTracingConfig, true), case ShouldTraceLog of true -> TraceLog = list_to_binary( io_lib:format("{~p, ~p}", [Fun, Arguments])), otter_span_pdict_api:log(TraceLog); false -> ok end end, apply(Fun, Arguments); intercept_nonlocal_function(Fun, Arguments) when is_atom(Fun) -> intercept_local_function(Fun, Arguments). execute_dynamic_function(FunctionNameBin, Arguments) when is_binary(FunctionNameBin) andalso is_list(Arguments) -> RealFunctionNameBin = case FunctionNameBin of <<"__simple_http_", RestFunctionNameBin/binary>> -> RestFunctionNameBin; _ -> FunctionNameBin end, Arity = length(Arguments), ArityBin = integer_to_binary(Arity, 10), FullFunctionName = <<RealFunctionNameBin/binary, $/, ArityBin/binary>>, case erlang:get(?CALL_TRACE_ENV_KEY) of undefined -> ok; OldCallTrace -> T1 = erlang:monotonic_time(micro_seconds), T = erlang:get(?CALL_TRACE_BASE_TIME), erlang:put(?CALL_TRACE_ENV_KEY, [{RealFunctionNameBin, Arguments, T1 - T} | OldCallTrace]) end, FResp = case erlang:get(?CALL_ENV_KEY) of undefined -> run_function(FullFunctionName, function); prod -> run_function(FullFunctionName, function); stage -> case run_function(FullFunctionName, function_stage) of {ok, F2} -> {ok, F2}; {error, not_found} -> run_function(FullFunctionName, function) end end, case FResp of {ok, {F, <<>>}} when is_function(F) -> apply(F, Arguments); {ok, {F, ConfigMap}} when is_function(F) -> TODO remove this key once the original function is complete beamparticle_dynamic:put_config(ConfigMap), apply(F, Arguments); {ok, {php, PhpCode, Config, _CompileType}} -> beamparticle_phpparser:evaluate_php_expression( PhpCode, Config, Arguments); {ok, {python, PythonCode, Config, _CompileType}} -> That is do not use RealFunctionNameBin here beamparticle_pythonparser:evaluate_python_expression( FunctionNameBin, PythonCode, Config, Arguments); {ok, {java, JavaCode, Config, _CompileType}} -> That is do not use RealFunctionNameBin here beamparticle_javaparser:evaluate_java_expression( FunctionNameBin, JavaCode, Config, Arguments); _ -> case {FunctionNameBin, Arity} of {<<"log_info">>, _} when Arity == 1 orelse Arity == 2 -> apply(beamparticle_dynamic, log_info, Arguments); {<<"log_error">>, _} when Arity == 1 orelse Arity == 2 -> apply(beamparticle_dynamic, log_error, Arguments); {<<"get_config">>, 0} -> apply(beamparticle_dynamic, get_config, Arguments); {<<"run_concurrent">>, 2} -> apply(beamparticle_dynamic, run_concurrent, Arguments); {<<"async_run_concurrent">>, 2} -> apply(beamparticle_dynamic, async_run_concurrent, Arguments); {<<"stage">>, 1} -> [Arg1] = Arguments, beamparticle_dynamic:stage(Arg1, []); {<<"release">>, 0} -> beamparticle_dynamic:release([]); _ -> lager:debug("FunctionNameBin=~p, Arguments=~p", [RealFunctionNameBin, Arguments]), R = list_to_binary(io_lib:format("Please teach me what must I do with ~s(~s)", [RealFunctionNameBin, lists:join(",", [io_lib:format("~p", [X]) || X <- Arguments])])), lager:debug("R=~p", [R]), erlang:throw({error, R}) end end. IMPORTANT : There is an order of 10 difference between the 10x speed . -spec discover_function_calls(fun() | string() | binary()) -> any(). discover_function_calls(Expression) when is_binary(Expression) -> discover_function_calls(binary_to_list(Expression)); discover_function_calls(Expression) when is_list(Expression) -> ErlangParsedExpressions = case detect_language(Expression) of {erlang, Code, _Config, _CompileType} -> get_erlang_parsed_expressions(Code); {elixir, Code, _Config, _CompileType} -> beamparticle_elixirparser:get_erlang_parsed_expressions(Code); {efene, Code, _Config, _CompileType} -> beamparticle_efeneparser:get_erlang_parsed_expressions(Code); {php, _Code, _Config, _CompileType} -> []; {python, _Code, _Config, _CompileType} -> TODO Erlang / Elixir / Efene world []; {java, _Code, _Config, _CompileType} -> TODO Erlang / Elixir / Efene world [] end, Functions = recursive_dig_function_calls(ErlangParsedExpressions, []), lists:usort(Functions); discover_function_calls(F) when is_function(F) -> {env, FunCodeAsEnv} = erlang:fun_info(F, env), Functions = recursive_dig_function_calls(FunCodeAsEnv, []), lists:usort(Functions). @private -spec recursive_dig_function_calls(term(), list()) -> [{binary(), binary(), integer()} | {binary(), integer()}]. recursive_dig_function_calls([], AccIn) -> AccIn; recursive_dig_function_calls([H | Rest], AccIn) -> AccIn2 = recursive_dig_function_calls(H, AccIn), recursive_dig_function_calls(Rest, AccIn2); recursive_dig_function_calls({[], _, _, Clauses}, AccIn) -> This matches the case when : fun_info/1 is used recursive_dig_function_calls(Clauses, AccIn); recursive_dig_function_calls({'fun', _LineNum, ClausesRec}, AccIn) -> recursive_dig_function_calls(ClausesRec, AccIn); recursive_dig_function_calls({clauses, [H | RestClauses]}, AccIn) -> AccIn2 = recursive_dig_function_calls(H, AccIn), recursive_dig_function_calls(RestClauses, AccIn2); recursive_dig_function_calls({clause, _LineNum, _, _, Expressions}, AccIn) -> recursive_dig_function_calls(Expressions, AccIn); recursive_dig_function_calls({match, _LineNum, Lhs, Rhs}, AccIn) -> AccIn2 = recursive_dig_function_calls(Lhs, AccIn), recursive_dig_function_calls(Rhs, AccIn2); recursive_dig_function_calls({var, _LineNum, _VarName}, AccIn) -> AccIn; recursive_dig_function_calls({op, _LineNum, _Op, Lhs, Rhs}, AccIn) -> AccIn2 = recursive_dig_function_calls(Lhs, AccIn), recursive_dig_function_calls(Rhs, AccIn2); recursive_dig_function_calls({op, _LineNum, _Op, Rhs}, AccIn) -> recursive_dig_function_calls(Rhs, AccIn); recursive_dig_function_calls({'case', _LineNum, Condition, Branches}, AccIn) -> AccIn2 = recursive_dig_function_calls(Condition, AccIn), recursive_dig_function_calls(Branches, AccIn2); recursive_dig_function_calls({call, _LineNum, {atom, _LineNum2, FunNameAtom}, Args}, AccIn) -> Arity = length(Args), recursive_dig_function_calls(Args, [{atom_to_binary(FunNameAtom, utf8), Arity} | AccIn]); recursive_dig_function_calls({call, _LineNum, {remote, _LineNum2, {atom, _LineNum3, ModuleNameAtom}, {atom, _LineNum4, FunNameAtom}}, Args}, AccIn) -> Arity = length(Args), recursive_dig_function_calls(Args, [{atom_to_binary(ModuleNameAtom, utf8), atom_to_binary(FunNameAtom, utf8), Arity} | AccIn]); recursive_dig_function_calls({map, _LineNum, _Var, Fields}, AccIn) -> recursive_dig_function_calls(Fields, AccIn); recursive_dig_function_calls({map_field_assoc, _LineNum, Key, Value}, AccIn) -> AccIn2 = recursive_dig_function_calls(Key, AccIn), recursive_dig_function_calls(Value, AccIn2); recursive_dig_function_calls({tuple, _LineNum, Fields}, AccIn) -> recursive_dig_function_calls(Fields, AccIn); recursive_dig_function_calls({cons, _LineNum, Arg1, Arg2}, AccIn) -> AccIn2 = recursive_dig_function_calls(Arg1, AccIn), recursive_dig_function_calls(Arg2, AccIn2); recursive_dig_function_calls(_, AccIn) -> AccIn. run_function(FullFunctionName, function) -> FunctionCacheKey = beamparticle_storage_util:function_cache_key( FullFunctionName, function), case timer:tc(beamparticle_cache_util, get, [FunctionCacheKey]) of {CacheLookupTimeUsec, {ok, {Func, ConfigMap}}} -> lager:debug("Took ~p usec for cache hit of ~s", [CacheLookupTimeUsec, FullFunctionName]), lager:debug("Cache lookup ~p", [{FullFunctionName, {Func, ConfigMap}}]), {ok, {Func, ConfigMap}}; {CacheLookupTimeUsec, _} -> lager:debug("Took ~p usec for cache miss of ~s", [CacheLookupTimeUsec, FullFunctionName]), T2 = erlang:monotonic_time(micro_seconds), KvResp = beamparticle_storage_util:read( FullFunctionName, function), case KvResp of {ok, FunctionBody} -> Resp2 = beamparticle_erlparser:evaluate_expression( FunctionBody), case Resp2 of {Func3, Config} when is_function(Func3) -> T3 = erlang:monotonic_time(micro_seconds), lager:debug("Took ~p micro seconds to read and compile ~s function",[T3 - T2, FullFunctionName]), ConfigMap = case Config of <<>> -> #{}; _ -> jiffy:decode(Config, [return_maps]) end, beamparticle_cache_util:async_put(FunctionCacheKey, {Func3, ConfigMap}), {ok, {Func3, ConfigMap}}; _ -> this is for php , python and at present , which do not compile to erlang {ok, Resp2} end; _ -> {error, not_found} end end; run_function(FullFunctionName, function_stage) -> FunctionCacheKey = beamparticle_storage_util:function_cache_key( FullFunctionName, function_stage), case beamparticle_cache_util:get(FunctionCacheKey) of {ok, {Func, ConfigMap}} -> {ok, {Func, ConfigMap}}; _ -> KvResp = beamparticle_storage_util:read( FullFunctionName, function_stage), case KvResp of {ok, FunctionBody} -> Resp2 = beamparticle_erlparser:evaluate_expression( binary_to_list(FunctionBody)), case Resp2 of {Func3, Config} when is_function(Func3) -> ConfigMap = case Config of <<>> -> #{}; _ -> jiffy:decode(Config, [return_maps]) end, beamparticle_cache_util:async_put(FunctionCacheKey, {Func3, ConfigMap}), {ok, {Func3, ConfigMap}}; _ -> this is for php , python and at present , which do not compile to erlang {ok, Resp2} end; _ -> {error, not_found} end end.
d60a5fee9d3a0136eb76b256370fe72e2c3420ea9eace6f8dcf633b59ce9561f
wavewave/fficxx
Gen.hs
{-# LANGUAGE OverloadedStrings #-} module Main where import qualified Data.HashMap.Strict as HM -- import qualified Data.HashMap.Strict as HM (fromList) import Data.Monoid (mempty) -- import FFICXX.Generate.Builder import FFICXX.Generate.Builder (simpleBuilder) import FFICXX.Generate.Code.Primitive import FFICXX.Generate.Code.Primitive ( bool_, charpp, cppclass, cppclass_, cstring, cstring_, double, double_, int, int_, uint, uint_, void_, voidp, ) import FFICXX.Generate.Config ( FFICXXConfig (..), SimpleBuilderConfig (..), ) import FFICXX.Generate.Type.Cabal ( AddCInc (..), AddCSrc (..), BuildType (..), Cabal (..), CabalName (..), ) import FFICXX.Generate.Type.Class import FFICXX.Generate.Type.Class ( Arg (..), CTypes (CTDouble), Class (..), Form (FormSimple), Function (..), ProtectedMethod (..), TopLevel (..), Variable (..), ) import FFICXX.Generate.Type.Config ( ModuleUnit (..), ModuleUnitImports (..), ModuleUnitMap (..), modImports, ) import FFICXX.Generate.Type.Module import FFICXX.Generate.Type.PackageInterface import FFICXX.Runtime.CodeGen.Cxx (HeaderName (..), Namespace (..)) import System.Directory (getCurrentDirectory) import System.Environment (getArgs) import System.FilePath ((</>)) -- ------------------------------------------------------------------- import from stdcxx -- ------------------------------------------------------------------- stdcxx_cabal :: Cabal stdcxx_cabal = Cabal { cabal_pkgname = CabalName "stdcxx", cabal_version = "0.6", cabal_cheaderprefix = "STD", cabal_moduleprefix = "STD", cabal_additional_c_incs = [], cabal_additional_c_srcs = [], cabal_additional_pkgdeps = [], cabal_license = Nothing, cabal_licensefile = Nothing, cabal_extraincludedirs = [], cabal_extralibdirs = [], cabal_extrafiles = [], cabal_pkg_config_depends = [], cabal_buildType = Simple } import from stdcxx deletable :: Class deletable = AbstractClass { class_cabal = stdcxx_cabal, class_name = "Deletable", class_parents = [], class_protected = Protected [], class_alias = Nothing, class_funcs = [Destructor Nothing], class_vars = [], class_tmpl_funcs = [] } import from stdcxx string :: Class string = Class stdcxx_cabal "string" [deletable] mempty (Just (ClassAlias {caHaskellName = "CppString", caFFIName = "string"})) [ Constructor [cstring "p"] Nothing, NonVirtual cstring_ "c_str" [] Nothing, NonVirtual (cppclassref_ string) "append" [cppclassref string "str"] Nothing, NonVirtual (cppclassref_ string) "erase" [] Nothing ] [] [] False t_vector :: TemplateClass t_vector = TmplCls stdcxx_cabal "Vector" (FormSimple "std::vector") ["tp1"] [ TFunNew [] Nothing, TFun void_ "push_back" "push_back" [Arg (TemplateParam "tp1") "x"], TFun void_ "pop_back" "pop_back" [], TFun (TemplateParam "tp1") "at" "at" [int "n"], TFun int_ "size" "size" [], TFunDelete ] [] t_unique_ptr :: TemplateClass t_unique_ptr = TmplCls stdcxx_cabal "UniquePtr" (FormSimple "std::unique_ptr") ["tp1"] [ TFunNew [] (Just "newUniquePtr0"), TFunNew [Arg (TemplateParamPointer "tp1") "p"] Nothing, TFun (TemplateParamPointer "tp1") "get" "get" [], TFun (TemplateParamPointer "tp1") "release" "release" [], TFun void_ "reset" "reset" [], TFunDelete ] [] -- ------------------------------------------------------------------- -- tmf-test -- ------------------------------------------------------------------- cabal_ :: FilePath -> FilePath -> Cabal cabal_ tmftestH tmftestCpp = Cabal { cabal_pkgname = CabalName "tmf-test", cabal_version = "0.0", cabal_cheaderprefix = "TMFTest", cabal_moduleprefix = "TMFTest", cabal_additional_c_incs = [AddCInc "tmftest.h" tmftestH], cabal_additional_c_srcs = [AddCSrc "tmftest.cpp" tmftestCpp], cabal_additional_pkgdeps = [CabalName "stdcxx"], cabal_license = Just "BSD-3-Clause", cabal_licensefile = Just "LICENSE", cabal_extraincludedirs = [], cabal_extralibdirs = [], cabal_extrafiles = [], cabal_pkg_config_depends = [], cabal_buildType = Simple } extraDep :: [(String, [String])] extraDep = [] extraLib :: [String] extraLib = [] classA :: Cabal -> Class classA cabal = Class { class_cabal = cabal, class_name = "A", class_parents = [deletable], class_protected = mempty, class_alias = Nothing, class_funcs = [Constructor [] Nothing], class_vars = [], class_tmpl_funcs = [ TemplateMemberFunction { tmf_params = ["tp1"], tmf_ret = void_, tmf_name = "method", tmf_args = [Arg (TemplateParamPointer "tp1") "x"], tmf_alias = Nothing }, TemplateMemberFunction { tmf_params = ["tp1"], tmf_ret = void_, tmf_name = "method2", tmf_args = [ Arg ( TemplateAppMove TemplateAppInfo { tapp_tclass = t_unique_ptr, tapp_tparams = [TArg_TypeParam "tp1"], tapp_CppTypeForParam = "std::unique_ptr<tp1>" } ) "x" ], tmf_alias = Nothing } ], class_has_proxy = False } classT1 :: Cabal -> Class classT1 cabal = Class { class_cabal = cabal, class_name = "T1", class_parents = [deletable], class_protected = mempty, class_alias = Nothing, class_funcs = [ Constructor [] Nothing, NonVirtual void_ "print" [] Nothing ], class_vars = [], class_tmpl_funcs = [], class_has_proxy = False } classT2 :: Cabal -> Class classT2 cabal = Class { class_cabal = cabal, class_name = "T2", class_parents = [deletable], class_protected = mempty, class_alias = Nothing, class_funcs = [ Constructor [] Nothing, NonVirtual void_ "print" [] Nothing ], class_vars = [], class_tmpl_funcs = [], class_has_proxy = False } classes :: Cabal -> [Class] classes cabal = [classA cabal, classT1 cabal, classT2 cabal] toplevels :: [TopLevel] toplevels = [] templates :: [TemplateClassImportHeader] templates = [] headers :: [(ModuleUnit, ModuleUnitImports)] headers = [ modImports "A" [] ["tmftest.h"], modImports "T1" [] ["tmftest.h"], modImports "T2" [] ["tmftest.h"] ] main :: IO () main = do args <- getArgs let tmpldir = if length args == 1 then args !! 0 else "../template" cwd <- getCurrentDirectory cabal <- do tmftestH <- readFile (tmpldir </> "tmftest.h") tmftestCpp <- readFile (tmpldir </> "tmftest.cpp") pure (cabal_ tmftestH tmftestCpp) let fficfg = FFICXXConfig { fficxxconfig_workingDir = cwd </> "tmp" </> "working", fficxxconfig_installBaseDir = cwd </> "tmf-test", fficxxconfig_staticFileDir = tmpldir } sbcfg = SimpleBuilderConfig { sbcTopModule = "TMFTest", sbcModUnitMap = ModuleUnitMap (HM.fromList headers), sbcCabal = cabal, sbcClasses = classes cabal, sbcTopLevels = toplevels, sbcTemplates = templates, sbcExtraLibs = extraLib, sbcCxxOpts = ["-std=c++17"], sbcExtraDeps = extraDep, sbcStaticFiles = [] } simpleBuilder fficfg sbcfg
null
https://raw.githubusercontent.com/wavewave/fficxx/489efb1d8dce9731133725b0adcc945c69944b6e/fficxx-multipkg-test/template-member/Gen.hs
haskell
# LANGUAGE OverloadedStrings # ------------------------------------------------------------------- ------------------------------------------------------------------- ------------------------------------------------------------------- tmf-test -------------------------------------------------------------------
module Main where import qualified Data.HashMap.Strict as HM import qualified Data.HashMap.Strict as HM (fromList) import Data.Monoid (mempty) import FFICXX.Generate.Builder import FFICXX.Generate.Builder (simpleBuilder) import FFICXX.Generate.Code.Primitive import FFICXX.Generate.Code.Primitive ( bool_, charpp, cppclass, cppclass_, cstring, cstring_, double, double_, int, int_, uint, uint_, void_, voidp, ) import FFICXX.Generate.Config ( FFICXXConfig (..), SimpleBuilderConfig (..), ) import FFICXX.Generate.Type.Cabal ( AddCInc (..), AddCSrc (..), BuildType (..), Cabal (..), CabalName (..), ) import FFICXX.Generate.Type.Class import FFICXX.Generate.Type.Class ( Arg (..), CTypes (CTDouble), Class (..), Form (FormSimple), Function (..), ProtectedMethod (..), TopLevel (..), Variable (..), ) import FFICXX.Generate.Type.Config ( ModuleUnit (..), ModuleUnitImports (..), ModuleUnitMap (..), modImports, ) import FFICXX.Generate.Type.Module import FFICXX.Generate.Type.PackageInterface import FFICXX.Runtime.CodeGen.Cxx (HeaderName (..), Namespace (..)) import System.Directory (getCurrentDirectory) import System.Environment (getArgs) import System.FilePath ((</>)) import from stdcxx stdcxx_cabal :: Cabal stdcxx_cabal = Cabal { cabal_pkgname = CabalName "stdcxx", cabal_version = "0.6", cabal_cheaderprefix = "STD", cabal_moduleprefix = "STD", cabal_additional_c_incs = [], cabal_additional_c_srcs = [], cabal_additional_pkgdeps = [], cabal_license = Nothing, cabal_licensefile = Nothing, cabal_extraincludedirs = [], cabal_extralibdirs = [], cabal_extrafiles = [], cabal_pkg_config_depends = [], cabal_buildType = Simple } import from stdcxx deletable :: Class deletable = AbstractClass { class_cabal = stdcxx_cabal, class_name = "Deletable", class_parents = [], class_protected = Protected [], class_alias = Nothing, class_funcs = [Destructor Nothing], class_vars = [], class_tmpl_funcs = [] } import from stdcxx string :: Class string = Class stdcxx_cabal "string" [deletable] mempty (Just (ClassAlias {caHaskellName = "CppString", caFFIName = "string"})) [ Constructor [cstring "p"] Nothing, NonVirtual cstring_ "c_str" [] Nothing, NonVirtual (cppclassref_ string) "append" [cppclassref string "str"] Nothing, NonVirtual (cppclassref_ string) "erase" [] Nothing ] [] [] False t_vector :: TemplateClass t_vector = TmplCls stdcxx_cabal "Vector" (FormSimple "std::vector") ["tp1"] [ TFunNew [] Nothing, TFun void_ "push_back" "push_back" [Arg (TemplateParam "tp1") "x"], TFun void_ "pop_back" "pop_back" [], TFun (TemplateParam "tp1") "at" "at" [int "n"], TFun int_ "size" "size" [], TFunDelete ] [] t_unique_ptr :: TemplateClass t_unique_ptr = TmplCls stdcxx_cabal "UniquePtr" (FormSimple "std::unique_ptr") ["tp1"] [ TFunNew [] (Just "newUniquePtr0"), TFunNew [Arg (TemplateParamPointer "tp1") "p"] Nothing, TFun (TemplateParamPointer "tp1") "get" "get" [], TFun (TemplateParamPointer "tp1") "release" "release" [], TFun void_ "reset" "reset" [], TFunDelete ] [] cabal_ :: FilePath -> FilePath -> Cabal cabal_ tmftestH tmftestCpp = Cabal { cabal_pkgname = CabalName "tmf-test", cabal_version = "0.0", cabal_cheaderprefix = "TMFTest", cabal_moduleprefix = "TMFTest", cabal_additional_c_incs = [AddCInc "tmftest.h" tmftestH], cabal_additional_c_srcs = [AddCSrc "tmftest.cpp" tmftestCpp], cabal_additional_pkgdeps = [CabalName "stdcxx"], cabal_license = Just "BSD-3-Clause", cabal_licensefile = Just "LICENSE", cabal_extraincludedirs = [], cabal_extralibdirs = [], cabal_extrafiles = [], cabal_pkg_config_depends = [], cabal_buildType = Simple } extraDep :: [(String, [String])] extraDep = [] extraLib :: [String] extraLib = [] classA :: Cabal -> Class classA cabal = Class { class_cabal = cabal, class_name = "A", class_parents = [deletable], class_protected = mempty, class_alias = Nothing, class_funcs = [Constructor [] Nothing], class_vars = [], class_tmpl_funcs = [ TemplateMemberFunction { tmf_params = ["tp1"], tmf_ret = void_, tmf_name = "method", tmf_args = [Arg (TemplateParamPointer "tp1") "x"], tmf_alias = Nothing }, TemplateMemberFunction { tmf_params = ["tp1"], tmf_ret = void_, tmf_name = "method2", tmf_args = [ Arg ( TemplateAppMove TemplateAppInfo { tapp_tclass = t_unique_ptr, tapp_tparams = [TArg_TypeParam "tp1"], tapp_CppTypeForParam = "std::unique_ptr<tp1>" } ) "x" ], tmf_alias = Nothing } ], class_has_proxy = False } classT1 :: Cabal -> Class classT1 cabal = Class { class_cabal = cabal, class_name = "T1", class_parents = [deletable], class_protected = mempty, class_alias = Nothing, class_funcs = [ Constructor [] Nothing, NonVirtual void_ "print" [] Nothing ], class_vars = [], class_tmpl_funcs = [], class_has_proxy = False } classT2 :: Cabal -> Class classT2 cabal = Class { class_cabal = cabal, class_name = "T2", class_parents = [deletable], class_protected = mempty, class_alias = Nothing, class_funcs = [ Constructor [] Nothing, NonVirtual void_ "print" [] Nothing ], class_vars = [], class_tmpl_funcs = [], class_has_proxy = False } classes :: Cabal -> [Class] classes cabal = [classA cabal, classT1 cabal, classT2 cabal] toplevels :: [TopLevel] toplevels = [] templates :: [TemplateClassImportHeader] templates = [] headers :: [(ModuleUnit, ModuleUnitImports)] headers = [ modImports "A" [] ["tmftest.h"], modImports "T1" [] ["tmftest.h"], modImports "T2" [] ["tmftest.h"] ] main :: IO () main = do args <- getArgs let tmpldir = if length args == 1 then args !! 0 else "../template" cwd <- getCurrentDirectory cabal <- do tmftestH <- readFile (tmpldir </> "tmftest.h") tmftestCpp <- readFile (tmpldir </> "tmftest.cpp") pure (cabal_ tmftestH tmftestCpp) let fficfg = FFICXXConfig { fficxxconfig_workingDir = cwd </> "tmp" </> "working", fficxxconfig_installBaseDir = cwd </> "tmf-test", fficxxconfig_staticFileDir = tmpldir } sbcfg = SimpleBuilderConfig { sbcTopModule = "TMFTest", sbcModUnitMap = ModuleUnitMap (HM.fromList headers), sbcCabal = cabal, sbcClasses = classes cabal, sbcTopLevels = toplevels, sbcTemplates = templates, sbcExtraLibs = extraLib, sbcCxxOpts = ["-std=c++17"], sbcExtraDeps = extraDep, sbcStaticFiles = [] } simpleBuilder fficfg sbcfg
87d684df0d96aed5d94e740c3e031518960268bba868ff314cfdbf5d4b74f80b
haskell-opengl/OpenGLRaw
Interlace.hs
# LANGUAGE PatternSynonyms # -------------------------------------------------------------------------------- -- | -- Module : Graphics.GL.SGIX.Interlace Copyright : ( c ) 2019 -- License : BSD3 -- Maintainer : < > -- Stability : stable -- Portability : portable -- -------------------------------------------------------------------------------- module Graphics.GL.SGIX.Interlace ( -- * Extension Support glGetSGIXInterlace, gl_SGIX_interlace, -- * Enums pattern GL_INTERLACE_SGIX ) where import Graphics.GL.ExtensionPredicates import Graphics.GL.Tokens
null
https://raw.githubusercontent.com/haskell-opengl/OpenGLRaw/57e50c9d28dfa62d6a87ae9b561af28f64ce32a0/src/Graphics/GL/SGIX/Interlace.hs
haskell
------------------------------------------------------------------------------ | Module : Graphics.GL.SGIX.Interlace License : BSD3 Stability : stable Portability : portable ------------------------------------------------------------------------------ * Extension Support * Enums
# LANGUAGE PatternSynonyms # Copyright : ( c ) 2019 Maintainer : < > module Graphics.GL.SGIX.Interlace ( glGetSGIXInterlace, gl_SGIX_interlace, pattern GL_INTERLACE_SGIX ) where import Graphics.GL.ExtensionPredicates import Graphics.GL.Tokens
b6089c0edd2162cf4190fc3100af9ed3c3466279c24a69a8725d17a74357e1ed
oliyh/martian
interceptors_test.cljc
(ns martian.interceptors-test (:require [martian.interceptors :as i] [martian.encoders :as encoders] [tripod.context :as tc] [schema.core :as s] [schema-tools.core :as st] #?(:clj [clojure.test :refer [deftest is testing]] :cljs [cljs.test :refer-macros [deftest testing is]]) #?(:clj [martian.test-utils :as tu]))) #?(:cljs (def Throwable js/Error)) (deftest encode-body-test (let [i i/default-encode-body body {:the {:wheels ["on" "the" "bus"]} :go {:round {:and "round"}}}] (testing "json" (is (= {:body (encoders/json-encode body) :headers {"Content-Type" "application/json"}} (:request ((:enter i) {:request {:body body} :handler {:consumes ["application/json"]}}))))) (testing "edn" (is (= {:body (pr-str body) :headers {"Content-Type" "application/edn"}} (:request ((:enter i) {:request {:body body} :handler {:consumes ["application/edn"]}}))))) (testing "transit" (testing "+json" (is (= {:body body :headers {"Content-Type" "application/transit+json"}} (-> ((:enter i) {:request {:body body} :handler {:consumes ["application/transit+json"]}}) :request (update :body #?(:clj (comp #(encoders/transit-decode % :json) tu/input-stream->byte-array) :cljs #(encoders/transit-decode % :json))))))) #?(:clj (testing "+msgpack" (is (= {:body body :headers {"Content-Type" "application/transit+msgpack"}} (-> ((:enter i) {:request {:body body} :handler {:consumes ["application/transit+msgpack"]}}) :request (update :body (comp #(encoders/transit-decode % :msgpack) tu/input-stream->byte-array)))))))))) (defn- stub-response [content-type body] {:name ::stub-response :enter (fn [ctx] (assoc ctx :response {:body body :headers {:content-type content-type}}))}) (deftest coerce-response-test (let [i i/default-coerce-response body {:the {:wheels ["on" "the" "bus"]} :go {:round {:and "round"}}}] (testing "json" (let [ctx (tc/enqueue* {} [i (stub-response "application/json" (encoders/json-encode body))])] (is (= body (-> (tc/execute ctx) :response :body))))) (testing "edn" (let [ctx (tc/enqueue* {} [i (stub-response "application/edn" (pr-str body))])] (is (= body (-> (tc/execute ctx) :response :body))))) (testing "transit" (testing "+json" (let [ctx (tc/enqueue* {} [i (stub-response "application/transit+json" #?(:clj (slurp (encoders/transit-encode body :json)) :cljs (encoders/transit-encode body :json)))])] (is (= body (-> (tc/execute ctx) :response :body))))) #?(:clj (testing "+msgpack" (let [ctx (tc/enqueue* {} [i (stub-response "application/transit+msgpack" (tu/input-stream->byte-array (encoders/transit-encode body :msgpack)))])] (is (= body (-> (tc/execute ctx) :response :body))))))))) (deftest custom-encoding-test (testing "a user can support an encoding that martian doesn't know about by default" (let [reverse-string #(apply str (reverse %)) encoders (assoc (encoders/default-encoders) "text/magical+json" {:encode (comp reverse-string encoders/json-encode) :decode (comp #(encoders/json-decode % keyword) reverse-string) :as :magic}) body {:the {:wheels ["on" "the" "bus"]} :go {:round {:and "round"}}} encoded-body (-> body encoders/json-encode reverse-string) ctx (tc/enqueue* {:request {:body body} :handler {:consumes ["text/magical+json"] :produces ["text/magical+json"]}} [(i/encode-body encoders) (i/coerce-response encoders) (stub-response "text/magical+json" encoded-body)]) result (tc/execute ctx)] (is (= {:body encoded-body :headers {"Content-Type" "text/magical+json" "Accept" "text/magical+json"} :as :magic} (:request result))) (is (= {:body body :headers {:content-type "text/magical+json"}} (:response result)))))) (deftest auto-encoder-test (testing "when the server speaks a language martian doesn't understand it leaves it alone" (let [reverse-string #(apply str (reverse %)) body {:the {:wheels ["on" "the" "bus"]} :go {:round {:and "round"}}} encoded-body (-> body encoders/json-encode reverse-string) ctx (tc/enqueue* {:request {:body encoded-body :headers {"Content-Type" "text/magical+json" "Accept" "text/magical+json"}} :handler {:consumes ["text/magical+json"] :produces ["text/magical+json"]}} [i/default-encode-body i/default-coerce-response (stub-response "text/magical+json" encoded-body)]) result (tc/execute ctx)] (is (= {:body encoded-body :headers {"Content-Type" "text/magical+json" "Accept" "text/magical+json"} :as :auto} (:request result))) (is (= {:body encoded-body :headers {:content-type "text/magical+json"}} (:response result)))))) (deftest supported-content-types-test (testing "picks up the supported content-types from the encoding/decoding interceptors" (let [encode-body i/default-encode-body coerce-response (i/coerce-response (assoc (encoders/default-encoders) "text/magical+json" {:encode encoders/json-encode :decode #(encoders/json-decode % keyword) :as :magic}))] (is (= {:encodes #?(:clj #{"application/json" "application/transit+msgpack" "application/transit+json" "application/edn"} :cljs #{"application/json" "application/transit+json" "application/edn"}) :decodes #?(:clj #{"application/json" "text/magical+json" "application/transit+msgpack" "application/transit+json" "application/edn"} :cljs #{"application/json" "text/magical+json" "application/transit+json" "application/edn"})} (i/supported-content-types [encode-body coerce-response])))))) (deftest validate-response-test (let [handler {:response-schemas [{:status (s/eq 200), :body {(s/optional-key :name) (s/maybe s/Str), (s/optional-key :age) (s/maybe s/Int), (s/optional-key :type) (s/maybe s/Str)}} {:status (s/eq 400) :body s/Str} {:status (s/eq 404) :body s/Str}]} happy? (fn [response & [strict?]] (let [ctx {:response response :handler handler}] (= ctx ((:leave (i/validate-response-body {:strict? strict?})) ctx))))] (is (happy? {:status 200 :body {:name "Dupont" :age 4 :type "Goldfish"}})) (is (happy? {:status 400 :body "You must supply a pet id"})) (is (happy? {:status 404 :body "No pet with that id"})) (is (thrown-with-msg? Throwable #"Value does not match schema" (happy? {:status 200 :body "Here is you pet :)"}))) (is (thrown-with-msg? Throwable #"Value does not match schema" (happy? {:status 400 :body {:message "Bad times"}}))) (testing "does not allow responses that aren't defined in strict mode" (is (thrown-with-msg? Throwable #"No response body schema found for status 500" (happy? {:status 500 :body {:message "That did not go well"}} true)))) (testing "allows responses that aren't defined in non-strict mode" (is (happy? {:status 500 :body {:message "That did not go well"}} false)))))
null
https://raw.githubusercontent.com/oliyh/martian/c20d3fad47709ecfc0493e2fb607d5b56ea3193d/core/test/martian/interceptors_test.cljc
clojure
(ns martian.interceptors-test (:require [martian.interceptors :as i] [martian.encoders :as encoders] [tripod.context :as tc] [schema.core :as s] [schema-tools.core :as st] #?(:clj [clojure.test :refer [deftest is testing]] :cljs [cljs.test :refer-macros [deftest testing is]]) #?(:clj [martian.test-utils :as tu]))) #?(:cljs (def Throwable js/Error)) (deftest encode-body-test (let [i i/default-encode-body body {:the {:wheels ["on" "the" "bus"]} :go {:round {:and "round"}}}] (testing "json" (is (= {:body (encoders/json-encode body) :headers {"Content-Type" "application/json"}} (:request ((:enter i) {:request {:body body} :handler {:consumes ["application/json"]}}))))) (testing "edn" (is (= {:body (pr-str body) :headers {"Content-Type" "application/edn"}} (:request ((:enter i) {:request {:body body} :handler {:consumes ["application/edn"]}}))))) (testing "transit" (testing "+json" (is (= {:body body :headers {"Content-Type" "application/transit+json"}} (-> ((:enter i) {:request {:body body} :handler {:consumes ["application/transit+json"]}}) :request (update :body #?(:clj (comp #(encoders/transit-decode % :json) tu/input-stream->byte-array) :cljs #(encoders/transit-decode % :json))))))) #?(:clj (testing "+msgpack" (is (= {:body body :headers {"Content-Type" "application/transit+msgpack"}} (-> ((:enter i) {:request {:body body} :handler {:consumes ["application/transit+msgpack"]}}) :request (update :body (comp #(encoders/transit-decode % :msgpack) tu/input-stream->byte-array)))))))))) (defn- stub-response [content-type body] {:name ::stub-response :enter (fn [ctx] (assoc ctx :response {:body body :headers {:content-type content-type}}))}) (deftest coerce-response-test (let [i i/default-coerce-response body {:the {:wheels ["on" "the" "bus"]} :go {:round {:and "round"}}}] (testing "json" (let [ctx (tc/enqueue* {} [i (stub-response "application/json" (encoders/json-encode body))])] (is (= body (-> (tc/execute ctx) :response :body))))) (testing "edn" (let [ctx (tc/enqueue* {} [i (stub-response "application/edn" (pr-str body))])] (is (= body (-> (tc/execute ctx) :response :body))))) (testing "transit" (testing "+json" (let [ctx (tc/enqueue* {} [i (stub-response "application/transit+json" #?(:clj (slurp (encoders/transit-encode body :json)) :cljs (encoders/transit-encode body :json)))])] (is (= body (-> (tc/execute ctx) :response :body))))) #?(:clj (testing "+msgpack" (let [ctx (tc/enqueue* {} [i (stub-response "application/transit+msgpack" (tu/input-stream->byte-array (encoders/transit-encode body :msgpack)))])] (is (= body (-> (tc/execute ctx) :response :body))))))))) (deftest custom-encoding-test (testing "a user can support an encoding that martian doesn't know about by default" (let [reverse-string #(apply str (reverse %)) encoders (assoc (encoders/default-encoders) "text/magical+json" {:encode (comp reverse-string encoders/json-encode) :decode (comp #(encoders/json-decode % keyword) reverse-string) :as :magic}) body {:the {:wheels ["on" "the" "bus"]} :go {:round {:and "round"}}} encoded-body (-> body encoders/json-encode reverse-string) ctx (tc/enqueue* {:request {:body body} :handler {:consumes ["text/magical+json"] :produces ["text/magical+json"]}} [(i/encode-body encoders) (i/coerce-response encoders) (stub-response "text/magical+json" encoded-body)]) result (tc/execute ctx)] (is (= {:body encoded-body :headers {"Content-Type" "text/magical+json" "Accept" "text/magical+json"} :as :magic} (:request result))) (is (= {:body body :headers {:content-type "text/magical+json"}} (:response result)))))) (deftest auto-encoder-test (testing "when the server speaks a language martian doesn't understand it leaves it alone" (let [reverse-string #(apply str (reverse %)) body {:the {:wheels ["on" "the" "bus"]} :go {:round {:and "round"}}} encoded-body (-> body encoders/json-encode reverse-string) ctx (tc/enqueue* {:request {:body encoded-body :headers {"Content-Type" "text/magical+json" "Accept" "text/magical+json"}} :handler {:consumes ["text/magical+json"] :produces ["text/magical+json"]}} [i/default-encode-body i/default-coerce-response (stub-response "text/magical+json" encoded-body)]) result (tc/execute ctx)] (is (= {:body encoded-body :headers {"Content-Type" "text/magical+json" "Accept" "text/magical+json"} :as :auto} (:request result))) (is (= {:body encoded-body :headers {:content-type "text/magical+json"}} (:response result)))))) (deftest supported-content-types-test (testing "picks up the supported content-types from the encoding/decoding interceptors" (let [encode-body i/default-encode-body coerce-response (i/coerce-response (assoc (encoders/default-encoders) "text/magical+json" {:encode encoders/json-encode :decode #(encoders/json-decode % keyword) :as :magic}))] (is (= {:encodes #?(:clj #{"application/json" "application/transit+msgpack" "application/transit+json" "application/edn"} :cljs #{"application/json" "application/transit+json" "application/edn"}) :decodes #?(:clj #{"application/json" "text/magical+json" "application/transit+msgpack" "application/transit+json" "application/edn"} :cljs #{"application/json" "text/magical+json" "application/transit+json" "application/edn"})} (i/supported-content-types [encode-body coerce-response])))))) (deftest validate-response-test (let [handler {:response-schemas [{:status (s/eq 200), :body {(s/optional-key :name) (s/maybe s/Str), (s/optional-key :age) (s/maybe s/Int), (s/optional-key :type) (s/maybe s/Str)}} {:status (s/eq 400) :body s/Str} {:status (s/eq 404) :body s/Str}]} happy? (fn [response & [strict?]] (let [ctx {:response response :handler handler}] (= ctx ((:leave (i/validate-response-body {:strict? strict?})) ctx))))] (is (happy? {:status 200 :body {:name "Dupont" :age 4 :type "Goldfish"}})) (is (happy? {:status 400 :body "You must supply a pet id"})) (is (happy? {:status 404 :body "No pet with that id"})) (is (thrown-with-msg? Throwable #"Value does not match schema" (happy? {:status 200 :body "Here is you pet :)"}))) (is (thrown-with-msg? Throwable #"Value does not match schema" (happy? {:status 400 :body {:message "Bad times"}}))) (testing "does not allow responses that aren't defined in strict mode" (is (thrown-with-msg? Throwable #"No response body schema found for status 500" (happy? {:status 500 :body {:message "That did not go well"}} true)))) (testing "allows responses that aren't defined in non-strict mode" (is (happy? {:status 500 :body {:message "That did not go well"}} false)))))
11c7c61f8726d07353116ba2224c43646359fba9ef09ddc8cb829c2f41070124
tanders/cluster-engine
8b.lisp
(in-package cluster-engine) (setf *random-state* (make-random-state t)) (print (cluster-engine::ClusterEngine 35 t nil (append (cluster-engine::R-mel-interval-one-voice '(0 1) :normal :normal := 1/16 :member '(1 2)) (cluster-engine::R-mel-interval-one-voice '(0 1) :normal :normal := 1/4 :member '(1 2 3 4 5 12)) (cluster-engine::R-pitch-pitch #'(lambda (x) (member (mod (apply-minus x) 12) '(3 4 7 8 9))) '(0 1) '(0) :beat :no_grace :pitch) (cluster-engine::R-pitch-pitch #'(lambda (x) (>= (first x) (second x)) ) '(0 1) '(0) :beat :no_grace :pitch) ) '((4 4)) '(((1/16 1/16) (1/4)) ((55) (57) (59) (60) (62) (64) (66) (67) (69) (71) (72) (74) (76) (78) (79)) ((1/4)) ((55) (57) (59) (60) (62) (64) (66) (67) (69) (71) (72) (74) (76) (78) (79)) )) )
null
https://raw.githubusercontent.com/tanders/cluster-engine/064ad4fd107f8d9a3dfcaf260524c2ab034c6d3f/test_files/8b.lisp
lisp
(in-package cluster-engine) (setf *random-state* (make-random-state t)) (print (cluster-engine::ClusterEngine 35 t nil (append (cluster-engine::R-mel-interval-one-voice '(0 1) :normal :normal := 1/16 :member '(1 2)) (cluster-engine::R-mel-interval-one-voice '(0 1) :normal :normal := 1/4 :member '(1 2 3 4 5 12)) (cluster-engine::R-pitch-pitch #'(lambda (x) (member (mod (apply-minus x) 12) '(3 4 7 8 9))) '(0 1) '(0) :beat :no_grace :pitch) (cluster-engine::R-pitch-pitch #'(lambda (x) (>= (first x) (second x)) ) '(0 1) '(0) :beat :no_grace :pitch) ) '((4 4)) '(((1/16 1/16) (1/4)) ((55) (57) (59) (60) (62) (64) (66) (67) (69) (71) (72) (74) (76) (78) (79)) ((1/4)) ((55) (57) (59) (60) (62) (64) (66) (67) (69) (71) (72) (74) (76) (78) (79)) )) )
0c9b6cb81188b149dc49f2bf862742d4ce7da80250b424d4ca5c733d57d2d054
heraldry/heraldicon
news.cljs
(ns heraldicon.frontend.news (:require [heraldicon.frontend.title :as title] [heraldicon.static :as static] [re-frame.core :as rf])) (defn- release-image [img-src] (let [src (static/static-url img-src)] [:a {:href src :target "_blank"} [:img {:style {:width "100%"} :src src :alt "release update overview"}]])) (defn view [] (rf/dispatch [::title/set :string.text.title/home]) [:div {:style {:padding "10px" :text-align "justify" :min-width "30em" :max-width "60em" :margin "auto"}} [:div.release-row [:div.info [:h2 "News"] [:p "In many cases new features are rolled out incrementally, without big release. But now and then I'll group some features and new development and post an update here, so it is easy to stay informed."]]] [:h3 "2023-01-12 - Escutcheon adjustments"] [:div.release-row [:div.info [:p "I just went over all the existing escutcheons and improved their shapes and how they define the field and where the fess point is."] [:p "This changed some of the escutcheons quite a bit, and even tho the vast majority of existing coats of arms is not affected, " [:span {:style {:color "darkred"}} [:b "some of your coats of arms may look different now if they use these escutcheons"]] "."] [:p "Please have a look and maybe adjust ordinaries or charges if necessary, I apologize for the inconvenience. This kind of change should be a very rare event."]]] [:h3 "2023-01-05 - Happy new year!"] [:div.release-row [:div.info [:p "I hope everybody had a good start into the year."] [:p "Heraldicon recently reached a few milestones, there are now:"] [:ul [:li "over 1,200 users"] [:li "over 1,700 public arms, over 10,000 private arms"] [:li "over 1,000 public charges, over 3,200 private charges"] [:li "over 50 public collections, over 280 private collections"]] [:p "Thanks to everybody who helped with feedback, feature requests, charge creations, especially public ones, community themes, community escutcheons, and all the other ways many of you contributed!"]]] [:h3 "2022-09-01 - New rendering engine and various improvements"] [:div.release-row [:div.info [:p "There have been various new small features over the past few months and a large rewrite of the rendering system, which improves some existing conditions and will allow many planned features that weren't possible in the previous version."] [:p "New features and changes:"] [:ul [:li [:strong "new rendering engine"] " - this is the biggest change, albeit largely invisible, some immediate differences are:" [:ul [:li "components are much more aware of their surrounding field's environment and shape"] [:li "line styles now detect the exact intersection with the shape and by default use the line length as a base for their width option; a new 'Size reference' option for lines allows configuration of this"] [:li "exact bounding boxes for all components can now be calculated, which allows more precise resizing of the achievement, based on its helms, ornaments, etc."] [:li "cottises inherit the parent ordinary's properties, synching their line styles with the ordinary"] [:li "couped/voided ordinaries can now be fimbriated"] [:li [:strong "some of these changes are not fully backwards compatible"] ", so if you see changes in your arms, especially in partitions, ordinaries, cottises, line styles, or fimbriation, then that may be why; I try to migrate data, but sometimes that's not feasible... and hopefully these cases can be fixed easily"]]] [:li "a 'Gyronny N' field partition for an arbitrary number of subfields"] [:li "a mechanism to load arms into a field (in the top right of the field form), e.g. to use existing arms in subfields"] [:li "many new escutcheons and some new themes, mostly provided by the community on the Discord server, thanks!"] [:li "sort options for lists, as well as a counter of accessible and filtered items"] [:li "'Copy to new', exporting, and sharing are now grouped in a new action button"] [:li "'Copy to new' now also works with items of other users, automatically filling in the appropriate source attribution"] [:li "improved licensing and attribution, also fixed a bug where BY-NC-SA and BY-SA were compatible"] [:li "new anchor/orientation points:" [:ul [:li [:stron "center"] " - the exact middle of the field's bounding box, often coincides with 'fess' on subfields"] [:li [:stron "hoist"] " - a point left of the center for flags, similar to 'fess' in arms"] [:li [:stron "fly"] " - a point right of the center for flags, opposite 'hoist'"]]] [:li "allow fimbriation for cottises"] [:li "new charge detail view, separating the original SVG view from the preview"] [:li "improved blazonry editor, it understands more concepts now and there's a Discord bot that can use it"] [:li "a few new tincture modifiers: flagged, feathered"] [:li "a few more tooltips to help with the UI"] [:li "some modals for login/logout/confirmation were buggy, that has been fixed"] [:li "various bugfixes"]]]] [:h3 "2022-04-14 - Change of 'origin'/'anchor' naming"] [:div.release-row [:div.info [:p "The names for the two points used to position and orient partitions, ordinaries, and charges, have been renamed."] [:ul [:li [:strong "anchor"] " (previously " [:em "origin"] "): is the main point an element is positioned with."] [:li [:strong "orientation"] " (previously " [:em "anchor"] "): is the point an element orients itself towards, but it can also be a fixed angle."]] [:p "This might be confusing for a while for anyone already used to the old names, but I think it more accurately describes these concepts and simplifies using them. I hope it won't cause too much trouble."]]] [:h3 "2022-04-07 - Blazonry reader, translations, bordures with line styles, metadata"] [:div.release-row [:div.info [:p "The main new feature is a blazonry reader, you can click on the pen nib next to any field to invoke it or click the dedicated button to create new arms from a blazon. Features include:"] [:ul [:li "immediate rendering of the blazon, feedback if a word is not understood"] [:li "auto completion suggestions for any incomplete or malformed blazon"] [:li "support for all charges added by the community, your blazonry reader will understand all publically available charges and your private ones"]] [:p "supported concepts:"] [:ul [:li "partitions with sub fields and line styles, e.g. 'quartered i. and iv. azure, ii. and iii. or'"] [:li "ordinaries with line styles, fimbriation, and cottising, e.g. 'or, a fess wavy fimbriared gules argent'"] [:li "humetty/voided ordinaries, e.g. 'or, a pale humetty voided azure'"] [:li "ordinary groups, e.g. 'or, three barrulets gules'"] [:li "charges and charge groups with fimbriation, e.g. 'or, in chief three estoiles of 8 points sable', 'or, 12 roundels sable in orle' (or 'in annullo', 'palewise', etc.)"] [:li "semy, e.g. 'azure semy fleur-de-lis or'"] [:li "tincture/field referencing, e.g. 'per pale or and azure, a fess azure charged with a roundel of the field' (or 'of the first')"] [:li "various modifiers for ordinaries and charges that support it, e.g. 'reversed', 'mirrored', 'truncated', 'throughout', 'enhanced', etc."]] [:p "Additional changes and new features:"] [:ul [:li "the site now has a language selection, so far only English and German are really populated, but any help is welcome at " [:a {:href "" :target "_blank"} "Crowdin"]] [:li "pages and dialogs that list objects now have preview images and better filtering options"] [:li "bordures and orles can have line styles now"] [:li "furs now have an option to offset and scale them"] [:li "there's a dedicated star/mullet ordinary now, which allows an arbitrary number of points and wavy rays (to make an estoile)"] [:li "users can have an avatar now, for the moment it uses the Gravatar (" [:a {:href "" :target "_blank"} "Gravatar"] ") for the user's email address"] [:li "more escutcheon options, in particular the flag shape now can be used with all the usual and arbitrary aspect ratios, and it can have a configurable swallow tail"] [:li "allow arbitrary metadata for charges, arms, collections, which is considered for searching"] [:li "various element options allow a wider range of values and/or got better defaults"] [:li "performance improvements and bugfixes"]]] [:div (release-image "/img/2022-04-07-release-update.png")]] [:h3 "2022-01-09 - Happy new year!"] [:div.release-row [:div.info [:p "The site has a new name: " [:b "Heraldicon"]] [:p "Since there is at least one other group and a well-known heraldic artist who already use the name 'Digital Heraldry', the old name collided somewhat with them. " "'Heraldry' also is rather generic on its own, making it hard to look for it among many heraldry-related websites."] [:p "I hope the new name identifies the project more directly and is easier to find if anyone wants to refer to the website."] [:p "Note: all export links remain unchanged and all links to the old website should redirect to the new website. Let me know if you see any problems after the move. :)"]]] [:h3 "2021-11-25 - Bordure/orle, in orle charge groups, chevronny"] [:div.release-row [:div.info [:p "Changes and new features:"] [:ul [:li "Bordures and orles" [:ul [:li "there now are bordure and orle ordinaries with arbitrary thickness/distance to the edge"] [:li "so far they don't allow line styles other than straight, which follows the surrounding field edge"]]] [:li "Humetty/couped and voided ordinaries" [:ul [:li "ordinaries can now be made humetty/couped"] [:li "ordinaries can now be voided, this also honours the line style of the surrounding ordinary"] [:li "ordinaries also can be humetty/couped and voided"]]] [:li "Charge groups can be arranged in orle" [:ul [:li "this allows arranging N charges in orle, based on the surrounding field edge"] [:li "use the distance and offset arguments to adjust where exactly the charges end up"]]] [:li "Others" [:ul [:li "chevronny now is a field partition, configurable in most aspects, like other field partitions"] [:li "fur fields now have an additional 'pattern scaling' option to scale, you've guessed it, the pattern, " "which is useful for artistic preferences or in charges, where smaller ermine spots make more sense"] [:li "fields are clickable again in the rendering to select them more easily"] [:li "landscapes can now be added if raster graphics are embedded in an SVG and uploaded as charge, this also can be used for diapering"] [:li "a new community theme 'Content Cranium' and a silly theme that transitions through ALL themes"] [:li "there are a few more escutcheon choices for Norman shields and flag variants"] [:li "the interface should be MUCH faster now due to a rewrite of large parts of it"] [:li "there's a dedicated " [:a {:href "" :target "_blank"} "Discord"] " server now, where my username is " [:em "or#5915"]]]] [:li "Known issues" [:ul [:li "the path for the bordure/orle and charge group in orle positions sometimes can have unexpected glitches, if that happens try to resize it a little or change the distance to the field edge"] [:li "charges sometimes block underlying fields when trying to click them, that's a technical issue with the way the browser works, hopefully it can be addressed someday"]]]]] [:div (release-image "/img/2021-11-25-release-update.png")]] [:h3 "2021-10-25 - Supporters, compartments, mantling, charge library improvements"] [:div.release-row [:div.info [:p "Changes and new features:"] [:ul [:li "Supporters, compartments, mantling" [:ul [:li "ornaments around the shield can now be added"] [:li "there are some default charges for supporters, compartment, and mantling"] [:li "any other existing charge or new custom charges can be used for this"] [:li "a mechanism allows rendering these charges behind and in front of the shield (see next point)"]]] [:li "charge library interface improvements" [:ul [:li "charges intended as ornaments can contain colour(s) that designate areas that separate background and foreground of the charge, so the shield can be rendered between them"] [:li "the charge library interface now allows highlighting colours to easily see which area of the charge is affected by configuring it"] [:li "a new shading option is available now, which can qualify colours with the level of shading it represents, so no alpha-transparency shadow/highlight has to be added manually for many existing SVGs"] [:li "colours can also be sorted by colour, function, and shading modifier, making it easier to group them while editing"]]] [:li "Known issues" [:ul [:li "mottos/slogans were moved into 'ornaments', and the achievement positioning system has been rewritten, unfortunately a " "migration preserving their position wasn't feasible for all cases, this means that " [:b "your mottos/slogans might have moved"] " so best check them and fix it"]]]]] [:div (release-image "/img/2021-10-25-release-update.png")]] [:h3 "2021-09-26 - German translation, undo/redo, quarter/canton/point ordinaries, fretty"] [:div.release-row [:div.info [:p "Changes and new features:"] [:ul [:li "German translation" [:ul [:li "the entire interface is now available in German"] [:li "News and About section aren't translated for the time being, might do that at some point as well"] [:li "there might be some translations that are not ideal or awkward the way they are used, email me if you find such cases! :)"]]] [:li "all forms now support undo/redo"] [:li "added the quarter/canton ordinary"] [:li "added the point ordinary"] [:li "added fretty"] [:li "added more flag aspect ratios"] [:li "Bugfixes" [:ul [:li "the environments for many ordinaries and subfields were broken (they still need some work, but now most of them should be reasonable)"] [:li "a bunch of minor things in the UI and rendering"]]]]]] [:h3 "2021-08-20 - helms/crests, mottos/slogans, ribbon editor + library"] [:div.release-row [:div.info [:p "Changes and new features:"] [:ul [:li "Helms/crests" [:ul [:li "helmets, torses, crests or any combination of them can now be added"] [:li "multiple helms are supported next to each other, they auto resize"] [:li "for the helmets three new tinctures were introduced: light, medium, dark, but a helmet is just a charge, so it has a normal field that allows any other modifications of a field"]]] [:li "Ribbons and mottos/slogans" [:ul [:li "a ribbon library can now be used to (hopefully easily) create dynamic ribbons to be used with mottos and slogans"] [:li "ribbons try to be reusable for many cases, things like thickness, size, the split of the ribbon's ends, various text properties for its segments can be changed in the arms where they are used"] [:li "mottos/slogans can live below/above the escutcheon (or overlap it) and be tinctured (foreground, background, text)"]]] [:li "the escutcheon can now be rotated freely from -45° to 45°, helms will settle at the respective top corner"] [:li "the SVG/PNG export is improved, now using a headless Chromium in the backend to generate pretty much the same as the preview on the page"] [:li "the PNG export yields a higher resolution"] [:li "charges can be masked vertically (top or bottom) to be able to make demi-charges that are issuant from behind torses or ordinaries or other charges, as can be seen in the examples in the crest and the lion behind a thin fess"]] [:p "Known issues:"] [:ul [:li "helms and mottos are labeled 'alpha', because they are bound to change still, positioning might change in the future"] [:li "the ribbon editor definitely needs more work to be more user friendly or have better explanation"] [:li "the default position for helmet/torse/crest is somewhat sensible only for the default helmet and torse right now, for others it needs to be tweaked manually, this should improve in the future"] [:li "similarly slogans are positioned rather high above the escutcheon to make room for helm crests, even if there aren't any; again this should be smarter in the future"] [:li "fonts are embedded in exported SVGs, some editors/viewers won't display them correctly due to the different way some SVG markup is interpreted, Chrome should work"]]] [:div (release-image "/img/2021-08-20-release-update.png")]] [:h3 "2021-07-30 - UI rewrite, validation system, social media sharing"] [:div.release-row [:div.info [:p "Changes and new features:"] [:ul [:li "UI rewrite" [:ul [:li "the nested components are gone, as they were confusing, hard to navigate, and caused annoying scrolling issues"] [:li "separate navigation tree and form for selected components"] [:li "big speed improvements, a lot of the UI interactions now take 1-5ms, where previously 100-200ms were commonplace"] [:li "the layout works a bit better on mobile devices in landscape more, but the target environment still is Chrome on a desktop"] [:li "the cogs next to options allow an easy jump back to the default value or in some cases the value inherited from other components"] [:li "sliders now have a text field next to it to update values with specific values"]]] [:li "a validation system to warn about components that might break rule of tincture and potentially other issues"] [:li "improved blazonry, it now makes more of an attempt of reporting the used charges in charge groups, and it includes fimbriation"] [:li "SVG/PNG exports now contain a short URL to reference the arms on Heraldicon"] [:li "pall ordinaries now can be added, with different fimbriation for each line and arbitrary issuing from anywhere"]]] [:div (release-image "/img/2021-07-30-release-update.png")]] [:h3 "2021-06-12 - Charge groups, public arms, collections, users"] [:div.release-row [:div.info [:p "New features:"] [:ul [:li "support for charge groups, charges can be arranged in rows, columns, grids or arcs/circles"] [:li "various charge group presets for the most common arrangements"] [:li "users can now be browsed"] [:li "public arms and collections can now be browsed"] [:li "tincture modifiers 'orbed' and 'illuminated' added"]] [:p "Known issues:"] [:ul [:li "many charges render slowly"] [:li "charge groups should take the surrounding field better into account in some situations, more work needed"] [:li "charge group presets inspired by ordinaries use the grid and might not align perfectly with ordinaries, more work needed"]]] [:div (release-image "/img/2021-06-12-release-update.png")]] [:h3 "2021-06-06 - Collections, tags, filter"] [:div.release-row [:div.info [:p "New features:"] [:ul [:li "support for collections, which can be used to group existing arms, to create rolls of arms, group drafts, display arms for a specific topic, etc."] [:li "arms, charges, and collections now also can be tagged arbitrarily, and these tags can then be used to filter for them or annotate some notes"] [:li "there are now separate options for escutcheon shadow and outline"] [:li "text in collections can be rendered with various fonts"]] [:p "Known issues:"] [:ul [:li "large collections might render slowly, now that there are multiple arms being rendered on the fly, it shows that some parts of the rendering engines are not optimized yet"]]] [:div (release-image "/img/2021-06-06-release-update.png")]] [:h3 "2021-05-09 - Cottising, labels, semy"] [:div.release-row [:div.info [:p "New features:"] [:ul [:li "support for cottising, cottises can have their own line styles, fimbriation, and follow the parent ordinary's alignment"] [:li "labels ordinaries can now be added, they can be full length, truncated/couped, and support various emblazonment options"] [:li "the chevron interface has changed a bit again, now using the anchor system as well, so they can be issuant from anywhere"] [:li "semys with arbitrary charges are now possible, charges can be resized, rotated, the whole semy pattern layout also can be configured"] [:li "new line styles: rayonny (flaming), rayonny (spiked), wolf toothed"] [:li "lines can be aligned to their top, bottom, or middle"]]] [:div (release-image "/img/2021-05-09-release-update.png")]] [:h3 "2021-03-31 - Embowed/enarched, nonrepeating line styles"] [:div.release-row [:div.info [:p "A big refactoring line styles, allowing line styles that are not pattern-based but extend across the full length of the line."] [:ul [:li "support of full-length line styles, such as bevilled, angled, and enarched"] [:li "new pattern-based line styles, such as potenty, embattled-grady, embattled-in-crosses, nebuly, fir-twigged, fir-tree-topped, thorny"] [:li "gore ordinaries, which also uses the enarched line style, but can use all other line styles as well"] [:li "bug fixes"]]] [:div (release-image "/img/2021-03-31-release-update.png")]] [:h3 "2021-03-16 - Chevron and pile"] [:div.release-row [:div.info [:p "A total refactoring of angular alignment necessary for chevron and pile variants."] [:ul [:li "chevron ordinary and division variants issuant from chief, dexter, and sinister"] [:li "pile ordinary and division variants issuant from anywhere, pointing at specific points or the opposite edge"] [:li "edge detection of the surrounding field for piles is dynamic and works for any shape and orientation"] [:li "orientation based on an " [:b "origin"] " and an " [:b "anchor"] ", which allows precise construction of bends, chevrons, saltires, piles, etc."] [:li "new concept of " [:b "alignment"] " allows aligning ordinary edges with the chosen origin/anchor, " "not just the middle axis"] [:li "more support of arbitrary SVGs for the charge library"] [:li "WappenWiki and Wikimedia licensing presets for charge attribution"] [:li "bug fixes"]]] [:div (release-image "/img/2021-03-16-release-update.png")]] [:h3 "2021-03-07 - Paly and fimbriation"] [:div.release-row [:div.info [:p "The main new features are:"] [:ul [:li "paly/barry/bendy/chequy/lozengy field divisions with configurable layout"] [:li "quarterly division of MxN fields"] [:li "vairy treatment and its variations"] [:li "potenty treatment and its variations"] [:li "papellony and masoned treatment"] [:li "line fimbriation (single and double) with configurable thickness, which can handle intersecting with itself and optional outlines"] [:li "charge fimbriation with configurable thickness"] [:li "shininess and shield textures, which also can be used as displacement maps for various effects"] [:li "optional alpha transparency shadow/highlight in charges, which is applied dynamically after rendering " "the charge field, i.e. it works with any tincture or treatment or division of the charge's field"] [:li "bug fixes"]]] [:div (release-image "/img/2021-03-07-release-update.png")]] [:h3 "2021-02-08 - First release"] [:div.release-row [:div.info [:p "Following a browser-only prototype, this site now has a backend, where users can build a public " "and private library of charges and arms."] [:p "Features include:"] [:ul [:li "various escutcheons with their own relevant points, e.g. fess, honour, nombril, etc."] [:li "several divisions"] [:li "several ordinaries"] [:li "several line styles"] [:li "some common charge shapes"] [:li "lion and wolf charges in various attitudes"] [:li "counterchanged ordinaries and charges"] [:li "ermine-like furs"] [:li "dimidiation"] [:li "very basic blazoning of the constructed arms"] [:li "tincture themes, including hatching"] [:li "licensing information and attribution can be given for charges and arms, and indeed is required to make either public"] [:li "SVG/PNG export of saved arms; the saving is necessary for proper attribution"]]] [:div.info (release-image "/img/2021-02-08-release-update.png")]]])
null
https://raw.githubusercontent.com/heraldry/heraldicon/0e72e14efdc6dc7f1aa059c4b10e49962cdf293c/src/heraldicon/frontend/news.cljs
clojure
(ns heraldicon.frontend.news (:require [heraldicon.frontend.title :as title] [heraldicon.static :as static] [re-frame.core :as rf])) (defn- release-image [img-src] (let [src (static/static-url img-src)] [:a {:href src :target "_blank"} [:img {:style {:width "100%"} :src src :alt "release update overview"}]])) (defn view [] (rf/dispatch [::title/set :string.text.title/home]) [:div {:style {:padding "10px" :text-align "justify" :min-width "30em" :max-width "60em" :margin "auto"}} [:div.release-row [:div.info [:h2 "News"] [:p "In many cases new features are rolled out incrementally, without big release. But now and then I'll group some features and new development and post an update here, so it is easy to stay informed."]]] [:h3 "2023-01-12 - Escutcheon adjustments"] [:div.release-row [:div.info [:p "I just went over all the existing escutcheons and improved their shapes and how they define the field and where the fess point is."] [:p "This changed some of the escutcheons quite a bit, and even tho the vast majority of existing coats of arms is not affected, " [:span {:style {:color "darkred"}} [:b "some of your coats of arms may look different now if they use these escutcheons"]] "."] [:p "Please have a look and maybe adjust ordinaries or charges if necessary, I apologize for the inconvenience. This kind of change should be a very rare event."]]] [:h3 "2023-01-05 - Happy new year!"] [:div.release-row [:div.info [:p "I hope everybody had a good start into the year."] [:p "Heraldicon recently reached a few milestones, there are now:"] [:ul [:li "over 1,200 users"] [:li "over 1,700 public arms, over 10,000 private arms"] [:li "over 1,000 public charges, over 3,200 private charges"] [:li "over 50 public collections, over 280 private collections"]] [:p "Thanks to everybody who helped with feedback, feature requests, charge creations, especially public ones, community themes, community escutcheons, and all the other ways many of you contributed!"]]] [:h3 "2022-09-01 - New rendering engine and various improvements"] [:div.release-row [:div.info [:p "There have been various new small features over the past few months and a large rewrite of the rendering system, which improves some existing conditions and will allow many planned features that weren't possible in the previous version."] [:p "New features and changes:"] [:ul [:li [:strong "new rendering engine"] " - this is the biggest change, albeit largely invisible, some immediate differences are:" [:ul [:li "components are much more aware of their surrounding field's environment and shape"] [:li "line styles now detect the exact intersection with the shape and by default use the line length as a base for their width option; a new 'Size reference' option for lines allows configuration of this"] [:li "exact bounding boxes for all components can now be calculated, which allows more precise resizing of the achievement, based on its helms, ornaments, etc."] [:li "cottises inherit the parent ordinary's properties, synching their line styles with the ordinary"] [:li "couped/voided ordinaries can now be fimbriated"] [:li [:strong "some of these changes are not fully backwards compatible"] ", so if you see changes in your arms, especially in partitions, ordinaries, cottises, line styles, or fimbriation, then that may be why; I try to migrate data, but sometimes that's not feasible... and hopefully these cases can be fixed easily"]]] [:li "a 'Gyronny N' field partition for an arbitrary number of subfields"] [:li "a mechanism to load arms into a field (in the top right of the field form), e.g. to use existing arms in subfields"] [:li "many new escutcheons and some new themes, mostly provided by the community on the Discord server, thanks!"] [:li "sort options for lists, as well as a counter of accessible and filtered items"] [:li "'Copy to new', exporting, and sharing are now grouped in a new action button"] [:li "'Copy to new' now also works with items of other users, automatically filling in the appropriate source attribution"] [:li "improved licensing and attribution, also fixed a bug where BY-NC-SA and BY-SA were compatible"] [:li "new anchor/orientation points:" [:ul [:li [:stron "center"] " - the exact middle of the field's bounding box, often coincides with 'fess' on subfields"] [:li [:stron "hoist"] " - a point left of the center for flags, similar to 'fess' in arms"] [:li [:stron "fly"] " - a point right of the center for flags, opposite 'hoist'"]]] [:li "allow fimbriation for cottises"] [:li "new charge detail view, separating the original SVG view from the preview"] [:li "improved blazonry editor, it understands more concepts now and there's a Discord bot that can use it"] [:li "a few new tincture modifiers: flagged, feathered"] [:li "a few more tooltips to help with the UI"] [:li "some modals for login/logout/confirmation were buggy, that has been fixed"] [:li "various bugfixes"]]]] [:h3 "2022-04-14 - Change of 'origin'/'anchor' naming"] [:div.release-row [:div.info [:p "The names for the two points used to position and orient partitions, ordinaries, and charges, have been renamed."] [:ul [:li [:strong "anchor"] " (previously " [:em "origin"] "): is the main point an element is positioned with."] [:li [:strong "orientation"] " (previously " [:em "anchor"] "): is the point an element orients itself towards, but it can also be a fixed angle."]] [:p "This might be confusing for a while for anyone already used to the old names, but I think it more accurately describes these concepts and simplifies using them. I hope it won't cause too much trouble."]]] [:h3 "2022-04-07 - Blazonry reader, translations, bordures with line styles, metadata"] [:div.release-row [:div.info [:p "The main new feature is a blazonry reader, you can click on the pen nib next to any field to invoke it or click the dedicated button to create new arms from a blazon. Features include:"] [:ul [:li "immediate rendering of the blazon, feedback if a word is not understood"] [:li "auto completion suggestions for any incomplete or malformed blazon"] [:li "support for all charges added by the community, your blazonry reader will understand all publically available charges and your private ones"]] [:p "supported concepts:"] [:ul [:li "partitions with sub fields and line styles, e.g. 'quartered i. and iv. azure, ii. and iii. or'"] [:li "ordinaries with line styles, fimbriation, and cottising, e.g. 'or, a fess wavy fimbriared gules argent'"] [:li "humetty/voided ordinaries, e.g. 'or, a pale humetty voided azure'"] [:li "ordinary groups, e.g. 'or, three barrulets gules'"] [:li "charges and charge groups with fimbriation, e.g. 'or, in chief three estoiles of 8 points sable', 'or, 12 roundels sable in orle' (or 'in annullo', 'palewise', etc.)"] [:li "semy, e.g. 'azure semy fleur-de-lis or'"] [:li "tincture/field referencing, e.g. 'per pale or and azure, a fess azure charged with a roundel of the field' (or 'of the first')"] [:li "various modifiers for ordinaries and charges that support it, e.g. 'reversed', 'mirrored', 'truncated', 'throughout', 'enhanced', etc."]] [:p "Additional changes and new features:"] [:ul [:li "the site now has a language selection, so far only English and German are really populated, but any help is welcome at " [:a {:href "" :target "_blank"} "Crowdin"]] [:li "pages and dialogs that list objects now have preview images and better filtering options"] [:li "bordures and orles can have line styles now"] [:li "furs now have an option to offset and scale them"] [:li "there's a dedicated star/mullet ordinary now, which allows an arbitrary number of points and wavy rays (to make an estoile)"] [:li "users can have an avatar now, for the moment it uses the Gravatar (" [:a {:href "" :target "_blank"} "Gravatar"] ") for the user's email address"] [:li "more escutcheon options, in particular the flag shape now can be used with all the usual and arbitrary aspect ratios, and it can have a configurable swallow tail"] [:li "allow arbitrary metadata for charges, arms, collections, which is considered for searching"] [:li "various element options allow a wider range of values and/or got better defaults"] [:li "performance improvements and bugfixes"]]] [:div (release-image "/img/2022-04-07-release-update.png")]] [:h3 "2022-01-09 - Happy new year!"] [:div.release-row [:div.info [:p "The site has a new name: " [:b "Heraldicon"]] [:p "Since there is at least one other group and a well-known heraldic artist who already use the name 'Digital Heraldry', the old name collided somewhat with them. " "'Heraldry' also is rather generic on its own, making it hard to look for it among many heraldry-related websites."] [:p "I hope the new name identifies the project more directly and is easier to find if anyone wants to refer to the website."] [:p "Note: all export links remain unchanged and all links to the old website should redirect to the new website. Let me know if you see any problems after the move. :)"]]] [:h3 "2021-11-25 - Bordure/orle, in orle charge groups, chevronny"] [:div.release-row [:div.info [:p "Changes and new features:"] [:ul [:li "Bordures and orles" [:ul [:li "there now are bordure and orle ordinaries with arbitrary thickness/distance to the edge"] [:li "so far they don't allow line styles other than straight, which follows the surrounding field edge"]]] [:li "Humetty/couped and voided ordinaries" [:ul [:li "ordinaries can now be made humetty/couped"] [:li "ordinaries can now be voided, this also honours the line style of the surrounding ordinary"] [:li "ordinaries also can be humetty/couped and voided"]]] [:li "Charge groups can be arranged in orle" [:ul [:li "this allows arranging N charges in orle, based on the surrounding field edge"] [:li "use the distance and offset arguments to adjust where exactly the charges end up"]]] [:li "Others" [:ul [:li "chevronny now is a field partition, configurable in most aspects, like other field partitions"] [:li "fur fields now have an additional 'pattern scaling' option to scale, you've guessed it, the pattern, " "which is useful for artistic preferences or in charges, where smaller ermine spots make more sense"] [:li "fields are clickable again in the rendering to select them more easily"] [:li "landscapes can now be added if raster graphics are embedded in an SVG and uploaded as charge, this also can be used for diapering"] [:li "a new community theme 'Content Cranium' and a silly theme that transitions through ALL themes"] [:li "there are a few more escutcheon choices for Norman shields and flag variants"] [:li "the interface should be MUCH faster now due to a rewrite of large parts of it"] [:li "there's a dedicated " [:a {:href "" :target "_blank"} "Discord"] " server now, where my username is " [:em "or#5915"]]]] [:li "Known issues" [:ul [:li "the path for the bordure/orle and charge group in orle positions sometimes can have unexpected glitches, if that happens try to resize it a little or change the distance to the field edge"] [:li "charges sometimes block underlying fields when trying to click them, that's a technical issue with the way the browser works, hopefully it can be addressed someday"]]]]] [:div (release-image "/img/2021-11-25-release-update.png")]] [:h3 "2021-10-25 - Supporters, compartments, mantling, charge library improvements"] [:div.release-row [:div.info [:p "Changes and new features:"] [:ul [:li "Supporters, compartments, mantling" [:ul [:li "ornaments around the shield can now be added"] [:li "there are some default charges for supporters, compartment, and mantling"] [:li "any other existing charge or new custom charges can be used for this"] [:li "a mechanism allows rendering these charges behind and in front of the shield (see next point)"]]] [:li "charge library interface improvements" [:ul [:li "charges intended as ornaments can contain colour(s) that designate areas that separate background and foreground of the charge, so the shield can be rendered between them"] [:li "the charge library interface now allows highlighting colours to easily see which area of the charge is affected by configuring it"] [:li "a new shading option is available now, which can qualify colours with the level of shading it represents, so no alpha-transparency shadow/highlight has to be added manually for many existing SVGs"] [:li "colours can also be sorted by colour, function, and shading modifier, making it easier to group them while editing"]]] [:li "Known issues" [:ul [:li "mottos/slogans were moved into 'ornaments', and the achievement positioning system has been rewritten, unfortunately a " "migration preserving their position wasn't feasible for all cases, this means that " [:b "your mottos/slogans might have moved"] " so best check them and fix it"]]]]] [:div (release-image "/img/2021-10-25-release-update.png")]] [:h3 "2021-09-26 - German translation, undo/redo, quarter/canton/point ordinaries, fretty"] [:div.release-row [:div.info [:p "Changes and new features:"] [:ul [:li "German translation" [:ul [:li "the entire interface is now available in German"] [:li "News and About section aren't translated for the time being, might do that at some point as well"] [:li "there might be some translations that are not ideal or awkward the way they are used, email me if you find such cases! :)"]]] [:li "all forms now support undo/redo"] [:li "added the quarter/canton ordinary"] [:li "added the point ordinary"] [:li "added fretty"] [:li "added more flag aspect ratios"] [:li "Bugfixes" [:ul [:li "the environments for many ordinaries and subfields were broken (they still need some work, but now most of them should be reasonable)"] [:li "a bunch of minor things in the UI and rendering"]]]]]] [:h3 "2021-08-20 - helms/crests, mottos/slogans, ribbon editor + library"] [:div.release-row [:div.info [:p "Changes and new features:"] [:ul [:li "Helms/crests" [:ul [:li "helmets, torses, crests or any combination of them can now be added"] [:li "multiple helms are supported next to each other, they auto resize"] [:li "for the helmets three new tinctures were introduced: light, medium, dark, but a helmet is just a charge, so it has a normal field that allows any other modifications of a field"]]] [:li "Ribbons and mottos/slogans" [:ul [:li "a ribbon library can now be used to (hopefully easily) create dynamic ribbons to be used with mottos and slogans"] [:li "ribbons try to be reusable for many cases, things like thickness, size, the split of the ribbon's ends, various text properties for its segments can be changed in the arms where they are used"] [:li "mottos/slogans can live below/above the escutcheon (or overlap it) and be tinctured (foreground, background, text)"]]] [:li "the escutcheon can now be rotated freely from -45° to 45°, helms will settle at the respective top corner"] [:li "the SVG/PNG export is improved, now using a headless Chromium in the backend to generate pretty much the same as the preview on the page"] [:li "the PNG export yields a higher resolution"] [:li "charges can be masked vertically (top or bottom) to be able to make demi-charges that are issuant from behind torses or ordinaries or other charges, as can be seen in the examples in the crest and the lion behind a thin fess"]] [:p "Known issues:"] [:ul [:li "helms and mottos are labeled 'alpha', because they are bound to change still, positioning might change in the future"] [:li "the ribbon editor definitely needs more work to be more user friendly or have better explanation"] [:li "the default position for helmet/torse/crest is somewhat sensible only for the default helmet and torse right now, for others it needs to be tweaked manually, this should improve in the future"] [:li "similarly slogans are positioned rather high above the escutcheon to make room for helm crests, even if there aren't any; again this should be smarter in the future"] [:li "fonts are embedded in exported SVGs, some editors/viewers won't display them correctly due to the different way some SVG markup is interpreted, Chrome should work"]]] [:div (release-image "/img/2021-08-20-release-update.png")]] [:h3 "2021-07-30 - UI rewrite, validation system, social media sharing"] [:div.release-row [:div.info [:p "Changes and new features:"] [:ul [:li "UI rewrite" [:ul [:li "the nested components are gone, as they were confusing, hard to navigate, and caused annoying scrolling issues"] [:li "separate navigation tree and form for selected components"] [:li "big speed improvements, a lot of the UI interactions now take 1-5ms, where previously 100-200ms were commonplace"] [:li "the layout works a bit better on mobile devices in landscape more, but the target environment still is Chrome on a desktop"] [:li "the cogs next to options allow an easy jump back to the default value or in some cases the value inherited from other components"] [:li "sliders now have a text field next to it to update values with specific values"]]] [:li "a validation system to warn about components that might break rule of tincture and potentially other issues"] [:li "improved blazonry, it now makes more of an attempt of reporting the used charges in charge groups, and it includes fimbriation"] [:li "SVG/PNG exports now contain a short URL to reference the arms on Heraldicon"] [:li "pall ordinaries now can be added, with different fimbriation for each line and arbitrary issuing from anywhere"]]] [:div (release-image "/img/2021-07-30-release-update.png")]] [:h3 "2021-06-12 - Charge groups, public arms, collections, users"] [:div.release-row [:div.info [:p "New features:"] [:ul [:li "support for charge groups, charges can be arranged in rows, columns, grids or arcs/circles"] [:li "various charge group presets for the most common arrangements"] [:li "users can now be browsed"] [:li "public arms and collections can now be browsed"] [:li "tincture modifiers 'orbed' and 'illuminated' added"]] [:p "Known issues:"] [:ul [:li "many charges render slowly"] [:li "charge groups should take the surrounding field better into account in some situations, more work needed"] [:li "charge group presets inspired by ordinaries use the grid and might not align perfectly with ordinaries, more work needed"]]] [:div (release-image "/img/2021-06-12-release-update.png")]] [:h3 "2021-06-06 - Collections, tags, filter"] [:div.release-row [:div.info [:p "New features:"] [:ul [:li "support for collections, which can be used to group existing arms, to create rolls of arms, group drafts, display arms for a specific topic, etc."] [:li "arms, charges, and collections now also can be tagged arbitrarily, and these tags can then be used to filter for them or annotate some notes"] [:li "there are now separate options for escutcheon shadow and outline"] [:li "text in collections can be rendered with various fonts"]] [:p "Known issues:"] [:ul [:li "large collections might render slowly, now that there are multiple arms being rendered on the fly, it shows that some parts of the rendering engines are not optimized yet"]]] [:div (release-image "/img/2021-06-06-release-update.png")]] [:h3 "2021-05-09 - Cottising, labels, semy"] [:div.release-row [:div.info [:p "New features:"] [:ul [:li "support for cottising, cottises can have their own line styles, fimbriation, and follow the parent ordinary's alignment"] [:li "labels ordinaries can now be added, they can be full length, truncated/couped, and support various emblazonment options"] [:li "the chevron interface has changed a bit again, now using the anchor system as well, so they can be issuant from anywhere"] [:li "semys with arbitrary charges are now possible, charges can be resized, rotated, the whole semy pattern layout also can be configured"] [:li "new line styles: rayonny (flaming), rayonny (spiked), wolf toothed"] [:li "lines can be aligned to their top, bottom, or middle"]]] [:div (release-image "/img/2021-05-09-release-update.png")]] [:h3 "2021-03-31 - Embowed/enarched, nonrepeating line styles"] [:div.release-row [:div.info [:p "A big refactoring line styles, allowing line styles that are not pattern-based but extend across the full length of the line."] [:ul [:li "support of full-length line styles, such as bevilled, angled, and enarched"] [:li "new pattern-based line styles, such as potenty, embattled-grady, embattled-in-crosses, nebuly, fir-twigged, fir-tree-topped, thorny"] [:li "gore ordinaries, which also uses the enarched line style, but can use all other line styles as well"] [:li "bug fixes"]]] [:div (release-image "/img/2021-03-31-release-update.png")]] [:h3 "2021-03-16 - Chevron and pile"] [:div.release-row [:div.info [:p "A total refactoring of angular alignment necessary for chevron and pile variants."] [:ul [:li "chevron ordinary and division variants issuant from chief, dexter, and sinister"] [:li "pile ordinary and division variants issuant from anywhere, pointing at specific points or the opposite edge"] [:li "edge detection of the surrounding field for piles is dynamic and works for any shape and orientation"] [:li "orientation based on an " [:b "origin"] " and an " [:b "anchor"] ", which allows precise construction of bends, chevrons, saltires, piles, etc."] [:li "new concept of " [:b "alignment"] " allows aligning ordinary edges with the chosen origin/anchor, " "not just the middle axis"] [:li "more support of arbitrary SVGs for the charge library"] [:li "WappenWiki and Wikimedia licensing presets for charge attribution"] [:li "bug fixes"]]] [:div (release-image "/img/2021-03-16-release-update.png")]] [:h3 "2021-03-07 - Paly and fimbriation"] [:div.release-row [:div.info [:p "The main new features are:"] [:ul [:li "paly/barry/bendy/chequy/lozengy field divisions with configurable layout"] [:li "quarterly division of MxN fields"] [:li "vairy treatment and its variations"] [:li "potenty treatment and its variations"] [:li "papellony and masoned treatment"] [:li "line fimbriation (single and double) with configurable thickness, which can handle intersecting with itself and optional outlines"] [:li "charge fimbriation with configurable thickness"] [:li "shininess and shield textures, which also can be used as displacement maps for various effects"] [:li "optional alpha transparency shadow/highlight in charges, which is applied dynamically after rendering " "the charge field, i.e. it works with any tincture or treatment or division of the charge's field"] [:li "bug fixes"]]] [:div (release-image "/img/2021-03-07-release-update.png")]] [:h3 "2021-02-08 - First release"] [:div.release-row [:div.info [:p "Following a browser-only prototype, this site now has a backend, where users can build a public " "and private library of charges and arms."] [:p "Features include:"] [:ul [:li "various escutcheons with their own relevant points, e.g. fess, honour, nombril, etc."] [:li "several divisions"] [:li "several ordinaries"] [:li "several line styles"] [:li "some common charge shapes"] [:li "lion and wolf charges in various attitudes"] [:li "counterchanged ordinaries and charges"] [:li "ermine-like furs"] [:li "dimidiation"] [:li "very basic blazoning of the constructed arms"] [:li "tincture themes, including hatching"] [:li "licensing information and attribution can be given for charges and arms, and indeed is required to make either public"] [:li "SVG/PNG export of saved arms; the saving is necessary for proper attribution"]]] [:div.info (release-image "/img/2021-02-08-release-update.png")]]])
12a7fc4af5e480bde2e5f1da87a9dd5126722ea265ee25ac57f2abfb3ccdfd75
MyDataFlow/ttalk-server
ranch_conns_sup.erl
Copyright ( c ) 2011 - 2014 , < > %% %% Permission to use, copy, modify, and/or distribute this software for any %% purpose with or without fee is hereby granted, provided that the above %% copyright notice and this permission notice appear in all copies. %% THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES %% WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF %% MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL , DIRECT , 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. %% Make sure to never reload this module outside a release upgrade, %% as calling l(ranch_conns_sup) twice will kill the process and all %% the currently open connections. -module(ranch_conns_sup). %% API. -export([start_link/6]). -export([start_protocol/2]). -export([active_connections/1]). %% Supervisor internals. -export([init/7]). -export([system_continue/3]). -export([system_terminate/4]). -export([system_code_change/4]). -type conn_type() :: worker | supervisor. -type shutdown() :: brutal_kill | timeout(). -record(state, { parent = undefined :: pid(), ref :: ranch:ref(), conn_type :: conn_type(), shutdown :: shutdown(), transport = undefined :: module(), protocol = undefined :: module(), opts :: any(), ack_timeout :: timeout(), max_conns = undefined :: ranch:max_conns() }). %% API. -spec start_link(ranch:ref(), conn_type(), shutdown(), module(), timeout(), module()) -> {ok, pid()}. start_link(Ref, ConnType, Shutdown, Transport, AckTimeout, Protocol) -> proc_lib:start_link(?MODULE, init, [self(), Ref, ConnType, Shutdown, Transport, AckTimeout, Protocol]). %% We can safely assume we are on the same node as the supervisor. %% %% We can also safely avoid having a monitor and a timeout here because only three things can happen : %% * The supervisor died; rest_for_one strategy killed all acceptors %% so this very calling process is going to di-- %% * There's too many connections, the supervisor will resume the %% acceptor only when we get below the limit again. %% * The supervisor is overloaded, there's either too many acceptors %% or the max_connections limit is too large. It's better if we %% don't keep accepting connections because this leaves %% more room for the situation to be resolved. %% %% We do not need the reply, we only need the ok from the supervisor %% to continue. The supervisor sends its own pid when the acceptor can %% continue. -spec start_protocol(pid(), inet:socket()) -> ok. start_protocol(SupPid, Socket) -> SupPid ! {?MODULE, start_protocol, self(), Socket}, receive SupPid -> ok end. %% We can't make the above assumptions here. This function might be %% called from anywhere. -spec active_connections(pid()) -> non_neg_integer(). active_connections(SupPid) -> Tag = erlang:monitor(process, SupPid), catch erlang:send(SupPid, {?MODULE, active_connections, self(), Tag}, [noconnect]), receive {Tag, Ret} -> erlang:demonitor(Tag, [flush]), Ret; {'DOWN', Tag, _, _, noconnection} -> exit({nodedown, node(SupPid)}); {'DOWN', Tag, _, _, Reason} -> exit(Reason) after 5000 -> erlang:demonitor(Tag, [flush]), exit(timeout) end. %% Supervisor internals. -spec init(pid(), ranch:ref(), conn_type(), shutdown(), module(), timeout(), module()) -> no_return(). init(Parent, Ref, ConnType, Shutdown, Transport, AckTimeout, Protocol) -> process_flag(trap_exit, true), ok = ranch_server:set_connections_sup(Ref, self()), MaxConns = ranch_server:get_max_connections(Ref), Opts = ranch_server:get_protocol_options(Ref), ok = proc_lib:init_ack(Parent, {ok, self()}), loop(#state{parent=Parent, ref=Ref, conn_type=ConnType, shutdown=Shutdown, transport=Transport, protocol=Protocol, opts=Opts, ack_timeout=AckTimeout, max_conns=MaxConns}, 0, 0, []). loop(State=#state{parent=Parent, ref=Ref, conn_type=ConnType, transport=Transport, protocol=Protocol, opts=Opts, ack_timeout=AckTimeout, max_conns=MaxConns}, CurConns, NbChildren, Sleepers) -> receive {?MODULE, start_protocol, To, Socket} -> case Protocol:start_link(Ref, Socket, Transport, Opts) of {ok, Pid} -> Transport:controlling_process(Socket, Pid), Pid ! {shoot, Ref, Transport, Socket, AckTimeout}, put(Pid, true), CurConns2 = CurConns + 1, if CurConns2 < MaxConns -> To ! self(), loop(State, CurConns2, NbChildren + 1, Sleepers); true -> loop(State, CurConns2, NbChildren + 1, [To|Sleepers]) end; Ret -> To ! self(), error_logger:error_msg( "Ranch listener ~p connection process start failure; " "~p:start_link/4 returned: ~999999p~n", [Ref, Protocol, Ret]), Transport:close(Socket), loop(State, CurConns, NbChildren, Sleepers) end; {?MODULE, active_connections, To, Tag} -> To ! {Tag, CurConns}, loop(State, CurConns, NbChildren, Sleepers); %% Remove a connection from the count of connections. {remove_connection, Ref} -> loop(State, CurConns - 1, NbChildren, Sleepers); Upgrade the number of connections allowed concurrently . %% We resume all sleeping acceptors if this number increases. {set_max_conns, MaxConns2} when MaxConns2 > MaxConns -> _ = [To ! self() || To <- Sleepers], loop(State#state{max_conns=MaxConns2}, CurConns, NbChildren, []); {set_max_conns, MaxConns2} -> loop(State#state{max_conns=MaxConns2}, CurConns, NbChildren, Sleepers); %% Upgrade the protocol options. {set_opts, Opts2} -> loop(State#state{opts=Opts2}, CurConns, NbChildren, Sleepers); {'EXIT', Parent, Reason} -> terminate(State, Reason, NbChildren); {'EXIT', Pid, Reason} when Sleepers =:= [] -> report_error(Ref, Protocol, Pid, Reason), erase(Pid), loop(State, CurConns - 1, NbChildren - 1, Sleepers); %% Resume a sleeping acceptor if needed. {'EXIT', Pid, Reason} -> report_error(Ref, Protocol, Pid, Reason), erase(Pid), [To|Sleepers2] = Sleepers, To ! self(), loop(State, CurConns - 1, NbChildren - 1, Sleepers2); {system, From, Request} -> sys:handle_system_msg(Request, From, Parent, ?MODULE, [], {State, CurConns, NbChildren, Sleepers}); %% Calls from the supervisor module. {'$gen_call', {To, Tag}, which_children} -> Pids = get_keys(true), Children = [{Protocol, Pid, ConnType, [Protocol]} || Pid <- Pids, is_pid(Pid)], To ! {Tag, Children}, loop(State, CurConns, NbChildren, Sleepers); {'$gen_call', {To, Tag}, count_children} -> Counts = case ConnType of worker -> [{supervisors, 0}, {workers, NbChildren}]; supervisor -> [{supervisors, NbChildren}, {workers, 0}] end, Counts2 = [{specs, 1}, {active, NbChildren}|Counts], To ! {Tag, Counts2}, loop(State, CurConns, NbChildren, Sleepers); {'$gen_call', {To, Tag}, _} -> To ! {Tag, {error, ?MODULE}}, loop(State, CurConns, NbChildren, Sleepers); Msg -> error_logger:error_msg( "Ranch listener ~p received unexpected message ~p~n", [Ref, Msg]) end. -spec terminate(#state{}, any(), non_neg_integer()) -> no_return(). Kill all children and then exit . We unlink first to avoid %% getting a message for each child getting killed. terminate(#state{shutdown=brutal_kill}, Reason, _) -> Pids = get_keys(true), _ = [begin unlink(P), exit(P, kill) end || P <- Pids], exit(Reason); %% Attempt to gracefully shutdown all children. terminate(#state{shutdown=Shutdown}, Reason, NbChildren) -> shutdown_children(), _ = if Shutdown =:= infinity -> ok; true -> erlang:send_after(Shutdown, self(), kill) end, wait_children(NbChildren), exit(Reason). %% Monitor processes so we can know which ones have shutdown before the timeout . so we avoid receiving an extra %% message. Then send a shutdown exit signal. shutdown_children() -> Pids = get_keys(true), _ = [begin monitor(process, P), unlink(P), exit(P, shutdown) end || P <- Pids], ok. wait_children(0) -> ok; wait_children(NbChildren) -> receive {'DOWN', _, process, Pid, _} -> _ = erase(Pid), wait_children(NbChildren - 1); kill -> Pids = get_keys(true), _ = [exit(P, kill) || P <- Pids], ok end. system_continue(_, _, {State, CurConns, NbChildren, Sleepers}) -> loop(State, CurConns, NbChildren, Sleepers). -spec system_terminate(any(), _, _, _) -> no_return(). system_terminate(Reason, _, _, {State, _, NbChildren, _}) -> terminate(State, Reason, NbChildren). system_code_change(Misc, _, _, _) -> {ok, Misc}. We use ~999999p here instead of ~w because the latter does n't %% support printable strings. report_error(_, _, _, normal) -> ok; report_error(_, _, _, shutdown) -> ok; report_error(_, _, _, {shutdown, _}) -> ok; report_error(Ref, Protocol, Pid, Reason) -> error_logger:error_msg( "Ranch listener ~p had connection process started with " "~p:start_link/4 at ~p exit with reason: ~999999p~n", [Ref, Protocol, Pid, Reason]).
null
https://raw.githubusercontent.com/MyDataFlow/ttalk-server/07a60d5d74cd86aedd1f19c922d9d3abf2ebf28d/deps/ranch/src/ranch_conns_sup.erl
erlang
Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. Make sure to never reload this module outside a release upgrade, as calling l(ranch_conns_sup) twice will kill the process and all the currently open connections. API. Supervisor internals. API. We can safely assume we are on the same node as the supervisor. We can also safely avoid having a monitor and a timeout here * The supervisor died; rest_for_one strategy killed all acceptors so this very calling process is going to di-- * There's too many connections, the supervisor will resume the acceptor only when we get below the limit again. * The supervisor is overloaded, there's either too many acceptors or the max_connections limit is too large. It's better if we don't keep accepting connections because this leaves more room for the situation to be resolved. We do not need the reply, we only need the ok from the supervisor to continue. The supervisor sends its own pid when the acceptor can continue. We can't make the above assumptions here. This function might be called from anywhere. Supervisor internals. Remove a connection from the count of connections. We resume all sleeping acceptors if this number increases. Upgrade the protocol options. Resume a sleeping acceptor if needed. Calls from the supervisor module. getting a message for each child getting killed. Attempt to gracefully shutdown all children. Monitor processes so we can know which ones have shutdown message. Then send a shutdown exit signal. support printable strings.
Copyright ( c ) 2011 - 2014 , < > THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN -module(ranch_conns_sup). -export([start_link/6]). -export([start_protocol/2]). -export([active_connections/1]). -export([init/7]). -export([system_continue/3]). -export([system_terminate/4]). -export([system_code_change/4]). -type conn_type() :: worker | supervisor. -type shutdown() :: brutal_kill | timeout(). -record(state, { parent = undefined :: pid(), ref :: ranch:ref(), conn_type :: conn_type(), shutdown :: shutdown(), transport = undefined :: module(), protocol = undefined :: module(), opts :: any(), ack_timeout :: timeout(), max_conns = undefined :: ranch:max_conns() }). -spec start_link(ranch:ref(), conn_type(), shutdown(), module(), timeout(), module()) -> {ok, pid()}. start_link(Ref, ConnType, Shutdown, Transport, AckTimeout, Protocol) -> proc_lib:start_link(?MODULE, init, [self(), Ref, ConnType, Shutdown, Transport, AckTimeout, Protocol]). because only three things can happen : -spec start_protocol(pid(), inet:socket()) -> ok. start_protocol(SupPid, Socket) -> SupPid ! {?MODULE, start_protocol, self(), Socket}, receive SupPid -> ok end. -spec active_connections(pid()) -> non_neg_integer(). active_connections(SupPid) -> Tag = erlang:monitor(process, SupPid), catch erlang:send(SupPid, {?MODULE, active_connections, self(), Tag}, [noconnect]), receive {Tag, Ret} -> erlang:demonitor(Tag, [flush]), Ret; {'DOWN', Tag, _, _, noconnection} -> exit({nodedown, node(SupPid)}); {'DOWN', Tag, _, _, Reason} -> exit(Reason) after 5000 -> erlang:demonitor(Tag, [flush]), exit(timeout) end. -spec init(pid(), ranch:ref(), conn_type(), shutdown(), module(), timeout(), module()) -> no_return(). init(Parent, Ref, ConnType, Shutdown, Transport, AckTimeout, Protocol) -> process_flag(trap_exit, true), ok = ranch_server:set_connections_sup(Ref, self()), MaxConns = ranch_server:get_max_connections(Ref), Opts = ranch_server:get_protocol_options(Ref), ok = proc_lib:init_ack(Parent, {ok, self()}), loop(#state{parent=Parent, ref=Ref, conn_type=ConnType, shutdown=Shutdown, transport=Transport, protocol=Protocol, opts=Opts, ack_timeout=AckTimeout, max_conns=MaxConns}, 0, 0, []). loop(State=#state{parent=Parent, ref=Ref, conn_type=ConnType, transport=Transport, protocol=Protocol, opts=Opts, ack_timeout=AckTimeout, max_conns=MaxConns}, CurConns, NbChildren, Sleepers) -> receive {?MODULE, start_protocol, To, Socket} -> case Protocol:start_link(Ref, Socket, Transport, Opts) of {ok, Pid} -> Transport:controlling_process(Socket, Pid), Pid ! {shoot, Ref, Transport, Socket, AckTimeout}, put(Pid, true), CurConns2 = CurConns + 1, if CurConns2 < MaxConns -> To ! self(), loop(State, CurConns2, NbChildren + 1, Sleepers); true -> loop(State, CurConns2, NbChildren + 1, [To|Sleepers]) end; Ret -> To ! self(), error_logger:error_msg( "Ranch listener ~p connection process start failure; " "~p:start_link/4 returned: ~999999p~n", [Ref, Protocol, Ret]), Transport:close(Socket), loop(State, CurConns, NbChildren, Sleepers) end; {?MODULE, active_connections, To, Tag} -> To ! {Tag, CurConns}, loop(State, CurConns, NbChildren, Sleepers); {remove_connection, Ref} -> loop(State, CurConns - 1, NbChildren, Sleepers); Upgrade the number of connections allowed concurrently . {set_max_conns, MaxConns2} when MaxConns2 > MaxConns -> _ = [To ! self() || To <- Sleepers], loop(State#state{max_conns=MaxConns2}, CurConns, NbChildren, []); {set_max_conns, MaxConns2} -> loop(State#state{max_conns=MaxConns2}, CurConns, NbChildren, Sleepers); {set_opts, Opts2} -> loop(State#state{opts=Opts2}, CurConns, NbChildren, Sleepers); {'EXIT', Parent, Reason} -> terminate(State, Reason, NbChildren); {'EXIT', Pid, Reason} when Sleepers =:= [] -> report_error(Ref, Protocol, Pid, Reason), erase(Pid), loop(State, CurConns - 1, NbChildren - 1, Sleepers); {'EXIT', Pid, Reason} -> report_error(Ref, Protocol, Pid, Reason), erase(Pid), [To|Sleepers2] = Sleepers, To ! self(), loop(State, CurConns - 1, NbChildren - 1, Sleepers2); {system, From, Request} -> sys:handle_system_msg(Request, From, Parent, ?MODULE, [], {State, CurConns, NbChildren, Sleepers}); {'$gen_call', {To, Tag}, which_children} -> Pids = get_keys(true), Children = [{Protocol, Pid, ConnType, [Protocol]} || Pid <- Pids, is_pid(Pid)], To ! {Tag, Children}, loop(State, CurConns, NbChildren, Sleepers); {'$gen_call', {To, Tag}, count_children} -> Counts = case ConnType of worker -> [{supervisors, 0}, {workers, NbChildren}]; supervisor -> [{supervisors, NbChildren}, {workers, 0}] end, Counts2 = [{specs, 1}, {active, NbChildren}|Counts], To ! {Tag, Counts2}, loop(State, CurConns, NbChildren, Sleepers); {'$gen_call', {To, Tag}, _} -> To ! {Tag, {error, ?MODULE}}, loop(State, CurConns, NbChildren, Sleepers); Msg -> error_logger:error_msg( "Ranch listener ~p received unexpected message ~p~n", [Ref, Msg]) end. -spec terminate(#state{}, any(), non_neg_integer()) -> no_return(). Kill all children and then exit . We unlink first to avoid terminate(#state{shutdown=brutal_kill}, Reason, _) -> Pids = get_keys(true), _ = [begin unlink(P), exit(P, kill) end || P <- Pids], exit(Reason); terminate(#state{shutdown=Shutdown}, Reason, NbChildren) -> shutdown_children(), _ = if Shutdown =:= infinity -> ok; true -> erlang:send_after(Shutdown, self(), kill) end, wait_children(NbChildren), exit(Reason). before the timeout . so we avoid receiving an extra shutdown_children() -> Pids = get_keys(true), _ = [begin monitor(process, P), unlink(P), exit(P, shutdown) end || P <- Pids], ok. wait_children(0) -> ok; wait_children(NbChildren) -> receive {'DOWN', _, process, Pid, _} -> _ = erase(Pid), wait_children(NbChildren - 1); kill -> Pids = get_keys(true), _ = [exit(P, kill) || P <- Pids], ok end. system_continue(_, _, {State, CurConns, NbChildren, Sleepers}) -> loop(State, CurConns, NbChildren, Sleepers). -spec system_terminate(any(), _, _, _) -> no_return(). system_terminate(Reason, _, _, {State, _, NbChildren, _}) -> terminate(State, Reason, NbChildren). system_code_change(Misc, _, _, _) -> {ok, Misc}. We use ~999999p here instead of ~w because the latter does n't report_error(_, _, _, normal) -> ok; report_error(_, _, _, shutdown) -> ok; report_error(_, _, _, {shutdown, _}) -> ok; report_error(Ref, Protocol, Pid, Reason) -> error_logger:error_msg( "Ranch listener ~p had connection process started with " "~p:start_link/4 at ~p exit with reason: ~999999p~n", [Ref, Protocol, Pid, Reason]).
330d846e4cc6ed52f305409841c17b6e9c492ad0e2d09b5f8c1d58534908b84c
yakaz/yamerl
dos_newlines.erl
-module('dos_newlines'). -include_lib("eunit/include/eunit.hrl"). -define(FILENAME, "test/parsing/" ?MODULE_STRING ".yaml"). single_test_() -> ?_assertMatch( {yamerl_parser, {file,?FILENAME}, [{io_blocksize, 1}], <<>>, 70, true, [], 0, 71, 7, 1, false, 6, 10, utf8, false, undefined, _, _, [], {bcoll,root,0,-1,1,1,-1,1,1}, false, false, false, [{impl_key,false,false,undefined,undefined,1,1}], false, false, _, [], 0, 11, 10, undefined, undefined, _, false, [], [ {yamerl_stream_end,6,10}, {yamerl_doc_end,6,10}, {yamerl_collection_end,6,10,block,sequence}, {yamerl_scalar,5,3, {yamerl_tag,5,3,{non_specific,"!"}}, flow,double_quoted,"Hello World"}, {yamerl_sequence_entry,5,1}, {yamerl_scalar,2,3, {yamerl_tag,2,3,{non_specific,"!"}}, block,folded,"Hello World\n"}, {yamerl_sequence_entry,2,1}, {yamerl_collection_start,2,1, {yamerl_tag,2,1,{non_specific,"?"}}, block,sequence}, {yamerl_doc_start,2,1,{1,2},_}, {yamerl_stream_start,1,1,utf8} ] }, yamerl_parser:file(?FILENAME, [{io_blocksize, 1}]) ).
null
https://raw.githubusercontent.com/yakaz/yamerl/0032607a7b27fa2b548fc9a02d7ae6b53469c0c5/test/parsing/dos_newlines.erl
erlang
-module('dos_newlines'). -include_lib("eunit/include/eunit.hrl"). -define(FILENAME, "test/parsing/" ?MODULE_STRING ".yaml"). single_test_() -> ?_assertMatch( {yamerl_parser, {file,?FILENAME}, [{io_blocksize, 1}], <<>>, 70, true, [], 0, 71, 7, 1, false, 6, 10, utf8, false, undefined, _, _, [], {bcoll,root,0,-1,1,1,-1,1,1}, false, false, false, [{impl_key,false,false,undefined,undefined,1,1}], false, false, _, [], 0, 11, 10, undefined, undefined, _, false, [], [ {yamerl_stream_end,6,10}, {yamerl_doc_end,6,10}, {yamerl_collection_end,6,10,block,sequence}, {yamerl_scalar,5,3, {yamerl_tag,5,3,{non_specific,"!"}}, flow,double_quoted,"Hello World"}, {yamerl_sequence_entry,5,1}, {yamerl_scalar,2,3, {yamerl_tag,2,3,{non_specific,"!"}}, block,folded,"Hello World\n"}, {yamerl_sequence_entry,2,1}, {yamerl_collection_start,2,1, {yamerl_tag,2,1,{non_specific,"?"}}, block,sequence}, {yamerl_doc_start,2,1,{1,2},_}, {yamerl_stream_start,1,1,utf8} ] }, yamerl_parser:file(?FILENAME, [{io_blocksize, 1}]) ).
b6bdad584985bb735d32b2578b416d1e262e8ea78c88fa3d4f16a84dd31e3a08
mhkoji/Senn
ex-dict.lisp
(defpackage :hachee.kkc.impl.mirror.ex-dict (:use :cl) (:export :entry-form :entry-cost :make-entry :list-entries :make-ex-dict)) (in-package :hachee.kkc.impl.mirror.ex-dict) (defstruct ex-dict hash) (defstruct entry form cost) (defun list-entries (dict pron) (gethash pron (ex-dict-hash dict)))
null
https://raw.githubusercontent.com/mhkoji/Senn/0701d380f437aa4b48e2fba89bcd3d25587e4d0b/hachee/src/kkc/impl/mirror/ex-dict.lisp
lisp
(defpackage :hachee.kkc.impl.mirror.ex-dict (:use :cl) (:export :entry-form :entry-cost :make-entry :list-entries :make-ex-dict)) (in-package :hachee.kkc.impl.mirror.ex-dict) (defstruct ex-dict hash) (defstruct entry form cost) (defun list-entries (dict pron) (gethash pron (ex-dict-hash dict)))
623defc9015918bb6c8d6f660944166de9f8d510e0b3375e35a51604193966c3
UBTECH-Walker/WalkerSimulationFor2020WAIC
msg_controler_joint.lisp
; Auto-generated. Do not edit! (cl:in-package cruiser_msgs-msg) ;//! \htmlinclude msg_controler_joint.msg.html (cl:defclass <msg_controler_joint> (roslisp-msg-protocol:ros-message) ((header :reader header :initarg :header :type std_msgs-msg:Header :initform (cl:make-instance 'std_msgs-msg:Header)) (datapacket :reader datapacket :initarg :datapacket :type cl:string :initform "")) ) (cl:defclass msg_controler_joint (<msg_controler_joint>) ()) (cl:defmethod cl:initialize-instance :after ((m <msg_controler_joint>) cl:&rest args) (cl:declare (cl:ignorable args)) (cl:unless (cl:typep m 'msg_controler_joint) (roslisp-msg-protocol:msg-deprecation-warning "using old message class name cruiser_msgs-msg:<msg_controler_joint> is deprecated: use cruiser_msgs-msg:msg_controler_joint instead."))) (cl:ensure-generic-function 'header-val :lambda-list '(m)) (cl:defmethod header-val ((m <msg_controler_joint>)) (roslisp-msg-protocol:msg-deprecation-warning "Using old-style slot reader cruiser_msgs-msg:header-val is deprecated. Use cruiser_msgs-msg:header instead.") (header m)) (cl:ensure-generic-function 'datapacket-val :lambda-list '(m)) (cl:defmethod datapacket-val ((m <msg_controler_joint>)) (roslisp-msg-protocol:msg-deprecation-warning "Using old-style slot reader cruiser_msgs-msg:datapacket-val is deprecated. Use cruiser_msgs-msg:datapacket instead.") (datapacket m)) (cl:defmethod roslisp-msg-protocol:serialize ((msg <msg_controler_joint>) ostream) "Serializes a message object of type '<msg_controler_joint>" (roslisp-msg-protocol:serialize (cl:slot-value msg 'header) ostream) (cl:let ((__ros_str_len (cl:length (cl:slot-value msg 'datapacket)))) (cl:write-byte (cl:ldb (cl:byte 8 0) __ros_str_len) ostream) (cl:write-byte (cl:ldb (cl:byte 8 8) __ros_str_len) ostream) (cl:write-byte (cl:ldb (cl:byte 8 16) __ros_str_len) ostream) (cl:write-byte (cl:ldb (cl:byte 8 24) __ros_str_len) ostream)) (cl:map cl:nil #'(cl:lambda (c) (cl:write-byte (cl:char-code c) ostream)) (cl:slot-value msg 'datapacket)) ) (cl:defmethod roslisp-msg-protocol:deserialize ((msg <msg_controler_joint>) istream) "Deserializes a message object of type '<msg_controler_joint>" (roslisp-msg-protocol:deserialize (cl:slot-value msg 'header) istream) (cl:let ((__ros_str_len 0)) (cl:setf (cl:ldb (cl:byte 8 0) __ros_str_len) (cl:read-byte istream)) (cl:setf (cl:ldb (cl:byte 8 8) __ros_str_len) (cl:read-byte istream)) (cl:setf (cl:ldb (cl:byte 8 16) __ros_str_len) (cl:read-byte istream)) (cl:setf (cl:ldb (cl:byte 8 24) __ros_str_len) (cl:read-byte istream)) (cl:setf (cl:slot-value msg 'datapacket) (cl:make-string __ros_str_len)) (cl:dotimes (__ros_str_idx __ros_str_len msg) (cl:setf (cl:char (cl:slot-value msg 'datapacket) __ros_str_idx) (cl:code-char (cl:read-byte istream))))) msg ) (cl:defmethod roslisp-msg-protocol:ros-datatype ((msg (cl:eql '<msg_controler_joint>))) "Returns string type for a message object of type '<msg_controler_joint>" "cruiser_msgs/msg_controler_joint") (cl:defmethod roslisp-msg-protocol:ros-datatype ((msg (cl:eql 'msg_controler_joint))) "Returns string type for a message object of type 'msg_controler_joint" "cruiser_msgs/msg_controler_joint") (cl:defmethod roslisp-msg-protocol:md5sum ((type (cl:eql '<msg_controler_joint>))) "Returns md5sum for a message object of type '<msg_controler_joint>" "550613a4ae39cd5ce70b393463b493f5") (cl:defmethod roslisp-msg-protocol:md5sum ((type (cl:eql 'msg_controler_joint))) "Returns md5sum for a message object of type 'msg_controler_joint" "550613a4ae39cd5ce70b393463b493f5") (cl:defmethod roslisp-msg-protocol:message-definition ((type (cl:eql '<msg_controler_joint>))) "Returns full string definition for message of type '<msg_controler_joint>" (cl:format cl:nil "Header header ~%string datapacket ~%~%================================================================================~%MSG: std_msgs/Header~%# Standard metadata for higher-level stamped data types.~%# This is generally used to communicate timestamped data ~%# in a particular coordinate frame.~%# ~%# sequence ID: consecutively increasing ID ~%uint32 seq~%#Two-integer timestamp that is expressed as:~%# * stamp.sec: seconds (stamp_secs) since epoch (in Python the variable is called 'secs')~%# * stamp.nsec: nanoseconds since stamp_secs (in Python the variable is called 'nsecs')~%# time-handling sugar is provided by the client library~%time stamp~%#Frame this data is associated with~%# 0: no frame~%# 1: global frame~%string frame_id~%~%~%")) (cl:defmethod roslisp-msg-protocol:message-definition ((type (cl:eql 'msg_controler_joint))) "Returns full string definition for message of type 'msg_controler_joint" (cl:format cl:nil "Header header ~%string datapacket ~%~%================================================================================~%MSG: std_msgs/Header~%# Standard metadata for higher-level stamped data types.~%# This is generally used to communicate timestamped data ~%# in a particular coordinate frame.~%# ~%# sequence ID: consecutively increasing ID ~%uint32 seq~%#Two-integer timestamp that is expressed as:~%# * stamp.sec: seconds (stamp_secs) since epoch (in Python the variable is called 'secs')~%# * stamp.nsec: nanoseconds since stamp_secs (in Python the variable is called 'nsecs')~%# time-handling sugar is provided by the client library~%time stamp~%#Frame this data is associated with~%# 0: no frame~%# 1: global frame~%string frame_id~%~%~%")) (cl:defmethod roslisp-msg-protocol:serialization-length ((msg <msg_controler_joint>)) (cl:+ 0 (roslisp-msg-protocol:serialization-length (cl:slot-value msg 'header)) 4 (cl:length (cl:slot-value msg 'datapacket)) )) (cl:defmethod roslisp-msg-protocol:ros-message-to-list ((msg <msg_controler_joint>)) "Converts a ROS message object to a list" (cl:list 'msg_controler_joint (cl:cons ':header (header msg)) (cl:cons ':datapacket (datapacket msg)) ))
null
https://raw.githubusercontent.com/UBTECH-Walker/WalkerSimulationFor2020WAIC/7cdb21dabb8423994ba3f6021bc7934290d5faa9/walker_WAIC_16.04_v1.2_20200616/walker_install/share/common-lisp/ros/cruiser_msgs/msg/msg_controler_joint.lisp
lisp
Auto-generated. Do not edit! //! \htmlinclude msg_controler_joint.msg.html
(cl:in-package cruiser_msgs-msg) (cl:defclass <msg_controler_joint> (roslisp-msg-protocol:ros-message) ((header :reader header :initarg :header :type std_msgs-msg:Header :initform (cl:make-instance 'std_msgs-msg:Header)) (datapacket :reader datapacket :initarg :datapacket :type cl:string :initform "")) ) (cl:defclass msg_controler_joint (<msg_controler_joint>) ()) (cl:defmethod cl:initialize-instance :after ((m <msg_controler_joint>) cl:&rest args) (cl:declare (cl:ignorable args)) (cl:unless (cl:typep m 'msg_controler_joint) (roslisp-msg-protocol:msg-deprecation-warning "using old message class name cruiser_msgs-msg:<msg_controler_joint> is deprecated: use cruiser_msgs-msg:msg_controler_joint instead."))) (cl:ensure-generic-function 'header-val :lambda-list '(m)) (cl:defmethod header-val ((m <msg_controler_joint>)) (roslisp-msg-protocol:msg-deprecation-warning "Using old-style slot reader cruiser_msgs-msg:header-val is deprecated. Use cruiser_msgs-msg:header instead.") (header m)) (cl:ensure-generic-function 'datapacket-val :lambda-list '(m)) (cl:defmethod datapacket-val ((m <msg_controler_joint>)) (roslisp-msg-protocol:msg-deprecation-warning "Using old-style slot reader cruiser_msgs-msg:datapacket-val is deprecated. Use cruiser_msgs-msg:datapacket instead.") (datapacket m)) (cl:defmethod roslisp-msg-protocol:serialize ((msg <msg_controler_joint>) ostream) "Serializes a message object of type '<msg_controler_joint>" (roslisp-msg-protocol:serialize (cl:slot-value msg 'header) ostream) (cl:let ((__ros_str_len (cl:length (cl:slot-value msg 'datapacket)))) (cl:write-byte (cl:ldb (cl:byte 8 0) __ros_str_len) ostream) (cl:write-byte (cl:ldb (cl:byte 8 8) __ros_str_len) ostream) (cl:write-byte (cl:ldb (cl:byte 8 16) __ros_str_len) ostream) (cl:write-byte (cl:ldb (cl:byte 8 24) __ros_str_len) ostream)) (cl:map cl:nil #'(cl:lambda (c) (cl:write-byte (cl:char-code c) ostream)) (cl:slot-value msg 'datapacket)) ) (cl:defmethod roslisp-msg-protocol:deserialize ((msg <msg_controler_joint>) istream) "Deserializes a message object of type '<msg_controler_joint>" (roslisp-msg-protocol:deserialize (cl:slot-value msg 'header) istream) (cl:let ((__ros_str_len 0)) (cl:setf (cl:ldb (cl:byte 8 0) __ros_str_len) (cl:read-byte istream)) (cl:setf (cl:ldb (cl:byte 8 8) __ros_str_len) (cl:read-byte istream)) (cl:setf (cl:ldb (cl:byte 8 16) __ros_str_len) (cl:read-byte istream)) (cl:setf (cl:ldb (cl:byte 8 24) __ros_str_len) (cl:read-byte istream)) (cl:setf (cl:slot-value msg 'datapacket) (cl:make-string __ros_str_len)) (cl:dotimes (__ros_str_idx __ros_str_len msg) (cl:setf (cl:char (cl:slot-value msg 'datapacket) __ros_str_idx) (cl:code-char (cl:read-byte istream))))) msg ) (cl:defmethod roslisp-msg-protocol:ros-datatype ((msg (cl:eql '<msg_controler_joint>))) "Returns string type for a message object of type '<msg_controler_joint>" "cruiser_msgs/msg_controler_joint") (cl:defmethod roslisp-msg-protocol:ros-datatype ((msg (cl:eql 'msg_controler_joint))) "Returns string type for a message object of type 'msg_controler_joint" "cruiser_msgs/msg_controler_joint") (cl:defmethod roslisp-msg-protocol:md5sum ((type (cl:eql '<msg_controler_joint>))) "Returns md5sum for a message object of type '<msg_controler_joint>" "550613a4ae39cd5ce70b393463b493f5") (cl:defmethod roslisp-msg-protocol:md5sum ((type (cl:eql 'msg_controler_joint))) "Returns md5sum for a message object of type 'msg_controler_joint" "550613a4ae39cd5ce70b393463b493f5") (cl:defmethod roslisp-msg-protocol:message-definition ((type (cl:eql '<msg_controler_joint>))) "Returns full string definition for message of type '<msg_controler_joint>" (cl:format cl:nil "Header header ~%string datapacket ~%~%================================================================================~%MSG: std_msgs/Header~%# Standard metadata for higher-level stamped data types.~%# This is generally used to communicate timestamped data ~%# in a particular coordinate frame.~%# ~%# sequence ID: consecutively increasing ID ~%uint32 seq~%#Two-integer timestamp that is expressed as:~%# * stamp.sec: seconds (stamp_secs) since epoch (in Python the variable is called 'secs')~%# * stamp.nsec: nanoseconds since stamp_secs (in Python the variable is called 'nsecs')~%# time-handling sugar is provided by the client library~%time stamp~%#Frame this data is associated with~%# 0: no frame~%# 1: global frame~%string frame_id~%~%~%")) (cl:defmethod roslisp-msg-protocol:message-definition ((type (cl:eql 'msg_controler_joint))) "Returns full string definition for message of type 'msg_controler_joint" (cl:format cl:nil "Header header ~%string datapacket ~%~%================================================================================~%MSG: std_msgs/Header~%# Standard metadata for higher-level stamped data types.~%# This is generally used to communicate timestamped data ~%# in a particular coordinate frame.~%# ~%# sequence ID: consecutively increasing ID ~%uint32 seq~%#Two-integer timestamp that is expressed as:~%# * stamp.sec: seconds (stamp_secs) since epoch (in Python the variable is called 'secs')~%# * stamp.nsec: nanoseconds since stamp_secs (in Python the variable is called 'nsecs')~%# time-handling sugar is provided by the client library~%time stamp~%#Frame this data is associated with~%# 0: no frame~%# 1: global frame~%string frame_id~%~%~%")) (cl:defmethod roslisp-msg-protocol:serialization-length ((msg <msg_controler_joint>)) (cl:+ 0 (roslisp-msg-protocol:serialization-length (cl:slot-value msg 'header)) 4 (cl:length (cl:slot-value msg 'datapacket)) )) (cl:defmethod roslisp-msg-protocol:ros-message-to-list ((msg <msg_controler_joint>)) "Converts a ROS message object to a list" (cl:list 'msg_controler_joint (cl:cons ':header (header msg)) (cl:cons ':datapacket (datapacket msg)) ))
81855ebe1c3f9582e220e1321fc42ae4f9855ab9cf72cb861080bb158e087cdf
old-reliable/steamroller
steamroller_formatter_test.erl
-module(steamroller_formatter_test). -include_lib("eunit/include/eunit.hrl"). -define(FILE_DIR, "./test/steamroller_formatter/"). basic_boilerplate_test_() -> Expect = {ok, <<"-module(test).\n\n-export([init/1]).\n">>}, [ ?_assertEqual( Expect, steamroller_formatter:test_format(<<"-module(test).\n\n-export([init/1]).\n">>) ), ?_assertEqual( Expect, steamroller_formatter:test_format(<<"-module(test).\n\n\n\n-export([init/1]).\n">>) ), ?_assertEqual( Expect, steamroller_formatter:test_format(<<"-module(test).\n\n-export([init/1]).">>) ) ]. function_test_() -> Expect = {ok, <<"-module(test).\n\n-export([run/1]).\n\nrun(foo) -> ok;\nrun(bar) -> error.\n">>}, [ ?_assertEqual( Expect, steamroller_formatter:test_format( <<"-module(test).\n\n-export([run/1]).\nrun(foo) -> ok;\nrun(bar) -> error.\n">> ) ) ]. define_test_() -> Expect = {ok, <<"-module(test).\n\n-define(SOMETHING, some_atom).\n">>}, [ ?_assertEqual( Expect, steamroller_formatter:test_format(<<"-module(test).\n\n-define(SOMETHING, some_atom).\n">>) ) ]. simple_module_test_() -> Expect = {ok, Correct} = file:read_file(?FILE_DIR ++ "simple_module/correct.sterl"), {ok, NotEnoughWhitespace} = file:read_file(?FILE_DIR ++ "simple_module/not_enough_whitespace.sterl"), {ok, TooMuchWhitespace} = file:read_file(?FILE_DIR ++ "simple_module/too_much_whitespace.sterl"), [ ?_assertEqual(Expect, steamroller_formatter:test_format(Correct)), ?_assertEqual(Expect, steamroller_formatter:test_format(NotEnoughWhitespace)), ?_assertEqual(Expect, steamroller_formatter:test_format(TooMuchWhitespace)) ]. specced_module_test_() -> Expect = {ok, Correct} = file:read_file(?FILE_DIR ++ "specced_module/correct.sterl"), {ok, Grim1} = file:read_file(?FILE_DIR ++ "specced_module/grim1.sterl"), {ok, Grim2} = file:read_file(?FILE_DIR ++ "specced_module/grim2.sterl"), [ ?_assertEqual(Expect, steamroller_formatter:test_format(Correct)), ?_assertEqual(Expect, steamroller_formatter:test_format(Grim1)), ?_assertEqual(Expect, steamroller_formatter:test_format(Grim2)) ]. commented_module_test_() -> Expect = {ok, Correct} = file:read_file(?FILE_DIR ++ "commented_module/correct.sterl"), {ok, Grim1} = file:read_file(?FILE_DIR ++ "commented_module/grim1.sterl"), [ ?_assertEqual(Expect, steamroller_formatter:test_format(Correct)), ?_assertEqual(Expect, steamroller_formatter:test_format(Grim1)) ]. unicode_test_() -> Expect = {ok, Correct} = file:read_file(?FILE_DIR ++ "unicode/correct.sterl"), [?_assertEqual(Expect, steamroller_formatter:test_format(Correct))].
null
https://raw.githubusercontent.com/old-reliable/steamroller/ebe4b5411a74dfda0a40304107464dba5ff109ae/test/steamroller_formatter_test.erl
erlang
-module(steamroller_formatter_test). -include_lib("eunit/include/eunit.hrl"). -define(FILE_DIR, "./test/steamroller_formatter/"). basic_boilerplate_test_() -> Expect = {ok, <<"-module(test).\n\n-export([init/1]).\n">>}, [ ?_assertEqual( Expect, steamroller_formatter:test_format(<<"-module(test).\n\n-export([init/1]).\n">>) ), ?_assertEqual( Expect, steamroller_formatter:test_format(<<"-module(test).\n\n\n\n-export([init/1]).\n">>) ), ?_assertEqual( Expect, steamroller_formatter:test_format(<<"-module(test).\n\n-export([init/1]).">>) ) ]. function_test_() -> Expect = {ok, <<"-module(test).\n\n-export([run/1]).\n\nrun(foo) -> ok;\nrun(bar) -> error.\n">>}, [ ?_assertEqual( Expect, steamroller_formatter:test_format( <<"-module(test).\n\n-export([run/1]).\nrun(foo) -> ok;\nrun(bar) -> error.\n">> ) ) ]. define_test_() -> Expect = {ok, <<"-module(test).\n\n-define(SOMETHING, some_atom).\n">>}, [ ?_assertEqual( Expect, steamroller_formatter:test_format(<<"-module(test).\n\n-define(SOMETHING, some_atom).\n">>) ) ]. simple_module_test_() -> Expect = {ok, Correct} = file:read_file(?FILE_DIR ++ "simple_module/correct.sterl"), {ok, NotEnoughWhitespace} = file:read_file(?FILE_DIR ++ "simple_module/not_enough_whitespace.sterl"), {ok, TooMuchWhitespace} = file:read_file(?FILE_DIR ++ "simple_module/too_much_whitespace.sterl"), [ ?_assertEqual(Expect, steamroller_formatter:test_format(Correct)), ?_assertEqual(Expect, steamroller_formatter:test_format(NotEnoughWhitespace)), ?_assertEqual(Expect, steamroller_formatter:test_format(TooMuchWhitespace)) ]. specced_module_test_() -> Expect = {ok, Correct} = file:read_file(?FILE_DIR ++ "specced_module/correct.sterl"), {ok, Grim1} = file:read_file(?FILE_DIR ++ "specced_module/grim1.sterl"), {ok, Grim2} = file:read_file(?FILE_DIR ++ "specced_module/grim2.sterl"), [ ?_assertEqual(Expect, steamroller_formatter:test_format(Correct)), ?_assertEqual(Expect, steamroller_formatter:test_format(Grim1)), ?_assertEqual(Expect, steamroller_formatter:test_format(Grim2)) ]. commented_module_test_() -> Expect = {ok, Correct} = file:read_file(?FILE_DIR ++ "commented_module/correct.sterl"), {ok, Grim1} = file:read_file(?FILE_DIR ++ "commented_module/grim1.sterl"), [ ?_assertEqual(Expect, steamroller_formatter:test_format(Correct)), ?_assertEqual(Expect, steamroller_formatter:test_format(Grim1)) ]. unicode_test_() -> Expect = {ok, Correct} = file:read_file(?FILE_DIR ++ "unicode/correct.sterl"), [?_assertEqual(Expect, steamroller_formatter:test_format(Correct))].
a1b44969b12396c93f09b284104ee64a34efa3182a5080e427592470975e1c37
armedbear/abcl
customizations-default.lisp
;;; Copy this file to "customizations.lisp" ;;; User customizations for the build. ;;; This file is LOADed by INITIALIZE-BUILD (in build-abcl.lisp). ;;; The variable *PLATFORM-IS-WINDOWS* should be true on Windows platforms. You ;;; can, of course, substitute your own test for this in the code below, or add a section for OS X , or Solaris , or whatever ... You MUST set * JDK * to the location of the you want to use . Remove or ;;; comment out settings that don't apply to your situation. You do n't really need to specify anything but * JDK * . * - COMPILER * and * JAR * default to javac and jar , respectively , from the configured . Directories should be specified with a trailing slash ( or , on Windows , a ;;; trailing backslash). (in-package :abcl/build) ;; Standard compiler options. (defparameter *javac-options* "-g") (defparameter *jikes-options* "+D -g") (defparameter *jdk* (cond ((uiop:os-macosx-p) "/usr/") (t (introspect-path-for "javac"))))
null
https://raw.githubusercontent.com/armedbear/abcl/36a4b5994227d768882ff6458b3df9f79caac664/contrib/abcl-build/build/customizations-default.lisp
lisp
Copy this file to "customizations.lisp" User customizations for the build. This file is LOADed by INITIALIZE-BUILD (in build-abcl.lisp). The variable *PLATFORM-IS-WINDOWS* should be true on Windows platforms. You can, of course, substitute your own test for this in the code below, or add comment out settings that don't apply to your situation. trailing backslash). Standard compiler options.
a section for OS X , or Solaris , or whatever ... You MUST set * JDK * to the location of the you want to use . Remove or You do n't really need to specify anything but * JDK * . * - COMPILER * and * JAR * default to javac and jar , respectively , from the configured . Directories should be specified with a trailing slash ( or , on Windows , a (in-package :abcl/build) (defparameter *javac-options* "-g") (defparameter *jikes-options* "+D -g") (defparameter *jdk* (cond ((uiop:os-macosx-p) "/usr/") (t (introspect-path-for "javac"))))
e6d16869e8cb680f27502138da3126f61b918f4f6694c72bbe446625a0e8ae90
b0-system/b0
b00_fexts.ml
--------------------------------------------------------------------------- Copyright ( c ) 2019 The b0 programmers . All rights reserved . Distributed under the ISC license , see terms at the end of the file . --------------------------------------------------------------------------- Copyright (c) 2019 The b0 programmers. All rights reserved. Distributed under the ISC license, see terms at the end of the file. ---------------------------------------------------------------------------*) open B0_std type t = String.Set.t type map = Fpath.t list String.Map.t let v = String.Set.of_list let ext = String.Set.singleton let find_files exts m = let add_ext ext acc = match String.Map.find ext m with | exception Not_found -> acc | fs -> List.rev_append fs acc in String.Set.fold add_ext exts [] let all_files m = let add _ files acc = List.rev_append files acc in String.Map.fold add m [] let exists_file exts fm = let check_ext ext = match String.Map.find ext fm with | exception Not_found -> () | [] -> () | _-> raise Exit in try String.Set.iter check_ext exts; false with Exit -> true let ( + ) = String.Set.union let ( - ) = String.Set.diff (* Constants *) let c_lang = v [".c"; ".h"] let cmark = v [".md"] let css = v [".css"] let data = v [".json"; ".xml"] let font = v [".otf"; ".ttf"; ".woff"; ".woff2" ] let html = v [".html"] let html_lang = v [".html"; ".css"; ".js"; ] let image = v [".eps"; ".gif"; ".ico"; ".jpeg"; ".jpg"; ".pdf"; ".png"; ".ps"; ".svg"; ".tiff"] let js = v [".js"] let latex_lang = v [".tex"; ".sty"; ".bib"; ".bibdoi"] let ocaml_lang = v [".ml"; ".mld"; ".mli"; ".mll"; ".mly"] let sound = v [".aiff"; ".flac"; ".mp3"; ".wav"] let tex = v [".tex"] let video = v [".flv"; ".mov"; ".mp4"] let www = data + font + html_lang + image + sound + video let all = c_lang + cmark + css + data + font + html_lang + image + js + latex_lang + video + ocaml_lang + sound --------------------------------------------------------------------------- Copyright ( c ) 2019 The b0 programmers Permission to use , copy , modify , and/or distribute this software for any purpose with or without fee is hereby granted , provided that the above copyright notice and this permission notice appear in all copies . THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS . IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES 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 . --------------------------------------------------------------------------- Copyright (c) 2019 The b0 programmers Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, 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. ---------------------------------------------------------------------------*)
null
https://raw.githubusercontent.com/b0-system/b0/cbe12b8a55da6b50ab01ed058b339dbed3cfe894/src/b00/kit/b00_fexts.ml
ocaml
Constants
--------------------------------------------------------------------------- Copyright ( c ) 2019 The b0 programmers . All rights reserved . Distributed under the ISC license , see terms at the end of the file . --------------------------------------------------------------------------- Copyright (c) 2019 The b0 programmers. All rights reserved. Distributed under the ISC license, see terms at the end of the file. ---------------------------------------------------------------------------*) open B0_std type t = String.Set.t type map = Fpath.t list String.Map.t let v = String.Set.of_list let ext = String.Set.singleton let find_files exts m = let add_ext ext acc = match String.Map.find ext m with | exception Not_found -> acc | fs -> List.rev_append fs acc in String.Set.fold add_ext exts [] let all_files m = let add _ files acc = List.rev_append files acc in String.Map.fold add m [] let exists_file exts fm = let check_ext ext = match String.Map.find ext fm with | exception Not_found -> () | [] -> () | _-> raise Exit in try String.Set.iter check_ext exts; false with Exit -> true let ( + ) = String.Set.union let ( - ) = String.Set.diff let c_lang = v [".c"; ".h"] let cmark = v [".md"] let css = v [".css"] let data = v [".json"; ".xml"] let font = v [".otf"; ".ttf"; ".woff"; ".woff2" ] let html = v [".html"] let html_lang = v [".html"; ".css"; ".js"; ] let image = v [".eps"; ".gif"; ".ico"; ".jpeg"; ".jpg"; ".pdf"; ".png"; ".ps"; ".svg"; ".tiff"] let js = v [".js"] let latex_lang = v [".tex"; ".sty"; ".bib"; ".bibdoi"] let ocaml_lang = v [".ml"; ".mld"; ".mli"; ".mll"; ".mly"] let sound = v [".aiff"; ".flac"; ".mp3"; ".wav"] let tex = v [".tex"] let video = v [".flv"; ".mov"; ".mp4"] let www = data + font + html_lang + image + sound + video let all = c_lang + cmark + css + data + font + html_lang + image + js + latex_lang + video + ocaml_lang + sound --------------------------------------------------------------------------- Copyright ( c ) 2019 The b0 programmers Permission to use , copy , modify , and/or distribute this software for any purpose with or without fee is hereby granted , provided that the above copyright notice and this permission notice appear in all copies . THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS . IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES 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 . --------------------------------------------------------------------------- Copyright (c) 2019 The b0 programmers Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, 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. ---------------------------------------------------------------------------*)
eec54763032b8ce46ae04f2ee321fe9e9342652310f5eaaadd8646731c3309b7
keera-studios/haskell-game-programming
Main.hs
{-# LANGUAGE Arrows #-} import Data.IORef import FRP.Yampa as Yampa import Graphics.UI.SDL as SDL import Graphics.UI.SDL.Primitives as SDL main = do Initialise SDL SDL.init [InitVideo] setVideoMode width height 32 [SWSurface] timeRef <- newIORef (0 :: Int) reactimate (return ()) (\_ -> do dtSecs <- yampaSDLTimeSense timeRef return (dtSecs, Nothing)) (\_ e -> display e >> return False) falling display :: (Double, Double) -> IO() display (x, y) = do -- Obtain surface screen <- getVideoSurface -- Paint screen green let format = surfaceGetPixelFormat screen green <- mapRGB format 0 0xFF 0 fillRect screen Nothing green let side = 10 -- Paint small red square, at an angle 'angle' with respect to the center x' = round x y' = round y filledCircle screen x' y' side (Pixel 0xFF0000FF) -- Double buffering SDL.flip screen falling = constant 50.8 > > > integral > > > integral > > > arr ( \y - > ( 320 , y ) ) falling :: SF () (Double, Double) falling = proc () -> do v <- integral -< 50.8 p <- integral -< v returnA -< (320, p) -- | Updates the time in an IO Ref and returns the time difference updateTime :: IORef Int -> Int -> IO Int updateTime timeRef newTime = do previousTime <- readIORef timeRef writeIORef timeRef newTime return (newTime - previousTime) yampaSDLTimeSense :: IORef Int -> IO Yampa.DTime yampaSDLTimeSense timeRef = do Get time passed since SDL init newTime <- fmap fromIntegral SDL.getTicks -- Obtain time difference dt <- updateTime timeRef newTime let dtSecs = fromIntegral dt / 1000 return dtSecs width :: Num a => a width = 640 height :: Num a => a height = 480
null
https://raw.githubusercontent.com/keera-studios/haskell-game-programming/d4998decb4664a978c87199347f53b420d763b1e/tutorials/frp/yampa/tutorial004-fallingball/Main.hs
haskell
# LANGUAGE Arrows # Obtain surface Paint screen green Paint small red square, at an angle 'angle' with respect to the center Double buffering | Updates the time in an IO Ref and returns the time difference Obtain time difference
import Data.IORef import FRP.Yampa as Yampa import Graphics.UI.SDL as SDL import Graphics.UI.SDL.Primitives as SDL main = do Initialise SDL SDL.init [InitVideo] setVideoMode width height 32 [SWSurface] timeRef <- newIORef (0 :: Int) reactimate (return ()) (\_ -> do dtSecs <- yampaSDLTimeSense timeRef return (dtSecs, Nothing)) (\_ e -> display e >> return False) falling display :: (Double, Double) -> IO() display (x, y) = do screen <- getVideoSurface let format = surfaceGetPixelFormat screen green <- mapRGB format 0 0xFF 0 fillRect screen Nothing green let side = 10 x' = round x y' = round y filledCircle screen x' y' side (Pixel 0xFF0000FF) SDL.flip screen falling = constant 50.8 > > > integral > > > integral > > > arr ( \y - > ( 320 , y ) ) falling :: SF () (Double, Double) falling = proc () -> do v <- integral -< 50.8 p <- integral -< v returnA -< (320, p) updateTime :: IORef Int -> Int -> IO Int updateTime timeRef newTime = do previousTime <- readIORef timeRef writeIORef timeRef newTime return (newTime - previousTime) yampaSDLTimeSense :: IORef Int -> IO Yampa.DTime yampaSDLTimeSense timeRef = do Get time passed since SDL init newTime <- fmap fromIntegral SDL.getTicks dt <- updateTime timeRef newTime let dtSecs = fromIntegral dt / 1000 return dtSecs width :: Num a => a width = 640 height :: Num a => a height = 480
ebe24410250116225f29193ab2b7043e9ec0b0bf6f3fe160908444acddc6617d
Eduap-com/WordMat
dlaev2.lisp
;;; Compiled by f2cl version: ( " f2cl1.l , v 95098eb54f13 2013/04/01 00:45:16 toy $ " " f2cl2.l , v 95098eb54f13 2013/04/01 00:45:16 toy $ " " f2cl3.l , v 96616d88fb7e 2008/02/22 22:19:34 rtoy $ " " f2cl4.l , v 96616d88fb7e 2008/02/22 22:19:34 rtoy $ " " f2cl5.l , v 95098eb54f13 2013/04/01 00:45:16 toy $ " " f2cl6.l , v 1d5cbacbb977 2008/08/24 00:56:27 rtoy $ " " macros.l , v 1409c1352feb 2013/03/24 20:44:50 toy $ " ) ;;; Using Lisp CMU Common Lisp snapshot-2013-11 (20E Unicode) ;;; ;;; Options: ((:prune-labels nil) (:auto-save t) (:relaxed-array-decls t) ;;; (:coerce-assigns :as-needed) (:array-type ':array) ;;; (:array-slicing t) (:declare-common nil) ;;; (:float-format single-float)) (in-package "LAPACK") (let* ((one 1.0d0) (two 2.0d0) (zero 0.0d0) (half 0.5d0)) (declare (type (double-float 1.0d0 1.0d0) one) (type (double-float 2.0d0 2.0d0) two) (type (double-float 0.0d0 0.0d0) zero) (type (double-float 0.5d0 0.5d0) half) (ignorable one two zero half)) (defun dlaev2 (a b c rt1 rt2 cs1 sn1) (declare (type (double-float) sn1 cs1 rt2 rt1 c b a)) (prog ((ab 0.0d0) (acmn 0.0d0) (acmx 0.0d0) (acs 0.0d0) (adf 0.0d0) (cs 0.0d0) (ct 0.0d0) (df 0.0d0) (rt 0.0d0) (sm 0.0d0) (tb 0.0d0) (tn 0.0d0) (sgn1 0) (sgn2 0)) (declare (type (double-float) ab acmn acmx acs adf cs ct df rt sm tb tn) (type (f2cl-lib:integer4) sgn1 sgn2)) (setf sm (+ a c)) (setf df (- a c)) (setf adf (abs df)) (setf tb (+ b b)) (setf ab (abs tb)) (cond ((> (abs a) (abs c)) (setf acmx a) (setf acmn c)) (t (setf acmx c) (setf acmn a))) (cond ((> adf ab) (setf rt (* adf (f2cl-lib:fsqrt (+ one (expt (/ ab adf) 2)))))) ((< adf ab) (setf rt (* ab (f2cl-lib:fsqrt (+ one (expt (/ adf ab) 2)))))) (t (setf rt (* ab (f2cl-lib:fsqrt two))))) (cond ((< sm zero) (setf rt1 (* half (- sm rt))) (setf sgn1 -1) (setf rt2 (- (* (/ acmx rt1) acmn) (* (/ b rt1) b)))) ((> sm zero) (setf rt1 (* half (+ sm rt))) (setf sgn1 1) (setf rt2 (- (* (/ acmx rt1) acmn) (* (/ b rt1) b)))) (t (setf rt1 (* half rt)) (setf rt2 (* (- half) rt)) (setf sgn1 1))) (cond ((>= df zero) (setf cs (+ df rt)) (setf sgn2 1)) (t (setf cs (- df rt)) (setf sgn2 -1))) (setf acs (abs cs)) (cond ((> acs ab) (setf ct (/ (- tb) cs)) (setf sn1 (/ one (f2cl-lib:fsqrt (+ one (* ct ct))))) (setf cs1 (* ct sn1))) (t (cond ((= ab zero) (setf cs1 one) (setf sn1 zero)) (t (setf tn (/ (- cs) tb)) (setf cs1 (/ one (f2cl-lib:fsqrt (+ one (* tn tn))))) (setf sn1 (* tn cs1)))))) (cond ((= sgn1 sgn2) (setf tn cs1) (setf cs1 (- sn1)) (setf sn1 tn))) (go end_label) end_label (return (values nil nil nil rt1 rt2 cs1 sn1))))) (in-package #-gcl #:cl-user #+gcl "CL-USER") #+#.(cl:if (cl:find-package '#:f2cl) '(and) '(or)) (eval-when (:load-toplevel :compile-toplevel :execute) (setf (gethash 'fortran-to-lisp::dlaev2 fortran-to-lisp::*f2cl-function-info*) (fortran-to-lisp::make-f2cl-finfo :arg-types '((double-float) (double-float) (double-float) (double-float) (double-float) (double-float) (double-float)) :return-values '(nil nil nil fortran-to-lisp::rt1 fortran-to-lisp::rt2 fortran-to-lisp::cs1 fortran-to-lisp::sn1) :calls 'nil)))
null
https://raw.githubusercontent.com/Eduap-com/WordMat/83c9336770067f54431cc42c7147dc6ed640a339/Windows/ExternalPrograms/maxima-5.45.1/share/maxima/5.45.1/share/lapack/lapack/dlaev2.lisp
lisp
Compiled by f2cl version: Using Lisp CMU Common Lisp snapshot-2013-11 (20E Unicode) Options: ((:prune-labels nil) (:auto-save t) (:relaxed-array-decls t) (:coerce-assigns :as-needed) (:array-type ':array) (:array-slicing t) (:declare-common nil) (:float-format single-float))
( " f2cl1.l , v 95098eb54f13 2013/04/01 00:45:16 toy $ " " f2cl2.l , v 95098eb54f13 2013/04/01 00:45:16 toy $ " " f2cl3.l , v 96616d88fb7e 2008/02/22 22:19:34 rtoy $ " " f2cl4.l , v 96616d88fb7e 2008/02/22 22:19:34 rtoy $ " " f2cl5.l , v 95098eb54f13 2013/04/01 00:45:16 toy $ " " f2cl6.l , v 1d5cbacbb977 2008/08/24 00:56:27 rtoy $ " " macros.l , v 1409c1352feb 2013/03/24 20:44:50 toy $ " ) (in-package "LAPACK") (let* ((one 1.0d0) (two 2.0d0) (zero 0.0d0) (half 0.5d0)) (declare (type (double-float 1.0d0 1.0d0) one) (type (double-float 2.0d0 2.0d0) two) (type (double-float 0.0d0 0.0d0) zero) (type (double-float 0.5d0 0.5d0) half) (ignorable one two zero half)) (defun dlaev2 (a b c rt1 rt2 cs1 sn1) (declare (type (double-float) sn1 cs1 rt2 rt1 c b a)) (prog ((ab 0.0d0) (acmn 0.0d0) (acmx 0.0d0) (acs 0.0d0) (adf 0.0d0) (cs 0.0d0) (ct 0.0d0) (df 0.0d0) (rt 0.0d0) (sm 0.0d0) (tb 0.0d0) (tn 0.0d0) (sgn1 0) (sgn2 0)) (declare (type (double-float) ab acmn acmx acs adf cs ct df rt sm tb tn) (type (f2cl-lib:integer4) sgn1 sgn2)) (setf sm (+ a c)) (setf df (- a c)) (setf adf (abs df)) (setf tb (+ b b)) (setf ab (abs tb)) (cond ((> (abs a) (abs c)) (setf acmx a) (setf acmn c)) (t (setf acmx c) (setf acmn a))) (cond ((> adf ab) (setf rt (* adf (f2cl-lib:fsqrt (+ one (expt (/ ab adf) 2)))))) ((< adf ab) (setf rt (* ab (f2cl-lib:fsqrt (+ one (expt (/ adf ab) 2)))))) (t (setf rt (* ab (f2cl-lib:fsqrt two))))) (cond ((< sm zero) (setf rt1 (* half (- sm rt))) (setf sgn1 -1) (setf rt2 (- (* (/ acmx rt1) acmn) (* (/ b rt1) b)))) ((> sm zero) (setf rt1 (* half (+ sm rt))) (setf sgn1 1) (setf rt2 (- (* (/ acmx rt1) acmn) (* (/ b rt1) b)))) (t (setf rt1 (* half rt)) (setf rt2 (* (- half) rt)) (setf sgn1 1))) (cond ((>= df zero) (setf cs (+ df rt)) (setf sgn2 1)) (t (setf cs (- df rt)) (setf sgn2 -1))) (setf acs (abs cs)) (cond ((> acs ab) (setf ct (/ (- tb) cs)) (setf sn1 (/ one (f2cl-lib:fsqrt (+ one (* ct ct))))) (setf cs1 (* ct sn1))) (t (cond ((= ab zero) (setf cs1 one) (setf sn1 zero)) (t (setf tn (/ (- cs) tb)) (setf cs1 (/ one (f2cl-lib:fsqrt (+ one (* tn tn))))) (setf sn1 (* tn cs1)))))) (cond ((= sgn1 sgn2) (setf tn cs1) (setf cs1 (- sn1)) (setf sn1 tn))) (go end_label) end_label (return (values nil nil nil rt1 rt2 cs1 sn1))))) (in-package #-gcl #:cl-user #+gcl "CL-USER") #+#.(cl:if (cl:find-package '#:f2cl) '(and) '(or)) (eval-when (:load-toplevel :compile-toplevel :execute) (setf (gethash 'fortran-to-lisp::dlaev2 fortran-to-lisp::*f2cl-function-info*) (fortran-to-lisp::make-f2cl-finfo :arg-types '((double-float) (double-float) (double-float) (double-float) (double-float) (double-float) (double-float)) :return-values '(nil nil nil fortran-to-lisp::rt1 fortran-to-lisp::rt2 fortran-to-lisp::cs1 fortran-to-lisp::sn1) :calls 'nil)))
e06fad9766338a85db3d51778d3bf5cd02824b567182afe6e4645a186c4e87fd
albertoruiz/easyVision
scatters.hs
import Classifier import Classifier.ToyProblems import Util.Stat import Classifier.Regression(msError) import Util.ICA import Util.Statistics(randomPermutation) import Util.Gaussian(mixturePDF,findMixture) import Numeric.LinearAlgebra import Vision.GUI.Simple import Data.Maybe(maybe) import System.Random(randomIO) import Text.Printf(printf) import Control.Monad((>=>)) import Image(Size(..),mat2img) --------------------------------------------------------------------------- rawmnist = loadExamples "../../data/ml/mnist.txt" main = do scatters (map return "0123") --------------------------------------------------------------------------- scw3 name ps = browser3D name xs (const id) where xs = map (\p-> scatter3D p (0,1,2) [] (Draw())) ps --------------------------------------------------------- scatters s = runIt $ do raw <- rawmnist let sel = filter ((`elem` s) . snd) raw scw3 "PCA All" [ (boxAttr `ofP` mef (NewDimension 3)) raw `preprocess` raw ] scw3 ("PCA " ++ concat s) [ (boxAttr `ofP` mef (NewDimension 3)) sel `preprocess` sel ] let redu = mef (NewDimension 40) raw `preprocess` raw sel = filter ((`elem` s) . snd) redu sep = (boxAttr `ofP` mdf) sel `preprocess` sel scw3 "MDF " [sep] let dig d = (boxAttr `ofP` mef (NewDimension 3)) they `preprocess` they where they = filter ((`elem` [d]) . snd) raw scw3 "PCA each" (map (dig.return) "0123456789")
null
https://raw.githubusercontent.com/albertoruiz/easyVision/26bb2efaa676c902cecb12047560a09377a969f2/projects/patrec/scatters.hs
haskell
------------------------------------------------------------------------- ------------------------------------------------------------------------- -------------------------------------------------------
import Classifier import Classifier.ToyProblems import Util.Stat import Classifier.Regression(msError) import Util.ICA import Util.Statistics(randomPermutation) import Util.Gaussian(mixturePDF,findMixture) import Numeric.LinearAlgebra import Vision.GUI.Simple import Data.Maybe(maybe) import System.Random(randomIO) import Text.Printf(printf) import Control.Monad((>=>)) import Image(Size(..),mat2img) rawmnist = loadExamples "../../data/ml/mnist.txt" main = do scatters (map return "0123") scw3 name ps = browser3D name xs (const id) where xs = map (\p-> scatter3D p (0,1,2) [] (Draw())) ps scatters s = runIt $ do raw <- rawmnist let sel = filter ((`elem` s) . snd) raw scw3 "PCA All" [ (boxAttr `ofP` mef (NewDimension 3)) raw `preprocess` raw ] scw3 ("PCA " ++ concat s) [ (boxAttr `ofP` mef (NewDimension 3)) sel `preprocess` sel ] let redu = mef (NewDimension 40) raw `preprocess` raw sel = filter ((`elem` s) . snd) redu sep = (boxAttr `ofP` mdf) sel `preprocess` sel scw3 "MDF " [sep] let dig d = (boxAttr `ofP` mef (NewDimension 3)) they `preprocess` they where they = filter ((`elem` [d]) . snd) raw scw3 "PCA each" (map (dig.return) "0123456789")
5134e99f9f2b2992e4e4db30501a10f0528ca8d98ee76f9d36c8777abb4f4079
janestreet/ecaml
browse_url.mli
* Pass a URL to a WWW browser . Ecaml bindings for [ browse-url.el ] open! Core open! Import module Url : sig type t = string val type_ : t Value.Type.t val t : t Value.Type.t end (** [(describe-function 'browse-url)] *) val browse_url : Url.t -> unit (** [(describe-function 'browse-url-chrome)] *) val browse_url_chrome : Url.t -> unit
null
https://raw.githubusercontent.com/janestreet/ecaml/7c16e5720ee1da04e0757cf185a074debf9088df/src/browse_url.mli
ocaml
* [(describe-function 'browse-url)] * [(describe-function 'browse-url-chrome)]
* Pass a URL to a WWW browser . Ecaml bindings for [ browse-url.el ] open! Core open! Import module Url : sig type t = string val type_ : t Value.Type.t val t : t Value.Type.t end val browse_url : Url.t -> unit val browse_url_chrome : Url.t -> unit
7a043004d64eecca1f58deff95164f3d1e7f3743e7ebf975d3317894f8d56613
thoughtstem/game-engine
spawn-once.rkt
#lang racket (require "../game-entities.rkt") ;(require "../components/after-time.rkt") (require "./direction.rkt") (require "./rotation-style.rkt") (require "./animated-sprite.rkt") (require posn threading) ( " LOADING ON START " ) (provide spawn-many-from spawn-once-inc update-what-will-spawn spawn-once-ready? spawn-once-almost-ready? (except-out (struct-out spawn-once) spawn-once) (rename-out [make-spawn-once spawn-once])) (component spawn-once (spawn speed accum next relative?)) (define (make-spawn-once spawn #:relative? [relative? #t]) (new-spawn-once spawn 1 0 #f relative?)) (define (update-what-will-spawn so f) (struct-copy spawn-once so [spawn (f (spawn-once-spawn so))])) (define (spawn-once-ready? s) (>= (spawn-once-accum s) (spawn-once-speed s))) (define (spawn-once-almost-ready? s) (= (spawn-once-accum s) (sub1 (spawn-once-speed s)))) (define (spawn-once-reset s) (struct-copy spawn-once s [accum 0] [next #f])) (define (next-spawn s) (define s2 (spawn-once-spawn s)) (if (procedure? s2) (s2) s2)) (define (spawn-once-do-spawn e) (lambda (s) (define to-spawn (next-spawn s)) (define relative? (spawn-once-relative? s #;(get-component e spawn-once?))) ( ( ~a " Spawning from : " ( get - name e ) " , Relative : " relative ? ) ) (define pos (get-component e posn?)) (define dir (if (get-component e direction?) (get-direction e) #f)) (define offset (get-component to-spawn posn?)) (define rot-offset (unless (eq? dir #f) (posn-rotate-origin-ccw (modulo (exact-round dir) 360) offset))) (define rs? (get-component e rotation-style?)) (define m (if rs? (rotation-style-mode rs?) #f)) (define facing-right? (if (eq? m 'left-right) (positive? (animated-sprite-x-scale (get-component e animated-sprite?))) #t)) (define new-posn (cond [(and (eq? m 'left-right) (eq? facing-right? #t)) (posn (+ (posn-x pos) (posn-x offset)) (+ (posn-y pos) (posn-y offset)))] [(and (eq? m 'left-right) (eq? facing-right? #f)) (posn (- (posn-x pos) (posn-x offset)) (+ (posn-y pos) (posn-y offset)))] [(eq? m 'face-direction) (posn (+ (posn-x pos) (posn-x rot-offset)) (+ (posn-y pos) (posn-y rot-offset)))] [else (posn (+ (posn-x pos) (posn-x offset)) (+ (posn-y pos) (posn-y offset)))])) (define new-entity (if (and (get-component to-spawn direction?) (get-component e direction?)) (~> to-spawn (update-entity _ posn? new-posn) (update-entity _ direction? (direction dir))) (update-entity to-spawn posn? new-posn))) (if relative? (struct-copy spawn-once s [next new-entity]) (struct-copy spawn-once s [next to-spawn])))) (define (spawn-once-inc s) (struct-copy spawn-once s [accum (add1 (spawn-once-accum s))])) (define (update-spawn-once g e c) (define new-c (spawn-once-inc c)) (if (spawn-once-ready? new-c) (update-entity e (component-is? c) ((spawn-once-do-spawn e) new-c)) e)) (define/contract (collect-spawn-once es) (-> (listof entity?) (listof entity?)) (define spawn-onces (flatten (map (curryr get-components spawn-once?) es))) ;get-components? (filter identity (map spawn-once-next spawn-onces))) (define (reset-spawn-once es) (map (λ(x) (define s (get-component x spawn-once?)) (if (and s (spawn-once-ready? s)) (remove-component x (and/c ;(component-is? s) spawn-once? spawn-once-ready?)) x)) es)) (define (handle-spawn-once g) (define es (game-entities g)) (define new-es (collect-spawn-once es)) #;(and (not (empty? new-es)) (displayln (~a "Spawning: " (map get-name new-es)))) new - es (map (curry uniqify-id g) new-es) (reset-spawn-once es))) (struct-copy game g [entities all])) (define (spawn-many-from source to-spawn #:relative (r #t)) (add-components source (map (curry make-spawn-once #:relative? r) to-spawn))) (new-component spawn-once? update-spawn-once) (new-game-function handle-spawn-once)
null
https://raw.githubusercontent.com/thoughtstem/game-engine/98c4b9e9b8c071818e564ef7efb55465cff487a8/components/spawn-once.rkt
racket
(require "../components/after-time.rkt") (get-component e spawn-once?))) get-components? (component-is? s) (and (not (empty? new-es))
#lang racket (require "../game-entities.rkt") (require "./direction.rkt") (require "./rotation-style.rkt") (require "./animated-sprite.rkt") (require posn threading) ( " LOADING ON START " ) (provide spawn-many-from spawn-once-inc update-what-will-spawn spawn-once-ready? spawn-once-almost-ready? (except-out (struct-out spawn-once) spawn-once) (rename-out [make-spawn-once spawn-once])) (component spawn-once (spawn speed accum next relative?)) (define (make-spawn-once spawn #:relative? [relative? #t]) (new-spawn-once spawn 1 0 #f relative?)) (define (update-what-will-spawn so f) (struct-copy spawn-once so [spawn (f (spawn-once-spawn so))])) (define (spawn-once-ready? s) (>= (spawn-once-accum s) (spawn-once-speed s))) (define (spawn-once-almost-ready? s) (= (spawn-once-accum s) (sub1 (spawn-once-speed s)))) (define (spawn-once-reset s) (struct-copy spawn-once s [accum 0] [next #f])) (define (next-spawn s) (define s2 (spawn-once-spawn s)) (if (procedure? s2) (s2) s2)) (define (spawn-once-do-spawn e) (lambda (s) (define to-spawn (next-spawn s)) ( ( ~a " Spawning from : " ( get - name e ) " , Relative : " relative ? ) ) (define pos (get-component e posn?)) (define dir (if (get-component e direction?) (get-direction e) #f)) (define offset (get-component to-spawn posn?)) (define rot-offset (unless (eq? dir #f) (posn-rotate-origin-ccw (modulo (exact-round dir) 360) offset))) (define rs? (get-component e rotation-style?)) (define m (if rs? (rotation-style-mode rs?) #f)) (define facing-right? (if (eq? m 'left-right) (positive? (animated-sprite-x-scale (get-component e animated-sprite?))) #t)) (define new-posn (cond [(and (eq? m 'left-right) (eq? facing-right? #t)) (posn (+ (posn-x pos) (posn-x offset)) (+ (posn-y pos) (posn-y offset)))] [(and (eq? m 'left-right) (eq? facing-right? #f)) (posn (- (posn-x pos) (posn-x offset)) (+ (posn-y pos) (posn-y offset)))] [(eq? m 'face-direction) (posn (+ (posn-x pos) (posn-x rot-offset)) (+ (posn-y pos) (posn-y rot-offset)))] [else (posn (+ (posn-x pos) (posn-x offset)) (+ (posn-y pos) (posn-y offset)))])) (define new-entity (if (and (get-component to-spawn direction?) (get-component e direction?)) (~> to-spawn (update-entity _ posn? new-posn) (update-entity _ direction? (direction dir))) (update-entity to-spawn posn? new-posn))) (if relative? (struct-copy spawn-once s [next new-entity]) (struct-copy spawn-once s [next to-spawn])))) (define (spawn-once-inc s) (struct-copy spawn-once s [accum (add1 (spawn-once-accum s))])) (define (update-spawn-once g e c) (define new-c (spawn-once-inc c)) (if (spawn-once-ready? new-c) (update-entity e (component-is? c) ((spawn-once-do-spawn e) new-c)) e)) (define/contract (collect-spawn-once es) (-> (listof entity?) (listof entity?)) (filter identity (map spawn-once-next spawn-onces))) (define (reset-spawn-once es) (map (λ(x) (define s (get-component x spawn-once?)) (if (and s (spawn-once-ready? s)) (remove-component x (and/c spawn-once? spawn-once-ready?)) x)) es)) (define (handle-spawn-once g) (define es (game-entities g)) (define new-es (collect-spawn-once es)) (displayln (~a "Spawning: " (map get-name new-es)))) new - es (map (curry uniqify-id g) new-es) (reset-spawn-once es))) (struct-copy game g [entities all])) (define (spawn-many-from source to-spawn #:relative (r #t)) (add-components source (map (curry make-spawn-once #:relative? r) to-spawn))) (new-component spawn-once? update-spawn-once) (new-game-function handle-spawn-once)
7c20fb2ce43504dea1b973e4f954d313bcb53253ce276a4de59804bcd3648507
logseq/mldoc
mldoc.ml
(** Entry point of the org library *) module Document = Document module Block = Type_parser.Block module Inline = Inline module Exporters = Exporter.Exporters module Conf = Conf module Exporter = Exporter module Timestamp = Timestamp module Parser = Mldoc_parser module Type = Type module Property = Property module Backends = struct module Html = Html end module Xml = Xml
null
https://raw.githubusercontent.com/logseq/mldoc/658cc20d5b79865cf909a644d4e4bd22ed61b477/lib/mldoc.ml
ocaml
* Entry point of the org library
module Document = Document module Block = Type_parser.Block module Inline = Inline module Exporters = Exporter.Exporters module Conf = Conf module Exporter = Exporter module Timestamp = Timestamp module Parser = Mldoc_parser module Type = Type module Property = Property module Backends = struct module Html = Html end module Xml = Xml
06ec796a701bb853725f9fb0fbbcad262f9427d17dc9b6075729bf3ee50f2f44
ryanpbrewster/haskell
P119Test.hs
module Problems.P119Test ( case_119_main ) where import Problems.P119 import Test.Tasty.Discover (Assertion, (@?=)) case_119_main :: Assertion case_119_main = solve @?= "248155780267521"
null
https://raw.githubusercontent.com/ryanpbrewster/haskell/6edd0afe234008a48b4871032dedfd143ca6e412/project-euler/tests/Problems/P119Test.hs
haskell
module Problems.P119Test ( case_119_main ) where import Problems.P119 import Test.Tasty.Discover (Assertion, (@?=)) case_119_main :: Assertion case_119_main = solve @?= "248155780267521"
f51072a9ef4d8dc23a3dafe2a7a340b22714a5010fd4142175bca16cd02b904c
camllight/camllight
int_misc.mli
(* Some extra operations on integers *) value gcd_int: int -> int -> int and num_bits_int: int -> int and compare_int: int -> int -> int and sign_int: int -> int and length_of_int: int and biggest_int: int and least_int: int and monster_int: int and sys_string_of_int : int -> string -> int -> string -> string and sys_int_of_string : int -> string -> int -> int -> int and int_to_string : int -> string -> int ref -> int -> int -> unit and digits : string and base_digit_of_char : int -> char -> int and check_base : int -> unit ;;
null
https://raw.githubusercontent.com/camllight/camllight/0cc537de0846393322058dbb26449427bfc76786/sources/contrib/libnum/int_misc.mli
ocaml
Some extra operations on integers
value gcd_int: int -> int -> int and num_bits_int: int -> int and compare_int: int -> int -> int and sign_int: int -> int and length_of_int: int and biggest_int: int and least_int: int and monster_int: int and sys_string_of_int : int -> string -> int -> string -> string and sys_int_of_string : int -> string -> int -> int -> int and int_to_string : int -> string -> int ref -> int -> int -> unit and digits : string and base_digit_of_char : int -> char -> int and check_base : int -> unit ;;
a6147856db02f7dc5ac3652d343ca1a84a001b3221d0e0d566aa265e1fc38da3
haskell-effectful/effectful
Async.hs
# LANGUAGE UndecidableInstances # -- | Lifted "Control.Concurrent.Async". module Effectful.Concurrent.Async ( -- * Effect Concurrent -- ** Handlers , runConcurrent -- * Asynchronous actions , Async -- * High-level API -- ** Spawning with automatic 'cancel'ation , withAsync, withAsyncBound, withAsyncOn, withAsyncWithUnmask , withAsyncOnWithUnmask -- ** Querying 'Async's , wait, poll, waitCatch, A.asyncThreadId , cancel, uninterruptibleCancel, cancelWith, A.AsyncCancelled(..) , A.compareAsyncs -- ** High-level utilities , race, race_ , concurrently, concurrently_ , mapConcurrently, forConcurrently , mapConcurrently_, forConcurrently_ , replicateConcurrently, replicateConcurrently_ -- *** Concurrently , Concurrently(..) -- *** Conc , Conc, conc, runConc, U.ConcException(..) -- ** Pooled concurrency , pooledMapConcurrentlyN , pooledMapConcurrently , pooledMapConcurrentlyN_ , pooledMapConcurrently_ , pooledForConcurrentlyN , pooledForConcurrently , pooledForConcurrentlyN_ , pooledForConcurrently_ , pooledReplicateConcurrentlyN , pooledReplicateConcurrently , pooledReplicateConcurrentlyN_ , pooledReplicateConcurrently_ -- ** Specialised operations * * * STM operations , A.waitSTM, A.pollSTM, A.waitCatchSTM -- *** Waiting for multiple 'Async's , waitAny, waitAnyCatch, waitAnyCancel, waitAnyCatchCancel , waitEither, waitEitherCatch, waitEitherCancel, waitEitherCatchCancel , waitEither_ , waitBoth * * * Waiting for multiple ' Async 's in STM , A.waitAnySTM, A.waitAnyCatchSTM , A.waitEitherSTM, A.waitEitherCatchSTM , A.waitEitherSTM_ , A.waitBothSTM -- * Low-level API -- ** Spawning (low-level API) , async, asyncBound, asyncOn, asyncWithUnmask, asyncOnWithUnmask -- ** Linking , link, linkOnly, link2, link2Only, A.ExceptionInLinkedThread(..) ) where import Control.Applicative import Control.Concurrent (threadDelay) import Control.Concurrent.Async (Async) import Control.Exception (Exception, SomeException) import Control.Monad (forever) import Data.Kind (Type) import qualified Control.Concurrent.Async as A import qualified UnliftIO.Async as U import qualified UnliftIO.Internals.Async as I import Effectful import Effectful.Concurrent.Effect import Effectful.Dispatch.Static import Effectful.Dispatch.Static.Primitive import Effectful.Dispatch.Static.Unsafe -- | Lifted 'A.async'. async :: Concurrent :> es => Eff es a -> Eff es (Async a) async = liftAsync A.async | Lifted ' A.asyncBound ' . asyncBound :: Concurrent :> es => Eff es a -> Eff es (Async a) asyncBound = liftAsync A.asyncBound -- | Lifted 'A.asyncOn'. asyncOn :: Concurrent :> es => Int -> Eff es a -> Eff es (Async a) asyncOn cpu = liftAsync (A.asyncOn cpu) | Lifted ' A.asyncWithUnmask ' . asyncWithUnmask :: Concurrent :> es => ((forall b. Eff es b -> Eff es b) -> Eff es a) -> Eff es (Async a) asyncWithUnmask = liftAsyncWithUnmask A.asyncWithUnmask | Lifted ' A.asyncOnWithUnmask ' . asyncOnWithUnmask :: Concurrent :> es => Int -> ((forall b. Eff es b -> Eff es b) -> Eff es a) -> Eff es (Async a) asyncOnWithUnmask cpu = liftAsyncWithUnmask (A.asyncOnWithUnmask cpu) -- | Lifted 'A.withAsync'. withAsync :: Concurrent :> es => Eff es a -> (Async a -> Eff es b) -> Eff es b withAsync = liftWithAsync A.withAsync -- | Lifted 'A.withAsyncBound'. withAsyncBound :: Concurrent :> es => Eff es a -> (Async a -> Eff es b) -> Eff es b withAsyncBound = liftWithAsync A.withAsyncBound | Lifted ' A.withAsyncOn ' . withAsyncOn :: Concurrent :> es => Int -> Eff es a -> (Async a -> Eff es b) -> Eff es b withAsyncOn cpu = liftWithAsync (A.withAsyncOn cpu) -- | Lifted 'A.withAsyncWithUnmask'. withAsyncWithUnmask :: Concurrent :> es => ((forall c. Eff es c -> Eff es c) -> Eff es a) -> (Async a -> Eff es b) -> Eff es b withAsyncWithUnmask = liftWithAsyncWithUnmask A.withAsyncWithUnmask | Lifted ' A.withAsyncOnWithUnmask ' . withAsyncOnWithUnmask :: Concurrent :> es => Int -> ((forall c. Eff es c -> Eff es c) -> Eff es a) -> (Async a -> Eff es b) -> Eff es b withAsyncOnWithUnmask cpu = liftWithAsyncWithUnmask (A.withAsyncOnWithUnmask cpu) -- | Lifted 'A.wait'. wait :: Concurrent :> es => Async a -> Eff es a wait = unsafeEff_ . A.wait -- | Lifted 'A.poll'. poll :: Concurrent :> es => Async a -> Eff es (Maybe (Either SomeException a)) poll = unsafeEff_ . A.poll -- | Lifted 'A.cancel'. cancel :: Concurrent :> es => Async a -> Eff es () cancel = unsafeEff_ . A.cancel -- | Lifted 'A.cancelWith'. cancelWith :: (Exception e, Concurrent :> es) => Async a -> e -> Eff es () cancelWith a = unsafeEff_ . A.cancelWith a -- | Lifted 'A.uninterruptibleCancel'. uninterruptibleCancel :: Concurrent :> es => Async a -> Eff es () uninterruptibleCancel = unsafeEff_ . A.uninterruptibleCancel -- | Lifted 'A.waitCatch'. waitCatch :: Concurrent :> es => Async a -> Eff es (Either SomeException a) waitCatch = unsafeEff_ . A.waitCatch -- | Lifted 'A.waitAny'. waitAny :: Concurrent :> es => [Async a] -> Eff es (Async a, a) waitAny = unsafeEff_ . A.waitAny -- | Lifted 'A.waitAnyCatch'. waitAnyCatch :: Concurrent :> es => [Async a] -> Eff es (Async a, Either SomeException a) waitAnyCatch = unsafeEff_ . A.waitAnyCatch | Lifted ' A.waitAnyCancel ' . waitAnyCancel :: Concurrent :> es => [Async a] -> Eff es (Async a, a) waitAnyCancel = unsafeEff_ . A.waitAnyCancel -- | Lifted 'A.waitAnyCatchCancel'. waitAnyCatchCancel :: Concurrent :> es => [Async a] -> Eff es (Async a, Either SomeException a) waitAnyCatchCancel = unsafeEff_ . A.waitAnyCatchCancel -- | Lifted 'A.waitEither'. waitEither :: Concurrent :> es => Async a -> Async b -> Eff es (Either a b) waitEither a b = unsafeEff_ $ A.waitEither a b -- | Lifted 'A.waitEitherCatch'. waitEitherCatch :: Concurrent :> es => Async a -> Async b -> Eff es (Either (Either SomeException a) (Either SomeException b)) waitEitherCatch a b = unsafeEff_ $ A.waitEitherCatch a b -- | Lifted 'A.waitEitherCancel'. waitEitherCancel :: Concurrent :> es => Async a -> Async b -> Eff es (Either a b) waitEitherCancel a b = unsafeEff_ $ A.waitEitherCancel a b -- | Lifted 'A.waitEitherCatchCancel'. waitEitherCatchCancel :: Concurrent :> es => Async a -> Async b -> Eff es (Either (Either SomeException a) (Either SomeException b)) waitEitherCatchCancel a b = unsafeEff_ $ A.waitEitherCatch a b -- | Lifted 'A.waitEither_'. waitEither_ :: Concurrent :> es => Async a -> Async b -> Eff es () waitEither_ a b = unsafeEff_ $ A.waitEither_ a b -- | Lifted 'A.waitBoth'. waitBoth :: Concurrent :> es => Async a -> Async b -> Eff es (a, b) waitBoth a b = unsafeEff_ $ A.waitBoth a b -- | Lifted 'A.link'. link :: Concurrent :> es => Async a -> Eff es () link = unsafeEff_ . A.link -- | Lifted 'A.linkOnly'. linkOnly :: Concurrent :> es => (SomeException -> Bool) -> Async a -> Eff es () linkOnly f = unsafeEff_ . A.linkOnly f -- | Lifted 'A.link2'. link2 :: Concurrent :> es => Async a -> Async b -> Eff es () link2 a b = unsafeEff_ $ A.link2 a b -- | Lifted 'A.link2Only'. link2Only :: Concurrent :> es => (SomeException -> Bool) -> Async a -> Async b -> Eff es () link2Only f a b = unsafeEff_ $ A.link2Only f a b -- | Lifted 'A.race'. race :: Concurrent :> es => Eff es a -> Eff es b -> Eff es (Either a b) race ma mb = unsafeEff $ \es -> do A.race (unEff ma =<< cloneEnv es) (unEff mb =<< cloneEnv es) -- | Lifted 'A.race_'. race_ :: Concurrent :> es => Eff es a -> Eff es b -> Eff es () race_ ma mb = unsafeEff $ \es -> do A.race_ (unEff ma =<< cloneEnv es) (unEff mb =<< cloneEnv es) -- | Lifted 'A.concurrently'. concurrently :: Concurrent :> es => Eff es a -> Eff es b -> Eff es (a, b) concurrently ma mb = unsafeEff $ \es -> do A.concurrently (unEff ma =<< cloneEnv es) (unEff mb =<< cloneEnv es) -- | Lifted 'A.concurrently_'. concurrently_ :: Concurrent :> es => Eff es a -> Eff es b -> Eff es () concurrently_ ma mb = unsafeEff $ \es -> do A.concurrently_ (unEff ma =<< cloneEnv es) (unEff mb =<< cloneEnv es) -- Below functions use variants from the @unliftio@ library as they minimize the -- amount of spawned threads and are thus much more efficient than the ones from -- the @async@ library. -- | Lifted 'A.mapConcurrently'. mapConcurrently :: (Traversable f, Concurrent :> es) => (a -> Eff es b) -> f a -> Eff es (f b) mapConcurrently f t = unsafeEff $ \es -> do U.mapConcurrently (\a -> unEff (f a) =<< cloneEnv es) t -- | Lifted 'A.mapConcurrently_'. mapConcurrently_ :: (Foldable f, Concurrent :> es) => (a -> Eff es b) -> f a -> Eff es () mapConcurrently_ f t = unsafeEff $ \es -> do U.mapConcurrently_ (\a -> unEff (f a) =<< cloneEnv es) t -- | Lifted 'A.forConcurrently'. forConcurrently :: (Traversable f, Concurrent :> es) => f a -> (a -> Eff es b) -> Eff es (f b) forConcurrently t f = unsafeEff $ \es -> do U.forConcurrently t (\a -> unEff (f a) =<< cloneEnv es) -- | Lifted 'A.forConcurrently_'. forConcurrently_ :: (Foldable f, Concurrent :> es) => f a -> (a -> Eff es b) -> Eff es () forConcurrently_ t f = unsafeEff $ \es -> do U.forConcurrently_ t (\a -> unEff (f a) =<< cloneEnv es) -- | Lifted 'A.replicateConcurrently'. replicateConcurrently :: Concurrent :> es => Int -> Eff es a -> Eff es [a] replicateConcurrently n f = unsafeEff $ \es -> do U.replicateConcurrently n (unEff f =<< cloneEnv es) -- | Lifted 'A.replicateConcurrently_'. replicateConcurrently_ :: Concurrent :> es => Int -> Eff es a -> Eff es () replicateConcurrently_ n f = unsafeEff $ \es -> do U.replicateConcurrently_ n (unEff f =<< cloneEnv es) ---------------------------------------- -- Pooled concurrency (unliftio) -- | Lifted 'U.pooledMapConcurrentlyN'. pooledMapConcurrentlyN :: (Concurrent :> es, Traversable t) => Int -> (a -> Eff es b) -> t a -> Eff es (t b) pooledMapConcurrentlyN threads f t = unsafeEff $ \es -> do U.pooledMapConcurrentlyN threads (\a -> unEff (f a) =<< cloneEnv es) t -- | Lifted 'U.pooledMapConcurrently'. pooledMapConcurrently :: (Concurrent :> es, Traversable t) => (a -> Eff es b) -> t a -> Eff es (t b) pooledMapConcurrently f t = unsafeEff $ \es -> do U.pooledMapConcurrently (\a -> unEff (f a) =<< cloneEnv es) t -- | Lifted 'U.pooledMapConcurrentlyN'. pooledMapConcurrentlyN_ :: (Concurrent :> es, Foldable f) => Int -> (a -> Eff es b) -> f a -> Eff es () pooledMapConcurrentlyN_ threads f t = unsafeEff $ \es -> do U.pooledMapConcurrentlyN_ threads (\a -> unEff (f a) =<< cloneEnv es) t -- | Lifted 'U.pooledMapConcurrently_'. pooledMapConcurrently_ :: (Concurrent :> es, Foldable f) => (a -> Eff es b) -> f a -> Eff es () pooledMapConcurrently_ f t = unsafeEff $ \es -> do U.pooledMapConcurrently_ (\a -> unEff (f a) =<< cloneEnv es) t | Lifted ' U.pooledForConcurrentlyN ' . pooledForConcurrentlyN :: (Concurrent :> es, Traversable t) => Int -> t a -> (a -> Eff es b) -> Eff es (t b) pooledForConcurrentlyN threads t f = unsafeEff $ \es -> do U.pooledForConcurrentlyN threads t (\a -> unEff (f a) =<< cloneEnv es) -- | Lifted 'U.pooledForConcurrently'. pooledForConcurrently :: (Concurrent :> es, Traversable t) => t a -> (a -> Eff es b) -> Eff es (t b) pooledForConcurrently t f = unsafeEff $ \es -> do U.pooledForConcurrently t (\a -> unEff (f a) =<< cloneEnv es) | Lifted ' U.pooledForConcurrentlyN ' . pooledForConcurrentlyN_ :: (Concurrent :> es, Foldable f) => Int -> f a -> (a -> Eff es b) -> Eff es () pooledForConcurrentlyN_ threads t f = unsafeEff $ \es -> do U.pooledForConcurrentlyN_ threads t (\a -> unEff (f a) =<< cloneEnv es) -- | Lifted 'U.pooledForConcurrently_'. pooledForConcurrently_ :: (Concurrent :> es, Foldable f) => f a -> (a -> Eff es b) -> Eff es () pooledForConcurrently_ t f = unsafeEff $ \es -> do U.pooledForConcurrently_ t (\a -> unEff (f a) =<< cloneEnv es) | Lifted ' U.pooledReplicateConcurrentlyN ' . pooledReplicateConcurrentlyN :: Concurrent :> es => Int -> Int -> Eff es a -> Eff es [a] pooledReplicateConcurrentlyN threads n f = unsafeEff $ \es -> do U.pooledReplicateConcurrentlyN threads n (unEff f =<< cloneEnv es) -- | Lifted 'U.pooledReplicateConcurrently'. pooledReplicateConcurrently :: Concurrent :> es => Int -> Eff es a -> Eff es [a] pooledReplicateConcurrently n f = unsafeEff $ \es -> do U.pooledReplicateConcurrently n (unEff f =<< cloneEnv es) | Lifted ' U.pooledReplicateConcurrentlyN _ ' . pooledReplicateConcurrentlyN_ :: Concurrent :> es => Int -> Int -> Eff es a -> Eff es () pooledReplicateConcurrentlyN_ threads n f = unsafeEff $ \es -> do U.pooledReplicateConcurrentlyN_ threads n (unEff f =<< cloneEnv es) -- | Lifted 'U.pooledReplicateConcurrently_'. pooledReplicateConcurrently_ :: Concurrent :> es => Int -> Eff es a -> Eff es () pooledReplicateConcurrently_ n f = unsafeEff $ \es -> do U.pooledReplicateConcurrently_ n (unEff f =<< cloneEnv es) ---------------------------------------- -- Conc -- | Lifted 'U.Conc'. data Conc :: [Effect] -> Type -> Type where Action :: Eff es a -> Conc es a Apply :: Conc es (v -> a) -> Conc es v -> Conc es a LiftA2 :: (x -> y -> a) -> Conc es x -> Conc es y -> Conc es a Pure :: a -> Conc es a Alt :: Conc es a -> Conc es a -> Conc es a Empty :: Conc es a deriving instance Functor (Conc es) instance Applicative (Conc es) where pure = Pure (<*>) = Apply (<*) = LiftA2 (\x _ -> x) (*>) = LiftA2 (\_ y -> y) liftA2 = LiftA2 instance Alternative (Conc es) where empty = Empty (<|>) = Alt instance Semigroup a => Semigroup (Conc es a) where (<>) = liftA2 (<>) instance Monoid a => Monoid (Conc es a) where mempty = pure mempty -- | Lifted 'U.conc'. conc :: Eff es a -> Conc es a conc = Action -- | Lifted 'U.runConc'. runConc :: Concurrent :> es => Conc es a -> Eff es a runConc m = unsafeEff $ \es -> U.runConc (unliftConc es m) where unliftConc :: Env es -> Conc es a -> U.Conc IO a unliftConc es = \case Action f -> I.Action $ unEff f =<< cloneEnv es Apply a b -> I.Apply (unliftConc es a) (unliftConc es b) LiftA2 f a b -> I.LiftA2 f (unliftConc es a) (unliftConc es b) Pure a -> I.Pure a Alt a b -> I.Alt (unliftConc es a) (unliftConc es b) Empty -> I.Empty ---------------------------------------- -- Concurrently -- | Lifted 'A.Concurrently'. newtype Concurrently es a = Concurrently { runConcurrently :: Eff es a } instance Functor (Concurrently es) where fmap f (Concurrently a) = Concurrently (fmap f a) instance Concurrent :> es => Applicative (Concurrently es) where pure = Concurrently . pure Concurrently fs <*> Concurrently as = Concurrently ((\(f, a) -> f a) <$> concurrently fs as) instance Concurrent :> es => Alternative (Concurrently es) where empty = Concurrently . unsafeEff_ . forever $ threadDelay maxBound Concurrently as <|> Concurrently bs = Concurrently (either id id <$> race as bs) instance (Concurrent :> es, Semigroup a) => Semigroup (Concurrently es a) where (<>) = liftA2 (<>) instance (Concurrent :> es, Monoid a) => Monoid (Concurrently es a) where mempty = pure mempty ---------------------------------------- -- Helpers liftAsync :: (IO a -> IO (Async a)) -> Eff es a -> Eff es (Async a) liftAsync fork action = unsafeEff $ \es -> do esA <- cloneEnv es fork $ unEff action esA liftAsyncWithUnmask :: (((forall b. IO b -> IO b) -> IO a) -> IO (Async a)) -> ((forall b. Eff es b -> Eff es b) -> Eff es a) -> Eff es (Async a) liftAsyncWithUnmask fork action = unsafeEff $ \es -> do esA <- cloneEnv es -- Unmask never runs its argument in a different thread. fork $ \unmask -> unEff (action $ reallyUnsafeLiftMapIO unmask) esA liftWithAsync :: (IO a -> (Async a -> IO b) -> IO b) -> Eff es a -> (Async a -> Eff es b) -> Eff es b liftWithAsync withA action k = unsafeEff $ \es -> do esA <- cloneEnv es withA (unEff action esA) (\a -> unEff (k a) es) liftWithAsyncWithUnmask :: (((forall c. IO c -> IO c) -> IO a) -> (Async a -> IO b) -> IO b) -> ((forall c. Eff es c -> Eff es c) -> Eff es a) -> (Async a -> Eff es b) -> Eff es b liftWithAsyncWithUnmask withA action k = unsafeEff $ \es -> do esA <- cloneEnv es -- Unmask never runs its argument in a different thread. withA (\unmask -> unEff (action $ reallyUnsafeLiftMapIO unmask) esA) (\a -> unEff (k a) es)
null
https://raw.githubusercontent.com/haskell-effectful/effectful/f7f82c149e7b4e67c3638e854a84d1c9695c0baa/effectful/src/Effectful/Concurrent/Async.hs
haskell
| Lifted "Control.Concurrent.Async". * Effect ** Handlers * Asynchronous actions * High-level API ** Spawning with automatic 'cancel'ation ** Querying 'Async's ** High-level utilities *** Concurrently *** Conc ** Pooled concurrency ** Specialised operations *** Waiting for multiple 'Async's * Low-level API ** Spawning (low-level API) ** Linking | Lifted 'A.async'. | Lifted 'A.asyncOn'. | Lifted 'A.withAsync'. | Lifted 'A.withAsyncBound'. | Lifted 'A.withAsyncWithUnmask'. | Lifted 'A.wait'. | Lifted 'A.poll'. | Lifted 'A.cancel'. | Lifted 'A.cancelWith'. | Lifted 'A.uninterruptibleCancel'. | Lifted 'A.waitCatch'. | Lifted 'A.waitAny'. | Lifted 'A.waitAnyCatch'. | Lifted 'A.waitAnyCatchCancel'. | Lifted 'A.waitEither'. | Lifted 'A.waitEitherCatch'. | Lifted 'A.waitEitherCancel'. | Lifted 'A.waitEitherCatchCancel'. | Lifted 'A.waitEither_'. | Lifted 'A.waitBoth'. | Lifted 'A.link'. | Lifted 'A.linkOnly'. | Lifted 'A.link2'. | Lifted 'A.link2Only'. | Lifted 'A.race'. | Lifted 'A.race_'. | Lifted 'A.concurrently'. | Lifted 'A.concurrently_'. Below functions use variants from the @unliftio@ library as they minimize the amount of spawned threads and are thus much more efficient than the ones from the @async@ library. | Lifted 'A.mapConcurrently'. | Lifted 'A.mapConcurrently_'. | Lifted 'A.forConcurrently'. | Lifted 'A.forConcurrently_'. | Lifted 'A.replicateConcurrently'. | Lifted 'A.replicateConcurrently_'. -------------------------------------- Pooled concurrency (unliftio) | Lifted 'U.pooledMapConcurrentlyN'. | Lifted 'U.pooledMapConcurrently'. | Lifted 'U.pooledMapConcurrentlyN'. | Lifted 'U.pooledMapConcurrently_'. | Lifted 'U.pooledForConcurrently'. | Lifted 'U.pooledForConcurrently_'. | Lifted 'U.pooledReplicateConcurrently'. | Lifted 'U.pooledReplicateConcurrently_'. -------------------------------------- Conc | Lifted 'U.Conc'. | Lifted 'U.conc'. | Lifted 'U.runConc'. -------------------------------------- Concurrently | Lifted 'A.Concurrently'. -------------------------------------- Helpers Unmask never runs its argument in a different thread. Unmask never runs its argument in a different thread.
# LANGUAGE UndecidableInstances # module Effectful.Concurrent.Async Concurrent , runConcurrent , Async , withAsync, withAsyncBound, withAsyncOn, withAsyncWithUnmask , withAsyncOnWithUnmask , wait, poll, waitCatch, A.asyncThreadId , cancel, uninterruptibleCancel, cancelWith, A.AsyncCancelled(..) , A.compareAsyncs , race, race_ , concurrently, concurrently_ , mapConcurrently, forConcurrently , mapConcurrently_, forConcurrently_ , replicateConcurrently, replicateConcurrently_ , Concurrently(..) , Conc, conc, runConc, U.ConcException(..) , pooledMapConcurrentlyN , pooledMapConcurrently , pooledMapConcurrentlyN_ , pooledMapConcurrently_ , pooledForConcurrentlyN , pooledForConcurrently , pooledForConcurrentlyN_ , pooledForConcurrently_ , pooledReplicateConcurrentlyN , pooledReplicateConcurrently , pooledReplicateConcurrentlyN_ , pooledReplicateConcurrently_ * * * STM operations , A.waitSTM, A.pollSTM, A.waitCatchSTM , waitAny, waitAnyCatch, waitAnyCancel, waitAnyCatchCancel , waitEither, waitEitherCatch, waitEitherCancel, waitEitherCatchCancel , waitEither_ , waitBoth * * * Waiting for multiple ' Async 's in STM , A.waitAnySTM, A.waitAnyCatchSTM , A.waitEitherSTM, A.waitEitherCatchSTM , A.waitEitherSTM_ , A.waitBothSTM , async, asyncBound, asyncOn, asyncWithUnmask, asyncOnWithUnmask , link, linkOnly, link2, link2Only, A.ExceptionInLinkedThread(..) ) where import Control.Applicative import Control.Concurrent (threadDelay) import Control.Concurrent.Async (Async) import Control.Exception (Exception, SomeException) import Control.Monad (forever) import Data.Kind (Type) import qualified Control.Concurrent.Async as A import qualified UnliftIO.Async as U import qualified UnliftIO.Internals.Async as I import Effectful import Effectful.Concurrent.Effect import Effectful.Dispatch.Static import Effectful.Dispatch.Static.Primitive import Effectful.Dispatch.Static.Unsafe async :: Concurrent :> es => Eff es a -> Eff es (Async a) async = liftAsync A.async | Lifted ' A.asyncBound ' . asyncBound :: Concurrent :> es => Eff es a -> Eff es (Async a) asyncBound = liftAsync A.asyncBound asyncOn :: Concurrent :> es => Int -> Eff es a -> Eff es (Async a) asyncOn cpu = liftAsync (A.asyncOn cpu) | Lifted ' A.asyncWithUnmask ' . asyncWithUnmask :: Concurrent :> es => ((forall b. Eff es b -> Eff es b) -> Eff es a) -> Eff es (Async a) asyncWithUnmask = liftAsyncWithUnmask A.asyncWithUnmask | Lifted ' A.asyncOnWithUnmask ' . asyncOnWithUnmask :: Concurrent :> es => Int -> ((forall b. Eff es b -> Eff es b) -> Eff es a) -> Eff es (Async a) asyncOnWithUnmask cpu = liftAsyncWithUnmask (A.asyncOnWithUnmask cpu) withAsync :: Concurrent :> es => Eff es a -> (Async a -> Eff es b) -> Eff es b withAsync = liftWithAsync A.withAsync withAsyncBound :: Concurrent :> es => Eff es a -> (Async a -> Eff es b) -> Eff es b withAsyncBound = liftWithAsync A.withAsyncBound | Lifted ' A.withAsyncOn ' . withAsyncOn :: Concurrent :> es => Int -> Eff es a -> (Async a -> Eff es b) -> Eff es b withAsyncOn cpu = liftWithAsync (A.withAsyncOn cpu) withAsyncWithUnmask :: Concurrent :> es => ((forall c. Eff es c -> Eff es c) -> Eff es a) -> (Async a -> Eff es b) -> Eff es b withAsyncWithUnmask = liftWithAsyncWithUnmask A.withAsyncWithUnmask | Lifted ' A.withAsyncOnWithUnmask ' . withAsyncOnWithUnmask :: Concurrent :> es => Int -> ((forall c. Eff es c -> Eff es c) -> Eff es a) -> (Async a -> Eff es b) -> Eff es b withAsyncOnWithUnmask cpu = liftWithAsyncWithUnmask (A.withAsyncOnWithUnmask cpu) wait :: Concurrent :> es => Async a -> Eff es a wait = unsafeEff_ . A.wait poll :: Concurrent :> es => Async a -> Eff es (Maybe (Either SomeException a)) poll = unsafeEff_ . A.poll cancel :: Concurrent :> es => Async a -> Eff es () cancel = unsafeEff_ . A.cancel cancelWith :: (Exception e, Concurrent :> es) => Async a -> e -> Eff es () cancelWith a = unsafeEff_ . A.cancelWith a uninterruptibleCancel :: Concurrent :> es => Async a -> Eff es () uninterruptibleCancel = unsafeEff_ . A.uninterruptibleCancel waitCatch :: Concurrent :> es => Async a -> Eff es (Either SomeException a) waitCatch = unsafeEff_ . A.waitCatch waitAny :: Concurrent :> es => [Async a] -> Eff es (Async a, a) waitAny = unsafeEff_ . A.waitAny waitAnyCatch :: Concurrent :> es => [Async a] -> Eff es (Async a, Either SomeException a) waitAnyCatch = unsafeEff_ . A.waitAnyCatch | Lifted ' A.waitAnyCancel ' . waitAnyCancel :: Concurrent :> es => [Async a] -> Eff es (Async a, a) waitAnyCancel = unsafeEff_ . A.waitAnyCancel waitAnyCatchCancel :: Concurrent :> es => [Async a] -> Eff es (Async a, Either SomeException a) waitAnyCatchCancel = unsafeEff_ . A.waitAnyCatchCancel waitEither :: Concurrent :> es => Async a -> Async b -> Eff es (Either a b) waitEither a b = unsafeEff_ $ A.waitEither a b waitEitherCatch :: Concurrent :> es => Async a -> Async b -> Eff es (Either (Either SomeException a) (Either SomeException b)) waitEitherCatch a b = unsafeEff_ $ A.waitEitherCatch a b waitEitherCancel :: Concurrent :> es => Async a -> Async b -> Eff es (Either a b) waitEitherCancel a b = unsafeEff_ $ A.waitEitherCancel a b waitEitherCatchCancel :: Concurrent :> es => Async a -> Async b -> Eff es (Either (Either SomeException a) (Either SomeException b)) waitEitherCatchCancel a b = unsafeEff_ $ A.waitEitherCatch a b waitEither_ :: Concurrent :> es => Async a -> Async b -> Eff es () waitEither_ a b = unsafeEff_ $ A.waitEither_ a b waitBoth :: Concurrent :> es => Async a -> Async b -> Eff es (a, b) waitBoth a b = unsafeEff_ $ A.waitBoth a b link :: Concurrent :> es => Async a -> Eff es () link = unsafeEff_ . A.link linkOnly :: Concurrent :> es => (SomeException -> Bool) -> Async a -> Eff es () linkOnly f = unsafeEff_ . A.linkOnly f link2 :: Concurrent :> es => Async a -> Async b -> Eff es () link2 a b = unsafeEff_ $ A.link2 a b link2Only :: Concurrent :> es => (SomeException -> Bool) -> Async a -> Async b -> Eff es () link2Only f a b = unsafeEff_ $ A.link2Only f a b race :: Concurrent :> es => Eff es a -> Eff es b -> Eff es (Either a b) race ma mb = unsafeEff $ \es -> do A.race (unEff ma =<< cloneEnv es) (unEff mb =<< cloneEnv es) race_ :: Concurrent :> es => Eff es a -> Eff es b -> Eff es () race_ ma mb = unsafeEff $ \es -> do A.race_ (unEff ma =<< cloneEnv es) (unEff mb =<< cloneEnv es) concurrently :: Concurrent :> es => Eff es a -> Eff es b -> Eff es (a, b) concurrently ma mb = unsafeEff $ \es -> do A.concurrently (unEff ma =<< cloneEnv es) (unEff mb =<< cloneEnv es) concurrently_ :: Concurrent :> es => Eff es a -> Eff es b -> Eff es () concurrently_ ma mb = unsafeEff $ \es -> do A.concurrently_ (unEff ma =<< cloneEnv es) (unEff mb =<< cloneEnv es) mapConcurrently :: (Traversable f, Concurrent :> es) => (a -> Eff es b) -> f a -> Eff es (f b) mapConcurrently f t = unsafeEff $ \es -> do U.mapConcurrently (\a -> unEff (f a) =<< cloneEnv es) t mapConcurrently_ :: (Foldable f, Concurrent :> es) => (a -> Eff es b) -> f a -> Eff es () mapConcurrently_ f t = unsafeEff $ \es -> do U.mapConcurrently_ (\a -> unEff (f a) =<< cloneEnv es) t forConcurrently :: (Traversable f, Concurrent :> es) => f a -> (a -> Eff es b) -> Eff es (f b) forConcurrently t f = unsafeEff $ \es -> do U.forConcurrently t (\a -> unEff (f a) =<< cloneEnv es) forConcurrently_ :: (Foldable f, Concurrent :> es) => f a -> (a -> Eff es b) -> Eff es () forConcurrently_ t f = unsafeEff $ \es -> do U.forConcurrently_ t (\a -> unEff (f a) =<< cloneEnv es) replicateConcurrently :: Concurrent :> es => Int -> Eff es a -> Eff es [a] replicateConcurrently n f = unsafeEff $ \es -> do U.replicateConcurrently n (unEff f =<< cloneEnv es) replicateConcurrently_ :: Concurrent :> es => Int -> Eff es a -> Eff es () replicateConcurrently_ n f = unsafeEff $ \es -> do U.replicateConcurrently_ n (unEff f =<< cloneEnv es) pooledMapConcurrentlyN :: (Concurrent :> es, Traversable t) => Int -> (a -> Eff es b) -> t a -> Eff es (t b) pooledMapConcurrentlyN threads f t = unsafeEff $ \es -> do U.pooledMapConcurrentlyN threads (\a -> unEff (f a) =<< cloneEnv es) t pooledMapConcurrently :: (Concurrent :> es, Traversable t) => (a -> Eff es b) -> t a -> Eff es (t b) pooledMapConcurrently f t = unsafeEff $ \es -> do U.pooledMapConcurrently (\a -> unEff (f a) =<< cloneEnv es) t pooledMapConcurrentlyN_ :: (Concurrent :> es, Foldable f) => Int -> (a -> Eff es b) -> f a -> Eff es () pooledMapConcurrentlyN_ threads f t = unsafeEff $ \es -> do U.pooledMapConcurrentlyN_ threads (\a -> unEff (f a) =<< cloneEnv es) t pooledMapConcurrently_ :: (Concurrent :> es, Foldable f) => (a -> Eff es b) -> f a -> Eff es () pooledMapConcurrently_ f t = unsafeEff $ \es -> do U.pooledMapConcurrently_ (\a -> unEff (f a) =<< cloneEnv es) t | Lifted ' U.pooledForConcurrentlyN ' . pooledForConcurrentlyN :: (Concurrent :> es, Traversable t) => Int -> t a -> (a -> Eff es b) -> Eff es (t b) pooledForConcurrentlyN threads t f = unsafeEff $ \es -> do U.pooledForConcurrentlyN threads t (\a -> unEff (f a) =<< cloneEnv es) pooledForConcurrently :: (Concurrent :> es, Traversable t) => t a -> (a -> Eff es b) -> Eff es (t b) pooledForConcurrently t f = unsafeEff $ \es -> do U.pooledForConcurrently t (\a -> unEff (f a) =<< cloneEnv es) | Lifted ' U.pooledForConcurrentlyN ' . pooledForConcurrentlyN_ :: (Concurrent :> es, Foldable f) => Int -> f a -> (a -> Eff es b) -> Eff es () pooledForConcurrentlyN_ threads t f = unsafeEff $ \es -> do U.pooledForConcurrentlyN_ threads t (\a -> unEff (f a) =<< cloneEnv es) pooledForConcurrently_ :: (Concurrent :> es, Foldable f) => f a -> (a -> Eff es b) -> Eff es () pooledForConcurrently_ t f = unsafeEff $ \es -> do U.pooledForConcurrently_ t (\a -> unEff (f a) =<< cloneEnv es) | Lifted ' U.pooledReplicateConcurrentlyN ' . pooledReplicateConcurrentlyN :: Concurrent :> es => Int -> Int -> Eff es a -> Eff es [a] pooledReplicateConcurrentlyN threads n f = unsafeEff $ \es -> do U.pooledReplicateConcurrentlyN threads n (unEff f =<< cloneEnv es) pooledReplicateConcurrently :: Concurrent :> es => Int -> Eff es a -> Eff es [a] pooledReplicateConcurrently n f = unsafeEff $ \es -> do U.pooledReplicateConcurrently n (unEff f =<< cloneEnv es) | Lifted ' U.pooledReplicateConcurrentlyN _ ' . pooledReplicateConcurrentlyN_ :: Concurrent :> es => Int -> Int -> Eff es a -> Eff es () pooledReplicateConcurrentlyN_ threads n f = unsafeEff $ \es -> do U.pooledReplicateConcurrentlyN_ threads n (unEff f =<< cloneEnv es) pooledReplicateConcurrently_ :: Concurrent :> es => Int -> Eff es a -> Eff es () pooledReplicateConcurrently_ n f = unsafeEff $ \es -> do U.pooledReplicateConcurrently_ n (unEff f =<< cloneEnv es) data Conc :: [Effect] -> Type -> Type where Action :: Eff es a -> Conc es a Apply :: Conc es (v -> a) -> Conc es v -> Conc es a LiftA2 :: (x -> y -> a) -> Conc es x -> Conc es y -> Conc es a Pure :: a -> Conc es a Alt :: Conc es a -> Conc es a -> Conc es a Empty :: Conc es a deriving instance Functor (Conc es) instance Applicative (Conc es) where pure = Pure (<*>) = Apply (<*) = LiftA2 (\x _ -> x) (*>) = LiftA2 (\_ y -> y) liftA2 = LiftA2 instance Alternative (Conc es) where empty = Empty (<|>) = Alt instance Semigroup a => Semigroup (Conc es a) where (<>) = liftA2 (<>) instance Monoid a => Monoid (Conc es a) where mempty = pure mempty conc :: Eff es a -> Conc es a conc = Action runConc :: Concurrent :> es => Conc es a -> Eff es a runConc m = unsafeEff $ \es -> U.runConc (unliftConc es m) where unliftConc :: Env es -> Conc es a -> U.Conc IO a unliftConc es = \case Action f -> I.Action $ unEff f =<< cloneEnv es Apply a b -> I.Apply (unliftConc es a) (unliftConc es b) LiftA2 f a b -> I.LiftA2 f (unliftConc es a) (unliftConc es b) Pure a -> I.Pure a Alt a b -> I.Alt (unliftConc es a) (unliftConc es b) Empty -> I.Empty newtype Concurrently es a = Concurrently { runConcurrently :: Eff es a } instance Functor (Concurrently es) where fmap f (Concurrently a) = Concurrently (fmap f a) instance Concurrent :> es => Applicative (Concurrently es) where pure = Concurrently . pure Concurrently fs <*> Concurrently as = Concurrently ((\(f, a) -> f a) <$> concurrently fs as) instance Concurrent :> es => Alternative (Concurrently es) where empty = Concurrently . unsafeEff_ . forever $ threadDelay maxBound Concurrently as <|> Concurrently bs = Concurrently (either id id <$> race as bs) instance (Concurrent :> es, Semigroup a) => Semigroup (Concurrently es a) where (<>) = liftA2 (<>) instance (Concurrent :> es, Monoid a) => Monoid (Concurrently es a) where mempty = pure mempty liftAsync :: (IO a -> IO (Async a)) -> Eff es a -> Eff es (Async a) liftAsync fork action = unsafeEff $ \es -> do esA <- cloneEnv es fork $ unEff action esA liftAsyncWithUnmask :: (((forall b. IO b -> IO b) -> IO a) -> IO (Async a)) -> ((forall b. Eff es b -> Eff es b) -> Eff es a) -> Eff es (Async a) liftAsyncWithUnmask fork action = unsafeEff $ \es -> do esA <- cloneEnv es fork $ \unmask -> unEff (action $ reallyUnsafeLiftMapIO unmask) esA liftWithAsync :: (IO a -> (Async a -> IO b) -> IO b) -> Eff es a -> (Async a -> Eff es b) -> Eff es b liftWithAsync withA action k = unsafeEff $ \es -> do esA <- cloneEnv es withA (unEff action esA) (\a -> unEff (k a) es) liftWithAsyncWithUnmask :: (((forall c. IO c -> IO c) -> IO a) -> (Async a -> IO b) -> IO b) -> ((forall c. Eff es c -> Eff es c) -> Eff es a) -> (Async a -> Eff es b) -> Eff es b liftWithAsyncWithUnmask withA action k = unsafeEff $ \es -> do esA <- cloneEnv es withA (\unmask -> unEff (action $ reallyUnsafeLiftMapIO unmask) esA) (\a -> unEff (k a) es)
ad64597e60d0aeaf50c79d564be1f60dddbc97aa1df2655a8dd10311ffa2f35c
blindglobe/clocc
mop.lisp
;;;; Meta-Object Protocol ;;; Copyright ( C ) 2006 - 2007 by ;;; This is open-source software. GNU Lesser General Public License ( LGPL ) is applicable : ;;; No warranty; you may copy/modify/redistribute under the same ;;; conditions with the source code. ;;; See <URL:> ;;; for details and the precise copyright document. ;;; $ I d : mop.lisp , v 1.4 2007/09/21 16:49:37 sds Exp $ ;;; $Source: /cvsroot/clocc/clocc/src/port/mop.lisp,v $ (eval-when (:compile-toplevel :load-toplevel :execute) #-(or (and allegro (version>= 6)) (and clisp mop) cmu lucid lispworks sbcl scl) (error 'not-implemented :proc "Meta-Object Protocol") (require :port-ext (translate-logical-pathname "clocc:src;port;ext"))) (in-package #+(and allegro (version>= 6)) :clos #+(and clisp mop) :clos #+cmu :pcl #+lucid :clos #+lispworks :hcl #+sbcl :sb-pcl #+scl :clos) (let ((cl-user::mop-symbols '(METAOBJECT ;; + classes: ;; class names STANDARD-READER-METHOD STANDARD-WRITER-METHOD FORWARD-REFERENCED-CLASS ;; functions ENSURE-CLASS ;; generic functions CLASS-DIRECT-SUPERCLASSES CLASS-PRECEDENCE-LIST CLASS-DIRECT-SLOTS CLASS-SLOTS CLASS-DIRECT-DEFAULT-INITARGS CLASS-DEFAULT-INITARGS ;; customizable generic functions ;; for class creation: ENSURE-CLASS-USING-CLASS VALIDATE-SUPERCLASS COMPUTE-DIRECT-SLOT-DEFINITION-INITARGS COMPUTE-CLASS-PRECEDENCE-LIST COMPUTE-EFFECTIVE-SLOT-DEFINITION COMPUTE-EFFECTIVE-SLOT-DEFINITION-INITARGS COMPUTE-SLOTS COMPUTE-DEFAULT-INITARGS READER-METHOD-CLASS WRITER-METHOD-CLASS ;; for notification about subclasses: CLASS-DIRECT-SUBCLASSES ADD-DIRECT-SUBCLASS REMOVE-DIRECT-SUBCLASS ;; + generic Functions: ;; classes FUNCALLABLE-STANDARD-CLASS FUNCALLABLE-STANDARD-OBJECT ;; functions ENSURE-GENERIC-FUNCTION SET-FUNCALLABLE-INSTANCE-FUNCTION COMPUTE-EFFECTIVE-METHOD-AS-FUNCTION ;; generic functions GENERIC-FUNCTION-NAME GENERIC-FUNCTION-METHODS GENERIC-FUNCTION-METHOD-CLASS GENERIC-FUNCTION-LAMBDA-LIST GENERIC-FUNCTION-METHOD-COMBINATION GENERIC-FUNCTION-ARGUMENT-PRECEDENCE-ORDER GENERIC-FUNCTION-DECLARATIONS ;; customizable generic functions ENSURE-GENERIC-FUNCTION-USING-CLASS COMPUTE-DISCRIMINATING-FUNCTION COMPUTE-APPLICABLE-METHODS COMPUTE-APPLICABLE-METHODS-USING-CLASSES ;; + Methods: ;; generic functions METHOD-FUNCTION METHOD-GENERIC-FUNCTION METHOD-LAMBDA-LIST METHOD-SPECIALIZERS ACCESSOR-METHOD-SLOT-DEFINITION ;; functions EXTRACT-LAMBDA-LIST EXTRACT-SPECIALIZER-NAMES ;; + Method-Combinations: ;; generic function FIND-METHOD-COMBINATION ;; customizable generic function COMPUTE-EFFECTIVE-METHOD ;; + Slot-Definitions: ;; classes SLOT-DEFINITION STANDARD-SLOT-DEFINITION DIRECT-SLOT-DEFINITION STANDARD-DIRECT-SLOT-DEFINITION EFFECTIVE-SLOT-DEFINITION STANDARD-EFFECTIVE-SLOT-DEFINITION ;; generic functions SLOT-DEFINITION-NAME SLOT-DEFINITION-INITFORM SLOT-DEFINITION-INITFUNCTION SLOT-DEFINITION-TYPE SLOT-DEFINITION-ALLOCATION SLOT-DEFINITION-INITARGS SLOT-DEFINITION-READERS SLOT-DEFINITION-WRITERS SLOT-DEFINITION-LOCATION ;; customizable generic functions DIRECT-SLOT-DEFINITION-CLASS EFFECTIVE-SLOT-DEFINITION-CLASS + Specializers : ;; classes SPECIALIZER EQL-SPECIALIZER ;; generic functions SPECIALIZER-DIRECT-GENERIC-FUNCTIONS SPECIALIZER-DIRECT-METHODS ;; functions EQL-SPECIALIZER-OBJECT INTERN-EQL-SPECIALIZER ;; customizable generic functions ADD-DIRECT-METHOD REMOVE-DIRECT-METHOD ;; + Slot access: ;; generic functions SLOT-VALUE-USING-CLASS SLOT-BOUNDP-USING-CLASS SLOT-MAKUNBOUND-USING-CLASS ;; functions STANDARD-INSTANCE-ACCESS FUNCALLABLE-STANDARD-INSTANCE-ACCESS ;; + Dependent object notification: ;; functions MAP-DEPENDENTS ;; customizable generic functions ADD-DEPENDENT REMOVE-DEPENDENT UPDATE-DEPENDENT))) (import cl-user::mop-symbols :port) (export cl-user::mop-symbols :port)) (provide :port-mop) ;;; file mop.lisp ends here
null
https://raw.githubusercontent.com/blindglobe/clocc/a50bb75edb01039b282cf320e4505122a59c59a7/src/port/mop.lisp
lisp
Meta-Object Protocol This is open-source software. No warranty; you may copy/modify/redistribute under the same conditions with the source code. See <URL:> for details and the precise copyright document. $Source: /cvsroot/clocc/clocc/src/port/mop.lisp,v $ + classes: class names functions generic functions customizable generic functions for class creation: for notification about subclasses: + generic Functions: classes functions generic functions customizable generic functions + Methods: generic functions functions + Method-Combinations: generic function customizable generic function + Slot-Definitions: classes generic functions customizable generic functions classes generic functions functions customizable generic functions + Slot access: generic functions functions + Dependent object notification: functions customizable generic functions file mop.lisp ends here
Copyright ( C ) 2006 - 2007 by GNU Lesser General Public License ( LGPL ) is applicable : $ I d : mop.lisp , v 1.4 2007/09/21 16:49:37 sds Exp $ (eval-when (:compile-toplevel :load-toplevel :execute) #-(or (and allegro (version>= 6)) (and clisp mop) cmu lucid lispworks sbcl scl) (error 'not-implemented :proc "Meta-Object Protocol") (require :port-ext (translate-logical-pathname "clocc:src;port;ext"))) (in-package #+(and allegro (version>= 6)) :clos #+(and clisp mop) :clos #+cmu :pcl #+lucid :clos #+lispworks :hcl #+sbcl :sb-pcl #+scl :clos) (let ((cl-user::mop-symbols '(METAOBJECT STANDARD-READER-METHOD STANDARD-WRITER-METHOD FORWARD-REFERENCED-CLASS ENSURE-CLASS CLASS-DIRECT-SUPERCLASSES CLASS-PRECEDENCE-LIST CLASS-DIRECT-SLOTS CLASS-SLOTS CLASS-DIRECT-DEFAULT-INITARGS CLASS-DEFAULT-INITARGS ENSURE-CLASS-USING-CLASS VALIDATE-SUPERCLASS COMPUTE-DIRECT-SLOT-DEFINITION-INITARGS COMPUTE-CLASS-PRECEDENCE-LIST COMPUTE-EFFECTIVE-SLOT-DEFINITION COMPUTE-EFFECTIVE-SLOT-DEFINITION-INITARGS COMPUTE-SLOTS COMPUTE-DEFAULT-INITARGS READER-METHOD-CLASS WRITER-METHOD-CLASS CLASS-DIRECT-SUBCLASSES ADD-DIRECT-SUBCLASS REMOVE-DIRECT-SUBCLASS FUNCALLABLE-STANDARD-CLASS FUNCALLABLE-STANDARD-OBJECT ENSURE-GENERIC-FUNCTION SET-FUNCALLABLE-INSTANCE-FUNCTION COMPUTE-EFFECTIVE-METHOD-AS-FUNCTION GENERIC-FUNCTION-NAME GENERIC-FUNCTION-METHODS GENERIC-FUNCTION-METHOD-CLASS GENERIC-FUNCTION-LAMBDA-LIST GENERIC-FUNCTION-METHOD-COMBINATION GENERIC-FUNCTION-ARGUMENT-PRECEDENCE-ORDER GENERIC-FUNCTION-DECLARATIONS ENSURE-GENERIC-FUNCTION-USING-CLASS COMPUTE-DISCRIMINATING-FUNCTION COMPUTE-APPLICABLE-METHODS COMPUTE-APPLICABLE-METHODS-USING-CLASSES METHOD-FUNCTION METHOD-GENERIC-FUNCTION METHOD-LAMBDA-LIST METHOD-SPECIALIZERS ACCESSOR-METHOD-SLOT-DEFINITION EXTRACT-LAMBDA-LIST EXTRACT-SPECIALIZER-NAMES FIND-METHOD-COMBINATION COMPUTE-EFFECTIVE-METHOD SLOT-DEFINITION STANDARD-SLOT-DEFINITION DIRECT-SLOT-DEFINITION STANDARD-DIRECT-SLOT-DEFINITION EFFECTIVE-SLOT-DEFINITION STANDARD-EFFECTIVE-SLOT-DEFINITION SLOT-DEFINITION-NAME SLOT-DEFINITION-INITFORM SLOT-DEFINITION-INITFUNCTION SLOT-DEFINITION-TYPE SLOT-DEFINITION-ALLOCATION SLOT-DEFINITION-INITARGS SLOT-DEFINITION-READERS SLOT-DEFINITION-WRITERS SLOT-DEFINITION-LOCATION DIRECT-SLOT-DEFINITION-CLASS EFFECTIVE-SLOT-DEFINITION-CLASS + Specializers : SPECIALIZER EQL-SPECIALIZER SPECIALIZER-DIRECT-GENERIC-FUNCTIONS SPECIALIZER-DIRECT-METHODS EQL-SPECIALIZER-OBJECT INTERN-EQL-SPECIALIZER ADD-DIRECT-METHOD REMOVE-DIRECT-METHOD SLOT-VALUE-USING-CLASS SLOT-BOUNDP-USING-CLASS SLOT-MAKUNBOUND-USING-CLASS STANDARD-INSTANCE-ACCESS FUNCALLABLE-STANDARD-INSTANCE-ACCESS MAP-DEPENDENTS ADD-DEPENDENT REMOVE-DEPENDENT UPDATE-DEPENDENT))) (import cl-user::mop-symbols :port) (export cl-user::mop-symbols :port)) (provide :port-mop)
fdf7aec68add7a5abc7bfe04340786f5e571744149156f1cb5ba79b5efe2b989
cbaggers/rtg-math
docs-non-consing.lisp
(in-package :rtg-math.projection.non-consing) ;;------------------------------------------------------------ (docs:define-docs (defun orthographic " Creates a `mat4` and mutates it to be an orthographic projection matrix ") (defun orthographic-v2 " Creates a `mat4` and mutates it to be an orthographic projection matrix (with the frame size specified by a `vec2`) "))
null
https://raw.githubusercontent.com/cbaggers/rtg-math/29fc5b3d0028a4a11a82355ecc8cca62662c69e0/projection/orthographic/docs-non-consing.lisp
lisp
------------------------------------------------------------
(in-package :rtg-math.projection.non-consing) (docs:define-docs (defun orthographic " Creates a `mat4` and mutates it to be an orthographic projection matrix ") (defun orthographic-v2 " Creates a `mat4` and mutates it to be an orthographic projection matrix (with the frame size specified by a `vec2`) "))
8d030953129cfcf924d5056f8926a78c624ca077f363347757f8f09262e3fc76
djblue/portal
node.cljs
(ns portal.client.node (:require [clojure.string :as str] [portal.client.common :refer (->submit)])) (defn fetch [url options] (let [https? (str/starts-with? url "https") http (js/require (str "http" (when https? "s")))] (js/Promise. (fn [resolve reject] (let [req (.request http url (clj->js options) (fn [res] (let [body (atom "")] (.on res "data" #(swap! body str %)) (.on res "error" reject) (.on res "end" #(resolve {:status (.-statusCode res) :body @body})))))] (.write req (:body options)) (.end req)))))) (def submit (->submit fetch)) (comment (submit {:runtime :node :value "hello node"}) (add-tap submit) (tap> {:runtime :node :value "hello node-tap"}) (add-tap submit))
null
https://raw.githubusercontent.com/djblue/portal/3119a24deba91c69dedf25a7048581d6c75ab3f6/src/portal/client/node.cljs
clojure
(ns portal.client.node (:require [clojure.string :as str] [portal.client.common :refer (->submit)])) (defn fetch [url options] (let [https? (str/starts-with? url "https") http (js/require (str "http" (when https? "s")))] (js/Promise. (fn [resolve reject] (let [req (.request http url (clj->js options) (fn [res] (let [body (atom "")] (.on res "data" #(swap! body str %)) (.on res "error" reject) (.on res "end" #(resolve {:status (.-statusCode res) :body @body})))))] (.write req (:body options)) (.end req)))))) (def submit (->submit fetch)) (comment (submit {:runtime :node :value "hello node"}) (add-tap submit) (tap> {:runtime :node :value "hello node-tap"}) (add-tap submit))
1ee5dde22056c1faef09d7035cd5ab13668489138678da145ab946e5b01c5f22
mukul-rathi/bolt
good_comments.ml
open Core open Print_typed_ast let%expect_test "Comments interspersed with code" = print_typed_ast " void main(){ /* This is a comment - it should not be parsed */ let x = 4;// Can occur after a line let y /*Or even midway*/ = 5; /* Or before */ x /* Comments Can Span Multiple Lines */ } " ; [%expect {| Program └──Main block └──Type expr: Int └──Expr: Let var: x └──Type expr: Int └──Expr: Int:4 └──Expr: Let var: y └──Type expr: Int └──Expr: Int:5 └──Expr: Variable: x └──Type expr: Int |}]
null
https://raw.githubusercontent.com/mukul-rathi/bolt/1faf19d698852fdb6af2ee005a5f036ee1c76503/tests/frontend/expect/typing/good_comments.ml
ocaml
open Core open Print_typed_ast let%expect_test "Comments interspersed with code" = print_typed_ast " void main(){ /* This is a comment - it should not be parsed */ let x = 4;// Can occur after a line let y /*Or even midway*/ = 5; /* Or before */ x /* Comments Can Span Multiple Lines */ } " ; [%expect {| Program └──Main block └──Type expr: Int └──Expr: Let var: x └──Type expr: Int └──Expr: Int:4 └──Expr: Let var: y └──Type expr: Int └──Expr: Int:5 └──Expr: Variable: x └──Type expr: Int |}]
5798e7b056f3a35b97a5b64fb2b3ad960960899e581881b69daae339b733a6bd
den1k/vimsical
db.cljc
(ns vimsical.frontend.vcs.db (:require [clojure.spec.alpha :as s] [vimsical.vcs.core :as vcs] [vimsical.vcs.branch :as branch] [vimsical.vcs.delta :as delta] [vimsical.vcs.state.timeline :as timeline] [vimsical.frontend.util.subgraph :as util.sg])) (s/def ::branch-uid ::branch/uid) (s/def ::delta-uid ::delta/prev-uid) (s/def ::playhead-entry (s/nilable ::timeline/entry)) (s/def ::skimhead-entry (s/nilable ::timeline/entry)) (s/def ::state (s/keys :req [::branch-uid ::delta-uid] :opt [::playhead-entry ::skimhead-entry])) (s/def ::vcs (s/merge ::vcs/vcs ::state )) (s/fdef get-playhead-entry :args (s/cat :vcs ::vcs) :ret ::playhead-entry) (defn get-playhead-entry [vcs] (get vcs ::playhead-entry)) (s/fdef set-playhead-entry :args (s/cat :vcs ::vcs :entry ::playhead-entry) :ret ::vcs) (defn set-playhead-entry [{::vcs/keys [branches] :as vcs} [_ {:keys [branch-uid]} :as entry]] (assoc vcs ::playhead-entry entry ::branch-uid (if entry branch-uid (-> branches branch/master :db/uid)))) (s/fdef get-skimhead-entry :args (s/cat :vcs ::vcs) :ret ::skimhead-entry) (defn get-skimhead-entry [vcs] (get vcs ::skimhead-entry)) (s/fdef set-skimhead-entry :args (s/cat :vcs ::vcs :entry ::skimhead-entry) :ret ::vcs) (defn set-skimhead-entry [vcs entry] (assoc vcs ::skimhead-entry entry)) ;; ;; * VCS Normalization ;; ;; NOTE sg/add will recursively traverse a datastructure looking for entities, eventhough the vcs is normalized in the db , this fn gets expensive as the vcs ;; gets large. So far the vcs only contains references for branches in : : vcs / branches making it simple to manually normalize and assoc into the db (defn- normalize [db vcs] (update vcs ::vcs/branches (fn [branches] (mapv (partial util.sg/->ref db) branches)))) (defn add [db vcs] (let [ref (util.sg/->ref db vcs) normd (normalize db vcs)] (assoc db ref normd)))
null
https://raw.githubusercontent.com/den1k/vimsical/1e4a1f1297849b1121baf24bdb7a0c6ba3558954/src/frontend/vimsical/frontend/vcs/db.cljc
clojure
* VCS Normalization NOTE sg/add will recursively traverse a datastructure looking for entities, gets large. So far the vcs only contains references for branches in
(ns vimsical.frontend.vcs.db (:require [clojure.spec.alpha :as s] [vimsical.vcs.core :as vcs] [vimsical.vcs.branch :as branch] [vimsical.vcs.delta :as delta] [vimsical.vcs.state.timeline :as timeline] [vimsical.frontend.util.subgraph :as util.sg])) (s/def ::branch-uid ::branch/uid) (s/def ::delta-uid ::delta/prev-uid) (s/def ::playhead-entry (s/nilable ::timeline/entry)) (s/def ::skimhead-entry (s/nilable ::timeline/entry)) (s/def ::state (s/keys :req [::branch-uid ::delta-uid] :opt [::playhead-entry ::skimhead-entry])) (s/def ::vcs (s/merge ::vcs/vcs ::state )) (s/fdef get-playhead-entry :args (s/cat :vcs ::vcs) :ret ::playhead-entry) (defn get-playhead-entry [vcs] (get vcs ::playhead-entry)) (s/fdef set-playhead-entry :args (s/cat :vcs ::vcs :entry ::playhead-entry) :ret ::vcs) (defn set-playhead-entry [{::vcs/keys [branches] :as vcs} [_ {:keys [branch-uid]} :as entry]] (assoc vcs ::playhead-entry entry ::branch-uid (if entry branch-uid (-> branches branch/master :db/uid)))) (s/fdef get-skimhead-entry :args (s/cat :vcs ::vcs) :ret ::skimhead-entry) (defn get-skimhead-entry [vcs] (get vcs ::skimhead-entry)) (s/fdef set-skimhead-entry :args (s/cat :vcs ::vcs :entry ::skimhead-entry) :ret ::vcs) (defn set-skimhead-entry [vcs entry] (assoc vcs ::skimhead-entry entry)) eventhough the vcs is normalized in the db , this fn gets expensive as the vcs : : vcs / branches making it simple to manually normalize and assoc into the db (defn- normalize [db vcs] (update vcs ::vcs/branches (fn [branches] (mapv (partial util.sg/->ref db) branches)))) (defn add [db vcs] (let [ref (util.sg/->ref db vcs) normd (normalize db vcs)] (assoc db ref normd)))
bb224bed6758837d9882c438163cf0f25b077adac73b875ff2037905f6c0382a
aroemers/rmap
project.clj
(defproject functionalbytes/rmap "2.2.0" :description "A Clojure library to define recursive maps." :url "" :license {:name "Eclipse Public License" :url "-v10.html"} :dependencies [[org.clojure/clojure "1.8.0"]])
null
https://raw.githubusercontent.com/aroemers/rmap/017c628f1e393cd73145ae61861706520c053c97/project.clj
clojure
(defproject functionalbytes/rmap "2.2.0" :description "A Clojure library to define recursive maps." :url "" :license {:name "Eclipse Public License" :url "-v10.html"} :dependencies [[org.clojure/clojure "1.8.0"]])
d86e5314fdeab4ff6c241653575d63548d4592e4fe2f74ca26f8d358cba1af31
utkarshkukreti/bs-preact
RouterRaw.ml
module P = Preact module RouterRaw = struct let make = fun [@preact.component "RouterRaw"] () -> let[@hook] url = P.Router.Url.use P.Router.Hash in let push string _ = P.Router.Url.push P.Router.Hash (P.Router.Url.fromString string) in let replace string _ = P.Router.Url.replace P.Router.Hash (P.Router.Url.fromString string) in P.div [ P.style "text-align" "center" ] [ P.button [ P.onClick (push "/foo") ] [ P.string "PUSH /foo" ] ; P.button [ P.onClick (push "/bar") ] [ P.string "PUSH /bar" ] ; P.button [ P.onClick (replace "/foo") ] [ P.string "REPLACE /foo" ] ; P.button [ P.onClick (replace "/bar") ] [ P.string "REPLACE /bar" ] ; P.h3 [] [ P.string (P.Router.Url.toString P.Router.Hash url) ] ] end let main = RouterRaw.make () let () = match P.find "main" with | Some element -> P.render main element | None -> Js.Console.error "<main> not found!"
null
https://raw.githubusercontent.com/utkarshkukreti/bs-preact/61d10d40543e1f8fc83b8a82f6353bcb52489c91/examples/RouterRaw.ml
ocaml
module P = Preact module RouterRaw = struct let make = fun [@preact.component "RouterRaw"] () -> let[@hook] url = P.Router.Url.use P.Router.Hash in let push string _ = P.Router.Url.push P.Router.Hash (P.Router.Url.fromString string) in let replace string _ = P.Router.Url.replace P.Router.Hash (P.Router.Url.fromString string) in P.div [ P.style "text-align" "center" ] [ P.button [ P.onClick (push "/foo") ] [ P.string "PUSH /foo" ] ; P.button [ P.onClick (push "/bar") ] [ P.string "PUSH /bar" ] ; P.button [ P.onClick (replace "/foo") ] [ P.string "REPLACE /foo" ] ; P.button [ P.onClick (replace "/bar") ] [ P.string "REPLACE /bar" ] ; P.h3 [] [ P.string (P.Router.Url.toString P.Router.Hash url) ] ] end let main = RouterRaw.make () let () = match P.find "main" with | Some element -> P.render main element | None -> Js.Console.error "<main> not found!"
249f118d634a5c7c97511cf32d6aa8aaa4b937ac367632a7076ef4cd7f81a9e4
RaphaelJ/friday
Interpolate.hs
{-# LANGUAGE BangPatterns , FlexibleContexts #-} -- | Provides a way to estimate the value of a pixel at rational coordinates -- using a linear interpolation. module Vision.Image.Interpolate ( Interpolable (..), bilinearInterpol ) where import Data.Int import Data.RatioInt (denominator, numerator) import Data.Word import Vision.Image.Class (Pixel (..), Image (..), ImagePixel, ImageChannel) import Vision.Primitive (RPoint (..), ix2) -- | Provides a way to apply the interpolation to every component of a pixel. class Interpolable p where | Given a function which interpolates two points over a single channel , returns a function which interpolates two points over every channel of two pixels . interpol :: (PixelChannel p -> PixelChannel p -> PixelChannel p) -> p -> p -> p instance Interpolable Int16 where interpol = id instance Interpolable Int32 where interpol = id instance Interpolable Int where interpol = id instance Interpolable Word8 where interpol = id instance Interpolable Word16 where interpol = id instance Interpolable Word32 where interpol = id instance Interpolable Word where interpol = id instance Interpolable Float where interpol = id instance Interpolable Double where interpol = id instance Interpolable Bool where interpol = id -- | Uses a bilinear interpolation to find the value of the pixel at the -- rational coordinates. -- Estimates the value of a rational point using @a@ , @b@ , @c@ and @d@ : -- -- @ -- x1 x2 -- -- y1 a ------ b -- - - -- - p - -- - - -- y2 c ------ d -- @ bilinearInterpol :: (Image i, Interpolable (ImagePixel i) , Integral (ImageChannel i)) => i -> RPoint -> ImagePixel i img `bilinearInterpol` RPoint x y | not integralX && not integralY = let (!x1, !deltaX1) = properFraction x (!y1, !deltaY1) = properFraction y !x2 = x1 + 1 !y2 = y1 + 1 !a = img `index` ix2 y1 x1 !b = img `index` ix2 y1 x2 !c = img `index` ix2 y2 x1 !d = img `index` ix2 y2 x2 Computes the relative distance to the four points . !deltaX2 = compl deltaX1 !deltaY2 = compl deltaY1 !interpolX1 = interpol (interpolChannel deltaX1 deltaX2) a b !interpolX2 = interpol (interpolChannel deltaX1 deltaX2) c d in interpol (interpolChannel deltaY1 deltaY2) interpolX1 interpolX2 | not integralX = let (!x1, !deltaX1) = properFraction x !y1 = truncate y !x2 = x1 + 1 !a = img `index` ix2 y1 x1 !b = img `index` ix2 y1 x2 !deltaX2 = compl deltaX1 in interpol (interpolChannel deltaX1 deltaX2) a b | not integralY = let !x1 = truncate x (!y1, !deltaY1) = properFraction y !y2 = y1 + 1 !a = img `index` ix2 y1 x1 !c = img `index` ix2 y2 x1 !deltaY2 = compl deltaY1 in interpol (interpolChannel deltaY1 deltaY2) a c | otherwise = img `index` ix2 (numerator y) (numerator x) where integralX = denominator x == 1 integralY = denominator y == 1 compl delta = 1 - delta compl delta = delta { numerator = denominator delta - numerator delta } # INLINE compl # Interpolates the value of a single channel given its two surrounding -- points. interpolChannel deltaA deltaB chanA chanB = truncate $ -- (fromIntegral chanA) * deltaB + (fromIntegral chanB) * deltaA -- deltaB { numerator = int chanA * numerator deltaB } -- + deltaA { numerator = int chanB * numerator deltaA } deltaA { numerator = int chanA * numerator deltaB + int chanB * numerator deltaA } # INLINE interpolChannel # # INLINE bilinearInterpol # int :: Integral a => a -> Int int = fromIntegral
null
https://raw.githubusercontent.com/RaphaelJ/friday/13c6bb16bb04856e0cb226726017e7a7ad502cb5/src/Vision/Image/Interpolate.hs
haskell
# LANGUAGE BangPatterns , FlexibleContexts # | Provides a way to estimate the value of a pixel at rational coordinates using a linear interpolation. | Provides a way to apply the interpolation to every component of a pixel. | Uses a bilinear interpolation to find the value of the pixel at the rational coordinates. @ x1 x2 y1 a ------ b - - - p - - - y2 c ------ d @ points. (fromIntegral chanA) * deltaB + (fromIntegral chanB) * deltaA deltaB { numerator = int chanA * numerator deltaB } + deltaA { numerator = int chanB * numerator deltaA }
module Vision.Image.Interpolate ( Interpolable (..), bilinearInterpol ) where import Data.Int import Data.RatioInt (denominator, numerator) import Data.Word import Vision.Image.Class (Pixel (..), Image (..), ImagePixel, ImageChannel) import Vision.Primitive (RPoint (..), ix2) class Interpolable p where | Given a function which interpolates two points over a single channel , returns a function which interpolates two points over every channel of two pixels . interpol :: (PixelChannel p -> PixelChannel p -> PixelChannel p) -> p -> p -> p instance Interpolable Int16 where interpol = id instance Interpolable Int32 where interpol = id instance Interpolable Int where interpol = id instance Interpolable Word8 where interpol = id instance Interpolable Word16 where interpol = id instance Interpolable Word32 where interpol = id instance Interpolable Word where interpol = id instance Interpolable Float where interpol = id instance Interpolable Double where interpol = id instance Interpolable Bool where interpol = id Estimates the value of a rational point using @a@ , @b@ , @c@ and @d@ : bilinearInterpol :: (Image i, Interpolable (ImagePixel i) , Integral (ImageChannel i)) => i -> RPoint -> ImagePixel i img `bilinearInterpol` RPoint x y | not integralX && not integralY = let (!x1, !deltaX1) = properFraction x (!y1, !deltaY1) = properFraction y !x2 = x1 + 1 !y2 = y1 + 1 !a = img `index` ix2 y1 x1 !b = img `index` ix2 y1 x2 !c = img `index` ix2 y2 x1 !d = img `index` ix2 y2 x2 Computes the relative distance to the four points . !deltaX2 = compl deltaX1 !deltaY2 = compl deltaY1 !interpolX1 = interpol (interpolChannel deltaX1 deltaX2) a b !interpolX2 = interpol (interpolChannel deltaX1 deltaX2) c d in interpol (interpolChannel deltaY1 deltaY2) interpolX1 interpolX2 | not integralX = let (!x1, !deltaX1) = properFraction x !y1 = truncate y !x2 = x1 + 1 !a = img `index` ix2 y1 x1 !b = img `index` ix2 y1 x2 !deltaX2 = compl deltaX1 in interpol (interpolChannel deltaX1 deltaX2) a b | not integralY = let !x1 = truncate x (!y1, !deltaY1) = properFraction y !y2 = y1 + 1 !a = img `index` ix2 y1 x1 !c = img `index` ix2 y2 x1 !deltaY2 = compl deltaY1 in interpol (interpolChannel deltaY1 deltaY2) a c | otherwise = img `index` ix2 (numerator y) (numerator x) where integralX = denominator x == 1 integralY = denominator y == 1 compl delta = 1 - delta compl delta = delta { numerator = denominator delta - numerator delta } # INLINE compl # Interpolates the value of a single channel given its two surrounding interpolChannel deltaA deltaB chanA chanB = truncate $ deltaA { numerator = int chanA * numerator deltaB + int chanB * numerator deltaA } # INLINE interpolChannel # # INLINE bilinearInterpol # int :: Integral a => a -> Int int = fromIntegral
bfb1be98caf46a7e812591690cff1a1494af4715c79bc77dd0ba8915e64bb9b6
metabase/metabase
parameters_test.clj
(ns metabase.query-processor.middleware.parameters-test "Testings to make sure the parameter substitution middleware works as expected. Even though the below tests are SQL-specific, they still confirm that the middleware itself is working correctly." (:require [clojure.test :refer :all] [metabase.driver :as driver] [metabase.mbql.normalize :as mbql.normalize] [metabase.models.card :refer [Card]] [metabase.models.native-query-snippet :refer [NativeQuerySnippet]] [metabase.query-processor.middleware.parameters :as parameters] [metabase.test :as mt] [metabase.util :as u] #_{:clj-kondo/ignore [:discouraged-namespace]} [metabase.util.honeysql-extensions :as hx] [metabase.util.schema :as su] [schema.core :as s]) (:import (clojure.lang ExceptionInfo))) (use-fixtures :each (fn [thunk] Make sure we 're in Honey SQL 2 mode for all the little SQL snippets we 're compiling in these ;; tests. (binding [#_{:clj-kondo/ignore [:deprecated-var]} hx/*honey-sql-version* 2] (thunk)))) (deftest ^:parallel move-top-level-params-to-inner-query-test (is (= {:type :native :native {:query "WOW", :parameters ["My Param"]} :user-parameters ["My Param"]} (#'parameters/move-top-level-params-to-inner-query {:type :native, :native {:query "WOW"}, :parameters ["My Param"]})))) (defn- substitute-params [query] (driver/with-driver :h2 (parameters/substitute-parameters (mbql.normalize/normalize query)))) (deftest ^:parallel expand-mbql-top-level-params-test (testing "can we expand MBQL params if they are specified at the top level?" (is (= (mt/mbql-query venues {:aggregation [[:count]] :filter [:= $price 1]}) (substitute-params (mt/mbql-query venues {:aggregation [[:count]] :parameters [{:name "price", :type :category, :target $price, :value 1}]})))))) (deftest ^:parallel expand-native-top-level-params-test (testing "can we expand native params if they are specified at the top level?" (is (= (mt/query nil {:type :native :native {:query "SELECT * FROM venues WHERE price = 1;", :params []} :user-parameters [{:type :category, :target [:variable [:template-tag "price"]], :value "1"}]}) (substitute-params (mt/query nil {:type :native :native {:query "SELECT * FROM venues WHERE price = {{price}};" :template-tags {"price" {:name "price", :display-name "Price", :type :number}}} :parameters [{:type "category", :target [:variable [:template-tag "price"]], :value "1"}]})))))) (deftest ^:parallel expand-mbql-source-query-params-test (testing "can we expand MBQL params in a source query?" (is (= (mt/mbql-query venues {:source-query {:source-table $$venues :filter [:= $price 1]} :aggregation [[:count]]}) (substitute-params (mt/mbql-query venues {:source-query {:source-table $$venues :parameters [{:name "price", :type :category, :target $price, :value 1}]} :aggregation [[:count]]})))))) (deftest ^:parallel expand-native-source-query-params-test (testing "can we expand native params if in a source query?" (is (= (mt/mbql-query nil {:source-query {:native "SELECT * FROM categories WHERE name = ?;" :params ["BBQ"]}}) (substitute-params (mt/mbql-query nil {:source-query {:native "SELECT * FROM categories WHERE name = {{cat}};" :template-tags {"cat" {:name "cat", :display-name "Category", :type :text}} :parameters [{:type "category", :target [:variable [:template-tag "cat"]], :value "BBQ"}]}})))))) (deftest ^:parallel expand-mbql-join-params-test (testing "can we expand MBQL params in a JOIN?" (is (= (mt/mbql-query venues {:aggregation [[:count]] :joins [{:source-query {:source-table $$categories :filter [:= $categories.name "BBQ"]} :alias "c" :condition [:= $category_id &c.categories.id]}]}) (substitute-params (mt/mbql-query venues {:aggregation [[:count]] :joins [{:source-table $$categories :alias "c" :condition [:= $category_id &c.categories.id] :parameters [{:type "category", :target $categories.name, :value "BBQ"}]}]})))))) (deftest ^:parallel expand-native-join-params-test (testing "can we expand native params in a JOIN?" (is (= (mt/mbql-query venues {:aggregation [[:count]] :joins [{:source-query {:native "SELECT * FROM categories WHERE name = ?;" :params ["BBQ"]} :alias "c" :condition [:= $category_id &c.*categories.id]}]}) (substitute-params (mt/mbql-query venues {:aggregation [[:count]] :joins [{:source-query {:native "SELECT * FROM categories WHERE name = {{cat}};" :template-tags {"cat" {:name "cat", :display-name "Category", :type :text}} :parameters [{:type "category", :target [:variable [:template-tag "cat"]], :value "BBQ"}]} :alias "c" :condition [:= $category_id &c.*categories.id]}]})))))) (deftest ^:parallel expand-multiple-mbql-params-test (testing "can we expand multiple sets of MBQL params?" (is (= (mt/mbql-query venues {:source-query {:source-table $$venues :filter [:= $price 1]} :aggregation [[:count]] :joins [{:source-query {:source-table $$categories :filter [:= $categories.name "BBQ"]} :alias "c" :condition [:= $category_id &c.categories.id]}]}) (substitute-params (mt/mbql-query venues {:source-query {:source-table $$venues :parameters [{:name "price", :type :category, :target $price, :value 1}]} :aggregation [[:count]] :joins [{:source-table $$categories :alias "c" :condition [:= $category_id &c.categories.id] :parameters [{:type "category", :target $categories.name, :value "BBQ"}]}]})))))) (deftest ^:parallel expand-multiple-mbql-params-in-joins-test ;; (This is dumb. Hopefully no one is creating queries like this. The `:parameters` should go in the source query ;; instead of in the join.) (testing "can we expand multiple sets of MBQL params with params in a join and the join's source query?" (is (= (mt/mbql-query venues {:aggregation [[:count]] :joins [{:source-query {:source-table $$categories :filter [:and [:= $categories.name "BBQ"] [:= $categories.id 5]]} :alias "c" :condition [:= $category_id &c.categories.id]}]}) (substitute-params (mt/mbql-query venues {:aggregation [[:count]] :joins [{:source-query {:source-table $$categories :parameters [{:name "id", :type :category, :target $categories.id, :value 5}]} :alias "c" :condition [:= $category_id &c.categories.id] :parameters [{:type "category", :target $categories.name, :value "BBQ"}]}]})))))) (defn- card-template-tag [card-id] (let [tag (str "#" card-id)] {:id tag, :name tag, :display-name tag, :type "card", :card-id card-id})) (defn card-template-tags "Generate the map representing card template tags (sub-queries) for the given `card-ids`." [card-ids] (into {} (for [card-id card-ids] [(str "#" card-id) (card-template-tag card-id)]))) (deftest expand-multiple-referenced-cards-in-template-tags (testing "multiple sub-queries, referenced in template tags, are correctly substituted" (mt/with-temp* [Card [card-1 {:dataset_query (mt/native-query {:query "SELECT 1"})}] Card [card-2 {:dataset_query (mt/native-query {:query "SELECT 2"})}]] (let [card-1-id (:id card-1) card-2-id (:id card-2)] (is (= (mt/native-query {:query "SELECT COUNT(*) FROM (SELECT 1) AS c1, (SELECT 2) AS c2", :params []}) (substitute-params (mt/native-query {:query (str "SELECT COUNT(*) FROM {{#" card-1-id "}} AS c1, {{#" card-2-id "}} AS c2") :template-tags (card-template-tags [card-1-id card-2-id])}))))))) (testing "multiple CTE queries, referenced in template tags, are correctly substituted" (mt/with-temp* [Card [card-1 {:dataset_query (mt/native-query {:query "SELECT 1"})}] Card [card-2 {:dataset_query (mt/native-query {:query "SELECT 2"})}]] (let [card-1-id (:id card-1) card-2-id (:id card-2)] (is (= (mt/native-query {:query "WITH c1 AS (SELECT 1), c2 AS (SELECT 2) SELECT COUNT(*) FROM c1, c2", :params []}) (substitute-params (mt/native-query {:query (str "WITH c1 AS {{#" card-1-id "}}, " "c2 AS {{#" card-2-id "}} SELECT COUNT(*) FROM c1, c2") :template-tags (card-template-tags [card-1-id card-2-id])}))))))) (testing "recursive native queries, referenced in template tags, are correctly substituted" (mt/with-temp* [Card [card-1 {:dataset_query (mt/native-query {:query "SELECT 1"})}] Card [card-2 {:dataset_query (mt/native-query {:query (str "SELECT * FROM {{#" (:id card-1) "}} AS c1") :template-tags (card-template-tags [(:id card-1)])})}]] (let [card-2-id (:id card-2)] (is (= (mt/native-query {:query "SELECT COUNT(*) FROM (SELECT * FROM (SELECT 1) AS c1) AS c2", :params []}) (substitute-params (mt/native-query {:query (str "SELECT COUNT(*) FROM {{#" card-2-id "}} AS c2") :template-tags (card-template-tags [card-2-id])}))))))) (testing "recursive native/MBQL queries, referenced in template tags, are correctly substituted" (mt/with-temp* [Card [card-1 {:dataset_query (mt/mbql-query venues)}] Card [card-2 {:dataset_query (mt/native-query {:query (str "SELECT * FROM {{#" (:id card-1) "}} AS c1") :template-tags (card-template-tags [(:id card-1)])})}]] (let [card-2-id (:id card-2) card-1-subquery (str "SELECT " "\"PUBLIC\".\"VENUES\".\"ID\" AS \"ID\", " "\"PUBLIC\".\"VENUES\".\"NAME\" AS \"NAME\", " "\"PUBLIC\".\"VENUES\".\"CATEGORY_ID\" AS \"CATEGORY_ID\", " "\"PUBLIC\".\"VENUES\".\"LATITUDE\" AS \"LATITUDE\", " "\"PUBLIC\".\"VENUES\".\"LONGITUDE\" AS \"LONGITUDE\", " "\"PUBLIC\".\"VENUES\".\"PRICE\" AS \"PRICE\" " "FROM \"PUBLIC\".\"VENUES\" " "LIMIT 1048575")] (is (= (mt/native-query {:query (str "SELECT COUNT(*) FROM (SELECT * FROM (" card-1-subquery ") AS c1) AS c2") :params []}) (substitute-params (mt/native-query {:query (str "SELECT COUNT(*) FROM {{#" card-2-id "}} AS c2") :template-tags (card-template-tags [card-2-id])})))))))) (deftest referencing-cards-with-parameters-test (testing "referencing card with parameter and default value substitutes correctly" (mt/with-temp Card [param-card {:dataset_query (mt/native-query {:query "SELECT {{x}}" :template-tags {"x" {:id "x", :name "x", :display-name "Number x", :type :number, :default "1", :required true}}})}] (is (= (mt/native-query {:query "SELECT * FROM (SELECT 1) AS x", :params []}) (substitute-params (mt/native-query {:query (str "SELECT * FROM {{#" (:id param-card) "}} AS x") :template-tags (card-template-tags [(:id param-card)])})))))) (testing "referencing card with parameter and NO default value, fails substitution" (mt/with-temp Card [param-card {:dataset_query (mt/native-query {:query "SELECT {{x}}" :template-tags {"x" {:id "x", :name "x", :display-name "Number x", :type :number, :required false}}})}] (is (thrown? ExceptionInfo (substitute-params (mt/native-query {:query (str "SELECT * FROM {{#" (:id param-card) "}} AS x") :template-tags (card-template-tags [(:id param-card)])}))))))) (defn- snippet-template-tags [snippet-name->id] (into {} (for [[snippet-name snippet-id] snippet-name->id] [snippet-name {:name snippet-name :display-name snippet-name :type :snippet :snippet-name snippet-name :snippet-id snippet-id}]))) (deftest expand-multiple-snippets-test (mt/with-temp* [NativeQuerySnippet [select-snippet {:content "name, price" :creator_id (mt/user->id :rasta) :description "Fields to SELECT" :name "Venue fields"}] NativeQuerySnippet [where-snippet {:content "price > 2" :creator_id (mt/user->id :rasta) :description "Meant for use in WHERE clause" :name "Filter: expensive venues"}] Card [card {:dataset_query (mt/native-query {:query (str "SELECT {{ Venue fields }} " "FROM venues " "WHERE {{ Filter: expensive venues }}") :template-tags (snippet-template-tags {"Venue fields" (:id select-snippet) "Filter: expensive venues" (:id where-snippet)})})}]] (testing "multiple snippets are correctly expanded in parent query" (is (= (mt/native-query {:query "SELECT name, price FROM venues WHERE price > 2", :params nil}) (substitute-params (:dataset_query card))))) (testing "multiple snippets are expanded from saved sub-query" (is (= (mt/native-query {:query "SELECT * FROM (SELECT name, price FROM venues WHERE price > 2) AS x", :params []}) (substitute-params (mt/native-query {:query (str "SELECT * FROM {{#" (:id card) "}} AS x") :template-tags (card-template-tags [(:id card)])}))))))) (deftest include-card-parameters-test (testing "Expanding a Card reference should include its parameters (#12236)" (mt/dataset sample-dataset (mt/with-temp Card [card {:dataset_query (mt/mbql-query orders {:filter [:between $total 30 60] :aggregation [[:aggregation-options [:count-where [:starts-with $product_id->products.category "G"]] {:name "G Monies", :display-name "G Monies"}]] :breakout [!month.created_at]})}] (let [card-tag (str "#" (u/the-id card)) query (mt/native-query {:query (format "SELECT * FROM {{%s}}" card-tag) :template-tags {card-tag {:id "5aa37572-058f-14f6-179d-a158ad6c029d" :name card-tag :display-name card-tag :type :card :card-id (u/the-id card)}}})] (is (schema= {:native {:query su/NonBlankString :params (s/eq ["G%"]) s/Keyword s/Any} s/Keyword s/Any} (substitute-params query))))))))
null
https://raw.githubusercontent.com/metabase/metabase/0c56664819bb84a7a317caf0fc393d2fa1bf3ccd/test/metabase/query_processor/middleware/parameters_test.clj
clojure
tests. (This is dumb. Hopefully no one is creating queries like this. The `:parameters` should go in the source query instead of in the join.)
(ns metabase.query-processor.middleware.parameters-test "Testings to make sure the parameter substitution middleware works as expected. Even though the below tests are SQL-specific, they still confirm that the middleware itself is working correctly." (:require [clojure.test :refer :all] [metabase.driver :as driver] [metabase.mbql.normalize :as mbql.normalize] [metabase.models.card :refer [Card]] [metabase.models.native-query-snippet :refer [NativeQuerySnippet]] [metabase.query-processor.middleware.parameters :as parameters] [metabase.test :as mt] [metabase.util :as u] #_{:clj-kondo/ignore [:discouraged-namespace]} [metabase.util.honeysql-extensions :as hx] [metabase.util.schema :as su] [schema.core :as s]) (:import (clojure.lang ExceptionInfo))) (use-fixtures :each (fn [thunk] Make sure we 're in Honey SQL 2 mode for all the little SQL snippets we 're compiling in these (binding [#_{:clj-kondo/ignore [:deprecated-var]} hx/*honey-sql-version* 2] (thunk)))) (deftest ^:parallel move-top-level-params-to-inner-query-test (is (= {:type :native :native {:query "WOW", :parameters ["My Param"]} :user-parameters ["My Param"]} (#'parameters/move-top-level-params-to-inner-query {:type :native, :native {:query "WOW"}, :parameters ["My Param"]})))) (defn- substitute-params [query] (driver/with-driver :h2 (parameters/substitute-parameters (mbql.normalize/normalize query)))) (deftest ^:parallel expand-mbql-top-level-params-test (testing "can we expand MBQL params if they are specified at the top level?" (is (= (mt/mbql-query venues {:aggregation [[:count]] :filter [:= $price 1]}) (substitute-params (mt/mbql-query venues {:aggregation [[:count]] :parameters [{:name "price", :type :category, :target $price, :value 1}]})))))) (deftest ^:parallel expand-native-top-level-params-test (testing "can we expand native params if they are specified at the top level?" (is (= (mt/query nil {:type :native :native {:query "SELECT * FROM venues WHERE price = 1;", :params []} :user-parameters [{:type :category, :target [:variable [:template-tag "price"]], :value "1"}]}) (substitute-params (mt/query nil {:type :native :native {:query "SELECT * FROM venues WHERE price = {{price}};" :template-tags {"price" {:name "price", :display-name "Price", :type :number}}} :parameters [{:type "category", :target [:variable [:template-tag "price"]], :value "1"}]})))))) (deftest ^:parallel expand-mbql-source-query-params-test (testing "can we expand MBQL params in a source query?" (is (= (mt/mbql-query venues {:source-query {:source-table $$venues :filter [:= $price 1]} :aggregation [[:count]]}) (substitute-params (mt/mbql-query venues {:source-query {:source-table $$venues :parameters [{:name "price", :type :category, :target $price, :value 1}]} :aggregation [[:count]]})))))) (deftest ^:parallel expand-native-source-query-params-test (testing "can we expand native params if in a source query?" (is (= (mt/mbql-query nil {:source-query {:native "SELECT * FROM categories WHERE name = ?;" :params ["BBQ"]}}) (substitute-params (mt/mbql-query nil {:source-query {:native "SELECT * FROM categories WHERE name = {{cat}};" :template-tags {"cat" {:name "cat", :display-name "Category", :type :text}} :parameters [{:type "category", :target [:variable [:template-tag "cat"]], :value "BBQ"}]}})))))) (deftest ^:parallel expand-mbql-join-params-test (testing "can we expand MBQL params in a JOIN?" (is (= (mt/mbql-query venues {:aggregation [[:count]] :joins [{:source-query {:source-table $$categories :filter [:= $categories.name "BBQ"]} :alias "c" :condition [:= $category_id &c.categories.id]}]}) (substitute-params (mt/mbql-query venues {:aggregation [[:count]] :joins [{:source-table $$categories :alias "c" :condition [:= $category_id &c.categories.id] :parameters [{:type "category", :target $categories.name, :value "BBQ"}]}]})))))) (deftest ^:parallel expand-native-join-params-test (testing "can we expand native params in a JOIN?" (is (= (mt/mbql-query venues {:aggregation [[:count]] :joins [{:source-query {:native "SELECT * FROM categories WHERE name = ?;" :params ["BBQ"]} :alias "c" :condition [:= $category_id &c.*categories.id]}]}) (substitute-params (mt/mbql-query venues {:aggregation [[:count]] :joins [{:source-query {:native "SELECT * FROM categories WHERE name = {{cat}};" :template-tags {"cat" {:name "cat", :display-name "Category", :type :text}} :parameters [{:type "category", :target [:variable [:template-tag "cat"]], :value "BBQ"}]} :alias "c" :condition [:= $category_id &c.*categories.id]}]})))))) (deftest ^:parallel expand-multiple-mbql-params-test (testing "can we expand multiple sets of MBQL params?" (is (= (mt/mbql-query venues {:source-query {:source-table $$venues :filter [:= $price 1]} :aggregation [[:count]] :joins [{:source-query {:source-table $$categories :filter [:= $categories.name "BBQ"]} :alias "c" :condition [:= $category_id &c.categories.id]}]}) (substitute-params (mt/mbql-query venues {:source-query {:source-table $$venues :parameters [{:name "price", :type :category, :target $price, :value 1}]} :aggregation [[:count]] :joins [{:source-table $$categories :alias "c" :condition [:= $category_id &c.categories.id] :parameters [{:type "category", :target $categories.name, :value "BBQ"}]}]})))))) (deftest ^:parallel expand-multiple-mbql-params-in-joins-test (testing "can we expand multiple sets of MBQL params with params in a join and the join's source query?" (is (= (mt/mbql-query venues {:aggregation [[:count]] :joins [{:source-query {:source-table $$categories :filter [:and [:= $categories.name "BBQ"] [:= $categories.id 5]]} :alias "c" :condition [:= $category_id &c.categories.id]}]}) (substitute-params (mt/mbql-query venues {:aggregation [[:count]] :joins [{:source-query {:source-table $$categories :parameters [{:name "id", :type :category, :target $categories.id, :value 5}]} :alias "c" :condition [:= $category_id &c.categories.id] :parameters [{:type "category", :target $categories.name, :value "BBQ"}]}]})))))) (defn- card-template-tag [card-id] (let [tag (str "#" card-id)] {:id tag, :name tag, :display-name tag, :type "card", :card-id card-id})) (defn card-template-tags "Generate the map representing card template tags (sub-queries) for the given `card-ids`." [card-ids] (into {} (for [card-id card-ids] [(str "#" card-id) (card-template-tag card-id)]))) (deftest expand-multiple-referenced-cards-in-template-tags (testing "multiple sub-queries, referenced in template tags, are correctly substituted" (mt/with-temp* [Card [card-1 {:dataset_query (mt/native-query {:query "SELECT 1"})}] Card [card-2 {:dataset_query (mt/native-query {:query "SELECT 2"})}]] (let [card-1-id (:id card-1) card-2-id (:id card-2)] (is (= (mt/native-query {:query "SELECT COUNT(*) FROM (SELECT 1) AS c1, (SELECT 2) AS c2", :params []}) (substitute-params (mt/native-query {:query (str "SELECT COUNT(*) FROM {{#" card-1-id "}} AS c1, {{#" card-2-id "}} AS c2") :template-tags (card-template-tags [card-1-id card-2-id])}))))))) (testing "multiple CTE queries, referenced in template tags, are correctly substituted" (mt/with-temp* [Card [card-1 {:dataset_query (mt/native-query {:query "SELECT 1"})}] Card [card-2 {:dataset_query (mt/native-query {:query "SELECT 2"})}]] (let [card-1-id (:id card-1) card-2-id (:id card-2)] (is (= (mt/native-query {:query "WITH c1 AS (SELECT 1), c2 AS (SELECT 2) SELECT COUNT(*) FROM c1, c2", :params []}) (substitute-params (mt/native-query {:query (str "WITH c1 AS {{#" card-1-id "}}, " "c2 AS {{#" card-2-id "}} SELECT COUNT(*) FROM c1, c2") :template-tags (card-template-tags [card-1-id card-2-id])}))))))) (testing "recursive native queries, referenced in template tags, are correctly substituted" (mt/with-temp* [Card [card-1 {:dataset_query (mt/native-query {:query "SELECT 1"})}] Card [card-2 {:dataset_query (mt/native-query {:query (str "SELECT * FROM {{#" (:id card-1) "}} AS c1") :template-tags (card-template-tags [(:id card-1)])})}]] (let [card-2-id (:id card-2)] (is (= (mt/native-query {:query "SELECT COUNT(*) FROM (SELECT * FROM (SELECT 1) AS c1) AS c2", :params []}) (substitute-params (mt/native-query {:query (str "SELECT COUNT(*) FROM {{#" card-2-id "}} AS c2") :template-tags (card-template-tags [card-2-id])}))))))) (testing "recursive native/MBQL queries, referenced in template tags, are correctly substituted" (mt/with-temp* [Card [card-1 {:dataset_query (mt/mbql-query venues)}] Card [card-2 {:dataset_query (mt/native-query {:query (str "SELECT * FROM {{#" (:id card-1) "}} AS c1") :template-tags (card-template-tags [(:id card-1)])})}]] (let [card-2-id (:id card-2) card-1-subquery (str "SELECT " "\"PUBLIC\".\"VENUES\".\"ID\" AS \"ID\", " "\"PUBLIC\".\"VENUES\".\"NAME\" AS \"NAME\", " "\"PUBLIC\".\"VENUES\".\"CATEGORY_ID\" AS \"CATEGORY_ID\", " "\"PUBLIC\".\"VENUES\".\"LATITUDE\" AS \"LATITUDE\", " "\"PUBLIC\".\"VENUES\".\"LONGITUDE\" AS \"LONGITUDE\", " "\"PUBLIC\".\"VENUES\".\"PRICE\" AS \"PRICE\" " "FROM \"PUBLIC\".\"VENUES\" " "LIMIT 1048575")] (is (= (mt/native-query {:query (str "SELECT COUNT(*) FROM (SELECT * FROM (" card-1-subquery ") AS c1) AS c2") :params []}) (substitute-params (mt/native-query {:query (str "SELECT COUNT(*) FROM {{#" card-2-id "}} AS c2") :template-tags (card-template-tags [card-2-id])})))))))) (deftest referencing-cards-with-parameters-test (testing "referencing card with parameter and default value substitutes correctly" (mt/with-temp Card [param-card {:dataset_query (mt/native-query {:query "SELECT {{x}}" :template-tags {"x" {:id "x", :name "x", :display-name "Number x", :type :number, :default "1", :required true}}})}] (is (= (mt/native-query {:query "SELECT * FROM (SELECT 1) AS x", :params []}) (substitute-params (mt/native-query {:query (str "SELECT * FROM {{#" (:id param-card) "}} AS x") :template-tags (card-template-tags [(:id param-card)])})))))) (testing "referencing card with parameter and NO default value, fails substitution" (mt/with-temp Card [param-card {:dataset_query (mt/native-query {:query "SELECT {{x}}" :template-tags {"x" {:id "x", :name "x", :display-name "Number x", :type :number, :required false}}})}] (is (thrown? ExceptionInfo (substitute-params (mt/native-query {:query (str "SELECT * FROM {{#" (:id param-card) "}} AS x") :template-tags (card-template-tags [(:id param-card)])}))))))) (defn- snippet-template-tags [snippet-name->id] (into {} (for [[snippet-name snippet-id] snippet-name->id] [snippet-name {:name snippet-name :display-name snippet-name :type :snippet :snippet-name snippet-name :snippet-id snippet-id}]))) (deftest expand-multiple-snippets-test (mt/with-temp* [NativeQuerySnippet [select-snippet {:content "name, price" :creator_id (mt/user->id :rasta) :description "Fields to SELECT" :name "Venue fields"}] NativeQuerySnippet [where-snippet {:content "price > 2" :creator_id (mt/user->id :rasta) :description "Meant for use in WHERE clause" :name "Filter: expensive venues"}] Card [card {:dataset_query (mt/native-query {:query (str "SELECT {{ Venue fields }} " "FROM venues " "WHERE {{ Filter: expensive venues }}") :template-tags (snippet-template-tags {"Venue fields" (:id select-snippet) "Filter: expensive venues" (:id where-snippet)})})}]] (testing "multiple snippets are correctly expanded in parent query" (is (= (mt/native-query {:query "SELECT name, price FROM venues WHERE price > 2", :params nil}) (substitute-params (:dataset_query card))))) (testing "multiple snippets are expanded from saved sub-query" (is (= (mt/native-query {:query "SELECT * FROM (SELECT name, price FROM venues WHERE price > 2) AS x", :params []}) (substitute-params (mt/native-query {:query (str "SELECT * FROM {{#" (:id card) "}} AS x") :template-tags (card-template-tags [(:id card)])}))))))) (deftest include-card-parameters-test (testing "Expanding a Card reference should include its parameters (#12236)" (mt/dataset sample-dataset (mt/with-temp Card [card {:dataset_query (mt/mbql-query orders {:filter [:between $total 30 60] :aggregation [[:aggregation-options [:count-where [:starts-with $product_id->products.category "G"]] {:name "G Monies", :display-name "G Monies"}]] :breakout [!month.created_at]})}] (let [card-tag (str "#" (u/the-id card)) query (mt/native-query {:query (format "SELECT * FROM {{%s}}" card-tag) :template-tags {card-tag {:id "5aa37572-058f-14f6-179d-a158ad6c029d" :name card-tag :display-name card-tag :type :card :card-id (u/the-id card)}}})] (is (schema= {:native {:query su/NonBlankString :params (s/eq ["G%"]) s/Keyword s/Any} s/Keyword s/Any} (substitute-params query))))))))
1026820b3c1fe6efac8b5143c6b7621074a79685d7702b86ed57dc27feb888ef
korya/efuns
terms.ml
(***********************************************************************) (* *) (* Objective Caml *) (* *) , projet Cristal , INRIA Rocquencourt (* *) Copyright 1996 Institut National de Recherche en Informatique et Automatique . Distributed only by permission . (* *) (***********************************************************************) $ I d : terms.ml , v 1.1 1999/11/22 10:35:59 lefessan Exp $ (****************** Term manipulations *****************) type term = Var of int | Term of string * term list let rec union l1 l2 = match l1 with [] -> l2 | a::r -> if List.mem a l2 then union r l2 else a :: union r l2 let rec vars = function Var n -> [n] | Term(_,l) -> vars_of_list l and vars_of_list = function [] -> [] | t::r -> union (vars t) (vars_of_list r) let rec substitute subst = function Term(oper,sons) -> Term(oper, List.map (substitute subst) sons) | Var(n) as t -> try List.assoc n subst with Not_found -> t Term replacement : replace M u N is M[u<-N ] . let rec replace m u n = match (u, m) with [], _ -> n | i::u, Term(oper, sons) -> Term(oper, replace_nth i sons u n) | _ -> failwith "replace" and replace_nth i sons u n = match sons with s::r -> if i = 1 then replace s u n :: r else s :: replace_nth (i-1) r u n | [] -> failwith "replace_nth" (* Term matching. *) let matching term1 term2 = let rec match_rec subst t1 t2 = match (t1, t2) with Var v, _ -> if List.mem_assoc v subst then if t2 = List.assoc v subst then subst else failwith "matching" else (v, t2) :: subst | Term(op1,sons1), Term(op2,sons2) -> if op1 = op2 then List.fold_left2 match_rec subst sons1 sons2 else failwith "matching" | _ -> failwith "matching" in match_rec [] term1 term2 (* A naive unification algorithm. *) let compsubst subst1 subst2 = (List.map (fun (v,t) -> (v, substitute subst1 t)) subst2) @ subst1 let rec occurs n = function Var m -> m = n | Term(_,sons) -> List.exists (occurs n) sons let rec unify term1 term2 = match (term1, term2) with Var n1, _ -> if term1 = term2 then [] else if occurs n1 term2 then failwith "unify" else [n1, term2] | term1, Var n2 -> if occurs n2 term1 then failwith "unify" else [n2, term1] | Term(op1,sons1), Term(op2,sons2) -> if op1 = op2 then List.fold_left2 (fun s t1 t2 -> compsubst (unify (substitute s t1) (substitute s t2)) s) [] sons1 sons2 else failwith "unify" (* We need to print terms with variables independently from input terms obtained by parsing. We give arbitrary names v1,v2,... to their variables. *) let infixes = ["+";"*"] let rec pretty_term = function Var n -> print_string "v"; print_int n | Term (oper,sons) -> if List.mem oper infixes then begin match sons with [s1;s2] -> pretty_close s1; print_string oper; pretty_close s2 | _ -> failwith "pretty_term : infix arity <> 2" end else begin print_string oper; match sons with [] -> () | t::lt -> print_string "("; pretty_term t; List.iter (fun t -> print_string ","; pretty_term t) lt; print_string ")" end and pretty_close = function Term(oper, _) as m -> if List.mem oper infixes then begin print_string "("; pretty_term m; print_string ")" end else pretty_term m | m -> pretty_term m
null
https://raw.githubusercontent.com/korya/efuns/78b21d9dff45b7eec764c63132c7a564f5367c30/inliner/perf/KB/terms.ml
ocaml
********************************************************************* Objective Caml ********************************************************************* ***************** Term manipulations **************** Term matching. A naive unification algorithm. We need to print terms with variables independently from input terms obtained by parsing. We give arbitrary names v1,v2,... to their variables.
, projet Cristal , INRIA Rocquencourt Copyright 1996 Institut National de Recherche en Informatique et Automatique . Distributed only by permission . $ I d : terms.ml , v 1.1 1999/11/22 10:35:59 lefessan Exp $ type term = Var of int | Term of string * term list let rec union l1 l2 = match l1 with [] -> l2 | a::r -> if List.mem a l2 then union r l2 else a :: union r l2 let rec vars = function Var n -> [n] | Term(_,l) -> vars_of_list l and vars_of_list = function [] -> [] | t::r -> union (vars t) (vars_of_list r) let rec substitute subst = function Term(oper,sons) -> Term(oper, List.map (substitute subst) sons) | Var(n) as t -> try List.assoc n subst with Not_found -> t Term replacement : replace M u N is M[u<-N ] . let rec replace m u n = match (u, m) with [], _ -> n | i::u, Term(oper, sons) -> Term(oper, replace_nth i sons u n) | _ -> failwith "replace" and replace_nth i sons u n = match sons with s::r -> if i = 1 then replace s u n :: r else s :: replace_nth (i-1) r u n | [] -> failwith "replace_nth" let matching term1 term2 = let rec match_rec subst t1 t2 = match (t1, t2) with Var v, _ -> if List.mem_assoc v subst then if t2 = List.assoc v subst then subst else failwith "matching" else (v, t2) :: subst | Term(op1,sons1), Term(op2,sons2) -> if op1 = op2 then List.fold_left2 match_rec subst sons1 sons2 else failwith "matching" | _ -> failwith "matching" in match_rec [] term1 term2 let compsubst subst1 subst2 = (List.map (fun (v,t) -> (v, substitute subst1 t)) subst2) @ subst1 let rec occurs n = function Var m -> m = n | Term(_,sons) -> List.exists (occurs n) sons let rec unify term1 term2 = match (term1, term2) with Var n1, _ -> if term1 = term2 then [] else if occurs n1 term2 then failwith "unify" else [n1, term2] | term1, Var n2 -> if occurs n2 term1 then failwith "unify" else [n2, term1] | Term(op1,sons1), Term(op2,sons2) -> if op1 = op2 then List.fold_left2 (fun s t1 t2 -> compsubst (unify (substitute s t1) (substitute s t2)) s) [] sons1 sons2 else failwith "unify" let infixes = ["+";"*"] let rec pretty_term = function Var n -> print_string "v"; print_int n | Term (oper,sons) -> if List.mem oper infixes then begin match sons with [s1;s2] -> pretty_close s1; print_string oper; pretty_close s2 | _ -> failwith "pretty_term : infix arity <> 2" end else begin print_string oper; match sons with [] -> () | t::lt -> print_string "("; pretty_term t; List.iter (fun t -> print_string ","; pretty_term t) lt; print_string ")" end and pretty_close = function Term(oper, _) as m -> if List.mem oper infixes then begin print_string "("; pretty_term m; print_string ")" end else pretty_term m | m -> pretty_term m
1c21a26caa794ed0cdee38b573623c51af801129f134d4e036aa14c9fe59ebf0
larcenists/larceny
diviter.scm
DIVITER -- Benchmark which divides by 2 using lists of n ( ) 's . (define (create-n n) (do ((n n (- n 1)) (a '() (cons '() a))) ((= n 0) a))) (define *ll* (create-n 200)) (define (iterative-div2 l) (do ((l l (cddr l)) (a '() (cons (car l) a))) ((null? l) a))) (define (main . args) (run-benchmark "diviter" diviter-iters (lambda () (iterative-div2 *ll*)) (lambda (result) (equal? result '(() () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () ())))))
null
https://raw.githubusercontent.com/larcenists/larceny/fef550c7d3923deb7a5a1ccd5a628e54cf231c75/test/Stress/src/diviter.scm
scheme
DIVITER -- Benchmark which divides by 2 using lists of n ( ) 's . (define (create-n n) (do ((n n (- n 1)) (a '() (cons '() a))) ((= n 0) a))) (define *ll* (create-n 200)) (define (iterative-div2 l) (do ((l l (cddr l)) (a '() (cons (car l) a))) ((null? l) a))) (define (main . args) (run-benchmark "diviter" diviter-iters (lambda () (iterative-div2 *ll*)) (lambda (result) (equal? result '(() () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () ())))))
f87540a0b410b914d625c084d520a3331a4777df32942512cd62cd78c3bfa688
ZeusWPI/contests
parcours.hs
import Control.Applicative (Alternative (..), Applicative (..), (<$>)) import Control.Monad (MonadPlus (..), ap, guard, replicateM, replicateM_) import Data.Char (isDigit, ord) import Data.List (find) import Data.Map (Map) import Data.Maybe (isNothing, maybeToList) import qualified Data.Map as M import qualified Data.Set as S import Debug.Trace (trace) -------------------------------------------------------------------------------- newtype Parser a = Parser {unParser :: String -> [(a, String)]} instance Alternative Parser where empty = mzero (<|>) = mplus instance Applicative Parser where pure = return (<*>) = ap instance MonadPlus Parser where mzero = Parser $ const [] Parser x `mplus` Parser y = Parser $ \str -> x str ++ y str instance Functor Parser where fmap f (Parser x) = Parser $ \str -> [(f x', str') | (x', str') <- x str] instance Monad Parser where return x = Parser $ \str -> [(x, str)] Parser x >>= f = Parser $ \str -> [ (x'', str'') | (x', str') <- x str , (x'', str'') <- unParser (f x') str' ] runParser :: Parser a -> String -> Maybe a runParser (Parser x) = fmap fst . find (null . snd) . x item :: Parser Char item = Parser $ \str -> case str of (x : xs) -> [(x, xs)] [] -> [] char :: Char -> Parser Char char c = do x <- item guard $ c == x return x digit :: Parser Int digit = do x <- item guard $ isDigit x return $ ord x - ord '0' number :: Parser Int number = do digits <- many digit return $ foldl (\x d -> 10 * x + d) 0 digits -------------------------------------------------------------------------------- data Value = Bool Bool | Int Int deriving (Eq, Show) data Expression = Literal Value | Equals Expression Expression | Plus Expression Expression | Minus Expression Expression | Times Expression Expression deriving (Show) value :: Parser Value value = Int <$> number expression :: Parser Expression expression = exp1 where exp1 = binop '=' Equals exp2 exp1 <|> exp2 exp2 = binop '+' Plus exp3 exp2 <|> binop '-' Minus exp3 exp2 <|> exp3 exp3 = binop 'x' Times exp4 exp3 <|> exp4 exp4 = Literal <$> value binop o cons e1 e2 = do x <- e1 _ <- char o y <- e2 return $ cons x y eval :: Expression -> Value eval e = case e of Literal val -> val Equals e1 e2 -> Bool $ eval e1 == eval e2 Plus e1 e2 -> binop (+) e1 e2 Minus e1 e2 -> binop (-) e1 e2 Times e1 e2 -> binop (*) e1 e2 where binop o e1 e2 = let Int x = eval e1 Int y = eval e2 in Int $ o x y -------------------------------------------------------------------------------- type Position = (Int, Int) type Grid = Map (Int, Int) Char parseGrid :: [String] -> Grid parseGrid rows = M.fromList [ ((r, c), x) | (r, row) <- zip [0 ..] rows , (c, x) <- zip [0 ..] row ] neighbours :: Position -> [Position] neighbours (r, c) = [(r - 1, c), (r, c + 1), (r + 1, c), (r, c - 1)] paths :: Grid -> [String] paths grid = [path | start <- M.keys grid, path <- paths' start "" S.empty] where paths' pos path visited | pos `M.notMember` grid = [] | pos `S.member` visited = [] | S.size visited + 1 >= M.size grid = [path'] | bound = [] | otherwise = [ p | neighbour <- neighbours pos , p <- paths' neighbour path' (S.insert pos visited) ] where path' = grid M.! pos : path bound = case path' of (x : y : _) | not (isDigit x || isDigit y) -> True | otherwise -> False [x] -> not (isDigit x) _ -> False solutions :: Grid -> [String] solutions grid = [ path | path <- paths grid , e <- maybeToList $ runParser expression path , eval e == Bool True ] -------------------------------------------------------------------------------- main :: IO () main = do cases <- readLn replicateM_ cases $ do [rows, _] <- map read . words <$> getLine grid <- parseGrid <$> replicateM rows getLine case solutions grid of (x : _) -> putStrLn x _ -> putStrLn "No solution"
null
https://raw.githubusercontent.com/ZeusWPI/contests/d78aec91be3ce32a436d160cd7a13825d36bbf3a/2011-vpw/parcours.hs
haskell
------------------------------------------------------------------------------ ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ ------------------------------------------------------------------------------
import Control.Applicative (Alternative (..), Applicative (..), (<$>)) import Control.Monad (MonadPlus (..), ap, guard, replicateM, replicateM_) import Data.Char (isDigit, ord) import Data.List (find) import Data.Map (Map) import Data.Maybe (isNothing, maybeToList) import qualified Data.Map as M import qualified Data.Set as S import Debug.Trace (trace) newtype Parser a = Parser {unParser :: String -> [(a, String)]} instance Alternative Parser where empty = mzero (<|>) = mplus instance Applicative Parser where pure = return (<*>) = ap instance MonadPlus Parser where mzero = Parser $ const [] Parser x `mplus` Parser y = Parser $ \str -> x str ++ y str instance Functor Parser where fmap f (Parser x) = Parser $ \str -> [(f x', str') | (x', str') <- x str] instance Monad Parser where return x = Parser $ \str -> [(x, str)] Parser x >>= f = Parser $ \str -> [ (x'', str'') | (x', str') <- x str , (x'', str'') <- unParser (f x') str' ] runParser :: Parser a -> String -> Maybe a runParser (Parser x) = fmap fst . find (null . snd) . x item :: Parser Char item = Parser $ \str -> case str of (x : xs) -> [(x, xs)] [] -> [] char :: Char -> Parser Char char c = do x <- item guard $ c == x return x digit :: Parser Int digit = do x <- item guard $ isDigit x return $ ord x - ord '0' number :: Parser Int number = do digits <- many digit return $ foldl (\x d -> 10 * x + d) 0 digits data Value = Bool Bool | Int Int deriving (Eq, Show) data Expression = Literal Value | Equals Expression Expression | Plus Expression Expression | Minus Expression Expression | Times Expression Expression deriving (Show) value :: Parser Value value = Int <$> number expression :: Parser Expression expression = exp1 where exp1 = binop '=' Equals exp2 exp1 <|> exp2 exp2 = binop '+' Plus exp3 exp2 <|> binop '-' Minus exp3 exp2 <|> exp3 exp3 = binop 'x' Times exp4 exp3 <|> exp4 exp4 = Literal <$> value binop o cons e1 e2 = do x <- e1 _ <- char o y <- e2 return $ cons x y eval :: Expression -> Value eval e = case e of Literal val -> val Equals e1 e2 -> Bool $ eval e1 == eval e2 Plus e1 e2 -> binop (+) e1 e2 Minus e1 e2 -> binop (-) e1 e2 Times e1 e2 -> binop (*) e1 e2 where binop o e1 e2 = let Int x = eval e1 Int y = eval e2 in Int $ o x y type Position = (Int, Int) type Grid = Map (Int, Int) Char parseGrid :: [String] -> Grid parseGrid rows = M.fromList [ ((r, c), x) | (r, row) <- zip [0 ..] rows , (c, x) <- zip [0 ..] row ] neighbours :: Position -> [Position] neighbours (r, c) = [(r - 1, c), (r, c + 1), (r + 1, c), (r, c - 1)] paths :: Grid -> [String] paths grid = [path | start <- M.keys grid, path <- paths' start "" S.empty] where paths' pos path visited | pos `M.notMember` grid = [] | pos `S.member` visited = [] | S.size visited + 1 >= M.size grid = [path'] | bound = [] | otherwise = [ p | neighbour <- neighbours pos , p <- paths' neighbour path' (S.insert pos visited) ] where path' = grid M.! pos : path bound = case path' of (x : y : _) | not (isDigit x || isDigit y) -> True | otherwise -> False [x] -> not (isDigit x) _ -> False solutions :: Grid -> [String] solutions grid = [ path | path <- paths grid , e <- maybeToList $ runParser expression path , eval e == Bool True ] main :: IO () main = do cases <- readLn replicateM_ cases $ do [rows, _] <- map read . words <$> getLine grid <- parseGrid <$> replicateM rows getLine case solutions grid of (x : _) -> putStrLn x _ -> putStrLn "No solution"
628e4ce82af43d2b7d50795d8f8a8681d4c73647cea733b9c03492e240c02d7e
adlai/cjhunt
config.lisp
(in-package :cl-user) (defpackage cjhunt.config (:use :cl) (:import-from :envy :config-env-var :defconfig) (:export :config :*application-root* :*static-directory* :*template-directory* :appenv :developmentp :productionp)) (in-package :cjhunt.config) (setf (config-env-var) "APP_ENV") (defparameter *application-root* (asdf:system-source-directory :cjhunt)) (defparameter *static-directory* (merge-pathnames #P"static/" *application-root*)) (defparameter *template-directory* (merge-pathnames #P"templates/" *application-root*)) (defconfig :common `(:databases ((:maindb :sqlite3 :database-name ":memory:")) :bitcoin #p"~/.bitcoin/bitcoin.conf")) (defconfig |development| '()) (defconfig |production| '()) (defconfig |test| '()) (defun config (&optional key) (envy:config #.(package-name *package*) key)) (defun appenv () (uiop:getenv (config-env-var #.(package-name *package*)))) (defun developmentp () (string= (appenv) "development")) (defun productionp () (string= (appenv) "production"))
null
https://raw.githubusercontent.com/adlai/cjhunt/fb89d8600e6b42c9d6b67dd3fded59907e91a3be/src/config.lisp
lisp
(in-package :cl-user) (defpackage cjhunt.config (:use :cl) (:import-from :envy :config-env-var :defconfig) (:export :config :*application-root* :*static-directory* :*template-directory* :appenv :developmentp :productionp)) (in-package :cjhunt.config) (setf (config-env-var) "APP_ENV") (defparameter *application-root* (asdf:system-source-directory :cjhunt)) (defparameter *static-directory* (merge-pathnames #P"static/" *application-root*)) (defparameter *template-directory* (merge-pathnames #P"templates/" *application-root*)) (defconfig :common `(:databases ((:maindb :sqlite3 :database-name ":memory:")) :bitcoin #p"~/.bitcoin/bitcoin.conf")) (defconfig |development| '()) (defconfig |production| '()) (defconfig |test| '()) (defun config (&optional key) (envy:config #.(package-name *package*) key)) (defun appenv () (uiop:getenv (config-env-var #.(package-name *package*)))) (defun developmentp () (string= (appenv) "development")) (defun productionp () (string= (appenv) "production"))
a1e8e157f8f209212428ec2a9b10db64baab51590bf1f049057c861d2f4bc5c5
dmitryvk/sbcl-win32-threads
early-defbangmethod.lisp
This software is part of the SBCL system . See the README file for ;;;; more information. ;;;; This software is derived from the CMU CL system , which was written at Carnegie Mellon University and released into the ;;;; public domain. The software is in the public domain and is ;;;; provided with absolutely no warranty. See the COPYING and CREDITS ;;;; files for more information. (in-package "SB!IMPL") #+sb-xc-host (defmacro def!method (&rest args) `(defmethod ,@args))
null
https://raw.githubusercontent.com/dmitryvk/sbcl-win32-threads/5abfd64b00a0937ba2df2919f177697d1d91bde4/src/code/early-defbangmethod.lisp
lisp
more information. public domain. The software is in the public domain and is provided with absolutely no warranty. See the COPYING and CREDITS files for more information.
This software is part of the SBCL system . See the README file for This software is derived from the CMU CL system , which was written at Carnegie Mellon University and released into the (in-package "SB!IMPL") #+sb-xc-host (defmacro def!method (&rest args) `(defmethod ,@args))
7d5a4a84914e185aa8d26dba2af849e6135a9f0d6dbe5b207a5321d5f1ad9fea
phadej/cabal-fmt
Parser.hs
-- | -- License: GPL-3.0-or-later Copyright : module CabalFmt.Parser where import qualified Data.ByteString as BS import qualified Distribution.Fields as C import qualified Distribution.PackageDescription.Parsec as C import qualified Distribution.Parsec as C import qualified Distribution.Types.GenericPackageDescription as C import CabalFmt.Error import CabalFmt.Monad import CabalFmt.Prelude runParseResult :: MonadCabalFmt r m => FilePath -> BS.ByteString -> C.ParseResult a -> m a runParseResult filepath contents pr = case result of Right gpd -> return gpd Left (mspecVersion, errors) -> throwError $ CabalParseError filepath contents errors mspecVersion warnings where (warnings, result) = C.runParseResult pr parseGpd :: MonadCabalFmt r m => FilePath -> BS.ByteString -> m C.GenericPackageDescription parseGpd filepath contents = runParseResult filepath contents $ C.parseGenericPackageDescription contents parseFields :: MonadCabalFmt r m => BS.ByteString -> m [C.Field C.Position] parseFields contents = case C.readFields contents of Left err -> throwError $ PanicCannotParseInput err Right x -> return x
null
https://raw.githubusercontent.com/phadej/cabal-fmt/ead940a3dd955a2c7b32b8817b03885ff550c128/src/CabalFmt/Parser.hs
haskell
| License: GPL-3.0-or-later
Copyright : module CabalFmt.Parser where import qualified Data.ByteString as BS import qualified Distribution.Fields as C import qualified Distribution.PackageDescription.Parsec as C import qualified Distribution.Parsec as C import qualified Distribution.Types.GenericPackageDescription as C import CabalFmt.Error import CabalFmt.Monad import CabalFmt.Prelude runParseResult :: MonadCabalFmt r m => FilePath -> BS.ByteString -> C.ParseResult a -> m a runParseResult filepath contents pr = case result of Right gpd -> return gpd Left (mspecVersion, errors) -> throwError $ CabalParseError filepath contents errors mspecVersion warnings where (warnings, result) = C.runParseResult pr parseGpd :: MonadCabalFmt r m => FilePath -> BS.ByteString -> m C.GenericPackageDescription parseGpd filepath contents = runParseResult filepath contents $ C.parseGenericPackageDescription contents parseFields :: MonadCabalFmt r m => BS.ByteString -> m [C.Field C.Position] parseFields contents = case C.readFields contents of Left err -> throwError $ PanicCannotParseInput err Right x -> return x
edff471e43adf456ed2bb071d1df69e4b3691e7ea11bcd7af6a3b49eb680e892
ucsd-progsys/liquidhaskell
Set00.hs
{-@ LIQUID "--expect-any-error" @-} TEST that the name ` member ` is properly resolved to Set_mem . TAG : LOGICMAP module Set00 where import Data.Set as S {-@ add :: x:a -> [a] -> {v:[a] | Set_mem x (listElts v)} @-} add :: a -> [a] -> [a] add x xs = xs
null
https://raw.githubusercontent.com/ucsd-progsys/liquidhaskell/f46dbafd6ce1f61af5b56f31924c21639c982a8a/tests/names/neg/Set00.hs
haskell
@ LIQUID "--expect-any-error" @ @ add :: x:a -> [a] -> {v:[a] | Set_mem x (listElts v)} @
TEST that the name ` member ` is properly resolved to Set_mem . TAG : LOGICMAP module Set00 where import Data.Set as S add :: a -> [a] -> [a] add x xs = xs
0f1d98fad9a17779e07131b82589dba79508cf8b5179e74887350012d8a55127
patoline/patoline
patDefault.ml
let share = try let (ic, _, _) as cs = let env = Unix.environment () in Unix.open_process_full "opam var share" env in let res = input_line ic in ignore (Unix.close_process_full cs); res with _ -> "/usr/local/share" let fonts_dir = Filename.concat share "patoline/fonts" let grammars_dir = Filename.concat share "patoline/grammars" let hyphen_dir = Filename.concat share "patoline/hyphen" let extra_fonts_dir = [] let extra_grammars_dir = [] let extra_hyphen_dir = [] FIXME generate dynamically ( using findlib ? ) . let formats = [ "DefaultFormat" ; "SimpleSlides" ; "FormatThese" ; "FormatWeb" ; "FormatLetter" ; "FormatSlides" ; "FormatMemoire" ; "FormatLivre" ; "LMFormat" ; "FormatArticle" ] FIXME generate dynamically ( using findlib ? ) . let drivers = [ "Bin" ; "DriverCairo" ; "DriverGL" ; "DriverImage" ; "Html" ; "Net" ; "None" ; "Patonet" ; "Pdf" ; "SVG" ]
null
https://raw.githubusercontent.com/patoline/patoline/3dcd41fdff64895d795d4a78baa27d572b161081/patconfig/patDefault.ml
ocaml
let share = try let (ic, _, _) as cs = let env = Unix.environment () in Unix.open_process_full "opam var share" env in let res = input_line ic in ignore (Unix.close_process_full cs); res with _ -> "/usr/local/share" let fonts_dir = Filename.concat share "patoline/fonts" let grammars_dir = Filename.concat share "patoline/grammars" let hyphen_dir = Filename.concat share "patoline/hyphen" let extra_fonts_dir = [] let extra_grammars_dir = [] let extra_hyphen_dir = [] FIXME generate dynamically ( using findlib ? ) . let formats = [ "DefaultFormat" ; "SimpleSlides" ; "FormatThese" ; "FormatWeb" ; "FormatLetter" ; "FormatSlides" ; "FormatMemoire" ; "FormatLivre" ; "LMFormat" ; "FormatArticle" ] FIXME generate dynamically ( using findlib ? ) . let drivers = [ "Bin" ; "DriverCairo" ; "DriverGL" ; "DriverImage" ; "Html" ; "Net" ; "None" ; "Patonet" ; "Pdf" ; "SVG" ]
00949ae8309b92d8403e8d0691fb2c4bca5d2240b932068ea8678217234aa0c6
lspitzner/brittany
Test369.hs
-- brittany { lconfig_columnAlignMode: { tag: ColumnAlignModeDisabled }, lconfig_indentPolicy: IndentPolicyLeft } func :: ( lkasdlkjalsdjlakjsdlkjasldkjalskdjlkajsd -> lkasdlkjalsdjlakjsdlkjasldkjalskdjlkajsd ) -> lakjsdlkjasldkj
null
https://raw.githubusercontent.com/lspitzner/brittany/a15eed5f3608bf1fa7084fcf008c6ecb79542562/data/Test369.hs
haskell
brittany { lconfig_columnAlignMode: { tag: ColumnAlignModeDisabled }, lconfig_indentPolicy: IndentPolicyLeft }
func :: ( lkasdlkjalsdjlakjsdlkjasldkjalskdjlkajsd -> lkasdlkjalsdjlakjsdlkjasldkjalskdjlkajsd ) -> lakjsdlkjasldkj
df193190c75c73930f0dc4263fac64d7d727aea67425d74eb4c930c001af155d
deobald/jok
slide.cljs
(ns slide (:require [goog.dom :as gdom] goog.dom.query [goog.events :as events] [goog.events.EventType :as event-type] interop)) (defn find-by-classes [classes] (.item (gdom/query classes) 0)) (defn slide-to [color] (set! (.-location js/window) (str "/" color))) (defn ready [] (doseq [color ["white" "yellow" "pink"]] (if-let [e (find-by-classes (str ".sidebar." color))] (events/listen e event-type/CLICK #(slide-to color)))))
null
https://raw.githubusercontent.com/deobald/jok/e1b9373603ad7fcc3dbc7304cb8b88b8163e73bc/src-cljs/slide.cljs
clojure
(ns slide (:require [goog.dom :as gdom] goog.dom.query [goog.events :as events] [goog.events.EventType :as event-type] interop)) (defn find-by-classes [classes] (.item (gdom/query classes) 0)) (defn slide-to [color] (set! (.-location js/window) (str "/" color))) (defn ready [] (doseq [color ["white" "yellow" "pink"]] (if-let [e (find-by-classes (str ".sidebar." color))] (events/listen e event-type/CLICK #(slide-to color)))))
fea1992651893c485ad9dd015627c508e6eb2f2112d88a5d5dd9e06a3fdb6615
ocharles/blog
2013-12-18-square.hs
module Square where | Given an integer , ' square ' returns the same number squared : > > > square 5 25 >>> square 5 25 -} square :: Int -> Int square x = x * x
null
https://raw.githubusercontent.com/ocharles/blog/fa8e911d3c03b134eee891d187a1bb574f23a530/code/2013-12-18-square.hs
haskell
module Square where | Given an integer , ' square ' returns the same number squared : > > > square 5 25 >>> square 5 25 -} square :: Int -> Int square x = x * x
fa5cc0537e4f933d1efb58efb2e4063697a96a54d6886e0db56d9c4b1fb9186a
wooga/locker
basho_bench_driver_locker.erl
-module(basho_bench_driver_locker). -export([new/1, run/4]). new(_Id) -> case mark_setup_completed() of true -> error_logger:info_msg("setting up cluster~n"), net_kernel:start([master, shortnames]), {ok, _LocalLocker} = locker:start_link(2), MasterNames = basho_bench_config:get(masters), ReplicaNames = basho_bench_config:get(replicas), W = basho_bench_config:get(w), case basho_bench_config:get(start_nodes) of true -> Masters = setup(MasterNames, W), Replicas = setup(ReplicaNames, W), ok = locker:set_nodes(Masters ++ Replicas, Masters, Replicas), error_logger:info_msg("~p~n", [rpc:call(hd(Replicas), locker, get_meta, [])]), {ok, {Masters, Replicas}}; false -> {ok, []} end; false -> timer : sleep(30000 ) , Masters = [list_to_atom(atom_to_list(N) ++ "@" ++ atom_to_list(H)) || {H, N} <- basho_bench_config:get(masters)], Replicas = [list_to_atom(atom_to_list(N) ++ "@" ++ atom_to_list(H)) || {H, N} <- basho_bench_config:get(replicas)], {ok, {Masters, Replicas}} end. setup(NodeNames, W) -> Nodes = [begin element(2, slave:start_link(Hostname, N)) end || {Hostname, N} <- NodeNames], [rpc:call(N, code, add_path, ["/home/knutin/git/locker/ebin"]) || N <- Nodes], [rpc:call(N, locker, start_link, [W]) || N <- Nodes], Nodes. mark_setup_completed() -> case whereis(locker_setup) of undefined -> true = register(locker_setup, self()), true; _ -> false end. run(set, KeyGen, _ValueGen, {[M | Masters], Replicas}) -> NewMasters = lists:reverse([M | lists:reverse(Masters)]), Key = KeyGen(), case rpc:call(M, locker, lock, [Key, Key]) of {ok, _, _, _} -> {ok, {NewMasters, Replicas}}; {error, Error} -> error_logger:info_msg("Key: ~p~, ~p~n", [Key, Error]), {error, Error, {NewMasters, Replicas}} end; run(get, KeyGen, _, {[M | Masters], Replicas}) -> NewMasters = lists:reverse([M | lists:reverse(Masters)]), Key = KeyGen(), case locker:dirty_read(Key) of {ok, Key} -> {ok, {NewMasters, Replicas}}; {ok, _OtherValue} -> {error, wrong_value, {NewMasters, Replicas}}; {error, not_found} -> {ok, {NewMasters, Replicas}} end.
null
https://raw.githubusercontent.com/wooga/locker/cf92412b95fd429066a8c511c0049447a10d58fa/test/basho_bench_driver_locker.erl
erlang
-module(basho_bench_driver_locker). -export([new/1, run/4]). new(_Id) -> case mark_setup_completed() of true -> error_logger:info_msg("setting up cluster~n"), net_kernel:start([master, shortnames]), {ok, _LocalLocker} = locker:start_link(2), MasterNames = basho_bench_config:get(masters), ReplicaNames = basho_bench_config:get(replicas), W = basho_bench_config:get(w), case basho_bench_config:get(start_nodes) of true -> Masters = setup(MasterNames, W), Replicas = setup(ReplicaNames, W), ok = locker:set_nodes(Masters ++ Replicas, Masters, Replicas), error_logger:info_msg("~p~n", [rpc:call(hd(Replicas), locker, get_meta, [])]), {ok, {Masters, Replicas}}; false -> {ok, []} end; false -> timer : sleep(30000 ) , Masters = [list_to_atom(atom_to_list(N) ++ "@" ++ atom_to_list(H)) || {H, N} <- basho_bench_config:get(masters)], Replicas = [list_to_atom(atom_to_list(N) ++ "@" ++ atom_to_list(H)) || {H, N} <- basho_bench_config:get(replicas)], {ok, {Masters, Replicas}} end. setup(NodeNames, W) -> Nodes = [begin element(2, slave:start_link(Hostname, N)) end || {Hostname, N} <- NodeNames], [rpc:call(N, code, add_path, ["/home/knutin/git/locker/ebin"]) || N <- Nodes], [rpc:call(N, locker, start_link, [W]) || N <- Nodes], Nodes. mark_setup_completed() -> case whereis(locker_setup) of undefined -> true = register(locker_setup, self()), true; _ -> false end. run(set, KeyGen, _ValueGen, {[M | Masters], Replicas}) -> NewMasters = lists:reverse([M | lists:reverse(Masters)]), Key = KeyGen(), case rpc:call(M, locker, lock, [Key, Key]) of {ok, _, _, _} -> {ok, {NewMasters, Replicas}}; {error, Error} -> error_logger:info_msg("Key: ~p~, ~p~n", [Key, Error]), {error, Error, {NewMasters, Replicas}} end; run(get, KeyGen, _, {[M | Masters], Replicas}) -> NewMasters = lists:reverse([M | lists:reverse(Masters)]), Key = KeyGen(), case locker:dirty_read(Key) of {ok, Key} -> {ok, {NewMasters, Replicas}}; {ok, _OtherValue} -> {error, wrong_value, {NewMasters, Replicas}}; {error, not_found} -> {ok, {NewMasters, Replicas}} end.
815fa4fcaf22ada9733d3453b43c034fc79c997efcf3885543a40baba4a39467
edbutler/nonograms-rule-synthesis
collection.rkt
#lang racket ; some data structures (e.g., a digraph) (provide digraph? make-digraph dg-identity-node-key? serialize-digraph deserialize-digraph dg-node-ref dg-node-value dg-edge-value dg-edge-source dg-edge-target dg-nodes dg-order dg-size dg-edge-values dg-add-node! dg-outgoing-edges dg-outgoing-neighbors dg-out-degree dg-sink? dg-sources dg-sinks dg-add-edge! dg-reachable? dg-all-reachable-nodes dg-filter-nodes dg-reverse-edges dg-shortest-path dg-all-reverse-paths dg-topological-sort) (require data/queue "util.rkt") (struct node (val out-edges)) (struct edge (val src dst)) (struct digraph (nodes key-fn)) (define (make-digraph node-key-fn) (digraph (make-hash) node-key-fn)) ; #f iff the node key function is the identity (define (dg-identity-node-key? grph) (eq? identity (digraph-key-fn grph))) ; maps both node and edge values of the graph then dumps nodes as a list ; the caller is going to have to remember the key-fn manually, unfortunately. (define (serialize-digraph node-fn edge-fn grph) (define nodes (dg-nodes grph)) (define node-to-index (for/hasheq ([i (in-range (length nodes))]) (values (list-ref nodes i) i))) (map (λ (n) (match-define (node val out-edges) n) (define new-edges (map (λ (e) (match-define (edge val src dst) e) (list 'edge (edge-fn val) (hash-ref node-to-index dst))) (unbox out-edges))) (list 'node (node-fn val) new-edges)) nodes)) (define (deserialize-digraph key-fn node-fn edge-fn serialized-graph) (define grph (make-digraph key-fn)) (define nodes (for/list ([n serialized-graph]) (match-define (list 'node val _) n) (dg-add-node! grph (node-fn val)))) (for ([n serialized-graph] [nde nodes] #:when #t [e (third n)]) (match-define (list 'edge val dst) e) (dg-add-edge! nde (list-ref nodes dst) (edge-fn val))) grph) (define (listbox-add! bx val) (update-box! bx (λ (lst) (cons val lst)))) (define dg-node-value node-val) (define dg-edge-value edge-val) (define dg-edge-source edge-src) (define dg-edge-target edge-dst) (define (dg-node-ref grph key #:default [default #f]) (hash-ref (digraph-nodes grph) key default)) (define (dg-nodes grph) (hash-values (digraph-nodes grph))) (define (dg-order grph) (hash-count (digraph-nodes grph))) (define (dg-size grph) (for/sum ([n (dg-nodes grph)]) (length (unbox (node-out-edges n))))) (define (dg-edge-values grph) (for*/list ([n (dg-nodes grph)] [e (unbox (node-out-edges n))]) (edge-val e))) ; digraph?, any? -> node? (define (dg-add-node! grph val) (define key ((digraph-key-fn grph) val)) (define nodes (digraph-nodes grph)) (when (hash-has-key? nodes key) (error "node already exists!")) (define n (node val (box empty))) (hash-set! nodes key n) n) ; node? -> (listof edge?) (define (dg-outgoing-edges nde) (unbox (node-out-edges nde))) node ? - > ( listof node ? ) (define (dg-outgoing-neighbors nde) (map edge-dst (unbox (node-out-edges nde)))) (define (dg-out-degree nde) (length (dg-outgoing-edges nde))) (define (dg-sink? nde) (= (dg-out-degree nde) 0)) (define (dg-add-edge! src-node dst-node edge-value) (node-val dst-node) (listbox-add! (node-out-edges src-node) (edge edge-value src-node dst-node))) (define (dg-reachable? start-node end-node #:filter-edge [filter-edge (λ (_) #t)]) ; do a dfs until we find end-node or exhaust (define visited (mutable-set)) (define (dfs n) (set-add! visited n) (or (equal? n end-node) (ormap (λ (e) (define next (edge-dst e)) (and (filter-edge (edge-val e)) (not (set-member? visited next)) (dfs next))) (unbox (node-out-edges n))))) (dfs start-node)) (define (dg-all-reachable-nodes start-nodes) (define visited (mutable-seteq)) (define (rec nde) (set-add! visited nde) (for ([e (in-list (unbox (node-out-edges nde)))] #:when (not (set-member? visited (edge-dst e)))) (rec (edge-dst e)))) (for-each rec start-nodes) visited) ; returns a new graph with only the nodes for which proc evaluates to true. ; will preserve all edges for which both source and target are in the filtered set (define (dg-filter-nodes proc graph) (match-define (digraph old-nodes key-fn) graph) (define nodes (for/hash ([(k v) old-nodes] #:when (proc v)) (values k (node k (box #f))))) (for ([(k v) old-nodes] #:when (proc v)) (define nde (hash-ref nodes k)) (define edges (filter-map (λ (e) (match-define (edge val src dst) e) (and (proc src) (proc dst) (edge val (hash-ref nodes (node-val src)) (hash-ref nodes (node-val dst))))) (unbox (node-out-edges v)))) (set-box! (node-out-edges nde) edges)) (digraph nodes key-fn)) (define (dg-reverse-edges old-grph) (define new-grph (make-digraph (digraph-key-fn old-grph))) (for ([nde (dg-nodes old-grph)]) (dg-add-node! new-grph (node-val nde))) (for ([nde (dg-nodes old-grph)]) (for ([e (unbox (node-out-edges nde))]) (match-define (edge val src dst) e) (dg-add-edge! (dg-node-ref new-grph (node-val dst)) (dg-node-ref new-grph (node-val src)) val))) new-grph) (define (dg-shortest-path grph start-node goal-nodes #:filter-edge [filter-edge (λ (_) #t)] #:edge-cost [edge-cost (λ (_) 1)]) ( " finding shortest path from ~a to ~a " ( node - val start - node ) ( map node - val goal - nodes ) ) (define nodes (dg-nodes grph)) (define node-to-index (for/hasheq ([i (in-range (length nodes))]) (values (list-ref nodes i) i))) (define (nvref vec nde) (vector-ref vec (hash-ref node-to-index nde))) (define (nvset! vec nde x) (vector-set! vec (hash-ref node-to-index nde) x)) (define distances (make-vector (length nodes) 100000)) (define prev (make-vector (length nodes) #f)) (nvset! distances start-node 0) (define to-visit (list->vector nodes)) (define (visit-cost x) (if x (nvref distances x) 10000000)) (define (loop) (define next (vector-argmin visit-cost to-visit)) ;(dprint next) (when next (nvset! to-visit next #f) (define d (nvref distances next)) (for ([e (dg-outgoing-edges next)] #:when (filter-edge (edge-val e))) ;(dprintf "looking at edge ~a" (edge-val e)) (define dst (edge-dst e)) (define alt (+ d (edge-cost (edge-val e)))) (when (< alt (nvref distances dst)) ( " updating cost to ~a for node ~a " alt ( node - val dst ) ) (nvset! distances dst alt) (nvset! prev dst e))) (loop))) (loop) (define closest-goal (argmin (λ (n) (nvref distances n)) goal-nodes)) (unless (or (nvref prev closest-goal) (eq? closest-goal start-node)) (dprintf "reachable? ~a" (ormap (λ (n) (dg-reachable? start-node n #:filter-edge filter-edge)) goal-nodes)) (dprint nodes) (dprint (node-val start-node)) (dprint closest-goal) (dprint (node-val closest-goal)) (dprint (eq? start-node closest-goal)) (dprint distances) (dprint prev) (error "something is wrong!")) (define (build-path n acc) (cond [(eq? n start-node) acc] [else (define e (nvref prev n)) (build-path (edge-src e) (cons (edge-val e) acc))])) (build-path closest-goal empty)) ; node? -> edge-value? list list ; returns all paths (reversed) from src-node to sinks, avoiding cycles. (define (dg-all-reverse-paths start-node) (define (rec nde acc visited) (define new-visited (set-add visited nde)) (match (unbox (node-out-edges nde)) ['() (list acc)] [edges (for*/list ([e (in-list edges)] #:when (not (set-member? visited (edge-dst e))) [r (in-list (rec (edge-dst e) (cons (edge-val e) acc) new-visited))]) r)])) (rec start-node empty (seteq))) (define (dg-sources grph) (define nodes (dg-nodes grph)) ; we don't store incoming edges, so have to calculate it instead (define has-incoming? (make-hasheq)) (for* ([n nodes] [d (dg-outgoing-neighbors n)]) (hash-set! has-incoming? d #t)) (filter (λ (n) (not (hash-ref has-incoming? n #f))) nodes)) (define (dg-sinks grph) (filter dg-sink? (dg-nodes grph))) digraph ? - > ( listof node ? ) Given a DAG , returns a list of nodes in ( arbitrary ) topological order . ; For any node, it will be earlier in the list than any of its outgoing neighbors. (define (dg-topological-sort grph) (define all-nodes (dg-nodes grph)) ; we don't store incoming edges, so have to calculate it instead (define incoming (make-hasheq)) ; node? -> (setof node?) (for* ([n all-nodes] [d (dg-outgoing-neighbors n)]) (hash-update! incoming d (curry cons n) empty)) ; they are currently lists, turn them all into sets (for ([n all-nodes]) (hash-update! incoming n list->seteq empty)) ; then go through them in an order consistent with a topological sort (let loop ([remaining (list->seteq all-nodes)] [visited (seteq)] [acc empty]) (cond [(set-empty? remaining) (reverse acc)] [else ; find any remaining node for which we've visited all incoming edges (define next (findf (λ (n) (set-empty? (set-subtract (hash-ref incoming n) visited))) (set->list remaining))) (unless next (error "graph is not a DAG! cannot find topological sort!")) (loop (set-remove remaining next) (set-add visited next) (cons next acc))])))
null
https://raw.githubusercontent.com/edbutler/nonograms-rule-synthesis/16f8dacb17bd77c9d927ab9fa0b8c1678dc68088/src/core/collection.rkt
racket
some data structures (e.g., a digraph) #f iff the node key function is the identity maps both node and edge values of the graph then dumps nodes as a list the caller is going to have to remember the key-fn manually, unfortunately. digraph?, any? -> node? node? -> (listof edge?) do a dfs until we find end-node or exhaust returns a new graph with only the nodes for which proc evaluates to true. will preserve all edges for which both source and target are in the filtered set (dprint next) (dprintf "looking at edge ~a" (edge-val e)) node? -> edge-value? list list returns all paths (reversed) from src-node to sinks, avoiding cycles. we don't store incoming edges, so have to calculate it instead For any node, it will be earlier in the list than any of its outgoing neighbors. we don't store incoming edges, so have to calculate it instead node? -> (setof node?) they are currently lists, turn them all into sets then go through them in an order consistent with a topological sort find any remaining node for which we've visited all incoming edges
#lang racket (provide digraph? make-digraph dg-identity-node-key? serialize-digraph deserialize-digraph dg-node-ref dg-node-value dg-edge-value dg-edge-source dg-edge-target dg-nodes dg-order dg-size dg-edge-values dg-add-node! dg-outgoing-edges dg-outgoing-neighbors dg-out-degree dg-sink? dg-sources dg-sinks dg-add-edge! dg-reachable? dg-all-reachable-nodes dg-filter-nodes dg-reverse-edges dg-shortest-path dg-all-reverse-paths dg-topological-sort) (require data/queue "util.rkt") (struct node (val out-edges)) (struct edge (val src dst)) (struct digraph (nodes key-fn)) (define (make-digraph node-key-fn) (digraph (make-hash) node-key-fn)) (define (dg-identity-node-key? grph) (eq? identity (digraph-key-fn grph))) (define (serialize-digraph node-fn edge-fn grph) (define nodes (dg-nodes grph)) (define node-to-index (for/hasheq ([i (in-range (length nodes))]) (values (list-ref nodes i) i))) (map (λ (n) (match-define (node val out-edges) n) (define new-edges (map (λ (e) (match-define (edge val src dst) e) (list 'edge (edge-fn val) (hash-ref node-to-index dst))) (unbox out-edges))) (list 'node (node-fn val) new-edges)) nodes)) (define (deserialize-digraph key-fn node-fn edge-fn serialized-graph) (define grph (make-digraph key-fn)) (define nodes (for/list ([n serialized-graph]) (match-define (list 'node val _) n) (dg-add-node! grph (node-fn val)))) (for ([n serialized-graph] [nde nodes] #:when #t [e (third n)]) (match-define (list 'edge val dst) e) (dg-add-edge! nde (list-ref nodes dst) (edge-fn val))) grph) (define (listbox-add! bx val) (update-box! bx (λ (lst) (cons val lst)))) (define dg-node-value node-val) (define dg-edge-value edge-val) (define dg-edge-source edge-src) (define dg-edge-target edge-dst) (define (dg-node-ref grph key #:default [default #f]) (hash-ref (digraph-nodes grph) key default)) (define (dg-nodes grph) (hash-values (digraph-nodes grph))) (define (dg-order grph) (hash-count (digraph-nodes grph))) (define (dg-size grph) (for/sum ([n (dg-nodes grph)]) (length (unbox (node-out-edges n))))) (define (dg-edge-values grph) (for*/list ([n (dg-nodes grph)] [e (unbox (node-out-edges n))]) (edge-val e))) (define (dg-add-node! grph val) (define key ((digraph-key-fn grph) val)) (define nodes (digraph-nodes grph)) (when (hash-has-key? nodes key) (error "node already exists!")) (define n (node val (box empty))) (hash-set! nodes key n) n) (define (dg-outgoing-edges nde) (unbox (node-out-edges nde))) node ? - > ( listof node ? ) (define (dg-outgoing-neighbors nde) (map edge-dst (unbox (node-out-edges nde)))) (define (dg-out-degree nde) (length (dg-outgoing-edges nde))) (define (dg-sink? nde) (= (dg-out-degree nde) 0)) (define (dg-add-edge! src-node dst-node edge-value) (node-val dst-node) (listbox-add! (node-out-edges src-node) (edge edge-value src-node dst-node))) (define (dg-reachable? start-node end-node #:filter-edge [filter-edge (λ (_) #t)]) (define visited (mutable-set)) (define (dfs n) (set-add! visited n) (or (equal? n end-node) (ormap (λ (e) (define next (edge-dst e)) (and (filter-edge (edge-val e)) (not (set-member? visited next)) (dfs next))) (unbox (node-out-edges n))))) (dfs start-node)) (define (dg-all-reachable-nodes start-nodes) (define visited (mutable-seteq)) (define (rec nde) (set-add! visited nde) (for ([e (in-list (unbox (node-out-edges nde)))] #:when (not (set-member? visited (edge-dst e)))) (rec (edge-dst e)))) (for-each rec start-nodes) visited) (define (dg-filter-nodes proc graph) (match-define (digraph old-nodes key-fn) graph) (define nodes (for/hash ([(k v) old-nodes] #:when (proc v)) (values k (node k (box #f))))) (for ([(k v) old-nodes] #:when (proc v)) (define nde (hash-ref nodes k)) (define edges (filter-map (λ (e) (match-define (edge val src dst) e) (and (proc src) (proc dst) (edge val (hash-ref nodes (node-val src)) (hash-ref nodes (node-val dst))))) (unbox (node-out-edges v)))) (set-box! (node-out-edges nde) edges)) (digraph nodes key-fn)) (define (dg-reverse-edges old-grph) (define new-grph (make-digraph (digraph-key-fn old-grph))) (for ([nde (dg-nodes old-grph)]) (dg-add-node! new-grph (node-val nde))) (for ([nde (dg-nodes old-grph)]) (for ([e (unbox (node-out-edges nde))]) (match-define (edge val src dst) e) (dg-add-edge! (dg-node-ref new-grph (node-val dst)) (dg-node-ref new-grph (node-val src)) val))) new-grph) (define (dg-shortest-path grph start-node goal-nodes #:filter-edge [filter-edge (λ (_) #t)] #:edge-cost [edge-cost (λ (_) 1)]) ( " finding shortest path from ~a to ~a " ( node - val start - node ) ( map node - val goal - nodes ) ) (define nodes (dg-nodes grph)) (define node-to-index (for/hasheq ([i (in-range (length nodes))]) (values (list-ref nodes i) i))) (define (nvref vec nde) (vector-ref vec (hash-ref node-to-index nde))) (define (nvset! vec nde x) (vector-set! vec (hash-ref node-to-index nde) x)) (define distances (make-vector (length nodes) 100000)) (define prev (make-vector (length nodes) #f)) (nvset! distances start-node 0) (define to-visit (list->vector nodes)) (define (visit-cost x) (if x (nvref distances x) 10000000)) (define (loop) (define next (vector-argmin visit-cost to-visit)) (when next (nvset! to-visit next #f) (define d (nvref distances next)) (for ([e (dg-outgoing-edges next)] #:when (filter-edge (edge-val e))) (define dst (edge-dst e)) (define alt (+ d (edge-cost (edge-val e)))) (when (< alt (nvref distances dst)) ( " updating cost to ~a for node ~a " alt ( node - val dst ) ) (nvset! distances dst alt) (nvset! prev dst e))) (loop))) (loop) (define closest-goal (argmin (λ (n) (nvref distances n)) goal-nodes)) (unless (or (nvref prev closest-goal) (eq? closest-goal start-node)) (dprintf "reachable? ~a" (ormap (λ (n) (dg-reachable? start-node n #:filter-edge filter-edge)) goal-nodes)) (dprint nodes) (dprint (node-val start-node)) (dprint closest-goal) (dprint (node-val closest-goal)) (dprint (eq? start-node closest-goal)) (dprint distances) (dprint prev) (error "something is wrong!")) (define (build-path n acc) (cond [(eq? n start-node) acc] [else (define e (nvref prev n)) (build-path (edge-src e) (cons (edge-val e) acc))])) (build-path closest-goal empty)) (define (dg-all-reverse-paths start-node) (define (rec nde acc visited) (define new-visited (set-add visited nde)) (match (unbox (node-out-edges nde)) ['() (list acc)] [edges (for*/list ([e (in-list edges)] #:when (not (set-member? visited (edge-dst e))) [r (in-list (rec (edge-dst e) (cons (edge-val e) acc) new-visited))]) r)])) (rec start-node empty (seteq))) (define (dg-sources grph) (define nodes (dg-nodes grph)) (define has-incoming? (make-hasheq)) (for* ([n nodes] [d (dg-outgoing-neighbors n)]) (hash-set! has-incoming? d #t)) (filter (λ (n) (not (hash-ref has-incoming? n #f))) nodes)) (define (dg-sinks grph) (filter dg-sink? (dg-nodes grph))) digraph ? - > ( listof node ? ) Given a DAG , returns a list of nodes in ( arbitrary ) topological order . (define (dg-topological-sort grph) (define all-nodes (dg-nodes grph)) (for* ([n all-nodes] [d (dg-outgoing-neighbors n)]) (hash-update! incoming d (curry cons n) empty)) (for ([n all-nodes]) (hash-update! incoming n list->seteq empty)) (let loop ([remaining (list->seteq all-nodes)] [visited (seteq)] [acc empty]) (cond [(set-empty? remaining) (reverse acc)] [else (define next (findf (λ (n) (set-empty? (set-subtract (hash-ref incoming n) visited))) (set->list remaining))) (unless next (error "graph is not a DAG! cannot find topological sort!")) (loop (set-remove remaining next) (set-add visited next) (cons next acc))])))